Web Security & OWASP (50 Qs)•Part 1: Candid Security Experience, Threat Modeling & Fundamentals (1 - 10)
Same-Origin Policy (SOP) vs. Cross-Origin Capabilities: What SOP blocks and postMessage security.
What is the Same-Origin Policy (SOP)?
The Same-Origin Policy is the cornerstone of browser security. Two URLs share the same origin only if their Scheme (protocol), Host (domain), and Port are strictly identical.
bash
URL Base: https://example.com:443/app
+---------------------------------------+-------------+-------------------------------+
| Compared URL | Same Origin?| Reason |
+---------------------------------------+-------------+-------------------------------+
| https://example.com/api | YES | Protocol, Host, Port match |
| http://example.com/app | NO | Scheme differs (http vs https)|
| https://api.example.com/app | NO | Subdomain differs |
| https://example.com:8080/app | NO | Port differs (8080 vs 443) |
+---------------------------------------+-------------+-------------------------------+
What SOP Blocks vs. What it Permits
- SOP Blocks: Reading responses from cross-origin
fetch()orXMLHttpRequest, accessing DOM trees inside cross-origin<iframe>elements, reading cross-origin cookies. - SOP Permits: Embedding cross-origin images (
<img src="cross.com/pic.png">), scripts (<script src="...">), stylesheets, and submitting HTML forms (<form action="cross.com">).
Securing window.postMessage Communication
When communicating between parent windows and iframes, always explicitly specify the expected target origin:
javascript
// SENDER: NEVER use wildcard '*' target origin!
iframe.contentWindow.postMessage({ token: userToken }, 'https://trusted-partner.com');
// RECEIVER: Always verify origin before trusting data!
window.addEventListener('message', (event) => {
if (event.origin !== 'https://trusted-partner.com') {
console.warn('Blocked untrusted cross-origin message from:', event.origin);
return;
}
processData(event.data);
});