@platform-sec/sensitive-string-testing 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +329 -2
  3. package/dist/assertions.d.ts +81 -0
  4. package/dist/assertions.d.ts.map +1 -0
  5. package/dist/assertions.js +132 -0
  6. package/dist/assertions.js.map +1 -0
  7. package/dist/canary.d.ts +49 -0
  8. package/dist/canary.d.ts.map +1 -0
  9. package/dist/canary.js +116 -0
  10. package/dist/canary.js.map +1 -0
  11. package/dist/create-test-secret.d.ts +78 -0
  12. package/dist/create-test-secret.d.ts.map +1 -0
  13. package/dist/create-test-secret.js +91 -0
  14. package/dist/create-test-secret.js.map +1 -0
  15. package/dist/describe-type.d.ts +16 -0
  16. package/dist/describe-type.d.ts.map +1 -0
  17. package/dist/describe-type.js +35 -0
  18. package/dist/describe-type.js.map +1 -0
  19. package/dist/index.d.ts +51 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +77 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/leak-scan.d.ts +94 -0
  24. package/dist/leak-scan.d.ts.map +1 -0
  25. package/dist/leak-scan.js +309 -0
  26. package/dist/leak-scan.js.map +1 -0
  27. package/dist/matchers.d.ts +93 -0
  28. package/dist/matchers.d.ts.map +1 -0
  29. package/dist/matchers.js +170 -0
  30. package/dist/matchers.js.map +1 -0
  31. package/dist/mocks.d.ts +140 -0
  32. package/dist/mocks.d.ts.map +1 -0
  33. package/dist/mocks.js +146 -0
  34. package/dist/mocks.js.map +1 -0
  35. package/dist/serializer.d.ts +136 -0
  36. package/dist/serializer.d.ts.map +1 -0
  37. package/dist/serializer.js +210 -0
  38. package/dist/serializer.js.map +1 -0
  39. package/dist/vitest.d.ts +59 -0
  40. package/dist/vitest.d.ts.map +1 -0
  41. package/dist/vitest.js +3 -0
  42. package/dist/vitest.js.map +1 -0
  43. package/package.json +55 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 AppSec Science, LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,330 @@
1
- # Temporary Holding Version
1
+ # @platform-sec/sensitive-string-testing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Test secrets, leak assertions, matchers, and audit mocks for
4
+ [`@platform-sec/sensitive-string-core`](../sensitive-core).
5
+
6
+ The core promise of `SensitiveString` is that a sensitive value does not reach
7
+ output it was never meant to reach. That promise has to be tested, and every
8
+ project that tests it ends up writing the same three things: a canary value, a
9
+ check that the canary is absent, and a fake audit context. This package is those
10
+ three things, written once.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ pnpm add -D @platform-sec/sensitive-string-testing
16
+ ```
17
+
18
+ `@platform-sec/sensitive-string-core` is a peer dependency. No test framework is:
19
+ the matchers are a plain object you hand to `expect.extend`, and anything that
20
+ needs a spy takes `vi.fn` or `jest.fn` as an argument.
21
+
22
+ ## Requirements
23
+
24
+ - Node.js 22.12+
25
+ - Vitest or Jest, or any runner whose `expect` has `extend`
26
+
27
+ ## Test secrets
28
+
29
+ ```typescript
30
+ import { createTestSecret } from '@platform-sec/sensitive-string-testing';
31
+
32
+ const apiKey = createTestSecret('credential', 'api_key');
33
+ // __CANARY_1767225600000_1_3f9c1ab4e207__
34
+ ```
35
+
36
+ The value is unique per call and conspicuous on purpose: when it turns up in a
37
+ log capture or a snapshot diff, there is no question about what it is or which
38
+ test produced it. Uniqueness comes from a counter, the clock, and
39
+ `node:crypto`, so it survives both fake timers and a stubbed `Math.random`.
40
+
41
+ `createTestSecret` takes everything `SensitiveStringOptions` takes, so a test
42
+ that needs an expiring secret or an `onExpire` hook passes those straight
43
+ through:
44
+
45
+ ```typescript
46
+ const otp = createTestSecret('credential', 'otp', { ttl: 30_000 });
47
+ const email = createTestSecret('sensitive', 'email', { value: 'jane@example.com' });
48
+ ```
49
+
50
+ Two shapes are common enough to have their own factory:
51
+
52
+ ```typescript
53
+ import { createExpiredSecret, createExpiringSecret } from '@platform-sec/sensitive-string-testing';
54
+
55
+ createExpiredSecret('credential', 'otp'); // already past its deadline
56
+ createExpiringSecret('credential', 'session', 60_000); // expires in a minute
57
+ ```
58
+
59
+ `createExpiredSecret` needs no fake timers: `ttl: 0` puts the deadline at
60
+ construction.
61
+
62
+ ## Leak assertions
63
+
64
+ ```typescript
65
+ import { createTestSecret, expectNotLeaked } from '@platform-sec/sensitive-string-testing';
66
+
67
+ it('does not leak the key into the response', async () => {
68
+ const apiKey = createTestSecret('credential', 'api_key');
69
+
70
+ const response = await handler(apiKey);
71
+
72
+ expectNotLeaked(apiKey, response, logger.entries, await response.text());
73
+ });
74
+ ```
75
+
76
+ `expectNotLeaked` walks each target rather than serializing it. `JSON.stringify`
77
+ asks an object what it wants to show, and what an object wants to show is
78
+ exactly the wrong question for a leak check: a `toJSON` that omits a field hides
79
+ a raw copy that is still sitting on the object, and a `SensitiveString` renders
80
+ as its redacted form whether or not a plain copy sits next to it.
81
+
82
+ The walk reaches strings, other primitives, arrays and the properties attached
83
+ to them, `Map` and `Set` contents, typed arrays and `Buffer` contents, `RegExp`
84
+ sources, object keys, values behind getters, and own properties whether or not
85
+ they are enumerable, which is how an `Error`'s `message` and `stack` and a
86
+ `match()` result's `input` are covered. It does not reach closure variables,
87
+ `WeakMap` contents, unsettled promises, or function bodies.
88
+
89
+ There is no depth limit. The walk uses an explicit stack, so a leak thousands of
90
+ levels down is still found; a limit would report it as no leak at all. Getters
91
+ are invoked, which is worth knowing if a getter in your fixture has side
92
+ effects.
93
+
94
+ A value still wrapped in a `SensitiveString` is not a leak and is not reported
95
+ as one.
96
+
97
+ When a value does leak, the failure names the class, the label, and the path it
98
+ was found at, and quotes the surrounding text with the value replaced:
99
+
100
+ ```
101
+ LeakageDetectedError: Sensitive value leaked.
102
+ Label: api_key
103
+ Class: credential
104
+ Target: [0].headers["authorization"]
105
+ Context: Bearer [LEAKED VALUE]
106
+ The value itself is withheld so this message is safe to log.
107
+ ```
108
+
109
+ A leak assertion that proves a secret leaked by printing the secret has only
110
+ moved the leak, so it prints the location instead.
111
+
112
+ ### Redaction assertions
113
+
114
+ ```typescript
115
+ import { expectRedacted } from '@platform-sec/sensitive-string-testing';
116
+
117
+ expectRedacted(formatUserLog({ email }), email);
118
+ ```
119
+
120
+ `expectRedacted` checks two things: the raw value is absent, and the rendering
121
+ the class policy actually produces is present. It reads that rendering from the
122
+ instance rather than assuming `[REDACTED:class]`, so a custom policy passes
123
+ without the test having to know its format, and a policy that stops redacting
124
+ fails. Pass `customPattern` when the output transforms the rendering.
125
+
126
+ Both assertions search for the complete value, so a policy that discloses only
127
+ part of one reads as a successful redaction. Partial disclosure is what `mask()`
128
+ and its `minMasked` floor govern in core, and `registerPolicy` already rejects a
129
+ redaction that embeds the value.
130
+
131
+ ## Matchers
132
+
133
+ ```typescript
134
+ // vitest.setup.ts
135
+ import { expect } from 'vitest';
136
+ import { setupSensitiveMatchers } from '@platform-sec/sensitive-string-testing';
137
+
138
+ setupSensitiveMatchers(expect);
139
+ ```
140
+
141
+ ```typescript
142
+ expect(token).toBeSensitiveString();
143
+ expect(token).toHaveSensitivityClass('credential');
144
+ expect(token).toHaveLabel('api_token');
145
+ expect(token).toRevealAs('abc123');
146
+ expect(otp).toBeExpired();
147
+ expect(response).not.toContainSensitive(token);
148
+ ```
149
+
150
+ Both frameworks expose a registered matcher asymmetrically as well, so this
151
+ works with no further setup:
152
+
153
+ ```typescript
154
+ expect(response).toEqual({
155
+ token: expect.toBeSensitiveString(),
156
+ status: 'ok',
157
+ });
158
+ ```
159
+
160
+ `toRevealAs` goes through `reveal()`, so an expired value or a policy denial
161
+ fails the assertion instead of passing on a remembered copy. When it fails it
162
+ reports the redacted rendering and the length rather than the value.
163
+
164
+ ### Types
165
+
166
+ With Vitest, import the ready-made augmentation once:
167
+
168
+ ```typescript
169
+ import '@platform-sec/sensitive-string-testing/vitest';
170
+ ```
171
+
172
+ With Jest, or to write it yourself, extend from the exported interface:
173
+
174
+ ```typescript
175
+ import type { SensitiveMatchers } from '@platform-sec/sensitive-string-testing';
176
+
177
+ declare global {
178
+ namespace jest {
179
+ interface Matchers<R> extends SensitiveMatchers<R> {}
180
+ }
181
+ }
182
+ ```
183
+
184
+ ## Snapshot serializer
185
+
186
+ ```typescript
187
+ // vitest.setup.ts
188
+ import { expect } from 'vitest';
189
+ import { sensitiveSerializer } from '@platform-sec/sensitive-string-testing';
190
+
191
+ expect.addSnapshotSerializer(sensitiveSerializer);
192
+ ```
193
+
194
+ ```javascript
195
+ // jest.config.js
196
+ module.exports = {
197
+ snapshotSerializers: ['@platform-sec/sensitive-string-testing/serializer'],
198
+ };
199
+ ```
200
+
201
+ A snapshot then keeps the shape of the structure and says what each sensitive
202
+ field is, without recording what it holds:
203
+
204
+ ```
205
+ {
206
+ "id": 1,
207
+ "email": SensitiveString<sensitive:email>,
208
+ "apiKey": SensitiveString<credential:api_key>,
209
+ "phone": SensitiveString<sensitive>,
210
+ }
211
+ ```
212
+
213
+ Without a serializer the same snapshot records whatever the class policy's
214
+ `redact()` returns, which loses the label, differs between projects, and changes
215
+ when a policy does. The rendering here is built from the class and the label,
216
+ which are public metadata. It never calls `reveal()`, never reads the policy,
217
+ and has no format placeholder for the value, so a value cannot reach a snapshot
218
+ through it even under a policy registered with `skipRedactValidation`.
219
+
220
+ For a different rendering:
221
+
222
+ ```typescript
223
+ import { createSensitiveSerializer } from '@platform-sec/sensitive-string-testing';
224
+
225
+ createSensitiveSerializer({ showLength: true });
226
+ // SensitiveString<credential:api_key:len=32>
227
+
228
+ createSensitiveSerializer({ showExpiration: true });
229
+ // SensitiveString<credential:otp:EXPIRED>
230
+
231
+ createSensitiveSerializer({ format: '<{class}{label}>' });
232
+ // <credential:api_key>
233
+ ```
234
+
235
+ `showLength` and `showExpiration` are off by default. A snapshot is committed to
236
+ version control, so the length of a credential is more than the class and the
237
+ label say about it, and whether a value is expired depends on when the test ran,
238
+ which makes a stored snapshot that records it stable only while the deadline
239
+ stays on the same side of the clock.
240
+
241
+ A `format` supersedes both options: the placeholders written in it decide what
242
+ appears. They are `{class}`, `{label}`, `{length}` and `{expired}`, and each
243
+ carries its own separator so the optional ones collapse cleanly. There is none
244
+ for the value, and an unknown one is rejected when the serializer is built
245
+ rather than passed through into every snapshot in the suite.
246
+
247
+ ## Audit mocks
248
+
249
+ ```typescript
250
+ import { mockRevealContext } from '@platform-sec/sensitive-string-testing';
251
+
252
+ const ctx = mockRevealContext('payment-handler', { fn: vi.fn });
253
+
254
+ token.reveal(ctx);
255
+
256
+ expect(ctx.calls).toHaveLength(1);
257
+ expect(ctx.calls[0]?.details.operation).toBe('reveal');
258
+ expect(ctx.auditReveal).toHaveBeenCalledTimes(1);
259
+ ```
260
+
261
+ `calls` is recorded whether or not a spy factory is given. Passing `vi.fn` or
262
+ `jest.fn` additionally makes `auditReveal` a spy, so the framework's own call
263
+ assertions work on it. `reset()` clears both.
264
+
265
+ Each call also records `context`, the context that operation ran under, which is
266
+ where the tags an integration attaches to a reveal appear:
267
+
268
+ ```typescript
269
+ expect(ctx.calls[0]?.context.tags).toEqual({ model: 'User', path: 'passwordHash' });
270
+ ```
271
+
272
+ It is a copy of the descriptive fields rather than the context itself, one level
273
+ deep. A record pointing at the live mock context would close a cycle through
274
+ `calls`, which neither `JSON.stringify` nor a snapshot assertion could walk.
275
+
276
+ Both helpers degrade rather than throw when something forwards the hook with the
277
+ two arguments it used to take: the record carries the mock's own name and no
278
+ tags, which is what a two-argument caller means. They run inside the reveal gate,
279
+ where a `TypeError` would surface as a failing reveal rather than as a missing
280
+ tag.
281
+
282
+ For assertions about a whole call path rather than a single operation:
283
+
284
+ ```typescript
285
+ import { createMockAuditLog } from '@platform-sec/sensitive-string-testing';
286
+ import { withRevealContext } from '@platform-sec/sensitive-string-core';
287
+
288
+ const audit = createMockAuditLog();
289
+
290
+ await withRevealContext(audit.context, () => chargeCard(card));
291
+
292
+ expect(audit.getEntriesFor('card_number')).toHaveLength(1);
293
+ expect(audit.getEntriesByClass('credential')).toHaveLength(1);
294
+ ```
295
+
296
+ An entry records the class, the label, the context name, and the operation. It
297
+ deliberately holds no raw value and no reference to the instance, because an
298
+ audit log is the thing most likely to end up in a failing assertion's output.
299
+
300
+ `contextName` is read from the context core reports the operation under, so a
301
+ reveal made under a nested child is recorded under the child's name rather than
302
+ the log's own.
303
+
304
+ ## How these utilities read a value
305
+
306
+ A leak check needs the raw value to search for. Values this package created are
307
+ remembered when they are created, so a leak check does not have to reveal them:
308
+ that keeps the class policy's authorization hook and the caller's audit context
309
+ out of an assertion about output, and it lets a leak check run on a secret whose
310
+ deadline has already passed.
311
+
312
+ A value from anywhere else is revealed under an explicit named context, exported
313
+ as `TESTING_CONTEXT_NAMES`, so a strict `checkRevealAllowed` can allow those
314
+ four names in one place. If that reveal is refused, by a deadline or by a
315
+ policy, the check raises `UnreadableSecretError` saying it could not run, rather
316
+ than letting an `ExpiredSensitiveValueError` surface from inside an assertion
317
+ about output where it would read as a clean result. The registry is keyed by object identity and is not
318
+ reachable from outside this package: it adds no property to the instance and no
319
+ second way to the value. It does hold whatever is passed through the `value`
320
+ option, which is a reason to keep real secrets out of that option.
321
+
322
+ ## Not included yet
323
+
324
+ - `createSingleUseSecret`, which needs the reveal counters from roadmap item
325
+ 1.4. There is nothing to exhaust until those exist.
326
+ - Streaming leak monitors, deferred by the design document.
327
+
328
+ ## License
329
+
330
+ MIT
@@ -0,0 +1,81 @@
1
+ import type { SensitivityClass, SensitiveString } from '@platform-sec/sensitive-string-core';
2
+ /**
3
+ * Raised when a raw sensitive value was found somewhere it should not be.
4
+ *
5
+ * The message names the value by label and class and says where it was found.
6
+ * It never contains the value itself, so a failing security test does not put
7
+ * the secret it is guarding into a CI log.
8
+ */
9
+ export declare class LeakageDetectedError extends Error {
10
+ readonly label: string | undefined;
11
+ readonly klass: SensitivityClass;
12
+ /** Index in the argument list of the target that leaked. */
13
+ readonly targetIndex: number;
14
+ /** Path within that target, such as `.headers['authorization']`. */
15
+ readonly path: string;
16
+ /** Surrounding text, with the value replaced by `[LEAKED VALUE]`. */
17
+ readonly context: string;
18
+ constructor(label: string | undefined, klass: SensitivityClass,
19
+ /** Index in the argument list of the target that leaked. */
20
+ targetIndex: number,
21
+ /** Path within that target, such as `.headers['authorization']`. */
22
+ path: string,
23
+ /** Surrounding text, with the value replaced by `[LEAKED VALUE]`. */
24
+ context: string);
25
+ }
26
+ /**
27
+ * Assert that the raw value of a secret appears in none of the targets.
28
+ *
29
+ * Targets are walked rather than serialized with `JSON.stringify`, because
30
+ * `JSON.stringify` asks each object what it wants to show. An object whose
31
+ * `toJSON` omits the field holding a leaked copy would pass a check built on
32
+ * it, and a `SensitiveString` would always render as its redacted form whether
33
+ * or not a plain copy sat next to it. See `collectFragments` for what the walk
34
+ * reaches and what it cannot.
35
+ *
36
+ * A value that is still wrapped in a `SensitiveString` is not a leak and is not
37
+ * reported as one.
38
+ *
39
+ * @throws LeakageDetectedError if the raw value is found.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const apiKey = createTestSecret('credential', 'api_key');
44
+ * const response = await handler(apiKey);
45
+ *
46
+ * expectNotLeaked(apiKey, response, logger.entries, JSON.stringify(response));
47
+ * ```
48
+ */
49
+ export declare function expectNotLeaked(secret: SensitiveString<SensitivityClass>, ...targets: unknown[]): void;
50
+ /**
51
+ * Options for `expectRedacted`.
52
+ */
53
+ export interface RedactionOptions {
54
+ /**
55
+ * Pattern the output must match instead of the class policy's redaction.
56
+ *
57
+ * Use it when the output transforms the redacted form, such as a log format
58
+ * that truncates it or a template that wraps it in quotes.
59
+ */
60
+ customPattern?: RegExp;
61
+ }
62
+ /**
63
+ * Assert that output holds a redacted rendering of a secret and not its value.
64
+ *
65
+ * The rendering that must be present is the one the class policy actually
66
+ * produces, read from the instance rather than assumed to be `[REDACTED:class]`.
67
+ * A custom policy, a per-label redaction, or a future deterministic redaction
68
+ * therefore passes this assertion without the test knowing the format, and a
69
+ * policy change that stops redacting fails it.
70
+ *
71
+ * @throws LeakageDetectedError if the raw value is present.
72
+ * @throws Error if the redacted rendering is absent.
73
+ *
74
+ * @example
75
+ * ```ts
76
+ * const email = createTestSecret('sensitive', 'email');
77
+ * expectRedacted(formatUserLog({ email }), email);
78
+ * ```
79
+ */
80
+ export declare function expectRedacted(output: string | object, secret: SensitiveString<SensitivityClass>, options?: RedactionOptions): void;
81
+ //# sourceMappingURL=assertions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assertions.d.ts","sourceRoot":"","sources":["../src/assertions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAO7F;;;;;;GAMG;AACH,qBAAa,oBAAqB,SAAQ,KAAK;IAE3C,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS;IAClC,QAAQ,CAAC,KAAK,EAAE,gBAAgB;IAChC,4DAA4D;IAC5D,QAAQ,CAAC,WAAW,EAAE,MAAM;IAC5B,oEAAoE;IACpE,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB,qEAAqE;IACrE,QAAQ,CAAC,OAAO,EAAE,MAAM;gBAPf,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,KAAK,EAAE,gBAAgB;IAChC,4DAA4D;IACnD,WAAW,EAAE,MAAM;IAC5B,oEAAoE;IAC3D,IAAI,EAAE,MAAM;IACrB,qEAAqE;IAC5D,OAAO,EAAE,MAAM;CAc3B;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,eAAe,CAAC,gBAAgB,CAAC,EACzC,GAAG,OAAO,EAAE,OAAO,EAAE,GACpB,IAAI,CAgBN;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;;;OAKG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,MAAM,GAAG,MAAM,EACvB,MAAM,EAAE,eAAe,CAAC,gBAAgB,CAAC,EACzC,OAAO,GAAE,gBAAqB,GAC7B,IAAI,CAyBN"}
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LeakageDetectedError = void 0;
4
+ exports.expectNotLeaked = expectNotLeaked;
5
+ exports.expectRedacted = expectRedacted;
6
+ const canary_js_1 = require("./canary.js");
7
+ const leak_scan_js_1 = require("./leak-scan.js");
8
+ /** How much of a target is quoted when a redaction placeholder is missing. */
9
+ const OUTPUT_PREVIEW = 300;
10
+ /**
11
+ * Raised when a raw sensitive value was found somewhere it should not be.
12
+ *
13
+ * The message names the value by label and class and says where it was found.
14
+ * It never contains the value itself, so a failing security test does not put
15
+ * the secret it is guarding into a CI log.
16
+ */
17
+ class LeakageDetectedError extends Error {
18
+ label;
19
+ klass;
20
+ targetIndex;
21
+ path;
22
+ context;
23
+ constructor(label, klass,
24
+ /** Index in the argument list of the target that leaked. */
25
+ targetIndex,
26
+ /** Path within that target, such as `.headers['authorization']`. */
27
+ path,
28
+ /** Surrounding text, with the value replaced by `[LEAKED VALUE]`. */
29
+ context) {
30
+ super([
31
+ 'Sensitive value leaked.',
32
+ ` Label: ${label ?? '(none)'}`,
33
+ ` Class: ${klass}`,
34
+ ` Target: [${targetIndex}]${path}`,
35
+ ` Context: ${context}`,
36
+ ' The value itself is withheld so this message is safe to log.',
37
+ ].join('\n'));
38
+ this.label = label;
39
+ this.klass = klass;
40
+ this.targetIndex = targetIndex;
41
+ this.path = path;
42
+ this.context = context;
43
+ this.name = 'LeakageDetectedError';
44
+ }
45
+ }
46
+ exports.LeakageDetectedError = LeakageDetectedError;
47
+ /**
48
+ * Assert that the raw value of a secret appears in none of the targets.
49
+ *
50
+ * Targets are walked rather than serialized with `JSON.stringify`, because
51
+ * `JSON.stringify` asks each object what it wants to show. An object whose
52
+ * `toJSON` omits the field holding a leaked copy would pass a check built on
53
+ * it, and a `SensitiveString` would always render as its redacted form whether
54
+ * or not a plain copy sat next to it. See `collectFragments` for what the walk
55
+ * reaches and what it cannot.
56
+ *
57
+ * A value that is still wrapped in a `SensitiveString` is not a leak and is not
58
+ * reported as one.
59
+ *
60
+ * @throws LeakageDetectedError if the raw value is found.
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * const apiKey = createTestSecret('credential', 'api_key');
65
+ * const response = await handler(apiKey);
66
+ *
67
+ * expectNotLeaked(apiKey, response, logger.entries, JSON.stringify(response));
68
+ * ```
69
+ */
70
+ function expectNotLeaked(secret, ...targets) {
71
+ const raw = (0, canary_js_1.rawValueOf)(secret, canary_js_1.LEAK_CHECK_CONTEXT);
72
+ for (let index = 0; index < targets.length; index += 1) {
73
+ const location = (0, leak_scan_js_1.findRawValue)(targets[index], raw);
74
+ if (location !== undefined) {
75
+ throw new LeakageDetectedError(secret.label, secret.klass, index, location.path, location.context);
76
+ }
77
+ }
78
+ }
79
+ /**
80
+ * Assert that output holds a redacted rendering of a secret and not its value.
81
+ *
82
+ * The rendering that must be present is the one the class policy actually
83
+ * produces, read from the instance rather than assumed to be `[REDACTED:class]`.
84
+ * A custom policy, a per-label redaction, or a future deterministic redaction
85
+ * therefore passes this assertion without the test knowing the format, and a
86
+ * policy change that stops redacting fails it.
87
+ *
88
+ * @throws LeakageDetectedError if the raw value is present.
89
+ * @throws Error if the redacted rendering is absent.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * const email = createTestSecret('sensitive', 'email');
94
+ * expectRedacted(formatUserLog({ email }), email);
95
+ * ```
96
+ */
97
+ function expectRedacted(output, secret, options = {}) {
98
+ const fragments = (0, leak_scan_js_1.collectFragments)(output);
99
+ const raw = (0, canary_js_1.rawValueOf)(secret, canary_js_1.REDACTION_CHECK_CONTEXT);
100
+ const location = (0, leak_scan_js_1.findRawValueIn)(fragments, raw);
101
+ if (location !== undefined) {
102
+ throw new LeakageDetectedError(secret.label, secret.klass, 0, location.path, location.context);
103
+ }
104
+ const text = (0, leak_scan_js_1.joinFragments)(fragments);
105
+ const expected = options.customPattern ?? redactionOf(secret);
106
+ if (matches(text, expected)) {
107
+ return;
108
+ }
109
+ throw new Error([
110
+ 'Expected a redaction placeholder in the output, but found none.',
111
+ ` Label: ${secret.label ?? '(none)'}`,
112
+ ` Class: ${secret.klass}`,
113
+ ` Expected: ${typeof expected === 'string' ? JSON.stringify(expected) : String(expected)}`,
114
+ ` Output: ${preview(text)}`,
115
+ ].join('\n'));
116
+ }
117
+ /**
118
+ * The rendering the class policy produces for this value.
119
+ *
120
+ * `toString()` is the same call every redacting path in core makes, so this
121
+ * stays correct for a policy whose redaction depends on the value or the label.
122
+ */
123
+ function redactionOf(secret) {
124
+ return secret.toString();
125
+ }
126
+ function matches(text, expected) {
127
+ return typeof expected === 'string' ? text.includes(expected) : expected.test(text);
128
+ }
129
+ function preview(text) {
130
+ return text.length > OUTPUT_PREVIEW ? `${text.slice(0, OUTPUT_PREVIEW)}...` : text;
131
+ }
132
+ //# sourceMappingURL=assertions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assertions.js","sourceRoot":"","sources":["../src/assertions.ts"],"names":[],"mappings":";;;AA8DA,0CAmBC;AAiCD,wCA6BC;AA9ID,2CAAsF;AACtF,iDAA+F;AAE/F,8EAA8E;AAC9E,MAAM,cAAc,GAAG,GAAG,CAAC;AAE3B;;;;;;GAMG;AACH,MAAa,oBAAqB,SAAQ,KAAK;IAElC;IACA;IAEA;IAEA;IAEA;IARX,YACW,KAAyB,EACzB,KAAuB;IAChC,4DAA4D;IACnD,WAAmB;IAC5B,oEAAoE;IAC3D,IAAY;IACrB,qEAAqE;IAC5D,OAAe;QAExB,KAAK,CACH;YACE,yBAAyB;YACzB,cAAc,KAAK,IAAI,QAAQ,EAAE;YACjC,cAAc,KAAK,EAAE;YACrB,eAAe,WAAW,IAAI,IAAI,EAAE;YACpC,cAAc,OAAO,EAAE;YACvB,gEAAgE;SACjE,CAAC,IAAI,CAAC,IAAI,CAAC,CACb,CAAC;QAlBO,UAAK,GAAL,KAAK,CAAoB;QACzB,UAAK,GAAL,KAAK,CAAkB;QAEvB,gBAAW,GAAX,WAAW,CAAQ;QAEnB,SAAI,GAAJ,IAAI,CAAQ;QAEZ,YAAO,GAAP,OAAO,CAAQ;QAYxB,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;IACrC,CAAC;CACF;AAvBD,oDAuBC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,SAAgB,eAAe,CAC7B,MAAyC,EACzC,GAAG,OAAkB;IAErB,MAAM,GAAG,GAAG,IAAA,sBAAU,EAAC,MAAM,EAAE,8BAAkB,CAAC,CAAC;IAEnD,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,OAAO,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;QACvD,MAAM,QAAQ,GAAG,IAAA,2BAAY,EAAC,OAAO,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC;QAEnD,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YAC3B,MAAM,IAAI,oBAAoB,CAC5B,MAAM,CAAC,KAAK,EACZ,MAAM,CAAC,KAAK,EACZ,KAAK,EACL,QAAQ,CAAC,IAAI,EACb,QAAQ,CAAC,OAAO,CACjB,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC;AAeD;;;;;;;;;;;;;;;;;GAiBG;AACH,SAAgB,cAAc,CAC5B,MAAuB,EACvB,MAAyC,EACzC,UAA4B,EAAE;IAE9B,MAAM,SAAS,GAAG,IAAA,+BAAgB,EAAC,MAAM,CAAC,CAAC;IAC3C,MAAM,GAAG,GAAG,IAAA,sBAAU,EAAC,MAAM,EAAE,mCAAuB,CAAC,CAAC;IACxD,MAAM,QAAQ,GAAG,IAAA,6BAAc,EAAC,SAAS,EAAE,GAAG,CAAC,CAAC;IAEhD,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QAC3B,MAAM,IAAI,oBAAoB,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,EAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;IACjG,CAAC;IAED,MAAM,IAAI,GAAG,IAAA,4BAAa,EAAC,SAAS,CAAC,CAAC;IACtC,MAAM,QAAQ,GAAG,OAAO,CAAC,aAAa,IAAI,WAAW,CAAC,MAAM,CAAC,CAAC;IAE9D,IAAI,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,EAAE,CAAC;QAC5B,OAAO;IACT,CAAC;IAED,MAAM,IAAI,KAAK,CACb;QACE,iEAAiE;QACjE,eAAe,MAAM,CAAC,KAAK,IAAI,QAAQ,EAAE;QACzC,eAAe,MAAM,CAAC,KAAK,EAAE;QAC7B,eAAe,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE;QAC3F,eAAe,OAAO,CAAC,IAAI,CAAC,EAAE;KAC/B,CAAC,IAAI,CAAC,IAAI,CAAC,CACb,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,WAAW,CAAC,MAAyC;IAC5D,OAAO,MAAM,CAAC,QAAQ,EAAE,CAAC;AAC3B,CAAC;AAED,SAAS,OAAO,CAAC,IAAY,EAAE,QAAyB;IACtD,OAAO,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACtF,CAAC;AAED,SAAS,OAAO,CAAC,IAAY;IAC3B,OAAO,IAAI,CAAC,MAAM,GAAG,cAAc,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AACrF,CAAC"}
@@ -0,0 +1,49 @@
1
+ import type { SensitivityClass, SensitiveString } from '@platform-sec/sensitive-string-core';
2
+ /** Record the raw value this package generated for an instance. */
3
+ export declare function rememberCanary(secret: SensitiveString<SensitivityClass>, raw: string): void;
4
+ /** The remembered raw value, or undefined for an instance from anywhere else. */
5
+ export declare function recallCanary(secret: SensitiveString<SensitivityClass>): string | undefined;
6
+ /**
7
+ * The raw value of a secret, for a check that has to search for it.
8
+ *
9
+ * A value this package created is read from the canary registry. Anything else
10
+ * is revealed under an explicit, named context, so the reveal is attributable
11
+ * and does not silently inherit an ambient context the test set up for its own
12
+ * assertions.
13
+ *
14
+ * A class policy whose `checkRevealAllowed` rejects unknown contexts will
15
+ * refuse these reveals. Such a policy should allow the names exported as
16
+ * `TESTING_CONTEXT_NAMES`, or the test should build its secrets with
17
+ * `createTestSecret`, which needs no reveal at all.
18
+ */
19
+ export declare function rawValueOf(secret: SensitiveString<SensitivityClass>, contextName: string): string;
20
+ /**
21
+ * Raised when a check could not read the value it was asked to look for.
22
+ *
23
+ * This is not a leak report and not a clean result. It means the assertion did
24
+ * not run, which matters because the alternative reading of a silent pass is
25
+ * that nothing leaked.
26
+ */
27
+ export declare class UnreadableSecretError extends Error {
28
+ readonly klass: SensitivityClass;
29
+ readonly label: string | undefined;
30
+ /** The context the reveal was attempted under. */
31
+ readonly contextName: string;
32
+ constructor(klass: SensitivityClass, label: string | undefined,
33
+ /** The context the reveal was attempted under. */
34
+ contextName: string, cause: unknown);
35
+ }
36
+ /** Context name used when a leak assertion has to reveal a foreign value. */
37
+ export declare const LEAK_CHECK_CONTEXT = "__test-leak-check__";
38
+ /** Context name used when a redaction assertion has to reveal a foreign value. */
39
+ export declare const REDACTION_CHECK_CONTEXT = "__test-redaction-check__";
40
+ /** Context name used when a matcher has to reveal a foreign value. */
41
+ export declare const MATCHER_CONTEXT = "__test-matcher__";
42
+ /** Context name used when `toContainSensitive` has to reveal a foreign value. */
43
+ export declare const CONTAINS_CHECK_CONTEXT = "__test-contains-check__";
44
+ /**
45
+ * Every context name this package reveals under, so a strict policy can
46
+ * allowlist them in one place.
47
+ */
48
+ export declare const TESTING_CONTEXT_NAMES: readonly string[];
49
+ //# sourceMappingURL=canary.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canary.d.ts","sourceRoot":"","sources":["../src/canary.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AAqB7F,mEAAmE;AACnE,wBAAgB,cAAc,CAAC,MAAM,EAAE,eAAe,CAAC,gBAAgB,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAE3F;AAED,iFAAiF;AACjF,wBAAgB,YAAY,CAAC,MAAM,EAAE,eAAe,CAAC,gBAAgB,CAAC,GAAG,MAAM,GAAG,SAAS,CAE1F;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,eAAe,CAAC,gBAAgB,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAejG;AAED;;;;;;GAMG;AACH,qBAAa,qBAAsB,SAAQ,KAAK;IAE5C,QAAQ,CAAC,KAAK,EAAE,gBAAgB;IAChC,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS;IAClC,kDAAkD;IAClD,QAAQ,CAAC,WAAW,EAAE,MAAM;gBAHnB,KAAK,EAAE,gBAAgB,EACvB,KAAK,EAAE,MAAM,GAAG,SAAS;IAClC,kDAAkD;IACzC,WAAW,EAAE,MAAM,EAC5B,KAAK,EAAE,OAAO;CAmBjB;AAMD,6EAA6E;AAC7E,eAAO,MAAM,kBAAkB,wBAAwB,CAAC;AAExD,kFAAkF;AAClF,eAAO,MAAM,uBAAuB,6BAA6B,CAAC;AAElE,sEAAsE;AACtE,eAAO,MAAM,eAAe,qBAAqB,CAAC;AAElD,iFAAiF;AACjF,eAAO,MAAM,sBAAsB,4BAA4B,CAAC;AAEhE;;;GAGG;AACH,eAAO,MAAM,qBAAqB,EAAE,SAAS,MAAM,EAKlD,CAAC"}