Skip to content
Open
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
2 changes: 1 addition & 1 deletion command-snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"command": "api:request:rest",
"flagAliases": [],
"flagChars": ["H", "S", "X", "b", "f", "i", "o"],
"flags": ["body", "file", "flags-dir", "header", "include", "method", "stream-to-file", "target-org"],
"flags": ["body", "file", "flags-dir", "header", "include", "json", "method", "stream-to-file", "target-org"],
"plugin": "@salesforce/plugin-api"
}
]
10 changes: 5 additions & 5 deletions src/commands/api/request/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,15 @@ import * as os from 'node:os';
import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
import { Messages, Org, SFDX_HTTP_HEADERS } from '@salesforce/core';
import { ProxyAgent } from 'proxy-agent';
import { includeFlag, sendAndPrintRequest, streamToFileFlag } from '../../../shared/shared.js';
import { type ApiResponseResult, includeFlag, sendAndPrintRequest, streamToFileFlag } from '../../../shared/shared.js';

Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-api', 'graphql');

export default class Graphql extends SfCommand<void> {
export default class Graphql extends SfCommand<ApiResponseResult> {
public static readonly summary = messages.getMessage('summary');
public static readonly description = messages.getMessage('description');
public static readonly examples = messages.getMessages('examples');
public static readonly state = 'beta';

public static readonly flags = {
'target-org': Flags.requiredOrg(),
Expand All @@ -43,7 +42,7 @@ export default class Graphql extends SfCommand<void> {
}),
};

public async run(): Promise<void> {
public async run(): Promise<ApiResponseResult> {
const { flags } = await this.parse(Graphql);

const org = flags['target-org'];
Expand All @@ -69,6 +68,7 @@ export default class Graphql extends SfCommand<void> {
followRedirect: false,
};

await sendAndPrintRequest({ streamFile, url, options, include: flags.include, this: this });
const result = await sendAndPrintRequest({ streamFile, url, options, include: flags.include, this: this });
return result ?? { statusCode: 0, headers: {}, body: '' };
}
}
11 changes: 5 additions & 6 deletions src/commands/api/request/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { Messages, Org, SFDX_HTTP_HEADERS, SfError } from '@salesforce/core';
import { Args } from '@oclif/core';
import FormData from 'form-data';
import { includeFlag, sendAndPrintRequest, streamToFileFlag } from '../../../shared/shared.js';
import { type ApiResponseResult, includeFlag, sendAndPrintRequest, streamToFileFlag } from '../../../shared/shared.js';

Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-api', 'rest');
Expand Down Expand Up @@ -56,12 +56,10 @@ export type PostmanSchema = {
body: RawPostmanSchema | FormDataPostmanSchema;
};

export class Rest extends SfCommand<void> {
export class Rest extends SfCommand<ApiResponseResult> {
public static readonly summary = messages.getMessage('summary');
public static readonly description = messages.getMessage('description');
public static readonly examples = messages.getMessages('examples');
public static state = 'beta';
public static enableJsonFlag = false;
public static readonly flags = {
'target-org': Flags.requiredOrg(),
include: includeFlag,
Expand Down Expand Up @@ -99,7 +97,7 @@ export class Rest extends SfCommand<void> {
}),
};

public async run(): Promise<void> {
public async run(): Promise<ApiResponseResult> {
const { flags, args } = await this.parse(Rest);

const org = flags['target-org'];
Expand Down Expand Up @@ -168,7 +166,8 @@ export class Rest extends SfCommand<void> {
followRedirect: false,
};

await sendAndPrintRequest({ streamFile, url, options, include: flags.include, this: this });
const result = await sendAndPrintRequest({ streamFile, url, options, include: flags.include, this: this });
return result ?? { statusCode: 0, headers: {}, body: '' };
}
}

Expand Down
91 changes: 66 additions & 25 deletions src/shared/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,33 @@ import got from 'got';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-api', 'shared');

export function redactError(error: unknown): unknown {
if (error instanceof Error && 'options' in error) {
const opts = error as Error & { options?: { headers?: Record<string, unknown> } };
if (opts.options?.headers) {
for (const key of Object.keys(opts.options.headers)) {
if (key.toLowerCase() === 'authorization') {
opts.options.headers[key] = '[REDACTED]';
}
}
}
}
return error;
}

export type ApiResponseResult = {
statusCode: number;
headers: Record<string, string | string[]>;
body: AnyJson | string;
};

export async function sendAndPrintRequest(options: {
streamFile?: string;
url: URL;
options: Record<string, unknown>;
include: boolean;
this: SfCommand<unknown>;
}): Promise<void> {
}): Promise<ApiResponseResult | undefined> {
if (options.streamFile) {
const responseStream = options.options.method
? got.stream(options.url, options.options)
Expand All @@ -41,36 +61,57 @@ export async function sendAndPrintRequest(options: {
// we just ensured it existed with the 'if'
fileStream.on('finish', () => options.this.log(`File saved to ${options.streamFile!}`));
fileStream.on('error', (error) => {
throw SfError.wrap(error);
throw SfError.wrap(redactError(error));
});
responseStream.on('error', (error) => {
throw SfError.wrap(error);
throw SfError.wrap(redactError(error));
});
} else {
const res = options.options.method
? // default to 'POST' if not specified
await got(options.url, options.options)
: await got.post(options.url, options.options);
// Print HTTP response status and headers.
if (options.include) {
options.this.log(`HTTP/${res.httpVersion} ${res.statusCode}`);
Object.entries(res.headers).map(([header, value]) => {
options.this.log(
`${ansis.blue.bold(header)}: ${Array.isArray(value) ? value.join(',') : value ?? '<undefined>'}`
);
});
}

return undefined;
} else {
try {
// Try to pretty-print JSON response.
options.this.styledJSON(JSON.parse(res.body) as AnyJson);
} catch (err) {
// If response body isn't JSON, just print it to stdout.
options.this.log(res.body);
}
const res = options.options.method
? // default to 'POST' if not specified
await got(options.url, options.options)
: await got.post(options.url, options.options);

// Print HTTP response status and headers.
if (options.include) {
options.this.log(`HTTP/${res.httpVersion} ${res.statusCode}`);
Object.entries(res.headers).map(([header, value]) => {
options.this.log(
`${ansis.blue.bold(header)}: ${Array.isArray(value) ? value.join(',') : value ?? '<undefined>'}`
);
});
}

let parsedBody: AnyJson | string;
try {
parsedBody = JSON.parse(res.body) as AnyJson;
options.this.styledJSON(parsedBody);
} catch (err) {
parsedBody = res.body;
options.this.log(res.body);
}

if (res.statusCode >= 400) {
process.exitCode = 1;
}

const responseHeaders: Record<string, string | string[]> = {};
for (const [header, value] of Object.entries(res.headers)) {
if (value !== undefined) {
responseHeaders[header] = value;
}
}

if (res.statusCode >= 400) {
process.exitCode = 1;
return {
statusCode: res.statusCode,
headers: responseHeaders,
body: parsedBody,
};
} catch (error) {
throw SfError.wrap(redactError(error));
}
}
}
Expand Down
89 changes: 89 additions & 0 deletions test/commands/api/request/rest/rest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import nock = require('nock');
import { stubUx } from '@salesforce/sf-plugins-core';
import * as FormData from 'form-data';
import { getBodyContents, getHeaders, PostmanSchema, Rest } from '../../../../../src/commands/api/request/rest.js';
import { redactError } from '../../../../../src/shared/shared.js';

describe('rest', () => {
const $$ = new TestContext();
Expand Down Expand Up @@ -217,4 +218,92 @@ describe('rest', () => {

expect(uxStub.styledJSON.args[0][0]).to.deep.equal(orgLimitsResponse);
});

describe('token redaction on network errors', () => {
it('should not expose access token in error when request fails', async () => {
nock(testOrg.instanceUrl).get('/services/data/v56.0/limits').replyWithError('ECONNREFUSED');

try {
await Rest.run(['/services/data/v56.0/limits', '--target-org', 'test@hub.com']);
assert.fail('should have thrown');
} catch (e) {
const fullError = JSON.stringify(e, Object.getOwnPropertyNames(e));
expect(fullError).to.not.include(testOrg.accessToken);
}
});

it('should not expose access token in error cause when request fails', async () => {
nock(testOrg.instanceUrl).get('/services/data/v56.0/limits').replyWithError('connect ECONNREFUSED');

try {
await Rest.run(['/services/data/v56.0/limits', '--target-org', 'test@hub.com']);
assert.fail('should have thrown');
} catch (e) {
const err = e as Error;
const causeStr = JSON.stringify(err.cause, Object.getOwnPropertyNames(err.cause as object));
expect(causeStr).to.not.include(testOrg.accessToken);
}
});
});

describe('redactError', () => {
it('should redact Authorization header from error options', () => {
const fakeToken = '00Dxx0000001gPL!FAKE_TOKEN';
const error = new Error('request failed') as Error & { options: { headers: Record<string, string> } };
error.options = {
headers: {
Authorization: `Bearer ${fakeToken}`,
'Content-Type': 'application/json',
},
};

redactError(error);

expect(error.options.headers.Authorization).to.equal('[REDACTED]');
expect(error.options.headers['Content-Type']).to.equal('application/json');
});

it('should handle case-insensitive Authorization header', () => {
const error = new Error('request failed') as Error & { options: { headers: Record<string, string> } };
error.options = {
headers: {
authorization: 'Bearer secret123',
},
};

redactError(error);

expect(error.options.headers.authorization).to.equal('[REDACTED]');
});

it('should not redact non-sensitive headers', () => {
const error = new Error('request failed') as Error & { options: { headers: Record<string, string> } };
error.options = {
headers: {
Authorization: 'Bearer secret',
'Content-Type': 'application/json',
Accept: 'application/xml',
},
};

redactError(error);

expect(error.options.headers.Authorization).to.equal('[REDACTED]');
expect(error.options.headers['Content-Type']).to.equal('application/json');
expect(error.options.headers.Accept).to.equal('application/xml');
});

it('should be a no-op for errors without options', () => {
const error = new Error('plain error');
const result = redactError(error);
expect(result).to.equal(error);
});

it('should be a no-op for non-Error values', () => {
const str = 'string error';
expect(redactError(str)).to.equal(str);
expect(redactError(null)).to.equal(null);
expect(redactError(undefined)).to.equal(undefined);
});
});
});
Loading