Skip to content

Commit

Permalink
Pass strings through wildcard key redaction (#32)
Browse files Browse the repository at this point in the history
Per #31, we currently throw a `TypeError` when we try to apply a
wildcard key redaction configuration to a string target. Strings spoofed
themselves into an object code path due to gotchas like:

```js
Object.keys('string')
// => [ '0', '1', '2', '3', '4', '5' ]
```

We already bail early on nullish targets, so we can extend this
behaviour to cover string targets as well. Other primitives are already
handled safely but I've added tests to cover them off.
  • Loading branch information
72636c authored Mar 19, 2024
1 parent 74e09b2 commit 3e93d32
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/modifiers.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module.exports = {
}

function groupRestore ({ keys, values, target }) {
if (target == null) return
if (target == null || typeof target === 'string') return
const length = keys.length
for (var i = 0; i < length; i++) {
const k = keys[i]
Expand All @@ -18,7 +18,7 @@ function groupRestore ({ keys, values, target }) {

function groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) {
const target = get(o, path)
if (target == null) return { keys: null, values: null, target: null, flat: true }
if (target == null || typeof target === 'string') return { keys: null, values: null, target, flat: true }
const keys = Object.keys(target)
const keysLength = keys.length
const pathLength = path.length
Expand Down
29 changes: 29 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,35 @@ test('returns original value when passed non-object using [strict: false, serial
end()
})

test('returns original value when passed non-object at wildcard key', ({ end, doesNotThrow, strictSame }) => {
const redactSerializeFalse = fastRedact({
paths: ['a.*'],
strict: false,
serialize: false
})

const primitives = [null, undefined, 'A', 1, false]

primitives.forEach((a) => {
doesNotThrow(() => redactSerializeFalse({ a }))
const res = redactSerializeFalse({ a })
strictSame(res, { a })
})

end()
})

test('returns censored values when passed array at wildcard key', ({ end, strictSame }) => {
const redactSerializeFalse = fastRedact({
paths: ['a.*'],
strict: false,
serialize: false
})
const res = redactSerializeFalse({ a: ['redact', 'me'] })
strictSame(res.a, [censor, censor])
end()
})

test('throws if a path is not a string', ({ end, throws }) => {
const invalidTypeMsg = 'fast-redact - Paths must be (non-empty) strings'
throws((e) => {
Expand Down

0 comments on commit 3e93d32

Please sign in to comment.