Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions packages/core/src/helpers/request-auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.

import { DEFAULT_SITE } from '@dd/core/constants';
import {
DEFAULT_API_AUTH_MISSING_AUTH_MESSAGE,
MissingRequestAuthError,
hasValidAppApiKey,
withApiAuth,
withBaseUrl,
} from '@dd/core/helpers/request-auth';
import type { AuthOptionsWithDefaults } from '@dd/core/types';
import { getMockLogger, mockLogFn } from '@dd/tests/_jest/helpers/mocks';

describe('Core - request auth', () => {
const auth: AuthOptionsWithDefaults = {
apiKey: 'api-key',
appKey: 'app-key',
site: DEFAULT_SITE,
};
const log = getMockLogger();

beforeEach(() => {
mockLogFn.mockClear();
});

test('Should identify valid APP/API key auth', () => {
expect(hasValidAppApiKey(auth)).toBe(true);
expect(hasValidAppApiKey({ apiKey: 'api-key' })).toBe(false);
});

test('Should inject API and APP key auth before calling request', async () => {
const request = jest.fn().mockResolvedValue('ok');
const requestWithAuth = withApiAuth({ auth, log })(request);
expect(() => requestWithAuth.assertAuthConfigured()).not.toThrow();

await expect(requestWithAuth({ url: 'https://api.datadoghq.com/test' })).resolves.toBe(
'ok',
);

expect(request).toHaveBeenCalledWith({
url: 'https://api.datadoghq.com/test',
auth: { apiKey: 'api-key', appKey: 'app-key' },
});
});

test('Should warn and reject when API key auth is selected without required credentials', async () => {
const request = jest.fn();
const requestWithAuth = withApiAuth({
auth: {},
log,
missingAuthMessage: 'Missing app/api keys.',
})(request);

expect(mockLogFn).not.toHaveBeenCalled();

await expect(requestWithAuth({ url: 'https://api.datadoghq.com/test' })).rejects.toThrow(
MissingRequestAuthError,
);
expect(mockLogFn).toHaveBeenCalledWith('Missing app/api keys.', 'warn');
expect(request).not.toHaveBeenCalled();
});

test('Should assert missing API key auth before calling request', () => {
const request = jest.fn();
const requestWithAuth = withApiAuth({
auth: {},
log,
missingAuthMessage: 'Missing app/api keys.',
})(request);

expect(() => requestWithAuth.assertAuthConfigured()).toThrow(MissingRequestAuthError);
expect(mockLogFn).toHaveBeenCalledWith('Missing app/api keys.', 'warn');
expect(request).not.toHaveBeenCalled();
});

test('Should use the API auth default missing auth message', async () => {
const request = jest.fn();
const requestWithAuth = withApiAuth({
auth: {},
log,
})(request);

expect(mockLogFn).not.toHaveBeenCalled();

await expect(requestWithAuth({ url: 'https://api.datadoghq.com/test' })).rejects.toThrow(
DEFAULT_API_AUTH_MISSING_AUTH_MESSAGE,
);
expect(mockLogFn).toHaveBeenCalledWith(DEFAULT_API_AUTH_MISSING_AUTH_MESSAGE, 'warn');
expect(request).not.toHaveBeenCalled();
});

test('Should prefix relative request URLs with a base URL', async () => {
const request = jest.fn().mockResolvedValue('ok');
const requestWithBaseUrl = withBaseUrl('https://api.datadoghq.com')(request);

await expect(requestWithBaseUrl({ url: '/api/v2/test' })).resolves.toBe('ok');

expect(request).toHaveBeenCalledWith({
url: 'https://api.datadoghq.com/api/v2/test',
});
});

test('Should preserve absolute request URLs', async () => {
const request = jest.fn().mockResolvedValue('ok');
const requestWithBaseUrl = withBaseUrl('https://api.datadoghq.com')(request);

await expect(requestWithBaseUrl({ url: 'https://custom.apps/upload' })).resolves.toBe('ok');

expect(request).toHaveBeenCalledWith({
url: 'https://custom.apps/upload',
});
});
});
76 changes: 76 additions & 0 deletions packages/core/src/helpers/request-auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.

import type { AuthOptionsWithDefaults, Logger, RequestAuthOptions, RequestOpts } from '../types';

export type RequestOptsWithoutAuth = Omit<RequestOpts, 'auth'>;
export type RequestFunction = <T>(opts: RequestOpts) => Promise<T>;
export type AuthenticatedRequestFunction = (<T>(opts: RequestOptsWithoutAuth) => Promise<T>) & {
assertAuthConfigured: () => void;
};

export const DEFAULT_API_AUTH_MISSING_AUTH_MESSAGE =
'Auth credentials not configured. Set DD_API_KEY and DD_APP_KEY.';

export class MissingRequestAuthError extends Error {
constructor(message = DEFAULT_API_AUTH_MISSING_AUTH_MESSAGE) {
super(message);
}
}

export const hasValidAppApiKey = (auth: Pick<AuthOptionsWithDefaults, 'apiKey' | 'appKey'>) =>
Boolean(auth.apiKey && auth.appKey);

const isAbsoluteUrl = (url: string) => /^https?:\/\//.test(url);

export const withBaseUrl =
(baseUrl: string) =>
(request: RequestFunction): RequestFunction =>
async <T>(opts: RequestOpts) => {
const normalizedBaseUrl = baseUrl.replace(/\/$/, '');
const url = isAbsoluteUrl(opts.url)
? opts.url
: `${normalizedBaseUrl}${opts.url.startsWith('/') ? '' : '/'}${opts.url}`;

return request<T>({ ...opts, url });
};

export const withApiAuth =
({
auth,
log,
missingAuthMessage = DEFAULT_API_AUTH_MISSING_AUTH_MESSAGE,
}: {
auth: Pick<AuthOptionsWithDefaults, 'apiKey' | 'appKey'>;
log?: Pick<Logger, 'warn'>;
missingAuthMessage?: string;
}) =>
(request: RequestFunction): AuthenticatedRequestFunction => {
const requestAuth: RequestAuthOptions | undefined = hasValidAppApiKey(auth)
? { apiKey: auth.apiKey, appKey: auth.appKey }
: undefined;
let didWarn = false;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems odd. Should we just warn when we setup withApiAuth?


const assertAuthConfigured = () => {
if (!requestAuth) {
if (!didWarn) {
log?.warn(missingAuthMessage);
didWarn = true;
}
throw new MissingRequestAuthError(missingAuthMessage);
}
};

const requestWithAuth = async <T>(opts: RequestOptsWithoutAuth) => {
assertAuthConfigured();

return request<T>({
...opts,
auth: requestAuth,
});
};

requestWithAuth.assertAuthConfigured = assertAuthConfigured;
return requestWithAuth;
};
4 changes: 3 additions & 1 deletion packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,11 @@ export type OptionsWithDefaults = Assign<
export type PluginName = `datadog-${Lowercase<string>}-plugin`;

type Data = { data?: BodyInit; headers?: Record<string, string> };
export type RequestAuthOptions = Pick<AuthOptions, 'apiKey' | 'appKey'>;

export type RequestOpts = {
url: string;
auth?: Pick<AuthOptions, 'apiKey' | 'appKey'>;
auth?: RequestAuthOptions;
method?: string;
getData?: () => Promise<Data> | Data;
type?: 'json' | 'text';
Expand Down
5 changes: 2 additions & 3 deletions packages/plugins/apps/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,13 +211,12 @@ describe('Apps Plugin - getPlugins', () => {
expect(uploader.uploadArchive).toHaveBeenCalledWith(
expect.objectContaining({ archivePath: '/tmp/dd-apps-123/datadog-apps-assets.zip' }),
{
apiKey: '123',
appKey: '123',
appBaseUrl: `https://app.${DEFAULT_SITE}`,
bundlerName: 'vite',
dryRun: true,
identifier: 'repo:app',
name: 'test-app',
site: DEFAULT_SITE,
request: expect.any(Function),
version: 'FAKE_VERSION',
},
expect.anything(),
Expand Down
Loading
Loading