Skip to content
11 changes: 11 additions & 0 deletions packages/bruno-cli/src/runner/interpolate-vars.js
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,17 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc
request.ntlmConfig.domain = _interpolate(request.ntlmConfig.domain) || '';
}

// interpolate vars for edgegrid auth
if (request.edgeGridConfig) {
request.edgeGridConfig.accessToken = _interpolate(request.edgeGridConfig.accessToken) || '';
request.edgeGridConfig.clientToken = _interpolate(request.edgeGridConfig.clientToken) || '';
request.edgeGridConfig.clientSecret = _interpolate(request.edgeGridConfig.clientSecret) || '';
request.edgeGridConfig.nonce = _interpolate(request.edgeGridConfig.nonce) || '';
request.edgeGridConfig.timestamp = _interpolate(request.edgeGridConfig.timestamp) || '';
request.edgeGridConfig.baseURL = _interpolate(request.edgeGridConfig.baseURL) || '';
request.edgeGridConfig.headersToSign = _interpolate(request.edgeGridConfig.headersToSign) || '';
}

// interpolate vars for oauth1config auth
if (request.oauth1config) {
request.oauth1config.consumerKey = _interpolate(request.oauth1config.consumerKey) || '';
Expand Down
4 changes: 3 additions & 1 deletion packages/bruno-common/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@
"watch": "rollup -c -w",
"prepack": "npm run test && npm run build"
},
"dependencies": {},
"dependencies": {
"crypto-js": "4.2.0"
},
Comment thread
sid-bruno marked this conversation as resolved.
Resolved
"devDependencies": {
"@babel/preset-env": "^7.26.9",
"@babel/preset-typescript": "^7.27.0",
Expand Down
43 changes: 43 additions & 0 deletions packages/bruno-common/src/generate-code/har/edgegrid.spec.ts
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 packages/bruno-common/src/generate-code/har/edgegrid.ts
Comment thread
sid-bruno marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import * as CryptoJS from 'crypto-js';
Comment thread
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`;
};
Comment thread
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);
});
Comment thread
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;
Comment thread
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}`;
};
30 changes: 27 additions & 3 deletions packages/bruno-common/src/generate-code/har/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import { cloneDeep, find, get } from 'lodash';
import interpolate, { interpolateObject } from '../../interpolate';
import { encodeUrl, parseQueryParams, patternHasher } from '../../utils';
import { signEdgeGridRequest } from './edgegrid';

// ---------------------------------------------------------------------------
// Types
Expand Down Expand Up @@ -352,7 +353,8 @@ const authToHeaders = (
auth: BrunoAuth | undefined,
variables: Record<string, unknown>,
oauth2Credentials: OAuth2CredentialRecord[] | undefined,
collectionUid: string | undefined
collectionUid: string | undefined,
request?: { method?: string; url?: string; headers?: BrunoKV[]; bodyText?: string }
): BrunoKV[] => {
if (!auth || !auth.mode || auth.mode === 'none' || auth.mode === 'inherit') return [];

Expand Down Expand Up @@ -414,6 +416,22 @@ const authToHeaders = (
return [{ name: 'Authorization', value: headerValue, enabled: true }];
}

case 'akamai-edgegrid': {
if (!request?.url || !request?.method) return [];
// EG1-HMAC-SHA256 signs the request itself, so we build the header from the request context.
const requestHeaders: Record<string, string> = {};
(request.headers || []).forEach((h) => {
if (h?.enabled !== false && h?.name) requestHeaders[h.name] = String(h.value ?? '');
});
const value = signEdgeGridRequest(get(auth, 'akamaiEdgegrid') || {}, {
method: request.method,
url: request.url,
headers: requestHeaders,
bodyText: request.bodyText
});
return value ? [{ name: 'Authorization', value, enabled: true }] : [];
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// OAuth1 cannot pre-compute the signature for a static snippet.
// Digest/NTLM/AWS/WSSE are runtime-signed.
default:
Expand Down Expand Up @@ -609,8 +627,14 @@ export function buildHar(input: BuildHarInput): BuildHarOutput {
throw new Error('invalid request url');
}

// Step 5 — Auth → headers. Append to request headers.
const authHeaders = authToHeaders(working.auth, variables, input.oauth2Credentials, input.collectionUid);
// Step 5 — Auth → headers. Append to request headers. Request-signing auth (EdgeGrid) must
// sign the same `encodedUrl` the snippet transmits, or the signature won't cover the sent bytes.
const authHeaders = authToHeaders(working.auth, variables, input.oauth2Credentials, input.collectionUid, {
method: working.method || 'GET',
url: encodedUrl,
headers: working.headers,
bodyText: buildPostData(working.body)?.text
});
const allHeaders = mergeAndDedupeHeaders(working.headers, authHeaders);

// Step 6 — Finalize headers (filter enabled, lowercase, default content-type).
Expand Down
11 changes: 11 additions & 0 deletions packages/bruno-electron/src/ipc/network/interpolate-vars.js
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,17 @@ const interpolateVars = (request, envVariables = {}, runtimeVariables = {}, proc
request.ntlmConfig.domain = _interpolate(request.ntlmConfig.domain) || '';
}

// interpolate vars for edgegrid auth
if (request.edgeGridConfig) {
request.edgeGridConfig.accessToken = _interpolate(request.edgeGridConfig.accessToken) || '';
request.edgeGridConfig.clientToken = _interpolate(request.edgeGridConfig.clientToken) || '';
request.edgeGridConfig.clientSecret = _interpolate(request.edgeGridConfig.clientSecret) || '';
request.edgeGridConfig.nonce = _interpolate(request.edgeGridConfig.nonce) || '';
request.edgeGridConfig.timestamp = _interpolate(request.edgeGridConfig.timestamp) || '';
request.edgeGridConfig.baseURL = _interpolate(request.edgeGridConfig.baseURL) || '';
request.edgeGridConfig.headersToSign = _interpolate(request.edgeGridConfig.headersToSign) || '';
}

// interpolate vars for oauth1config auth
if (request.oauth1config) {
request.oauth1config.consumerKey = _interpolate(request.oauth1config.consumerKey) || '';
Expand Down
104 changes: 104 additions & 0 deletions tests/auth/akamai-edgegrid/akamai-edgegrid-generate-code.spec.ts
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');
Comment thread
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);
});
});
Loading
Loading