Repository navigation
fix(interpolation): add interpolation for akamai-auth #8631
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
Merged
Merged
Changes from 4 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
22e90ac
fix(interpolation): add interpolation for akamai-auth
3978782
feat(generate-code): sign akamai-edgegrid Authorization header in sni…
9710246
test(akamai-edgegrid): cover generate-code and timeline e2e
6dd8939
chore(generate-code): drop crypto-js.d.ts
6b69318
fix: resolved comments
3d761ac
chore: revert lock.json
a0c53af
chore: revert diff-space
d6dafe1
test: update locators
b1f2420
fix: update deps
47c2ccb
fix: resolved comments & refactor
491beaa
fix: handle sensitive env data in akamai
148970c
fix: resolve comments
8c30f47
chore: style change
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
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
43 changes: 43 additions & 0 deletions
43
packages/bruno-common/src/generate-code/har/edgegrid.spec.ts
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,43 @@ | ||
| import { signEdgeGridRequest } from './edgegrid'; | ||
|
|
||
| /** | ||
| * Akamai's OFFICIAL EdgeGrid vectors (github.com/akamai/AkamaiOPEN-edgegrid-node). Matching them | ||
| * byte-for-byte proves the crypto-js (browser) signer here produces the same signature as the | ||
| * Node runtime signer, so Generate Code snippets validate against the real gateway. | ||
| */ | ||
| const CREDS = { | ||
| clientToken: 'akab-client-token-xxx-xxxxxxxxxxxxxxxx', | ||
| accessToken: 'akab-access-token-xxx-xxxxxxxxxxxxxxxx', | ||
| clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=', | ||
| nonce: 'nonce-xx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', | ||
| timestamp: '20140321T19:34:21+0000' | ||
| }; | ||
| const HOST = 'https://akaa-baseurl-xxxxxxxxxxx-xxxxxxxxxxxxx.luna.akamaiapis.net'; | ||
|
|
||
| const sig = (header: string | null) => (header || '').split('signature=')[1]; | ||
|
|
||
| describe('signEdgeGridRequest (codegen) - Akamai official vectors', () => { | ||
| const cases = [ | ||
| { name: 'simple GET', request: { method: 'GET', url: `${HOST}/` }, expected: 'tL+y4hxyHxgWVD30X3pWnGKHcPzmrIF+LThiAOhMxYU=' }, | ||
| { name: 'GET with query string', request: { method: 'GET', url: `${HOST}/testapi/v1/t1?p1=1&p2=2` }, expected: 'hKDH1UlnQySSHjvIcZpDMbQHihTQ0XyVAKZaApabdeA=' }, | ||
| { name: 'POST within body limit', request: { method: 'POST', url: `${HOST}/testapi/v1/t3`, bodyText: 'datadatadatadatadatadatadatadata' }, expected: 'hXm4iCxtpN22m4cbZb4lVLW5rhX8Ca82vCFqXzSTPe4=' }, | ||
| { name: 'POST with empty body', request: { method: 'POST', url: `${HOST}/testapi/v1/t6`, bodyText: '' }, expected: '1gEDxeQGD5GovIkJJGcBaKnZ+VaPtrc4qBUHixjsPCQ=' } | ||
| ]; | ||
|
|
||
| test.each(cases)('$name', ({ request, expected }) => { | ||
| expect(sig(signEdgeGridRequest(CREDS, request))).toBe(expected); | ||
| }); | ||
|
|
||
| it('returns null when required credentials are missing (caller omits the header)', () => { | ||
| expect(signEdgeGridRequest({ ...CREDS, clientSecret: '' }, { method: 'GET', url: `${HOST}/` })).toBeNull(); | ||
| }); | ||
|
|
||
| it('emits a placeholder signature when credentials are unresolved {{var}} (interpolation off)', () => { | ||
| const header = signEdgeGridRequest( | ||
| { ...CREDS, clientToken: '{{client_token}}', clientSecret: '{{client_secret}}' }, | ||
| { method: 'POST', url: `${HOST}/edgegrid/verify` } | ||
| ); | ||
| expect(header).toContain('client_token={{client_token}}'); | ||
| expect(sig(header)).toBe('<computed-at-request-time>'); | ||
| }); | ||
| }); |
137 changes: 137 additions & 0 deletions
137
packages/bruno-common/src/generate-code/har/edgegrid.ts
|
sid-bruno marked this conversation as resolved.
Resolved
|
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,137 @@ | ||
| import * as CryptoJS from 'crypto-js'; | ||
|
shubh-bruno marked this conversation as resolved.
Resolved
|
||
|
|
||
| /** | ||
| * Browser-safe EG1-HMAC-SHA256 signer for Generate Code snippets. | ||
| * | ||
| * Ported from the runtime signer (packages/bruno-requests/src/auth/edgegrid-helper.js) so the | ||
| * generated `Authorization` header validates against the real Akamai gateway - the difference is | ||
| * this variant uses crypto-js (works in the browser) instead of Node's `crypto`, since codegen | ||
| * runs in the renderer. Kept byte-for-byte compatible with Akamai's reference implementation. | ||
| */ | ||
|
|
||
| const MAX_BODY_SIZE_DEFAULT = 131072; // 128 KB | ||
|
|
||
| const isStrPresent = (str?: string | null): boolean => | ||
| !!str && String(str).trim() !== '' && String(str).trim() !== 'undefined'; | ||
|
|
||
| // base64(HMAC-SHA256(data, key)) - key is a UTF-8 string, matching the runtime signer. | ||
| const base64HmacSha256 = (data: string, key: string): string => | ||
| CryptoJS.HmacSHA256(data, key).toString(CryptoJS.enc.Base64); | ||
|
|
||
| // base64(SHA256(data)) | ||
| const base64Sha256 = (data: string): string => CryptoJS.SHA256(data).toString(CryptoJS.enc.Base64); | ||
|
|
||
| // UTC timestamp in EdgeGrid format: YYYYMMDDTHH:MM:SS+0000 | ||
| const makeEdgeGridTimestamp = (): string => { | ||
| const [datePart, timePart] = new Date().toISOString().split('T'); | ||
| return `${datePart.replace(/-/g, '')}T${timePart.replace(/\.\d+Z$/, '')}+0000`; | ||
| }; | ||
|
shubh-bruno marked this conversation as resolved.
Resolved
|
||
|
|
||
| // UUID v4 for the nonce. A snippet nonce need not be cryptographically strong. | ||
| const makeNonce = (): string => | ||
| 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { | ||
| const r = (Math.random() * 16) | 0; | ||
| return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16); | ||
| }); | ||
|
shubh-bruno marked this conversation as resolved.
Resolved
|
||
|
|
||
| // `name:value` per signed header (lowercased name, trimmed + whitespace-collapsed value), | ||
| // tab-joined. Only headers present on the request are emitted, preserving config order. | ||
| const canonicalizeHeaders = (headersToSign?: string, requestHeaders: Record<string, string> = {}): string => { | ||
| if (!isStrPresent(headersToSign)) return ''; | ||
| const lookup: Record<string, string> = {}; | ||
| Object.keys(requestHeaders || {}).forEach((name) => { | ||
| lookup[name.toLowerCase()] = requestHeaders[name]; | ||
| }); | ||
| return (headersToSign as string) | ||
| .split(',') | ||
| .map((name) => name.trim().toLowerCase()) | ||
| .filter((name) => name.length > 0) | ||
| .filter((name) => Object.prototype.hasOwnProperty.call(lookup, name)) | ||
| .map((name) => `${name}:${String(lookup[name]).trim().replace(/\s+/g, ' ')}`) | ||
| .join('\t'); | ||
| }; | ||
|
|
||
| // Akamai hashes the body for POST only, over the bytes as sent, truncated to maxBodySize. | ||
| const makeContentHash = (method: string, bodyText: string | undefined, maxBodySize: number): string => { | ||
| if (!method || method.toUpperCase() !== 'POST' || !bodyText) return ''; | ||
| let body = bodyText; | ||
| if (body.length === 0) return ''; | ||
| if (body.length > maxBodySize) body = body.substring(0, maxBodySize); | ||
| return base64Sha256(body); | ||
| }; | ||
|
|
||
| export interface EdgeGridSignConfig { | ||
| accessToken?: string | null; | ||
| clientToken?: string | null; | ||
| clientSecret?: string | null; | ||
| baseURL?: string | null; | ||
| nonce?: string | null; | ||
| timestamp?: string | null; | ||
| headersToSign?: string | null; | ||
| maxBodySize?: number | string | null; | ||
| } | ||
|
|
||
| export interface EdgeGridSignRequest { | ||
| method: string; | ||
| url: string; | ||
| headers?: Record<string, string>; | ||
| bodyText?: string; | ||
| } | ||
|
|
||
| /** | ||
| * Compute the EG1-HMAC-SHA256 `Authorization` header value, or `null` when the | ||
| * required credentials / a valid URL are missing (so the caller can omit the header). | ||
| */ | ||
| export const signEdgeGridRequest = ( | ||
| config: EdgeGridSignConfig, | ||
| request: EdgeGridSignRequest | ||
| ): string | null => { | ||
| const { accessToken, clientToken, clientSecret, baseURL, headersToSign } = config; | ||
| if (!isStrPresent(accessToken) || !isStrPresent(clientToken) || !isStrPresent(clientSecret)) return null; | ||
| if (!request?.url || !request?.method) return null; | ||
|
|
||
| const maxBodySize = config.maxBodySize ? parseInt(String(config.maxBodySize), 10) : MAX_BODY_SIZE_DEFAULT; | ||
|
sid-bruno marked this conversation as resolved.
Resolved
|
||
| const nonce = isStrPresent(config.nonce) ? (config.nonce as string) : makeNonce(); | ||
| const timestamp = isStrPresent(config.timestamp) ? (config.timestamp as string) : makeEdgeGridTimestamp(); | ||
|
|
||
| let parsedUrl: URL; | ||
| try { | ||
| let urlToSign = request.url; | ||
| if (isStrPresent(baseURL)) { | ||
| const requestUrl = new URL(request.url); | ||
| const trimmed = (baseURL as string).trim(); | ||
| // A scheme-less baseURL ("localhost:6000") mis-parses; borrow the request scheme. | ||
| const normalized = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `${requestUrl.protocol}//${trimmed}`; | ||
| const baseParsed = new URL(normalized); | ||
| urlToSign = `${baseParsed.protocol}//${baseParsed.host}${requestUrl.pathname}${requestUrl.search}`; | ||
| } | ||
| parsedUrl = new URL(urlToSign); | ||
| } catch { | ||
| return null; | ||
| } | ||
|
|
||
| // The auth header (sans signature) is also the last field of the data-to-sign, per spec. | ||
| const authHeader = `EG1-HMAC-SHA256 client_token=${clientToken};access_token=${accessToken};timestamp=${timestamp};nonce=${nonce};`; | ||
|
|
||
| // With variables unresolved (Generate Code, interpolation off) a real signature can't be | ||
| // produced - it would sign literal `{{var}}` tokens. Emit a placeholder the user replaces | ||
| // once the request is signed at send time. | ||
| if (/\{\{.+?\}\}/.test(authHeader) || /\{\{.+?\}\}/.test(clientSecret as string)) { | ||
| return `${authHeader}signature=<computed-at-request-time>`; | ||
| } | ||
|
|
||
| const dataToSign = [ | ||
| request.method.toUpperCase(), | ||
| parsedUrl.protocol.replace(':', ''), | ||
| parsedUrl.host, | ||
| parsedUrl.pathname + parsedUrl.search, | ||
| canonicalizeHeaders(headersToSign as string, request.headers), | ||
| makeContentHash(request.method, request.bodyText, maxBodySize), | ||
| authHeader | ||
| ].join('\t'); | ||
|
|
||
| const signingKey = base64HmacSha256(timestamp, clientSecret as string); | ||
| const signature = base64HmacSha256(dataToSign, signingKey); | ||
|
|
||
| return `${authHeader}signature=${signature}`; | ||
| }; | ||
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
104 changes: 104 additions & 0 deletions
104
tests/auth/akamai-edgegrid/akamai-edgegrid-generate-code.spec.ts
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,104 @@ | ||
| import { expect, Page, test } from '../../../playwright'; | ||
| import { | ||
| closeAllCollections, | ||
| closeGenerateCodeDialog, | ||
| createCollection, | ||
| createRequest, | ||
| getGeneratedSnippet, | ||
| openRequest, | ||
| saveRequest, | ||
| selectAuthMode, | ||
| selectRequestPaneTab, | ||
| typeIntoField | ||
| } from '../../utils/page'; | ||
|
|
||
| /** | ||
| * Generate Code for Akamai EdgeGrid. The snippet must carry a real EG1-HMAC-SHA256 | ||
| * `Authorization` header - computed at codegen time (bruno-common signs the HAR) - for both | ||
| * request-level and inherited auth. When a credential is an unresolved `{{var}}`, no real | ||
| * signature can be produced, so a placeholder stands in. | ||
| */ | ||
|
|
||
| const { TEST_EDGEGRID } = require('../../../packages/bruno-tests/src/auth/edgegrid'); | ||
| const REQUEST_URL = 'http://localhost:8081/api/auth/edgegrid/resource'; | ||
|
|
||
| // The credential tokens are embedded verbatim in the header; asserting the prefix proves both | ||
| // tokens made it in, in the right order. | ||
| const authHeaderPrefix = `EG1-HMAC-SHA256 client_token=${TEST_EDGEGRID.clientToken};access_token=${TEST_EDGEGRID.accessToken};`; | ||
| // A real signature is base64; the placeholder is the literal sentinel below. | ||
| const SIGNATURE_PLACEHOLDER = 'signature=<computed-at-request-time>'; | ||
| const realSignature = /signature=[A-Za-z0-9+/]{20,}={0,2}/; | ||
|
|
||
| const fillEdgeGridCredentials = async (page: Page) => { | ||
| await typeIntoField(page, 'Access Token', TEST_EDGEGRID.accessToken); | ||
| await typeIntoField(page, 'Client Token', TEST_EDGEGRID.clientToken); | ||
| await typeIntoField(page, 'Client Secret', TEST_EDGEGRID.clientSecret); | ||
| }; | ||
|
|
||
| test.describe('Akamai EdgeGrid - Generate Code', () => { | ||
| test.afterEach(async ({ page }) => { | ||
| await closeAllCollections(page); | ||
| }); | ||
|
|
||
| test('request-level auth produces a signed EG1-HMAC-SHA256 Authorization header', async ({ page, createTmpDir }) => { | ||
| await createCollection(page, 'edgegrid-gencode-request', await createTmpDir()); | ||
| await createRequest(page, 'signed-request', 'edgegrid-gencode-request', { url: REQUEST_URL }); | ||
| await openRequest(page, 'edgegrid-gencode-request', 'signed-request'); | ||
| await selectRequestPaneTab(page, 'Auth'); | ||
| await selectAuthMode(page, 'Akamai EdgeGrid'); | ||
| await fillEdgeGridCredentials(page); | ||
| await saveRequest(page); | ||
|
|
||
| const snippet = await getGeneratedSnippet(page); | ||
|
|
||
| expect(snippet).toContain(authHeaderPrefix); | ||
| expect(snippet).toMatch(realSignature); | ||
| expect(snippet).not.toContain(SIGNATURE_PLACEHOLDER); | ||
|
|
||
| await closeGenerateCodeDialog(page); | ||
| }); | ||
|
|
||
| test('inherited collection auth is resolved and signed in the snippet', async ({ page, createTmpDir }) => { | ||
| await createCollection(page, 'edgegrid-gencode-inherit', await createTmpDir()); | ||
| // Collection settings open on creation - configure collection-level EdgeGrid auth. | ||
| await page.locator('.tab.auth').click(); | ||
| await selectAuthMode(page, 'Akamai EdgeGrid'); | ||
| await fillEdgeGridCredentials(page); | ||
| await page.getByRole('button', { name: 'Save' }).click(); | ||
|
|
||
| await createRequest(page, 'inheriting-request', 'edgegrid-gencode-inherit', { url: REQUEST_URL }); | ||
| await openRequest(page, 'edgegrid-gencode-inherit', 'inheriting-request'); | ||
| await selectRequestPaneTab(page, 'Auth'); | ||
| // A new request already defaults to Inherit; Generate Code reads the draft and resolves | ||
| // inheritance from the collection, so no save is needed here. | ||
| await expect(page.locator('.inherit-mode-text')).toHaveText('Akamai EdgeGrid'); | ||
|
sid-bruno marked this conversation as resolved.
Resolved
|
||
|
|
||
| const snippet = await getGeneratedSnippet(page); | ||
|
|
||
| expect(snippet).toContain(authHeaderPrefix); | ||
| expect(snippet).toMatch(realSignature); | ||
| expect(snippet).not.toContain(SIGNATURE_PLACEHOLDER); | ||
|
|
||
| await closeGenerateCodeDialog(page); | ||
| }); | ||
|
|
||
| test('unresolved {{variable}} credentials produce a placeholder signature', async ({ page, createTmpDir }) => { | ||
| await createCollection(page, 'edgegrid-gencode-vars', await createTmpDir()); | ||
| await createRequest(page, 'templated-request', 'edgegrid-gencode-vars', { url: REQUEST_URL }); | ||
| await openRequest(page, 'edgegrid-gencode-vars', 'templated-request'); | ||
| await selectRequestPaneTab(page, 'Auth'); | ||
| await selectAuthMode(page, 'Akamai EdgeGrid'); | ||
| await typeIntoField(page, 'Access Token', TEST_EDGEGRID.accessToken); | ||
| await typeIntoField(page, 'Client Token', '{{clientToken}}'); | ||
| await typeIntoField(page, 'Client Secret', '{{clientSecret}}'); | ||
| await saveRequest(page); | ||
|
|
||
| const snippet = await getGeneratedSnippet(page); | ||
|
|
||
| // Unresolved token stays verbatim in the header; the signature can't be computed from it. | ||
| expect(snippet).toContain('client_token={{clientToken}}'); | ||
| expect(snippet).toContain(SIGNATURE_PLACEHOLDER); | ||
|
|
||
| await closeGenerateCodeDialog(page); | ||
| }); | ||
| }); | ||
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.
Uh oh!
There was an error while loading. Please reload this page.