|
| 1 | +"""Tests for security headers middleware.""" |
| 2 | + |
| 3 | +from http import HTTPStatus |
| 4 | + |
| 5 | +import pytest |
| 6 | +from flask import Flask |
| 7 | +from flask.testing import FlaskClient |
| 8 | +from hamcrest import assert_that, contains_string, equal_to, has_entries, is_ |
| 9 | + |
| 10 | +from eligibility_signposting_api.middleware import SecurityHeadersMiddleware |
| 11 | + |
| 12 | + |
| 13 | +class MiddlewareTestError(Exception): |
| 14 | + """Custom exception for middleware error handling tests.""" |
| 15 | + |
| 16 | + |
| 17 | +@pytest.fixture |
| 18 | +def test_app() -> Flask: |
| 19 | + """Create a test Flask app with security headers middleware.""" |
| 20 | + app = Flask(__name__) |
| 21 | + SecurityHeadersMiddleware(app) |
| 22 | + |
| 23 | + @app.route("/test") |
| 24 | + def test_route(): |
| 25 | + return {"status": "ok"}, HTTPStatus.OK |
| 26 | + |
| 27 | + @app.route("/error") |
| 28 | + def error_route(): |
| 29 | + msg = "Test error" |
| 30 | + raise MiddlewareTestError(msg) |
| 31 | + |
| 32 | + @app.errorhandler(MiddlewareTestError) |
| 33 | + def handle_value_error(e): |
| 34 | + return {"error": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR |
| 35 | + |
| 36 | + return app |
| 37 | + |
| 38 | + |
| 39 | +@pytest.fixture |
| 40 | +def client(test_app: Flask) -> FlaskClient: |
| 41 | + """Create a test client.""" |
| 42 | + return test_app.test_client() |
| 43 | + |
| 44 | + |
| 45 | +class TestSecurityHeadersMiddleware: |
| 46 | + """Test suite for SecurityHeadersMiddleware.""" |
| 47 | + |
| 48 | + def test_security_headers_present_on_successful_response(self, client: FlaskClient) -> None: |
| 49 | + """Test that security headers are added to successful responses.""" |
| 50 | + response = client.get("/test") |
| 51 | + |
| 52 | + assert_that(response.status_code, is_(equal_to(HTTPStatus.OK))) |
| 53 | + assert_that( |
| 54 | + dict(response.headers), |
| 55 | + has_entries( |
| 56 | + { |
| 57 | + "Cache-Control": "no-store, private", |
| 58 | + "Strict-Transport-Security": "max-age=31536000; includeSubDomains", |
| 59 | + "X-Content-Type-Options": "nosniff", |
| 60 | + } |
| 61 | + ), |
| 62 | + ) |
| 63 | + |
| 64 | + def test_security_headers_present_on_error_response(self, client: FlaskClient) -> None: |
| 65 | + """Test that security headers are added to error responses.""" |
| 66 | + response = client.get("/error") |
| 67 | + |
| 68 | + assert_that(response.status_code, is_(equal_to(HTTPStatus.INTERNAL_SERVER_ERROR))) |
| 69 | + assert_that( |
| 70 | + dict(response.headers), |
| 71 | + has_entries( |
| 72 | + { |
| 73 | + "Cache-Control": "no-store, private", |
| 74 | + "Strict-Transport-Security": "max-age=31536000; includeSubDomains", |
| 75 | + "X-Content-Type-Options": "nosniff", |
| 76 | + } |
| 77 | + ), |
| 78 | + ) |
| 79 | + |
| 80 | + def test_security_headers_present_on_404(self, client: FlaskClient) -> None: |
| 81 | + """Test that security headers are added to 404 responses.""" |
| 82 | + response = client.get("/nonexistent") |
| 83 | + |
| 84 | + assert_that(response.status_code, is_(equal_to(HTTPStatus.NOT_FOUND))) |
| 85 | + assert_that( |
| 86 | + dict(response.headers), |
| 87 | + has_entries( |
| 88 | + { |
| 89 | + "Cache-Control": "no-store, private", |
| 90 | + "Strict-Transport-Security": "max-age=31536000; includeSubDomains", |
| 91 | + "X-Content-Type-Options": "nosniff", |
| 92 | + } |
| 93 | + ), |
| 94 | + ) |
| 95 | + |
| 96 | + def test_all_expected_headers_are_present(self, client: FlaskClient) -> None: |
| 97 | + """Test that all expected security headers are present.""" |
| 98 | + response = client.get("/test") |
| 99 | + |
| 100 | + expected_headers = { |
| 101 | + "Cache-Control", |
| 102 | + "Strict-Transport-Security", |
| 103 | + "X-Content-Type-Options", |
| 104 | + } |
| 105 | + |
| 106 | + response_headers = set(response.headers.keys()) |
| 107 | + assert expected_headers.issubset(response_headers), ( |
| 108 | + f"Missing security headers: {expected_headers - response_headers}" |
| 109 | + ) |
| 110 | + |
| 111 | + def test_cache_control_prevents_caching(self, client: FlaskClient) -> None: |
| 112 | + """Test that Cache-Control header prevents caching of sensitive data.""" |
| 113 | + response = client.get("/test") |
| 114 | + |
| 115 | + cache_control = response.headers.get("Cache-Control") |
| 116 | + assert_that(cache_control, contains_string("no-store")) |
| 117 | + assert_that(cache_control, contains_string("private")) |
| 118 | + |
| 119 | + def test_hsts_header_enforces_https(self, client: FlaskClient) -> None: |
| 120 | + """Test that HSTS header is properly configured.""" |
| 121 | + response = client.get("/test") |
| 122 | + |
| 123 | + hsts = response.headers.get("Strict-Transport-Security") |
| 124 | + assert_that(hsts, contains_string("max-age=31536000")) |
| 125 | + assert_that(hsts, contains_string("includeSubDomains")) |
| 126 | + |
| 127 | + def test_content_type_options_prevents_sniffing(self, client: FlaskClient) -> None: |
| 128 | + """Test that X-Content-Type-Options prevents MIME sniffing.""" |
| 129 | + response = client.get("/test") |
| 130 | + |
| 131 | + content_type_options = response.headers.get("X-Content-Type-Options") |
| 132 | + assert_that(content_type_options, is_(equal_to("nosniff"))) |
| 133 | + |
| 134 | + def test_middleware_init_app_method(self) -> None: |
| 135 | + """Test that middleware can be initialized separately using init_app.""" |
| 136 | + app = Flask(__name__) |
| 137 | + middleware = SecurityHeadersMiddleware() |
| 138 | + middleware.init_app(app) |
| 139 | + |
| 140 | + @app.route("/test") |
| 141 | + def test_route(): |
| 142 | + return {"status": "ok"}, HTTPStatus.OK |
| 143 | + |
| 144 | + with app.test_client() as client: |
| 145 | + response = client.get("/test") |
| 146 | + assert_that(response.headers.get("Cache-Control"), is_(equal_to("no-store, private"))) |
| 147 | + |
| 148 | + def test_existing_headers_are_not_overridden(self) -> None: |
| 149 | + """Test that existing headers are not overridden by middleware.""" |
| 150 | + app = Flask(__name__) |
| 151 | + SecurityHeadersMiddleware(app) |
| 152 | + |
| 153 | + @app.route("/test") |
| 154 | + def test_route(): |
| 155 | + from flask import make_response |
| 156 | + |
| 157 | + resp = make_response({"status": "ok"}, HTTPStatus.OK) |
| 158 | + resp.headers["Cache-Control"] = "public, max-age=3600" |
| 159 | + return resp |
| 160 | + |
| 161 | + with app.test_client() as client: |
| 162 | + response = client.get("/test") |
| 163 | + # Should keep the custom Cache-Control value |
| 164 | + assert_that(response.headers.get("Cache-Control"), is_(equal_to("public, max-age=3600"))) |
| 165 | + # But other headers should still be added |
| 166 | + assert_that(response.headers.get("X-Content-Type-Options"), is_(equal_to("nosniff"))) |
0 commit comments