Okay, the user wants a micro-frontend security hardening guide focusing on four key areas: iframe isolation, CSP, integrity checks, and cross-app communication. This is a technical request from someone likely involved in frontend architecture or security, possibly a senior developer or DevOps engineer. They're not just asking for generic advice—they want structured, actionable controls specifically for micro-frontends.
Micro-frontends introduce unique risks because multiple teams deploy independently, often with different frameworks. The user probably knows the basics but needs a consolidated playbook to mitigate supply-chain attacks and runtime threats. I should avoid theoretical fluff and stick to implementable steps.
First, iframe isolation: I'll emphasize sandboxing with restrictive attributes, avoiding same-origin, and postMessage protocols. Need to warn about allow-same-origin pitfalls. Maybe include a table for quick reference.
CSP is tricky here because micro-frontends often need dynamic script loading. Suggest nonce/hash per deployment but acknowledge the operational overhead. Highlight reporting-only mode for staged rollout.
Integrity checks—Subresource Integrity (SRI) is table stakes. But for dynamic scripts, propose runtime hash verification via trust-on-first-use (TOFU) with a fallback to CSP hashes. Mention package integrity tools like npm ci and Sigstore.
Cross-app communication must avoid global pollution. Recommend BroadcastChannel for same-origin but caution about same-site restrictions. For cross-origin, enforce strict postMessage validation (origin, source, data schema). Suggest a shared types library to prevent schema drift.
Wait, did I cover all four pillars? Iframe: sandbox + postMessage. CSP: nonce/hash + reporting. Integrity: SRI + runtime hash. Comms: structured cloning + origin checks. Yes. Also need a summary table for quick wins vs. advanced mitigations. The user might be time-pressed, so prioritize high-impact items first (CSP, SRI, sandbox).
Should I mention Service Workers? They're powerful but add complexity. Maybe as an optional advanced control. Similarly, Web Workers for isolation but note messaging overhead. Keep the core guide focused—advanced topics can be in "further considerations."
Potential pitfalls: Teams might disable sandbox attributes for convenience. Stress that allow-scripts is dangerous without allow-same-origin. Also, remind them that CSP headers must be set at the host level, not in the micro-frontend itself.
Final structure: Start with threat model context, then each pillar with problem, solution, and code snippets. End with a maturity roadmap (basic/intermediate/advanced). Avoid vendor-specific tools—stay framework-agnostic. Mention standards like W3C specs where relevant.
Micro-Frontend Security Hardening Guide
1. Overview & Threat Model
Micro-frontends introduce unique security challenges:
- Increased attack surface through third-party dependencies
- Supply chain risks from multiple independent deployments
- Cross-app contamination via shared browser context
- Privilege escalation between host and remote apps
Core Security Principles:
- Defense in depth - Multiple security layers
- Least privilege - Minimal permissions per component
- Isolation by default - Fail securely, not permissively
- Zero trust communication - Validate all cross-app messages
2. iframe Isolation (Primary Isolation Mechanism)
2.1 Sandbox Configuration
<!-- MOST RESTRICTIVE (Start here) -->
<iframe
src="https://app.example.com"
sandbox="allow-scripts allow-same-origin"
csp="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'"
referrerpolicy="strict-origin-when-cross-origin"
loading="lazy"
></iframe>
<!-- Progressive Enhancement -->
<iframe
src="https://app.example.com"
sandbox="allow-forms allow-scripts allow-popups allow-same-origin allow-modals"
allow="accelerometer; camera; gyroscope; microphone"
csp="default-src 'self'; connect-src https://api.example.com"
></iframe>
2.2 Sandbox Attribute Guide
| Attribute | Risk if Enabled | Recommended |
|---|
allow-same-origin | iframe can access host DOM/cookies | Only with additional CSP restrictions |
allow-scripts | XSS within iframe | Required for most apps |
allow-forms | Form submission attacks | Minimize use |
allow-popups | Pop-up phishing | Avoid unless essential |
allow-top-navigation | Hijack host page | Never enable |
allow-modals | Alert/Confirm phishing | Restrict to trusted apps |
2.3 Advanced iframe Controls
// Communication channel with Origin Validation
window.addEventListener('message', (event) => {
// 1. Verify origin (exact match, not prefix)
const ALLOWED_ORIGINS = ['https://app1.example.com', 'https://app2.example.com'];
if (!ALLOWED_ORIGINS.includes(event.origin)) return;
// 2. Validate message structure
const { type, payload, nonce } = event.data;
if (!type || typeof payload !== 'object') return;
// 3. Verify nonce (CSRF protection)
if (nonce !== sessionStorage.getItem('iframeNonce')) return;
handleMessage(type, payload);
});
3. Content Security Policy (CSP)
3.1 CSP Header Strategy by Context
Host Page (Container App):
Content-Security-Policy:
default-src 'self';
script-src 'self' https://cdn.jsdelivr.net 'nonce-${RANDOM}';
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
font-src 'self' https://fonts.gstatic.com;
img-src 'self' data: https:;
connect-src 'self' https://api.example.com;
frame-src https://app1.example.com https://app2.example.com;
frame-ancestors 'none';
sandbox allow-scripts allow-same-origin;
Micro-Frontend Apps (Dynamic Loading):
// Generate nonce per page load
const cspNonce = crypto.randomUUID();
document.currentScript.setAttribute('nonce', cspNonce);
// Inject CSP via meta tag (fallback for some CDNs)
const meta = document.createElement('meta');
meta.httpEquiv = 'Content-Security-Policy';
meta.content = `
default-src 'self';
script-src 'self' 'nonce-${cspNonce}';
style-src 'self' 'unsafe-inline';
connect-src https://api.${window.location.hostname};
frame-ancestors 'self' https://host.example.com;
`;
document.head.appendChild(meta);
3.2 CSP Reporting
Content-Security-Policy-Report-Only:
default-src 'none';
script-src 'self';
report-uri https://csp-report.example.com/collect;
report-to csp-endpoint
// CSP Report Example
{
"document-uri": "https://app.example.com/",
"referrer": "https://host.example.com/",
"violated-directive": "script-src-elem",
"blocked-uri": "https://malicious.com/evil.js",
"source-file": "https://app.example.com/main.js",
"line-number": 42,
"column-number": 15,
"original-policy": "..."
}
4. Integrity Checks
4.1 Subresource Integrity (SRI)
<!-- For static CDN resources -->
<script
src="https://cdn.jsdelivr.net/npm/react@18/umd/react.production.min.js"
integrity="sha384-+bZ7YgG5Q5a+/K6yKf5b5Q5Q5Q5Q5Q5Q5Q5Q5Q5"
crossorigin="anonymous"
></script>
<!-- Dynamic micro-frontend loading -->
function loadMicrofrontend(url, expectedHash) {
return fetch(url)
.then(res => res.arrayBuffer())
.then(buffer => {
const hash = await crypto.subtle.digest('SHA-256', buffer);
const hashHex = Array.from(new Uint8Array(hash))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
if (hashHex !== expectedHash) {
throw new Error(`Integrity check failed: ${hashHex} !== ${expectedHash}`);
}
const blob = new Blob([buffer], { type: 'text/javascript' });
return URL.createObjectURL(blob);
});
}
4.2 Package Integrity Verification
// package.json with exact versions + integrity checks
{
"dependencies": {
"react": {
"version": "18.2.0",
"integrity": "sha384-..."
}
},
"scripts": {
"preinstall": "npx spdx-snippets --threshold 1",
"postinstall": "npm audit --audit-level=high"
}
}
4.3 Trust-On-First-Use (TOFU) Pattern
class MicrofrontendLoader {
constructor() {
this.trustedHashes = this.loadTrustedHashes();
this.firstLoad = new Map();
}
async load(url, name) {
const response = await fetch(url);
const bytes = await response.arrayBuffer();
const hash = await this.calculateHash(bytes);
// First load: store hash for future verification
if (!this.trustedHashes.has(name)) {
if (!this.firstLoad.has(name)) {
this.firstLoad.set(name, hash);
console.warn(`First load of ${name}: storing hash ${hash}`);
return URL.createObjectURL(new Blob([bytes]));
}
// Verify subsequent loads match first load
if (this.firstLoad.get(name) !== hash) {
throw new Error(`Hash mismatch for ${name}`);
}
} else {
// Verify against trusted store
if (this.trustedHashes.get(name) !== hash) {
throw new Error(`Untrusted hash for ${name}`);
}
}
return URL.createObjectURL(new Blob([bytes]));
}
}
5. Cross-App Communication Security
5.1 PostMessage Best Practices
Sending Messages:
function sendSecureMessage(targetWindow, targetOrigin, message) {
// 1. Target exact origin (never '*')
if (!targetOrigin.match(/^https:\/\/[a-z0-9.-]+\.example\.com$/)) {
throw new Error('Invalid target origin');
}
// 2. Use structured data (no functions/dom nodes)
const securedMessage = {
type: 'APP_COMMUNICATION',
payload: message,
timestamp: Date.now(),
nonce: crypto.randomUUID(),
sender: window.location.origin
};
// 3. Send with transferable objects where possible
targetWindow.postMessage(
securedMessage,
targetOrigin,
[securedMessage.payload.buffer] // Transfer ownership
);
}
Receiving Messages:
window.addEventListener('message', (event) => {
// 1. Validate origin (exact match, case-sensitive)
const ALLOWED_ORIGINS = new Set([
'https://host.example.com',
'https://app1.example.com'
]);
if (!ALLOWED_ORIGINS.has(event.origin)) {
console.warn('Blocked message from unknown origin:', event.origin);
return;
}
// 2. Validate message structure
const message = event.data;
if (!message || typeof message !== 'object') return;
if (message.type !== 'APP_COMMUNICATION') return;
if (!message.payload || !message.nonce) return;
// 3. Check timestamp (prevent replay attacks)
const age = Date.now() - message.timestamp;
if (age > 30000) { // 30 seconds
console.warn('Stale message rejected');
return;
}
// 4. Validate nonce (prevents CSRF)
const usedNonces = sessionStorage.getItem('usedNonces') || '[]';
const nonces = JSON.parse(usedNonces);
if (nonces.includes(message.nonce)) {
console.warn('Duplicate nonce detected');
return;
}
// 5. Process message
nonces.push(message.nonce);
sessionStorage.setItem('usedNonces', JSON.stringify(nonces.slice(-100)));
handleMessage(message.payload);
});
5.2 Communication Contract Design
// Shared types (single source of truth)
interface AppMessage {
version: '1.0';
type: 'DATA_UPDATE' | 'AUTH_EVENT' | 'ERROR_REPORT';
payload: unknown;
metadata: {
sender: string;
timestamp: number;
nonce: string;
correlationId?: string;
};
}
// Type guard
function isValidMessage(obj: any): obj is AppMessage {
return (
obj &&
typeof obj === 'object' &&
['DATA_UPDATE', 'AUTH_EVENT', 'ERROR_REPORT'].includes(obj.type) &&
obj.metadata &&
typeof obj.metadata.timestamp === 'number' &&
typeof obj.metadata.nonce === 'string' &&
typeof obj.metadata.sender === 'string'
);
}
5.3 BroadcastChannel (Same-Origin Only)
const channel = new BroadcastChannel('microfrontend-channel');
// Prevent pollution
channel.onmessage = (event) => {
if (!event.data || !event.data.__v) return; // Version check
// Rate limiting
const now = Date.now();
const last = channel.lastMessage || 0;
if (now - last < 100) return; // 100ms minimum
channel.lastMessage = now;
processMessage(event.data);
};
// Send with channel validation
channel.postMessage({
__v: '1.0',
type: 'PING',
timestamp: Date.now()
});
6. Security Checklist & Maturity Roadmap
6.1 Quick Wins (Day 1)
6.2 Intermediate (Week 1-2)
6.3 Advanced (Month 1+)
6.4 Continuous Monitoring
// Security metrics collection
const securityMetrics = {
cspViolations: 0,
messageRejections: 0,
iframeLoadFailures: 0,
integrityCheckFailures: 0
};
// Report to monitoring system
setInterval(() => {
if (Object.values(securityMetrics).some(v => v > 0)) {
fetch('/api/security-metrics', {
method: 'POST',
body: JSON.stringify(securityMetrics)
});
// Reset counters
Object.keys(securityMetrics).forEach(k => securityMetrics[k] = 0);
}
}, 60000);
7. Common Pitfalls & Anti-Patterns
❌ Avoid These:
iframe sandbox="" (empty sandbox = no restrictions)
postMessage('*') (wildcard target origin)
eval() or new Function() in micro-frontends
- Trusting
event.source without origin check
- Storing sensitive data in localStorage/sessionStorage
- Using
allow-same-origin without additional CSP
- Overly permissive CSP
script-src 'unsafe-inline'
✅ Instead:
- Start with maximum sandbox restrictions, add only needed permissions
- Whitelist exact origins for communication
- Use CSP nonces/hashes instead of
unsafe-inline
- Validate message schema and origin on every message
- Use HTTP-only cookies for session data
- Implement defense-in-depth with multiple security layers
- Regularly update allowed origins list
8. Framework-Specific Considerations
React/Vue/Angular (SPA Micro-Frontends):
- Bundle runtime with framework (avoid framework CDN loading)
- Use
helmet (React) or equivalent for CSP management
- Disable
dangerouslySetInnerHTML/v-html unless absolutely needed
Web Components:
- Leverage Shadow DOM for style isolation
- Use
adoptedStyleSheets for controlled style sharing
- Avoid
innerHTML in custom elements
SSR Micro-Frontends:
- Sanitize all user-generated content before hydration
- Implement separate CSP for SSR response vs client-side
- Validate hydration boundaries
9. Incident Response
When security violation occurs:
- Immediate: Log full message details (origin, payload, stack trace)
- Contain: Block originating micro-frontend at load time via denylist
- Analyze: Check if it's targeted attack or supply chain issue
- Remediate: Update CSP, rotate secrets, patch dependencies
- Post-mortem: Update shared security contracts and checks
10. References & Tools
Remember: Security is a process, not a checklist. Regularly test your implementation with tools like OWASP ZAP, Burp Suite, and custom penetration testing focused on micro-frontend communication channels.
Last Updated: October 2023
Maintained by: Security Architecture Team
Review Cycle: Quarterly or after any security incident