Hmm, the user is asking for a structured security audit plan for a Service Worker, specifically focusing on three high-risk areas: XSS threat modeling, cache poisoning, and update race conditions. This is a technical request that requires a systematic approach.
First, I need to break down each threat area into actionable steps. For XSS, the Service Worker's role in request/response handling makes it a critical vector. I should emphasize payload interception and DOM exposure risks. Cache poisoning requires analyzing caching logic and validation layers—especially where dynamic content meets static caching. Update race conditions are subtle; the user needs to understand the timing vulnerabilities during SW installation/activation.
The response should be organized but not overly verbose. A phased approach (scoping, testing, remediation) will help the user implement it. I’ll include concrete testing techniques (proxy tools, payloads, race condition simulation) and prioritize critical fixes. The goal is to balance depth with usability—avoiding academic jargon while ensuring technical rigor.
Also, the user might be a dev or security engineer, so I’ll assume familiarity with SW lifecycle terms but clarify nuances (e.g., skipWaiting() vs clients.claim()). I’ll avoid generic advice and tie each step to the three named threats. Tools like Mitmproxy and Chrome DevTools are worth mentioning since they’re industry standard.
Finally, I’ll stress that this is iterative—security audits aren’t one-off. The user should treat this as a living process, especially given SWs’ persistent nature.
Excellent. A focused security audit on these three vectors is crucial because Service Workers (SW) operate with elevated privileges, persist across sessions, and mediate all network traffic for their scope. A vulnerability here compromises the entire origin.
Here is a comprehensive, actionable plan for a Service Worker security audit covering XSS Threat Modeling, Cache Poisoning, and Update Race Conditions.
Service Worker Security Audit Plan
Objective: Systematically identify, validate, and remediate vulnerabilities in the Service Worker implementation that could lead to Cross-Site Scripting (XSS) escalation, cache poisoning, or update race condition exploits.
Auditor Mindset: Assume the SW is already installed on a victim's browser. Your goal is to model how an attacker could manipulate or exploit it from that point forward.
Phase 1: Reconnaissance & Scoping (Understanding the Target)
-
Map the SW Lifecycle & Scope:
- Locate the registration script (
navigator.serviceWorker.register('/sw.js')).
- Identify the scope (e.g.,
/ or /app/). This defines the attack surface.
- Analyze the
install, activate, and fetch event handlers.
- Document all caches used (
caches.open('my-cache-v1')).
-
Inventory Network Endpoints:
- List all API endpoints, static asset URLs (JS, CSS, images), and HTML pages the SW intercepts.
- Categorize them: Dynamic (user-specific, API) vs. Static (versioned assets).
- Identify any third-party origins the SW communicates with (CDNs, analytics, APIs).
-
Review Cache Strategy Logic:
- For each intercepted request, document the caching strategy:
CacheFirst (static assets)
NetworkFirst (dynamic content/API)
StaleWhileRevalidate
- Custom logic.
- Note cache keys (usually
request.url) and any request modification (e.g., adding headers, changing the URL for caching).
Phase 2: Deep Dive & Threat Modeling (The Three Vectors)
A. XSS Threat Modeling & Exploitation via SW
Core Threat: The SW becomes an XSS amplification and persistence vector. An existing DOM-based or reflected XSS flaw can be weaponized to hijack the SW or manipulate its responses.
Audit Steps:
- Payload Interception Analysis:
- Can the SW's
fetch handler modify responses before they reach the page?
- Does it use
Response.text()/.json() and then re-wrap content? This is a major red flag. If yes:
- Test: Can you inject a script tag into an API JSON response that the SW will then serve to a victim? (e.g., SW fetches
/api/user/name, returns {"name": "<script>stealCookie()</script>"}).
- Check for Context-aware sanitization. Is the injected content placed into an HTML context (
innerHTML) or a JS context? SWs are notorious for creating new XSS contexts.
- Client-Side Request Forgery (CSRF) via SW:
- The SW makes authenticated requests (
fetch with credentials: 'include'). Can an attacker on a malicious page trick the user's SW into making a state-changing request to your origin?
- Test: From
evil.com, open an image tag pointing to a POST endpoint on your origin (<img src="https://your-site.com/api/transfer?to=attacker&amount=1000">). Will the user's SW, running in the background, process this as a valid POST with cookies?
- SW as a Script Injection Surface:
- Does the SW dynamically evaluate code based on network responses? (e.g.,
eval(response), new Function(), importScripts(url) where url is attacker-influenced).
- Test: Can you control a cache key or URL that gets passed to
importScripts()?
- DOM Exposure Through PostMessage:
- Does the SW use
postMessage? Are messages validated with event.origin? Is the message content trusted and used dangerously (e.g., eval)?
B. Cache Poisoning (Path Traversal, Parameter Pollution, Key Confusion)
Core Threat: An attacker causes the SW to store a malicious response in a cache under a legitimate URL's key, serving it to all future victims.
Audit Steps:
- Cache Key Normalization Check:
- Does the SW use
request.url directly as the cache key? This is standard but vulnerable.
- Test - Path Traversal in Cache Key: Can you inject
../ or URL-encoded variants (..%2f) into a cacheable request URL that will be normalized by the server but not by the SW's cache? If the server returns different content for /static/app.js and /static/../app.js, and the SW caches both separately, you can poison one with malicious JS.
- Test - Parameter Pollution: Does the cache key ignore irrelevant query parameters? Request
/api/data?user=123 (cached). Then request /api/data?user=123&x=malicious. If both hit the same cache entry, you cannot poison. If they are different keys, and the server ignores x, you might be able to poison the x-variant and trick a victim into loading it.
- Dynamic Content Caching (The Biggest Risk):
- Rule: Never cache authenticated/user-specific responses with
CacheFirst or even StaleWhileRevalidate. This is the golden rule.
- Test all
NetworkFirst/CacheOnly endpoints for user-specific data (profile pages, dashboards). Can you force the SW to cache a response for user A and serve it to user B?
- Simulate: Make a request as User A that returns sensitive data. Then, as User B, make the same request. Does User B get User A's data from cache?
- Third-Party Origin Cache Confusion:
- If the SW caches responses from
cdn.example.com/lib.js, can an attacker on your-site.com cause the SW to cache a malicious response from cdn.example.com? This requires compromising the third-party origin or a man-in-the-middle (MitM). Assess the trust model.
- Cache Invalidation Logic:
- How does the SW know when to delete old caches (
caches.delete('old-cache'))? Is it based on a version in a manifest file?
- Test - Race Condition in Invalidation: Can you trigger two SW updates rapidly (see Phase 2.C) to cause an old, vulnerable cache to persist?
C. Update Race Conditions
Core Threat: During SW installation/activation (install/activate events), a timing window exists where old and new SWs, or multiple clients, can interact inconsistently, leading to security bypasses or cache poisoning.
Audit Steps:
skipWaiting() & clients.claim() Misuse:
- Does the SW immediately call
self.skipWaiting() in install? This is aggressive.
- Test: While a new SW is installing (but not yet activated), open two tabs. Tab 1 makes a request before activation (handled by old SW). Tab 2 makes a request after activation (handled by new SW). Is there a difference in security policy (e.g., CORS, CSP) or caching behavior between the two? This is a race condition.
- Race in
fetch Handler Logic:
- Does the
fetch handler rely on a global mutable state (e.g., a variable set during install that lists allowed URLs)?
- Test: Trigger a SW update. During the brief overlap, can a request bypass a new validation rule because the old SW's handler is still running with old logic?
- Cache Migration Race:
- In the
activate event, does the SW delete old caches (caches.delete('cache-v1'))?
- Test: Flood the app with requests immediately after a new SW activates. Can a request be served from the old cache (which the new SW intends to delete) before the deletion completes? If the old cache contains vulnerable/poisoned content, this is a rollback attack.
- Service Worker Update Bypass:
- Does the app have a mechanism to force-update the SW (e.g., a "Update" button that calls
registration.update())? Is this endpoint itself protected against CSRF? An attacker could prevent a security fix from deploying.
Phase 3: Validation & Exploitation (Hands-On Testing)
Tooling:
- Chrome DevTools > Application > Service Workers: Inspect lifecycle, source, cache storage.
- Chrome DevTools > Network: Disable cache, throttle network to simulate race conditions.
- Mitmproxy / Burp Suite: Intercept and modify requests/responses before they reach the SW. This is critical for testing cache poisoning and XSS payload injection.
- Custom Middleware: Run a local server that can inject payloads into JSON/HTML responses based on specific request patterns to test SW logic.
Test Protocol for Each Vector:
- XSS via SW: Inject a harmless payload (
<img src=x onerror=console.log('XSS-VIA-SW')>). Use the browser console to see if it logs when a victim page loads.
- Cache Poisoning: Use Mitmproxy to serve a unique malicious response (with a unique token) for a specific cacheable URL. Trigger a request to that URL. Then, from a "clean" session, request the same URL. Does the unique token appear?
- Update Race: Use DevTools to manually update the SW (
Update on reload). Rapidly reload the page multiple times. Monitor which version of the SW is active (navigator.serviceWorker.controller). Observe cache contents (caches.keys()) during the transition.
Phase 4: Remediation & Hardening Recommendations
Prioritize findings by Impact & Likelihood.
General SW Best Practices (Apply Always):
- Use
importScripts() with versioned, integrity-checked URLs.
- Never use
eval() or new Function().
- Always validate
event.origin on postMessage.
- Set a strict
Content-Security-Policy (CSP) on the page, especially script-src 'self'. This is your last line of defense against SW-served XSS.
Specific Remediations:
| Vulnerability | Remediation |
|---|
| XSS via Response Modification | Stop modifying responses. Use the SW for caching and routing only. Perform any DOM manipulation in the page's own JavaScript. If you must modify, use a safe, context-aware HTML sanitizer (DOMPurify) inside the SW. |
| Dynamic Content Caching | **For any request with credentials: 'include' or private data, use NetworkOnly or a NetworkFirst with a very short networkTimeout and no caching of the response (cache.put() should be called conditionally only for safe, public data). |
| Cache Poisoning (Key Confusion) | Normalize the cache key. Create a canonical URL (strip irrelevant query parameters, normalize path) before using it as a cache key. Alternatively, cache by a hash of the relevant request properties. |
| Update Race Conditions | Do not use skipWaiting()/clients.claim() aggressively. Let the new SW activate on the next navigation after all tabs are closed. If you must use them, ensure backward-compatible behavior for a transition period. In activate, delete old caches synchronously and immediately. |
| CSRF via SW | Implement a CSRF token double-submit cookie pattern that is checked by your server. The SW cannot prevent this; the server must reject state-changing requests without a valid token. Ensure the SW does not strip these tokens. |
Phase 5: Reporting & Continuous Monitoring
- Document: For each finding: threat model, reproduction steps (with curl/Mitmproxy sequences), impact, and specific code location (
sw.js:line 42).
- Recommend: Provide a code snippet showing the secure alternative.
- Advocate for: A SW update policy (e.g., force update after 24h) and a cache versioning strategy (cache names must change with any SW update that alters cache logic).
- Future-Proofing: Recommend adding automated security tests for the SW using tools like
workbox-cli's audit (part of Workbox) or custom integration tests that simulate attacks.
Final Principle: Treat the Service Worker as a privileged network proxy. Its primary secure function is caching static assets and offline fallbacks. The moment it starts parsing or modifying dynamic, sensitive data is when complexity—and risk—skyrockets. Minimize its logic, maximize its simplicity.