Skip to content

Commit 4d87db1

Browse files
committed
fix(gax): base64-encode binary data in response.payload
Buffers and other binary data (Uint8Array, ArrayBuffer) were serialized one JSON entry per byte, e.g. {"type":"Buffer","data":[...]} or {"0":123,...}, bloating logs. Binary payloads are now base64 encoded, as are binary values nested in a response such as bytes fields. Base64 is how the protobuf JSON mapping represents bytes and matches what REST responses already emit. Uses Buffer when available and protobufjs's pure JavaScript encoder otherwise (e.g. in browsers).
1 parent a81eda5 commit 4d87db1

2 files changed

Lines changed: 119 additions & 7 deletions

File tree

‎core/packages/gax/src/observability/errorUtil.ts‎

Lines changed: 62 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616

1717
import {Attributes, Span} from '@opentelemetry/api';
18+
import * as protobuf from 'protobufjs';
1819
import {GoogleError} from '../googleError';
1920
import {Status} from '../status';
2021
/**
@@ -798,9 +799,46 @@ export function isServerSideError(
798799
return resolveServerErrorCode(e, rpcType) !== undefined;
799800
}
800801

802+
/**
803+
* Returns the bytes of binary data: an ArrayBuffer, or a view of one such as a Buffer
804+
* or Uint8Array.
805+
*
806+
* @param {unknown} value - The value to check.
807+
* @returns {Uint8Array | undefined} The bytes of `value`, or undefined if it is not binary data.
808+
*/
809+
function toBytes(value: unknown): Uint8Array | undefined {
810+
if (ArrayBuffer.isView(value)) {
811+
return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
812+
}
813+
if (value instanceof ArrayBuffer) {
814+
return new Uint8Array(value);
815+
}
816+
return undefined;
817+
}
818+
819+
/**
820+
* Encodes bytes as base64, using Buffer when it is available and a pure JavaScript
821+
* encoder otherwise (e.g. in browsers).
822+
*
823+
* @param {Uint8Array} bytes - The bytes to encode.
824+
* @returns {string} The base64 encoding of `bytes`.
825+
*/
826+
function encodeBase64(bytes: Uint8Array): string {
827+
if (typeof Buffer !== 'undefined') {
828+
return Buffer.from(
829+
bytes.buffer,
830+
bytes.byteOffset,
831+
bytes.byteLength,
832+
).toString('base64');
833+
}
834+
return protobuf.util.base64.encode(bytes, 0, bytes.length);
835+
}
836+
801837
/**
802838
* Safely converts a value to a JSON string without throwing exceptions on
803-
* circular references, BigInt values, or non-serializable properties.
839+
* circular references, BigInt values, or non-serializable properties. Binary data
840+
* (e.g. a Buffer or Uint8Array) is serialized as a base64 string rather than one
841+
* JSON entry per byte.
804842
*
805843
* @param {unknown} value - The value to serialize.
806844
* @returns {string | undefined} The serialized JSON string, or undefined if `value` is undefined or unserializable.
@@ -813,13 +851,24 @@ export function safeJsonStringify(value: unknown): string | undefined {
813851
const ancestors: unknown[] = [];
814852
return JSON.stringify(
815853
value,
816-
function (this: unknown, _key: string, val: unknown) {
854+
function (this: unknown, key: string, val: unknown) {
817855
if (typeof val === 'bigint') {
818856
return val.toString();
819857
}
820858
if (typeof val !== 'object' || val === null) {
821859
return val;
822860
}
861+
// Encode binary data as base64. Buffer#toJSON runs before this replacer and
862+
// turns a Buffer into {type: 'Buffer', data: [...]}, so in that case the
863+
// original Buffer is read back from the holder.
864+
const bytes = toBytes(
865+
(val as {type?: unknown}).type === 'Buffer'
866+
? (this as Record<string, unknown>)[key]
867+
: val,
868+
);
869+
if (bytes) {
870+
return encodeBase64(bytes);
871+
}
823872
// Track object ancestry to replace circular references.
824873
if (ancestors.includes(this)) {
825874
while (
@@ -847,10 +896,11 @@ export function safeJsonStringify(value: unknown): string | undefined {
847896

848897
/**
849898
* Resolves the `response.payload` attribute: the full response payload of a call,
850-
* serialized as JSON (string payloads are returned as-is) without truncation or
851-
* redaction. Prefers `rawResponse`, the unprocessed response gax provides for
852-
* paginated and long-running calls (the full page response or the raw Operation),
853-
* over the processed `response`.
899+
* serialized as JSON without truncation or redaction. String payloads are returned
900+
* as-is and binary payloads (e.g. a Buffer or Uint8Array) as base64, as are binary
901+
* values nested in the response (e.g. `bytes` fields). Prefers `rawResponse`, the
902+
* unprocessed response gax provides for paginated and long-running calls (the full
903+
* page response or the raw Operation), over the processed `response`.
854904
*
855905
* @param {unknown} response - The response passed to the callback or resolved by the promise.
856906
* @param {unknown} [rawResponse] - The raw (unprocessed) response, when gax provides one.
@@ -868,7 +918,12 @@ export function resolveResponsePayload(
868918
// as the raw response, so it can contain sensitive data (e.g. secret values or access
869919
// tokens). Only emit it when logging is explicitly enabled (see `checkLoggingEnabled`),
870920
// and consider redacting known sensitive fields.
871-
return typeof payload === 'string' ? payload : safeJsonStringify(payload);
921+
if (typeof payload === 'string') {
922+
return payload;
923+
}
924+
// Binary payloads are base64 encoded and, like strings, not wrapped in JSON quotes.
925+
const bytes = toBytes(payload);
926+
return bytes ? encodeBase64(bytes) : safeJsonStringify(payload);
872927
}
873928

874929
/**

‎core/packages/gax/test/unit/errorUtil.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1122,6 +1122,23 @@ describe('errorUtil', () => {
11221122
};
11231123
assert.strictEqual(safeJsonStringify(badObj), undefined);
11241124
});
1125+
1126+
it('serializes binary data as base64 instead of one entry per byte', () => {
1127+
// Buffers reach the replacer already converted by Buffer#toJSON, unlike other
1128+
// binary data such as Uint8Arrays, so both are covered.
1129+
assert.strictEqual(
1130+
safeJsonStringify({
1131+
buffer: Buffer.from('hello'),
1132+
list: [new Uint8Array([1, 2, 3])],
1133+
}),
1134+
'{"buffer":"aGVsbG8=","list":["AQID"]}',
1135+
);
1136+
// Objects that only look like a serialized Buffer are left as-is.
1137+
assert.strictEqual(
1138+
safeJsonStringify({type: 'Buffer', data: [1, 2]}),
1139+
'{"type":"Buffer","data":[1,2]}',
1140+
);
1141+
});
11251142
});
11261143

11271144
describe('resolveResponsePayload', () => {
@@ -1178,6 +1195,46 @@ describe('errorUtil', () => {
11781195
'{"size":"10","self":"[Circular]"}',
11791196
);
11801197
});
1198+
1199+
it('encodes binary payloads as base64', () => {
1200+
assert.strictEqual(
1201+
resolveResponsePayload(Buffer.from('hello')),
1202+
'aGVsbG8=',
1203+
);
1204+
assert.strictEqual(
1205+
resolveResponsePayload(new Uint8Array([1, 2, 3]).buffer),
1206+
'AQID',
1207+
);
1208+
// Only the viewed bytes are encoded, not the rest of the underlying ArrayBuffer.
1209+
assert.strictEqual(
1210+
resolveResponsePayload(new Uint8Array([0, 1, 2, 3, 4]).subarray(1, 4)),
1211+
'AQID',
1212+
);
1213+
// Typed arrays from another realm are recognized too.
1214+
assert.strictEqual(
1215+
resolveResponsePayload(vm.runInNewContext('new Uint8Array([1, 2, 3])')),
1216+
'AQID',
1217+
);
1218+
});
1219+
1220+
it('encodes binary payloads as base64 when Buffer is not defined', () => {
1221+
const originalBuffer = (globalThis as Record<string, unknown>).Buffer;
1222+
try {
1223+
delete (globalThis as Record<string, unknown>).Buffer;
1224+
assert.strictEqual(
1225+
resolveResponsePayload(
1226+
new Uint8Array([0, 1, 2, 3, 4]).subarray(1, 4),
1227+
),
1228+
'AQID',
1229+
);
1230+
assert.strictEqual(
1231+
resolveResponsePayload(new Uint8Array([255])),
1232+
'/w==',
1233+
);
1234+
} finally {
1235+
(globalThis as Record<string, unknown>).Buffer = originalBuffer;
1236+
}
1237+
});
11811238
});
11821239

11831240
describe('isPreConnectionFailure', () => {

0 commit comments

Comments
 (0)