File size: 1,584 Bytes
ee446e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""Security headers on every response (app/middleware/security_headers.py).

These are defense-in-depth against content sniffing, clickjacking and
referrer leakage — the assertions pin presence and value, not placement.
"""

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from app.middleware.security_headers import SecurityHeadersMiddleware


@pytest.fixture()
def client() -> TestClient:
    app = FastAPI()
    app.add_middleware(SecurityHeadersMiddleware)

    @app.get("/anything")
    def anything() -> dict[str, bool]:
        return {"ok": True}

    return TestClient(app)


def test_headers_present_on_json_response(client: TestClient) -> None:
    resp = client.get("/anything")
    assert resp.headers["X-Content-Type-Options"] == "nosniff"
    assert resp.headers["X-Frame-Options"] == "DENY"
    assert resp.headers["Referrer-Policy"] == "strict-origin-when-cross-origin"


def test_headers_do_not_override_existing_values(client: TestClient) -> None:
    app = FastAPI()
    app.add_middleware(SecurityHeadersMiddleware)

    @app.get("/preset")
    def preset() -> dict[str, bool]:
        return {"ok": True}

    @app.middleware("http")
    async def set_frame_header(request, call_next):  # type: ignore[no-untyped-def]
        response = await call_next(request)
        # An endpoint that deliberately frames itself keeps its value.
        response.headers["X-Frame-Options"] = "SAMEORIGIN"
        return response

    with TestClient(app) as c:
        assert c.get("/preset").headers["X-Frame-Options"] == "SAMEORIGIN"