Skip to content

Commit

Permalink
fix: keep encoded value if uri decoding fails. (#2387)
Browse files Browse the repository at this point in the history
  • Loading branch information
chohmann authored Sep 18, 2023
1 parent 59de042 commit aba9bee
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
19 changes: 18 additions & 1 deletion packages/http/src/validator/validators/__tests__/body.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { HttpParamStyles, IMediaTypeContent } from '@stoplight/types';
import { JSONSchema } from '../../..';
import { validate, findContentByMediaTypeOrFirst } from '../body';
import { validate, findContentByMediaTypeOrFirst, decodeUriEntities } from '../body';
import { assertRight, assertLeft, assertSome } from '@stoplight/prism-core/src/__tests__/utils';
import { ValidationContext } from '../types';
import * as faker from '@faker-js/faker/locale/en';
Expand Down Expand Up @@ -279,3 +279,20 @@ describe('findContentByMediaTypeOrFirst()', () => {
});
});
});

describe('decodeUriEntities', () => {
it('should decode both key and value', () => {
const target = { 'profile%2DImage': 'outer%20space' };
const results = decodeUriEntities(target);
expect(results).toEqual({ 'profile-Image': 'outer space' });
});

it('should decode the key but leave the value as encoded if decoding fails', () => {
const target = {
'profile%2DImage':
'�PNG\r\n\u001a\n\u0000\u0000\u0000\rIHDR\u0000\u0000\u0000\u0001\u0000\u0000\u0000\u0001\u0001\u0003\u0000\u0000\u0000%�V�\u0000\u0000\u0000\u0003PLTE\u0000\u0000\u0000�z=�\u0000\u0000\u0000\u0001tRNS\u0000@��f\u0000\u0000\u0000\nIDAT\b�c`\u0000\u0000\u0000\u0002\u0000\u0001�!�3\u0000\u0000\u0000\u0000IEND�B`�',
};
const results = decodeUriEntities(target);
expect(results).toEqual({ 'profile-Image': target['profile%2DImage'] });
});
});
9 changes: 8 additions & 1 deletion packages/http/src/validator/validators/body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,14 @@ export function parseMultipartFormDataParams(

export function decodeUriEntities(target: Dictionary<string>) {
return Object.entries(target).reduce((result, [k, v]) => {
result[decodeURIComponent(k)] = decodeURIComponent(v);
try {
// NOTE: this will decode the value even if it shouldn't (i.e when text/plain mime type).
// the decision to decode or not should be made before calling this function
result[decodeURIComponent(k)] = decodeURIComponent(v);
} catch (e) {
// when the data is binary, for example, uri decoding will fail so leave value as-is
result[decodeURIComponent(k)] = v;
}
return result;
}, {});
}
Expand Down

0 comments on commit aba9bee

Please sign in to comment.