API Security Training

Exercise: The Secure Header

In this activity, you will configure Content Security Policy (CSP) headers to prevent unauthorized scripts from executing.

Scenario: Your API is returning a webpage that has a Cross-Site Scripting (XSS) bug. We cannot fix the code bug right now, so we must block the attack at the Browser Level.

An attacker is trying to load: <script src="http://evil.com/hack.js">.

Your Task

Update the get_security_headers function:

  1. Add a new key: "Content-Security-Policy".
  2. Set the value to: "default-src 'self'".
  3. This instructs the browser to only trust scripts coming from your own domain.

Why Headers?

Modern security is often about "Defense in Depth". Even if your code has bugs, good headers can prevent the bugs from being exploited.

PYTHON EDITOR (middleware.py) Engine: Initializing...
1
BROWSER CONSOLE SIMULATION
Waiting for server headers...
from js import window, document window.python_is_ready = True try: document.getElementById("engine-status").innerHTML = "Engine: Python Active" except: pass def python_test_logic(user_code): results = [] def add_log(msg, type="normal"): results.append({"msg": msg, "type": type}) add_log("[SYSTEM] Inspecting HTTP Headers...", "system") test_env = {} try: exec(user_code, test_env) if "get_security_headers" not in test_env: add_log("[!] Error: Function 'get_security_headers' not found.", "fail") return results, "FAILED" headers = test_env["get_security_headers"]() if not isinstance(headers, dict): add_log("[!] Error: Function must return a dictionary.", "fail") return results, "FAILED" # Normalize keys to lowercase for checking headers_lower = {k.lower(): v for k, v in headers.items()} # TEST 1: Check for CSP Key add_log("--- TEST 1: Header Presence ---", "system") if "content-security-policy" not in headers_lower: add_log(" -> FAIL: CSP Header missing entirely.", "fail") add_log(" [Browser] Script from 'evil.com' executed!", "fail") return results, "FAILED" else: add_log(" -> PASS: CSP Header found.", "pass") # TEST 2: Check Value add_log("--- TEST 2: Policy Strength ---", "system") val = headers_lower["content-security-policy"] if "default-src 'self'" in val: add_log(f" -> PASS: Policy '{val}' allows self only.", "pass") add_log(" [Browser] Blocked loading resource from 'http://evil.com/hack.js'", "pass") add_log(" SUCCESS: Attack Mitigated.", "pass") return results, "PASSED - Secure" elif "'none'" in val: add_log(" -> PASS: Strict 'none' policy detected.", "pass") return results, "PASSED - Secure" else: add_log(f" -> FAIL: Policy '{val}' is too weak or incorrect.", "fail") add_log(" [Browser] 'evil.com' might still be allowed.", "fail") return results, "FAILED" except Exception as e: add_log(f"[!] Runtime Error: {e}", "fail") return results, "ERROR" return results, "UNKNOWN" window.python_test_runner = python_test_logic