乐闻世界logo
搜索文章和话题

How to ensure security in Module Federation? What are the security best practices?

2026年2月19日 17:45

Security is an important consideration for Module Federation. Here are the main security issues and protective measures:

1. Cross-Origin Resource Sharing (CORS) Security

Problem: Remote module loading involves cross-origin requests, which can be exploited maliciously.

Solution:

javascript
// Configure strict CORS policy devServer: { headers: { 'Access-Control-Allow-Origin': 'https://trusted-domain.com', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '86400' } } // Use whitelist in production const allowedOrigins = [ 'https://app1.example.com', 'https://app2.example.com' ] devServer: { setupMiddlewares: (middlewares, devServer) => { devServer.app.use((req, res, next) => { const origin = req.headers.origin if (allowedOrigins.includes(origin)) { res.setHeader('Access-Control-Allow-Origin', origin) } next() }) return middlewares } }

2. Content Security Policy (CSP)

Problem: Dynamically loaded scripts may violate CSP rules.

Solution:

html
<!-- Configure CSP header --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://trusted-cdn.com 'nonce-randomValue'; style-src 'self' 'unsafe-inline';"> <!-- Or in server configuration --> Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; object-src 'none'

3. Remote Module Verification

Problem: Loaded remote modules may be tampered with or contain malicious code.

Solution:

javascript
// Use Subresource Integrity (SRI) const loadRemoteModule = async (url, integrity) => { const response = await fetch(url) const content = await response.text() // Verify content integrity const computedHash = await crypto.subtle.digest( 'SHA-256', new TextEncoder().encode(content) ) const computedIntegrity = 'sha256-' + btoa(String.fromCharCode(...new Uint8Array(computedHash))) if (computedIntegrity !== integrity) { throw new Error('Module integrity check failed') } // Dynamically execute module const blob = new Blob([content], { type: 'application/javascript' }) const moduleUrl = URL.createObjectURL(blob) return import(moduleUrl) } // Usage example loadRemoteModule( 'https://cdn.example.com/remoteEntry.js', 'sha256-abc123...' )

4. Dependency Security Scanning

Problem: Shared dependencies may contain known vulnerabilities.

Solution:

bash
# Use npm audit to scan dependencies npm audit # Use Snyk for deep scanning npm install -g snyk snyk test # Integrate security scanning in CI/CD # .github/workflows/security.yml name: Security Scan on: [push, pull_request] jobs: security: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Run npm audit run: npm audit --audit-level=moderate - name: Run Snyk uses: snyk/actions/node@master env: SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}

5. Access Control

Problem: Remote modules may access resources they shouldn't.

Solution:

javascript
// Use sandbox to isolate remote modules class Sandbox { constructor() { this.context = Object.create(null) } execute(code) { const fn = new Function('context', ` with (context) { return (${code}) } `) return fn(this.context) } } // Restrict accessible global objects const sandbox = new Sandbox() sandbox.context.console = { log: (...args) => console.log('[Sandbox]', ...args) } // Proxy intercept access const secureProxy = new Proxy(target, { get(target, prop) { if (allowedProps.includes(prop)) { return target[prop] } throw new Error(`Access to ${prop} is not allowed`) } })

6. HTTPS and Certificate Verification

Problem: Man-in-the-middle attacks may cause remote modules to be tampered with.

Solution:

javascript
// Force HTTPS usage const secureFetch = async (url) => { if (!url.startsWith('https://')) { throw new Error('Only HTTPS URLs are allowed') } const response = await fetch(url, { credentials: 'omit', mode: 'cors' }) if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`) } return response } // Configure certificate pinning // Note: This needs to be implemented at the native application layer

7. Version Locking and Dependency Management

Problem: Dependency version drift may lead to security vulnerabilities.

Solution:

json
// package-lock.json ensures dependency version consistency { "lockfileVersion": 2, "dependencies": { "react": { "version": "17.0.2", "integrity": "sha512-..." } } } // Use npm shrinkwrap to lock dependencies npm shrinkwrap // Regularly update dependencies and audit npm update npm audit fix

8. Monitoring and Logging

Problem: Difficult to track remote module loading and execution.

Solution:

javascript
// Module loading monitoring const moduleLoadTracker = { track(moduleName, url, status, duration) { const event = { timestamp: Date.now(), moduleName, url, status, duration } // Send to monitoring system if (navigator.sendBeacon) { navigator.sendBeacon('/api/module-tracking', JSON.stringify(event)) } } } // Usage example const loadWithTracking = async (moduleName, url) => { const startTime = performance.now() try { const module = await import(url) moduleLoadTracker.track(moduleName, url, 'success', performance.now() - startTime) return module } catch (error) { moduleLoadTracker.track(moduleName, url, 'error', performance.now() - startTime) throw error } }

Best Practices Summary:

  1. Use HTTPS: All remote modules must be loaded via HTTPS
  2. Implement CSP: Configure strict content security policies
  3. Verify Integrity: Use SRI to verify remote module integrity
  4. Regular Audits: Regularly scan for dependency vulnerabilities
  5. Principle of Least Privilege: Restrict remote module access permissions
  6. Monitor Logs: Record all module loading events
  7. Version Locking: Use package-lock.json to lock dependency versions
  8. Whitelist Mechanism: Only allow trusted domains to load remote modules

Through these security measures, the security risks of Module Federation can be effectively reduced.

标签:Module Federation