Skip to content

Commit 6d32057

Browse files
committed
fix(signals): mask secret Signal Forms field values in signal graphs
Signal Forms keeps each field value in a signal with no name, and the signal graph masked values by name, so a password, token or API key field reached the panel, agents and the static report in clear. This happened whenever that component's graph was shown: when it was selected in the panel or with `highlight`, and now also through an `inspect-signals` peek. The page now collects the secret field values of each component, by the same rules as the component values (secret names, password and one-time-code fields, `data-pangular="mask"`, and `unmask`), and masks them in every node and history entry before the graph leaves the page.
1 parent ab22991 commit 6d32057

12 files changed

Lines changed: 542 additions & 14 deletions

‎apps/docs/src/content/inspectors/signals.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,10 @@ Signals join the graph when a template or an effect reads them. If a signal is m
268268

269269
The graph shows up to 400 nodes. When Angular reports more, a notice says **Showing 400 of N signals**, and the edges to the rest are left out. The drawing holds up to 120 nodes. Past that, it draws the selected node and as much of its chain as fits, or the first 120 nodes when none is selected, and says **Drawing N of M signals**. The history keeps 50 entries per signal, and the **N changes** count keeps counting past that.
270270

271+
### Secret form fields are masked
272+
273+
A Signal Forms field keeps its value in a signal with no name, which the graph shows as a `computed` or `linkedSignal` node without a label. When the field is secret (by name, `type="password"`, a credential `autocomplete` or a mask marker), that node, any other node that holds the value, and their history show `[redacted]`. See [Access and redaction](../security.md#components-signals-ngrx-and-pipes).
274+
271275
### Injector graphs hold effects only
272276

273277
The root and route graphs start from the effects registered on that injector. A signal in a root service that no effect reads doesn't appear there. It appears in the graph of a component whose template reads it.

‎apps/docs/src/content/security.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,8 @@ TanStack Query keys and mutation variables have positional parts with no name to
313313

314314
Component values follow the form masks of the fields in the component, not only their names. When a form field in the component's template is masked by its element (a password field, a credential `autocomplete`, `data-pangular="mask"` or another mask marker), its value is replaced with `[redacted]` wherever it shows in the component's inputs and properties: the `FormGroup` that holds it, the `ngModel` model object and the Signal Forms model. Values such a field held earlier stay masked too (the last 50 on the page).
315315

316+
Signal graphs follow the same form masks. Signal Forms keeps each field's value in a signal of its own, which has no name, so the name rules can't see it. The page masks those values by value instead, before the graph leaves it: the values of the masked fields in the component's template, and of the Signal Forms fields of the component whose name looks secret, or matches `redaction.secretNames`, also when the template doesn't bind them. Such a value shows as `[redacted]` in every node, resource and history entry of the graph, as a whole value and inside objects and strings, and values the fields held earlier stay masked too (the last 50 on the page). This holds for the graph the Signals page shows, for `inspect-signals` and `watch-signal`, the `signal-graph` resource, WebMCP and the static report. Root and route injector graphs mask the values the page already knows as secret. Fields named in `unmask` or marked `data-pangular="unmask"` stay readable.
317+
316318
NgRx signal store method calls in the change log mask their arguments. When the call writes a state key whose name looks secret, at any depth, every argument shows as `[redacted]`, for that call, its earlier entries and every later call of the method. A method that returns a promise counts as making the writes that follow its `await` until the promise settles: if such a write touches a secret key, the arguments of every call of the store still running are masked, also in the entries the panel already received. An `rxMethod` stream returns no promise, so a secret it writes later doesn't mask the arguments it was called with. Otherwise an argument whose parameter name looks secret (`password` in `login(email, password)`) is masked, and values the store holds under secret keys are cut out of the other arguments. The URL and title of the NgRx page, and the request URL of an `httpResource`, are redacted like router URLs.
317319

318320
The **Components** tab and the `set-component-property` and `set-signal` tools never write a value you could not see: a name on the path that looks secret, or a value that shows `[redacted]` anywhere, is refused. Write a field next to a secret instead of the object that holds it. See [Editing values](./inspectors/components.md#editing-values).

‎packages/devtools/CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ What remains: `/config` exports `DEFAULT_POPUP_HOTKEY`, `PANGULAR_ACTIONS`, `PAN
116116
- Hide the shared state of a turned-off inspector from agents.
117117
- Mask secret route params in named outlets, such as the token in `/(side:reset/:token)`, before the navigation is recognized and in router link targets. The route config match read only the primary path. It also follows an empty-path layout route into its named-outlet children, as the router does, so `/(side:reset/:token)` and `/home(side:reset/:token)` are masked when `reset/:token` sits under `{path: '', children: [...]}`. The active route walk also follows `firstChild` when `children` is missing, and stops after 200 routes.
118118
- Leave the `redaction` config (`secretNames`, `unmask`) out of `__connection.json`, which answers before the one-time code. Pages get it from the server once they are trusted, and read nothing from the app until they have it. `initOverlay()` still resolves once connected, without waiting for the code. The Dashboard asks for the config the same way to list **Extra secret names** and **Unmasked names**. A static report leaves those rows out (#419).
119+
- Mask secret Signal Forms field values in signal graphs and their history. Signal Forms keeps each field value in an unnamed signal, so a `password`, `token` or `apiKey` field showed in the graph of its component on the Signals page, in `inspect-signals` (also when it reads a component by `component` or `selector`), in the `signal-graph` resource, over WebMCP and in the static report. The page now masks the values of the component's secret fields (by name, `redaction.secretNames`, `type="password"`, a credential `autocomplete` or a mask marker, and their last 50 values) in every node, resource and history entry before the graph leaves it.
119120

120121
### Features
121122

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
// @vitest-environment jsdom
2+
import '@angular/compiler';
3+
import {
4+
Component,
5+
computed,
6+
provideZonelessChangeDetection,
7+
signal,
8+
type ApplicationRef,
9+
} from '@angular/core';
10+
import { FormField, form } from '@angular/forms/signals';
11+
import { bootstrapApplication } from '@angular/platform-browser';
12+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
13+
import { forgetMaskedFormValues } from '../component-form-masks.ts';
14+
import { setRedaction } from '../forms-privacy.ts';
15+
import { collectSignalGraph, graphValue, type SignalDebugNg } from '../signal-graph.ts';
16+
import { createSignalHistory } from '../signal-history.ts';
17+
import { maskHistory, secretsOfGraph } from '../signal-masks.ts';
18+
import { answerPeek } from '../signal-peek.ts';
19+
import { serializeNamed } from '../serialize.ts';
20+
import { angularAtLeast, STANDALONE } from './angular-version.ts';
21+
22+
const PW = 'CNRY_pw_q7Zx';
23+
const TOKEN = 'CNRY_token_k2Lm';
24+
const API_KEY = 'CNRY_apiKey_w9Rt';
25+
const CONFIRM = 'CNRY_confirm_b4Np';
26+
const CLIENT_SECRET = 'CNRY_clientSecret_h3Vd';
27+
const NICKNAME = 'CNRY_nickname_z8Qa';
28+
const EMAIL = '[email protected]';
29+
30+
class SignalSecrets {
31+
readonly model = signal({
32+
email: EMAIL,
33+
password: PW,
34+
token: TOKEN,
35+
apiKey: API_KEY,
36+
confirm: CONFIRM,
37+
clientSecret: CLIENT_SECRET,
38+
nickname: NICKNAME,
39+
});
40+
readonly login = form(this.model);
41+
// Not bound in the template: only the name tells it is secret.
42+
readonly secretSize = computed(() => this.login.clientSecret().value().length);
43+
readonly nicknameSize = computed(() => this.login.nickname().value().length);
44+
}
45+
46+
Component({
47+
...STANDALONE,
48+
selector: 'app-signal-secrets',
49+
imports: [FormField],
50+
template: `
51+
<input [formField]="login.email" />
52+
<input [formField]="login.password" />
53+
<input [formField]="login.token" />
54+
<input [formField]="login.apiKey" />
55+
<input type="password" [formField]="login.confirm" />
56+
{{ secretSize() }} {{ nicknameSize() }}
57+
`,
58+
})(SignalSecrets);
59+
60+
const settle = async (app: ApplicationRef) => {
61+
for (let i = 0; i < 5; i++) {
62+
await new Promise((resolve) => setTimeout(resolve, 0));
63+
app.tick();
64+
}
65+
};
66+
67+
const CANARIES = [PW, TOKEN, API_KEY, CONFIRM, CLIENT_SECRET];
68+
69+
function history() {
70+
return createSignalHistory(
71+
(value, name) => serializeNamed(name, value, { budget: 1000 }),
72+
Date.now,
73+
(value, name) => graphValue(name, value),
74+
);
75+
}
76+
77+
describe.skipIf(!angularAtLeast('21.0.0'))('signal graph of a Signal Forms form', () => {
78+
let app: ApplicationRef | null = null;
79+
const ng = () => (globalThis as { ng?: SignalDebugNg }).ng!;
80+
81+
beforeEach(async () => {
82+
forgetMaskedFormValues();
83+
setRedaction();
84+
document.body.innerHTML = '<app-signal-secrets></app-signal-secrets>';
85+
app = await bootstrapApplication(SignalSecrets, {
86+
providers: [provideZonelessChangeDetection()],
87+
});
88+
await settle(app);
89+
});
90+
91+
afterEach(() => {
92+
app?.destroy();
93+
app = null;
94+
setRedaction();
95+
delete (globalThis as { __PANGULAR_FORMS__?: unknown }).__PANGULAR_FORMS__;
96+
});
97+
98+
it('masks secret field values in the nodes the page pushes, and keeps other fields readable', () => {
99+
// No target: the graph the page pushes for its root component.
100+
for (const target of [null, { selector: 'app-signal-secrets' }]) {
101+
const graph = collectSignalGraph(ng(), target)!;
102+
const text = JSON.stringify(graph);
103+
// Signal Forms keeps each field value in an unnamed computed node.
104+
expect(graph.nodes.some((n) => n.kind === 'computed' && !n.label && n.value === EMAIL)).toBe(
105+
true,
106+
);
107+
expect(graph.nodes.filter((n) => n.value === '[redacted]').length).toBeGreaterThanOrEqual(5);
108+
for (const canary of CANARIES) expect(text).not.toContain(canary);
109+
}
110+
});
111+
112+
it('masks a field named by redaction.secretNames', () => {
113+
expect(JSON.stringify(collectSignalGraph(ng(), null))).toContain(NICKNAME);
114+
setRedaction({ secretNames: ['nickname'] });
115+
expect(JSON.stringify(collectSignalGraph(ng(), null))).not.toContain(NICKNAME);
116+
});
117+
118+
it('keeps a field the page unmasks readable', () => {
119+
(globalThis as { __PANGULAR_FORMS__?: unknown }).__PANGULAR_FORMS__ = { unmask: ['token'] };
120+
const text = JSON.stringify(collectSignalGraph(ng(), null));
121+
expect(text).toContain(TOKEN);
122+
for (const canary of [PW, API_KEY, CONFIRM, CLIENT_SECRET]) expect(text).not.toContain(canary);
123+
});
124+
125+
it('masks secret values in a peek and its history, also after the value changed', async () => {
126+
const signals = history();
127+
const peek = () =>
128+
answerPeek(
129+
{ requestId: 'r1', selector: 'app-signal-secrets' },
130+
'page-1',
131+
(target) => collectSignalGraph(ng(), target),
132+
signals,
133+
).graph!;
134+
const first = peek();
135+
expect(first.component?.tag).toBe('app-signal-secrets');
136+
expect(JSON.stringify(first.history)).toContain(EMAIL);
137+
for (const canary of CANARIES) expect(JSON.stringify(first)).not.toContain(canary);
138+
139+
const component = (
140+
ng() as unknown as { getComponent(el: Element): SignalSecrets }
141+
).getComponent(document.querySelector('app-signal-secrets')!);
142+
component.model.update((m) => ({ ...m, password: 'CNRY_pw_next_r5Tu' }));
143+
await settle(app!);
144+
145+
const second = peek();
146+
const text = JSON.stringify(second);
147+
// The history now holds the old and the new password: both masked.
148+
for (const canary of [...CANARIES, 'CNRY_pw_next_r5Tu']) expect(text).not.toContain(canary);
149+
expect(Object.values(second.history!).some((changes) => changes.length > 1)).toBe(true);
150+
});
151+
152+
it('masks history entries recorded before the value was known to be secret', () => {
153+
const graph = collectSignalGraph(ng(), null)!;
154+
const recorded = {
155+
'1': [{ epoch: 1, value: PW, at: 0, source: 'write' as const }],
156+
'2': [{ epoch: 1, value: { note: `copy of ${TOKEN}` }, at: 0, source: 'sample' as const }],
157+
'3': [{ epoch: 1, value: EMAIL, at: 0, source: 'initial' as const }],
158+
};
159+
const masked = maskHistory(recorded, secretsOfGraph({ ...graph }));
160+
expect(masked['1']![0]!.value).toBe('[redacted]');
161+
expect(masked['2']![0]!.value).toEqual({ note: 'copy of [redacted]' });
162+
expect(masked['3']![0]).toBe(recorded['3'][0]);
163+
// The kept entries are left as recorded, for restores.
164+
expect(recorded['1'][0].value).toBe(PW);
165+
});
166+
});
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
// @vitest-environment jsdom
2+
import { afterEach, describe, expect, it } from 'vitest';
3+
import { forgetMaskedFormValues } from '../component-form-masks.ts';
4+
import { collectSignalGraph, graphValue, type SignalDebugNg } from '../signal-graph.ts';
5+
import { createSignalHistory } from '../signal-history.ts';
6+
import { maskHistory, secretsOfGraph } from '../signal-masks.ts';
7+
import { answerPeek } from '../signal-peek.ts';
8+
9+
function directive(selector: string, fields: Record<string, unknown>) {
10+
class Dir {}
11+
(Dir as unknown as Record<string, unknown>)['ɵdir'] = { selectors: [['', selector, '']] };
12+
return Object.assign(new Dir(), fields);
13+
}
14+
15+
const field = (name: string, value: unknown) =>
16+
directive('formField', { state: () => ({ name: () => `login.${name}`, value: () => value }) });
17+
18+
class Login {}
19+
20+
const root = { scopes: new Set(['environment', 'root']) };
21+
22+
/**
23+
* A component with Signal Forms fields bound with `[formField]`, and a signal
24+
* graph shaped like Angular's: one unnamed `computed` per field value.
25+
*/
26+
function setup(values: Record<string, string>) {
27+
document.body.innerHTML = `
28+
<app-login ng-version="22.0.0">
29+
<input id="email" />
30+
<input id="password" />
31+
<input id="token" />
32+
<input id="apiKey" />
33+
<input id="code" autocomplete="one-time-code" />
34+
<input id="note" data-pangular="mask" />
35+
</app-login>`;
36+
const host = document.querySelector('app-login')!;
37+
const at = (id: string) => document.getElementById(id)!;
38+
const instance = new Login();
39+
const ng: SignalDebugNg = {
40+
getComponent: (el) => (el === host ? instance : null),
41+
getInjector: (el) => el,
42+
getDirectives: (el) => (el.id && el.id in values ? [field(el.id, values[el.id])] : []),
43+
ɵgetInjectorResolutionPath: (injector) => [injector, root],
44+
ɵgetInjectorMetadata: (injector) =>
45+
injector === root
46+
? { type: 'environment', source: null }
47+
: { type: 'element', source: at('email') },
48+
ɵgetSignalGraph: (injector) => ({
49+
nodes:
50+
injector === root
51+
? [{ id: '20', kind: 'signal', label: 'lastLogin', epoch: 1, value: values['password'] }]
52+
: [
53+
{ id: '1', kind: 'signal', label: 'model', epoch: 1, value: { ...values } },
54+
...Object.keys(values).map((key, i) => ({
55+
id: String(i + 2),
56+
kind: 'computed',
57+
epoch: 1,
58+
value: values[key],
59+
})),
60+
{
61+
id: '9',
62+
kind: 'computed',
63+
label: 'summary',
64+
epoch: 1,
65+
value: `token ${values['token']} for ${values['email']}`,
66+
},
67+
],
68+
edges: [],
69+
}),
70+
};
71+
return { ng, host };
72+
}
73+
74+
const VALUES = {
75+
76+
password: 'CNRY_pw_q7Zx',
77+
token: 'CNRY_token_k2Lm',
78+
apiKey: 'CNRY_apiKey_w9Rt',
79+
code: '845210',
80+
note: 'CNRY_note_m1Xc',
81+
};
82+
const SECRETS = ['CNRY_pw_q7Zx', 'CNRY_token_k2Lm', 'CNRY_apiKey_w9Rt', '845210', 'CNRY_note_m1Xc'];
83+
84+
function history() {
85+
return createSignalHistory(
86+
(value, name) => graphValue(name, value),
87+
Date.now,
88+
(value, name) => graphValue(name, value),
89+
);
90+
}
91+
92+
describe('signal graph form masks', () => {
93+
afterEach(() => {
94+
forgetMaskedFormValues();
95+
document.body.innerHTML = '';
96+
});
97+
98+
it('masks unnamed nodes that hold a secret field value, in the graph the page pushes', () => {
99+
const { ng } = setup(VALUES);
100+
const graph = collectSignalGraph(ng, null)!;
101+
expect(graph.component?.tag).toBe('app-login');
102+
const text = JSON.stringify(graph);
103+
for (const secret of SECRETS) expect(text).not.toContain(secret);
104+
const byId = Object.fromEntries(graph.nodes.map((n) => [n.id, n.value]));
105+
expect(byId['2']).toBe('[email protected]');
106+
expect(byId['3']).toBe('[redacted]');
107+
expect(byId['9']).toBe('token [redacted] for [email protected]');
108+
});
109+
110+
it('masks a peek by selector, by id and its history, and keeps harmless values', () => {
111+
const { ng } = setup(VALUES);
112+
const signals = history();
113+
for (const request of [{ selector: 'app-login' }, { env: 'root' }]) {
114+
const answer = answerPeek(
115+
{ requestId: 'r', ...request },
116+
'page-1',
117+
(target) => collectSignalGraph(ng, target),
118+
signals,
119+
);
120+
const text = JSON.stringify(answer);
121+
expect(answer.graph).not.toBeNull();
122+
for (const secret of SECRETS) expect(text).not.toContain(secret);
123+
}
124+
// The environment graph masks the values the component's fields showed as secret.
125+
const env = collectSignalGraph(ng, { env: 'root' })!;
126+
expect(env.nodes[0]!.value).toBe('[redacted]');
127+
const peek = answerPeek(
128+
{ requestId: 'r', selector: 'app-login' },
129+
'page-1',
130+
(target) => collectSignalGraph(ng, target),
131+
signals,
132+
).graph!;
133+
expect(peek.history!['2']![0]!.value).toBe('[email protected]');
134+
expect(peek.history!['3']![0]!.value).toBe('[redacted]');
135+
});
136+
137+
it('keeps masking a secret value after the field changed', () => {
138+
const first = setup(VALUES);
139+
collectSignalGraph(first.ng, null);
140+
const { ng } = setup({ ...VALUES, password: 'CNRY_pw_next_r5Tu' });
141+
const graph = collectSignalGraph(ng, null)!;
142+
const old = maskHistory(
143+
{ '3': [{ epoch: 1, value: 'CNRY_pw_q7Zx', at: 0, source: 'initial' }] },
144+
secretsOfGraph(graph),
145+
);
146+
expect(old['3']![0]!.value).toBe('[redacted]');
147+
expect(JSON.stringify(graph)).not.toContain('CNRY_pw_next_r5Tu');
148+
});
149+
150+
it('leaves history alone when the graph has no secrets', () => {
151+
const recorded = { '1': [{ epoch: 1, value: 'x', at: 0, source: 'write' as const }] };
152+
expect(maskHistory(recorded, new Set())).toBe(recorded);
153+
});
154+
});

‎packages/devtools/src/component-form-masks.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,17 @@ export function maskedFormValues<H extends object>(
176176
return new Set([...seen, ...out, ...formSecretValues()]);
177177
}
178178

179+
/**
180+
* Keeps secret values found another way than the element scan, such as the
181+
* secret Signal Forms fields of a component instance (`signal-masks.ts`), so
182+
* they stay hidden like the scanned ones, also after they change.
183+
*/
184+
export function rememberMaskedValues(values: Iterable<string>) {
185+
const out = new Set<string>();
186+
for (const value of values) addValue(out, value);
187+
if (out.size) remember(out);
188+
}
189+
179190
/** Forgets the values seen so far, for tests. */
180191
export function forgetMaskedFormValues() {
181192
seen.clear();

‎packages/devtools/src/overlay-angular-native.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
type SignalTarget,
3131
} from './signal-graph.ts';
3232
import { createSignalHistory, installSignalWriteHook } from './signal-history.ts';
33+
import { maskHistory, secretsOfGraph } from './signal-masks.ts';
3334
import { registerSignalPeek } from './signal-peek.ts';
3435
import { claimPageOnServer, newPageId, newPageKey } from './page-id.ts';
3536

@@ -282,10 +283,11 @@ async function startSession(
282283
epoch: r.epoch,
283284
value: r.status,
284285
}));
285-
const { changes: history, rollback } = signalHistory.collectDeltaWithRollback(
286+
const { changes: collected, rollback } = signalHistory.collectDeltaWithRollback(
286287
[...graph.nodes, ...statuses],
287288
full,
288289
);
290+
const history = maskHistory(collected, secretsOfGraph(graph));
289291
for (const item of [...graph.nodes, ...(graph.resources ?? [])]) {
290292
const changes = signalHistory.changesOf(item.id);
291293
if (changes) item.changes = changes;

0 commit comments

Comments
 (0)