Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions docs/PROGRESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1290,12 +1290,13 @@ recorded" was false.
element, so the guard never sees that change itself. Evidence: with the fork's emit-time gates disabled but the
marker kept (a scratch bundle), the 3 `raw` "released after recording" scenarios that still have live observers
leak and every `provider` scenario holds. LIMITS: see the header of `iframe-guard.ts` (a CONTEXTUAL `unblockSelector`
such as `#trusted iframe`, `.x > iframe` or `:first-child` is tested against a detached copy of the iframe and can
never match, so the guard removes an iframe the recorder records and reports a violation, value selectors like
`iframe[data-embed="x"]` are fine: #123; the guard still reports once per session, but the recorder's marker on a
such as `#trusted iframe`, `.x > iframe` or `:first-child` cannot be tested on the guard's detached copy of the iframe, so
for such a selector (combinator or pseudo-class) an iframe without the recorder's `rr_width`/`rr_height` marker is trusted
to the recorder and the guard's own block rules are not applied to it; value selectors like
`iframe#x` keep the full fail-closed check: #123 fixed; the guard still reports once per session, but the recorder's marker on a
nested iframe whose outer frame was already blocked is removed silently so those flows no longer use the report up (#124;
an iframe blocked, unblocked and navigated is still dropped and reported until the next full snapshot: the fork has to
emit an unblock signal); Font/CustomElement events carry no node id, the marker is the only ancestor signal, entries of an iframe added after the snapshot are
emit an unblock signal, #147); Font/CustomElement events carry no node id, the marker is the only ancestor signal, entries of an iframe added after the snapshot are
released by the next full snapshot rather than by removing its container).
- **Real-browser masking e2e** (#120, partially): `packages/instrumentation-tests/test/replay-masking.browser.e2e.ts`
(headless Chromium, runs in `test:e2e`/CI) — iframes (default, `.bugsee-block`, `maskAllText:false`, explicitly
Expand Down
16 changes: 16 additions & 0 deletions packages/instrumentation-tests/test/replay-masking.browser.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,22 @@ describe('replay masking — REAL Chromium + REAL rrweb bundle', () => {
await page.close();
});

it('a contextual unblockSelector keeps the iframe recorded, with no guard violation (#123)', async () => {
await open();
await mountFrames({ id: 'a', n: 1 }, { id: 'b', n: 3 });
await start(mode, { unblockSelector: '#mount > iframe#a' }); // matches only the first frame
await settle(400);
await pokeFrame('a', 'CTX');
await settle();
const events = await dump();
expect(events).toContain('CONTROL_FRAME1'); // the iframe's document IS recorded
expect(events).not.toContain('CONTROL_FRAME3'); // the non-matching neighbour stays blocked
expect(leaks(events)).toEqual([]); // and still masked by the rules
const errors = await page.evaluate(() => (window as unknown as { __rm: Rm }).__rm.errors);
expect(errors).toEqual([]);
await page.close();
});
Comment thread
krassx marked this conversation as resolved.
Resolved

it('shadow DOM: host removed and re-added, nested roots, host moved, shadow attached while detached', async () => {
await open();
await page.evaluate(() => {
Expand Down
2 changes: 1 addition & 1 deletion packages/replay/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ The `replay` option takes `false`, `true` or an object. Masking is fail-closed:

- `maskAllText`: mask every text node, default `true`.
- `maskAllInputs`: mask every input value, default `true`.
- `blockAllMedia`: block all media and iframes, default `true`. A blocked iframe is recorded as an empty placeholder of the same size: its document, text, inputs and live changes are never recorded. Mark an iframe `.bugsee-show` to record it (its content is then masked like the rest of the page). Limit: a defence-in-depth guard re-checks every iframe against your `unblockSelector` on a detached copy of the element, so keep that selector to the iframe's own attributes (`.bugsee-show`, `iframe[data-embed="x"]`). A contextual selector (`#trusted iframe`, `.x > iframe`, `:first-child`) is honoured by the recorder but the guard removes that iframe's document and reports an error (#123).
- `blockAllMedia`: block all media and iframes, default `true`. A blocked iframe is recorded as an empty placeholder of the same size: its document, text, inputs and live changes are never recorded. Mark an iframe `.bugsee-show` to record it (its content is then masked like the rest of the page). Limit: a defence-in-depth guard re-checks every iframe against your block rules on a detached copy of the element. A contextual `unblockSelector` (`#trusted iframe`, `.x > iframe`, `:first-child`; any combinator or pseudo-class, even `:not(.x)`) cannot be evaluated there, so for such a selector the guard trusts the recorder for iframes that carry no placeholder marker (the recorder evaluates it on the live element); the guard's own block rules are then not applied to unmarked iframes. Value selectors (`.bugsee-show`, `iframe#x`) keep the full check.
- `maskTextSelector`, `blockSelector`, `ignoreSelector`: extra CSS selectors to mask, block or ignore.
- `checkoutEveryNms`: full-snapshot interval in milliseconds, default `60000`.
- `canvas`: opt-in canvas recording, see `@bugsee/replay-canvas`.
Expand Down
94 changes: 94 additions & 0 deletions packages/replay/src/iframe-guard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ const make = (overrides: Partial<Parameters<typeof createIframeGuard>[0]> = {})
};

const SECRET = 'GUARD-SECRET';
// U+00A0 is not CSS whitespace: in a selector it is a name character (JS `\s` would call it whitespace)
const NBSP = String.fromCharCode(0xa0);

describe('iframe guard: a blocked iframe is a placeholder, whatever the recorder emitted', () => {
it('passes events that have nothing to do with iframes through untouched (same object)', () => {
Expand Down Expand Up @@ -131,6 +133,78 @@ describe('iframe guard: a blocked iframe is a placeholder, whatever the recorder
expect(shown.childNodes).toHaveLength(1); // unblockSelector beats the iframe block selector
});

describe('a contextual unblockSelector cannot be evaluated on a detached copy: the recorder is trusted', () => {
const contextual = [
'#trusted iframe',
'.x > iframe',
'.x + iframe',
'.x ~ iframe',
'.x>iframe',
'.x+iframe',
'.x~iframe',
'iframe:first-child',
'iframe:nth-child(2)',
'body iframe',
'.bugsee-show, #trusted iframe',
'iframe:not([data-a="b c"]):last-child',
"iframe[data-x=']a b']:first-child",
];
for (const unblockSelector of contextual) {
it(`keeps an unmarked iframe recorded: ${unblockSelector}`, () => {
const { guard, onViolation } = make({ unblockSelector });
const frame = el('iframe', { src: '/same.html' }, [text('ok')]);
guard(snapshot(doc([frame])));
expect(frame.childNodes).toHaveLength(1);
const added = el('iframe', { src: '/b.html' });
guard(mutation({ adds: [{ parentId: 1, nextId: null, node: added }] }));
const kept = guard(attach(added.id, text('inner')));
expect(kept).toBeDefined();
expect(onViolation).not.toHaveBeenCalled();
});
}

it('still blocks an iframe the recorder marked as a placeholder', () => {
const { guard, onViolation } = make({ unblockSelector: '#trusted iframe' });
const frame = el('iframe', { rr_width: '10px', rr_height: '10px' }, [text(SECRET)]);
guard(snapshot(doc([frame])));
expect(frame.childNodes).toEqual([]);
expect(onViolation).toHaveBeenCalledTimes(1);
expect(guard(attach(frame.id, text(SECRET)))).toBeUndefined();
});

it('a value selector stays fail-closed: no unblock match, the block rules apply', () => {
for (const unblockSelector of [
'.bugsee-show',
'iframe[data-embed="x y"]',
'iframe[data-x="]a b"]',
"iframe[data-x=']a b']",
'.bugsee-show, iframe.x',
`.a${NBSP}b`,
`.a\\${NBSP}b`,
`.a\\31${NBSP}b`,
'.md\\:embed',
'#a\\ b',
'.\\31 0',
'iframe[data-a~="b"]',
'',
]) {
const { guard } = make({ unblockSelector });
const frame = el('iframe', { src: '/same.html' }, [text(SECRET)]);
guard(snapshot(doc([frame])));
expect(frame.childNodes).toEqual([]);
}
});

it('an iframe that becomes marked after being recorded is closed', () => {
const { guard } = make({ unblockSelector: '#trusted iframe' });
const frame = el('iframe', { src: '/x' });
guard(snapshot(doc([frame])));
expect(guard(attach(frame.id, text('a')))).toBeDefined();
guard(mutation({ attributes: [{ id: frame.id, attributes: { rr_width: '5px' } }] }));
expect(guard(attach(frame.id, text(SECRET)))).toBeUndefined();
});
});

it('a regexless/odd blockClass option is fine (no blockClass: only the selectors decide)', () => {
const { guard } = make({ blockClass: undefined, blockSelector: '' });
const frame = el('iframe', { class: 'rr-block' }, [text('kept')]);
Expand Down Expand Up @@ -1039,4 +1113,24 @@ describe('legitimate iframe flows are not violations (#124)', () => {
guard(mutation({ attributes: [{ id: inner.id }] }));
expect(onViolation).toHaveBeenCalledTimes(1);
});
it('an open iframe that is re-added blocked (a moved node) is closed: what it attached is tainted', () => {
const { guard, onViolation } = make({ blockSelector: 'iframe.private' });
const frame = el('iframe', {});
guard(snapshot(doc([el('body', {}, [frame])])));
const t = text('inside');
guard(attach(frame.id, el('p', {}, [t])));
const moved = { ...frame, attributes: { class: 'private' } };
guard(mutation({ adds: [{ parentId: 1, nextId: null, node: moved }] }));
expect(guard(mutation({ texts: [{ id: t.id, value: SECRET }] }))).toBeUndefined();
expect(onViolation).toHaveBeenCalledTimes(1);
});
it('LIMIT: a blocked iframe re-added without the marker (moved into its unblock context) stays closed', () => {
const { guard, onViolation } = make({ blockSelector: 'iframe.private' });
const frame = el('iframe', { class: 'private' });
guard(snapshot(doc([el('body', {}, [frame])])));
guard(mutation({ adds: [{ parentId: 1, nextId: null, node: { ...frame, attributes: {} } }] }));
expect(onViolation).not.toHaveBeenCalled(); // the re-add itself is silent; the attach is what is reported
expect(guard(attach(frame.id, el('p', {})))).toBeUndefined();
expect(onViolation).toHaveBeenCalledTimes(1);
});
});
42 changes: 36 additions & 6 deletions packages/replay/src/iframe-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// 1. every iframe element node the guard sees (full snapshot, or added by a mutation) is classified BLOCKED
// if the recorder marked it a placeholder (`rr_width`/`rr_height`) or if the block rules say so for its
// serialized attributes (`blockSelector`/`blockClass`, unless `unblockSelector` opts it back in; a rule that
// cannot be evaluated counts as blocked);
// cannot be evaluated counts as blocked; a CONTEXTUAL `unblockSelector` skips the block rules, see LIMITS);
// 2. children of a blocked iframe node are stripped, and an attach mutation whose parent is a blocked iframe
// is dropped; the ids of everything removed that way are remembered ("tainted");
// 3. any later event that names a tainted id (text, attribute, add, remove, input, scroll, mouse, media,
Expand Down Expand Up @@ -44,15 +44,18 @@
// the serialized ancestors. Against a recorder that does not emit that marker (the previous pins) the guard
// only protects iframes that were blocked from the start;
// - the caller's `unblockSelector` is tested against a DETACHED copy of the iframe (built from its serialized
// attributes), so a contextual selector (`#trusted iframe`, `.x > iframe`, `:first-child`, ...) can never match:
// the recorder records such an iframe, the guard removes its document and reports a violation. Value selectors
// (`iframe[data-embed="x"]`, `.bugsee-show`) are unaffected. See bugsee-javascript#123;
// attributes), which a contextual selector (`#trusted iframe`, `.x > iframe`, `:first-child`, ...) can never
// match. When the selector has a combinator or a pseudo-class, an iframe WITHOUT the recorder's placeholder
// marker is trusted to the recorder (it evaluates the selector on the live element), so the guard does not
// drop what the app opted in; the guard's own block rules are then not applied to unmarked iframes. Value
// selectors (`iframe#x`, `.bugsee-show`) keep the full fail-closed check;
// - a blocked iframe is never reopened by the guard: once it is blocked, whatever it attaches stays dropped (and is
// reported) until the next full snapshot. The recorder drops the change that blocks an iframe, and every
// attribute change while `iframe` is in `blockSelector` (the default), and emits only the placeholder marker, so
// the guard cannot see an unblock, nor tell an iframe's own block from an ancestor's. An iframe that is blocked,
// unblocked and navigated therefore still produces one (false) report. That needs an "unblocked" signal from the
// fork; see bugsee-javascript#124;
// fork; see bugsee-javascript#147 (case 2 of #124). The same goes for a blocked iframe that is MOVED into its
// unblock context: it is re-added without the marker, but stays closed (and its next attach is reported);
// - it cannot tell that a node that is not an iframe should have been blocked: that is the recorder's job and
// has its own tests (see the real-browser masking e2e);
// - cross-origin iframes are never recorded (`recordCrossOriginIframes: false`) so there is nothing to strip.
Expand Down Expand Up @@ -120,6 +123,24 @@ function styleIdsOf(data: Record<string, unknown>): number[] {
return ids;
}

/**
* Whether any alternative of a selector list needs more than the element's own attributes to match: a combinator
* (descendant, `>`, `+`, `~`) or any pseudo-class (`:first-child`, `:nth-child()`, `:not()`, `:has()`, ...).
* Attribute selectors and quoted strings are ignored; such a selector cannot be tested on a detached copy.
*/
function isContextual(selector: string): boolean {
const flat = selector
.replace(/\\[0-9a-fA-F]{1,6}[ \t\n\f\r]?|\\./g, 'x') // CSS escapes (`.md\:embed`, `#a\ b`) are name characters
.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""')
.replace(/\[[^\]]*\]/g, '[]');
// CSS whitespace only: JS `\s` also matches U+00A0 and friends, which are name characters in a selector
return flat
.split(',')
.some((alternative) =>
/[ \t\n\f\r>+~:]/.test(alternative.replace(/^[ \t\n\f\r]+|[ \t\n\f\r]+$/g, '')),
);
}

export function createIframeGuard(options: IframeGuardOptions): IframeGuard {
const blockedIframes = new Set<number>();
const tainted = new Set<number>();
Expand All @@ -139,6 +160,7 @@ export function createIframeGuard(options: IframeGuardOptions): IframeGuard {
const styleOwner = new Map<number, number>();
const taintedStyles = new Set<number>();
let reported = false;
const contextualUnblock = isContextual(options.unblockSelector);

const report = (message: string): void => {
if (reported) {
Expand Down Expand Up @@ -166,6 +188,12 @@ export function createIframeGuard(options: IframeGuardOptions): IframeGuard {
if (options.unblockSelector !== '' && probe.matches(options.unblockSelector)) {
return false;
}
if (contextualUnblock) {
// The unblock rule may match the LIVE iframe through its context, which a detached copy cannot show. The
// recorder evaluates it on the live element and marks a blocked iframe as a placeholder, which
// isBlockedIframe checks before getting here. So trust the recorder.
return false;
}
if (options.blockClass !== undefined && probe.classList.contains(options.blockClass)) {
return true;
}
Expand Down Expand Up @@ -268,7 +296,9 @@ export function createIframeGuard(options: IframeGuardOptions): IframeGuard {
let holdsOpenIframe = false;
if (node.type === ELEMENT_NODE && node.tagName === 'iframe') {
if (isBlockedIframe(node)) {
blockedIframes.add(node.id);
// an iframe that was open and is re-added blocked (a moved node is re-serialized with the same id) is closed
// like any other: what it already attached is tainted
closeIframe(node.id);
if (node.childNodes !== undefined && node.childNodes.length > 0) {
for (const child of node.childNodes) {
taint(child);
Expand Down
Loading