implement CSRF protection by adding token generation, validation, and cookie management in login flows

This commit is contained in:
Eduardo Silva
2026-03-16 20:23:18 -03:00
parent ebbffca21d
commit ca63b87123
8 changed files with 214 additions and 24 deletions

View File

@@ -1,3 +1,4 @@
import importlib.util
import tempfile
import unittest
from pathlib import Path
@@ -8,6 +9,13 @@ from auth_gateway.services.policy_engine import build_effective_policy, evaluate
from auth_gateway.services.resolver import resolve_request_context
from auth_gateway.services.totp_service import verify_totp
_PROCESS_CONFIG_PATH = Path(__file__).resolve().parents[2] / "caddy" / "process_config.py"
_PROCESS_CONFIG_SPEC = importlib.util.spec_from_file_location("caddy_process_config", _PROCESS_CONFIG_PATH)
_PROCESS_CONFIG_MODULE = importlib.util.module_from_spec(_PROCESS_CONFIG_SPEC)
assert _PROCESS_CONFIG_SPEC and _PROCESS_CONFIG_SPEC.loader
_PROCESS_CONFIG_SPEC.loader.exec_module(_PROCESS_CONFIG_MODULE)
build_caddyfile = _PROCESS_CONFIG_MODULE.build_caddyfile
class AuthGatewayConfigTests(unittest.TestCase):
def test_existing_config_loads_and_resolves_routes(self):
@@ -58,6 +66,40 @@ class AuthGatewayConfigTests(unittest.TestCase):
token = pyotp.TOTP(secret).now()
self.assertTrue(verify_totp(secret, token))
def test_caddyfile_uses_boundary_matchers_and_clears_identity_headers(self):
caddyfile = build_caddyfile(
apps=[
{
"id": "app-one",
"hosts": ["app.example.com"],
"upstream": "http://backend:8080",
}
],
auth_policies={
"policies": {
"public": {"policy_type": "bypass"},
"protected": {"policy_type": "protected"},
}
},
routes={
"entries": {
"app-one": {
"routes": [
{"path_prefix": "/public", "policy": "public"},
],
"default_policy": "protected",
}
}
},
)
self.assertIn("@route_app_one_0 {", caddyfile)
self.assertIn("path /public /public/*", caddyfile)
self.assertIn("request_header -X-Auth-User", caddyfile)
self.assertIn("request_header -X-Auth-Email", caddyfile)
self.assertIn("handle @route_app_one_0 {", caddyfile)
self.assertNotIn("handle /public*", caddyfile)
if __name__ == "__main__":
unittest.main()