-
Notifications
You must be signed in to change notification settings - Fork 10
[APPS] Add core request auth plumbing #396
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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', | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
|
|
||
| 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; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?