Skip to content
Merged
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
7 changes: 7 additions & 0 deletions .changeset/respect-har-post-data.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@redocly/cli': patch
---

Fixed an issue where `respect --har-output` recorded an empty `postData` for every request.
Request bodies are written to the HAR.
Captures replayed through `drift` can have their request bodies validated instead of silently passing.
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { buildPostData } from '../../../../../commands/respect/har-logs/helpers/build-post-data.js';

describe('buildPostData', () => {
it('records a JSON body with the content type the request declared', () => {
const headers = { 'content-type': 'application/json' };

expect(buildPostData('{"bio":"x"}', headers)).toEqual({
mimeType: 'application/json',
text: '{"bio":"x"}',
});
});

it('matches the content-type header regardless of its casing', () => {
expect(buildPostData('{}', { 'Content-Type': 'application/json' }).mimeType).toBe(
'application/json'
);
});

it('reads the content type from the flat array header form', () => {
const headers = ['accept', '*/*', 'content-type', 'application/json'];

expect(buildPostData('{}', headers).mimeType).toBe('application/json');
});

it('reads the content type from a Headers-like object', () => {
const headers = new Map([['content-type', 'application/json']]);

expect(buildPostData('{}', headers).mimeType).toBe('application/json');
});

it('falls back to application/octet-stream when no content type was declared', () => {
expect(buildPostData('raw', {}).mimeType).toBe('application/octet-stream');
});

it('returns an empty object for a request with no body, as before', () => {
expect(buildPostData(undefined, {})).toEqual({});
});

it('treats an empty string body as no body', () => {
expect(buildPostData('', {})).toEqual({});
});

it('serializes a URLSearchParams body', () => {
const body = new URLSearchParams({ a: '1', b: '2' });

expect(buildPostData(body, {}).text).toBe('a=1&b=2');
});

it('does not attempt to serialize a stream body', () => {
expect(buildPostData(Buffer.from('binary'), {})).toEqual({});
});

it('omits a non-string body rather than recording "[object Object]"', () => {
expect(buildPostData({ bio: 'x' }, { 'content-type': 'application/json' })).toEqual({});
});

it('omits a FormData body, which cannot be read without consuming it', () => {
expect(buildPostData(new FormData(), { 'content-type': 'multipart/form-data' })).toEqual({});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { buildHeaders } from './build-headers.js';

/**
* The HAR `postData` entry for a request body.
*
* Without this the capture records the request line and headers but not what
* was sent, so anything reading the HAR back — `drift`'s request-body
* validation, for one — silently has nothing to check.
*/
export function buildPostData(
body: unknown,
headers: any = {}
): { mimeType?: string; text?: string } {
const text = serializeBody(body);
if (text === undefined || text === '') return {};

// Via `buildHeaders`, so every shape a request can carry its headers in is
// handled the same way here as it is for the entry's `headers` list.
const contentTypeValue = buildHeaders(headers).find(
({ name }) => String(name).toLowerCase() === 'content-type'
)?.value;
const contentType = Array.isArray(contentTypeValue)
? contentTypeValue.join(',')
: contentTypeValue;
const fallbackMimeType =
Comment thread
DmitryAnansky marked this conversation as resolved.
body instanceof URLSearchParams
? 'application/x-www-form-urlencoded;charset=UTF-8'
: 'application/octet-stream';
return {
mimeType: typeof contentType === 'string' ? contentType : fallbackMimeType,
text,
};
}

/** Only bodies that are already text; a stream or binary body is left out. */
function serializeBody(body: unknown): string | undefined {
if (typeof body === 'string') return body;
if (body instanceof URLSearchParams) return body.toString();

return undefined;
}
8 changes: 6 additions & 2 deletions packages/cli/src/commands/respect/har-logs/with-har.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { URL } from 'url';

import { addHeaders } from './helpers/add-headers.js';
import { buildHeaders } from './helpers/build-headers.js';
import { buildPostData } from './helpers/build-post-data.js';
import { buildRequestCookies } from './helpers/build-request-cookies.js';
import { buildResponseCookies } from './helpers/build-response-cookies.js';
import { getDuration } from './helpers/get-duration.js';
Expand Down Expand Up @@ -43,6 +44,7 @@ export const withHar: WithHar = function <T extends typeof fetch>(
const startTime = process.hrtime();

const url = new URL(typeof input === 'string' ? input : input.url);
const postData = buildPostData(options.body, options.headers || {});

Comment thread
DmitryAnansky marked this conversation as resolved.
const entry = {
_compressed: false,
Expand Down Expand Up @@ -82,8 +84,10 @@ export const withHar: WithHar = function <T extends typeof fetch>(
value,
})),
headersSize: -1,
bodySize: -1,
postData: {},
// -1 means "not available": a body was sent but not recorded (for example FormData).
bodySize:
postData.text !== undefined ? Buffer.byteLength(postData.text) : options.body ? -1 : 0,
...(postData.text !== undefined && { postData }),
Comment thread
DmitryAnansky marked this conversation as resolved.
httpVersion: 'HTTP/1.1',
},
response: {},
Expand Down
Loading