Skip to content

Commit

Permalink
fix(v4-policy): encode special characters
Browse files Browse the repository at this point in the history
  • Loading branch information
jkwlui committed Apr 28, 2020
1 parent 38d5a9f commit c5ad12a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
8 changes: 4 additions & 4 deletions conformance-test/v4SignedUrl.ts
Expand Up @@ -220,16 +220,16 @@ describe('v4 conformance test', () => {

assert.strictEqual(policy.url, testCase.policyOutput.url);
const outputFields = testCase.policyOutput.fields;
const decodedPolicy = Buffer.from(
const decodedPolicy = JSON.parse(Buffer.from(
policy.fields.policy,
'base64'
).toString();
).toString());
assert.deepStrictEqual(
decodedPolicy,
testCase.policyOutput.expectedDecodedPolicy
JSON.parse(testCase.policyOutput.expectedDecodedPolicy),
);

assert.deepStrictEqual(outputFields, testCase.policyOutput.fields);
assert.deepStrictEqual(policy.fields, outputFields);

fakeTimer.restore();
});
Expand Down
4 changes: 2 additions & 2 deletions src/file.ts
Expand Up @@ -63,7 +63,7 @@ import {
} from '@google-cloud/common/build/src/util';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const duplexify: DuplexifyConstructor = require('duplexify');
import {normalize, objectKeyToLowercase} from './util';
import {normalize, objectKeyToLowercase, unicodeJSONStringify} from './util';
import {GaxiosError, Headers, request as gaxiosRequest} from 'gaxios';

export type GetExpirationDateResponse = [Date];
Expand Down Expand Up @@ -2611,7 +2611,7 @@ class File extends ServiceObject<File> {
expiration,
};

const policyString = JSON.stringify(policy);
const policyString = unicodeJSONStringify(policy);
const policyBase64 = Buffer.from(policyString).toString('base64');

try {
Expand Down
13 changes: 13 additions & 0 deletions src/util.ts
Expand Up @@ -90,3 +90,16 @@ export function objectKeyToLowercase<T>(object: {[key: string]: T}) {
}
return newObj;
}

/**
* JSON encode str, with unicode \u+ representation.
* @param {object} obj The object to encode.
* @return {string} Serialized string.
*/
export function unicodeJSONStringify(obj: object) {
return JSON.stringify(obj).replace(
/[\u0080-\uFFFF]/g,
(char: string) =>
'\\u' + ('0000' + char.charCodeAt(0).toString(16)).slice(-4),
);
}

0 comments on commit c5ad12a

Please sign in to comment.