Use regexes to validate metadata

This commit is contained in:
Kelvin Jin 2017-08-17 12:07:14 -07:00
parent 0a1eb630f3
commit 44b97e660b
2 changed files with 14 additions and 23 deletions

View File

@ -22,33 +22,12 @@ function cloneMetadataObject(repr: MetadataObject): MetadataObject {
return result;
}
function isLegal(legalChars: Array<number>, str: string): boolean {
for (let i = 0; i < str.length; i++) {
const legalCharsIndex = str.charCodeAt(i) >> 3;
if (!(1 << (str.charCodeAt(i) & 7) & legalChars[legalCharsIndex])) {
return false;
}
}
return true;
}
const legalKeyChars = [
0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xff, 0x03, 0x00, 0x00, 0x00,
0x80, 0xfe, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
];
const legalNonBinValueChars = [
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
];
function isLegalKey(key: string): boolean {
return key.length > 0 && isLegal(legalKeyChars, key);
return !!key.match(/^[0-9a-z_.-]+$/);
}
function isLegalNonBinaryValue(value: string): boolean {
return isLegal(legalNonBinValueChars, value);
return !!value.match(/^[ -~]+$/);
}
function isBinaryKey(key: string): boolean {

View File

@ -1,4 +1,5 @@
import * as assert from 'assert';
import { range } from 'lodash';
import * as metadata from '../src/metadata';
class Metadata extends metadata.Metadata {
@ -7,6 +8,11 @@ class Metadata extends metadata.Metadata {
}
}
const validKeyChars = '0123456789abcdefghijklmnopqrstuvwxyz_-.';
const validNonBinValueChars = range(0x20, 0x7f)
.map(code => String.fromCharCode(code))
.join('');
describe('Metadata', () => {
let metadata: Metadata;
@ -34,6 +40,9 @@ describe('Metadata', () => {
});
it('Rejects invalid keys', () => {
assert.doesNotThrow(() => {
metadata.set(validKeyChars, 'value');
});
assert.throws(() => {
metadata.set('key$', 'value');
});
@ -43,6 +52,9 @@ describe('Metadata', () => {
});
it('Rejects values with non-ASCII characters', () => {
assert.doesNotThrow(() => {
metadata.set('key', validNonBinValueChars);
});
assert.throws(() => {
metadata.set('key', 'résumé');
});