Cookies, CSRF and cross-window attacks · mid
Iframes, sandboxing and postMessage origin checks
When you embed or are embedded, sandbox untrusted iframes, send postMessage only to an exact targetOrigin, and in every message listener check event.origin against an exact allow-list before trusting event.data.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- postMessage(data, targetOrigin): always pass the exact origin (for example 'https://pay.example.com'), never '*' for sensitive data, because the other window may have navigated to an attacker's page.
- In the listener: if (event.origin !== 'https://pay.example.com') return; then validate the shape of event.data. Never use startsWith, includes or a loose regex for origins.
- Do not add a message listener at all if you don't expect messages.
- sandbox on an iframe removes powers (scripts, forms, popups, top navigation, same-origin). Add back only what you need (allow-scripts allow-forms). Never combine allow-scripts with allow-same-origin for same-origin content: the frame can remove its own sandbox.
- allow="camera; payment" (Permissions Policy) grants features to the iframe; referrerpolicy limits what it learns.
- Links opened with target=_blank now get rel=noopener behaviour by default in modern browsers; add rel=noopener noreferrer for old ones so the new page cannot control window.opener (reverse tabnabbing).
The red pen
Common traps: mistake → fix
Mistake: "event.origin.includes('example.com') is a good check"
Fix: https://example.com.evil.io passes; compare exact strings or use an exact Set.
Mistake: "postMessage(data, '*') is fine because we know the iframe"
Fix: the iframe may have been navigated elsewhere; specify the origin.
Mistake: "Checking the origin is enough"
Fix: also validate the message data; a trusted origin may itself have an XSS bug.
Easy to hard
Questions interviewers ask, easy to hard
- How does postMessage work and what are its security rules?
- How do you safely embed a third-party payment iframe and talk to it?
- What does the iframe sandbox attribute do? What is dangerous about allow-scripts + allow-same-origin?
- Design the message protocol between your page and an embedded checkout widget.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.