Skip to content

Commit

Permalink
fix: correct document ID validation (#149)
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Mar 13, 2023
1 parent 90e4952 commit b5799c9
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const validateObject = (op: string, val: Any) => {
}

export const validateDocumentId = (op: string, id: string) => {
if (typeof id !== 'string' || !/^[a-z0-9_.-]+$/i.test(id)) {
if (typeof id !== 'string' || !/^[a-z0-9_][a-z0-9_.-]{0,127}$/i.test(id) || id.includes('..')) {
throw new Error(`${op}(): "${id}" is not a valid document ID`)
}
}
Expand Down
39 changes: 34 additions & 5 deletions test/validators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,47 @@ describe('validators', async () => {
test('validateDocumentId', () => {
expect(
() => validators.validateDocumentId('op', 'barfoo'),
'does not throw on valid ID (simple)'
).not.toThrow()

'does not throw on valid ID'
).not.toThrow(/document ID in format/)
expect(
() => validators.validateDocumentId('op', 'bar.foo.baz'),
'does not throw on valid ID (pathed)'
).not.toThrow()

expect(
() => validators.validateDocumentId('op', 'all.allowed-chars_used'),
'does not throw on valid ID (all allowed characters)'
).not.toThrow()

expect(
() => validators.validateDocumentId('op', '_underscored'),
'does not throw on valid ID (underscore-first)'
).not.toThrow()

expect(
() => validators.validateDocumentId('op', '3abcdef'),
'does not throw on valid ID (digit-first)'
).not.toThrow()

'does not throw on valid ID'
).not.toThrow(/document ID in format/)
expect(
() => validators.validateDocumentId('op', 'blah#blah'),
'throws on invalid ID (disallowed character)'
).toThrow(/not a valid document ID/)

'throws on invalid ID'
expect(
() => validators.validateDocumentId('op', '-not-allowed'),
'throws on invalid ID (dash-first)'
).toThrow(/not a valid document ID/)

expect(
() => validators.validateDocumentId('op', 'some..path'),
'throws on invalid ID (double-dot)'
).toThrow(/not a valid document ID/)

expect(
() => validators.validateDocumentId('op', 'a'.repeat(129)),
'throws on invalid ID (too long)'
).toThrow(/not a valid document ID/)
})
})

0 comments on commit b5799c9

Please sign in to comment.