|
| 1 | +"""Trusted-proxy authentication module for requests forwarded by a K8s proxy.""" |
| 2 | + |
| 3 | +from typing import cast |
| 4 | + |
| 5 | +import kubernetes.client |
| 6 | +from fastapi import HTTPException, Request |
| 7 | + |
| 8 | +from authentication.interface import NO_AUTH_TUPLE, AuthInterface, AuthTuple |
| 9 | +from authentication.k8s import get_user_info |
| 10 | +from authentication.utils import extract_user_token |
| 11 | +from configuration import configuration |
| 12 | +from constants import DEFAULT_VIRTUAL_PATH, NO_USER_TOKEN |
| 13 | +from log import get_logger |
| 14 | +from models.api.responses.error import ForbiddenResponse, UnauthorizedResponse |
| 15 | +from models.config import TrustedProxyConfiguration |
| 16 | + |
| 17 | +logger = get_logger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +class TrustedProxyAuthDependency( |
| 21 | + AuthInterface |
| 22 | +): # pylint: disable=too-few-public-methods |
| 23 | + """FastAPI dependency for trusted-proxy authentication. |
| 24 | +
|
| 25 | + Validates that the caller is an expected Kubernetes ServiceAccount |
| 26 | + via TokenReview, then extracts the end user's identity from a |
| 27 | + configurable HTTP header set by the proxy. |
| 28 | + """ |
| 29 | + |
| 30 | + def __init__( |
| 31 | + self, |
| 32 | + config: TrustedProxyConfiguration, |
| 33 | + virtual_path: str = DEFAULT_VIRTUAL_PATH, |
| 34 | + ) -> None: |
| 35 | + """Initialize the trusted-proxy authentication dependency. |
| 36 | +
|
| 37 | + Parameters: |
| 38 | + ---------- |
| 39 | + config: Trusted-proxy configuration with user header |
| 40 | + and optional SA allowlist. |
| 41 | + virtual_path: The request path used for authorization checks; |
| 42 | + defaults to DEFAULT_VIRTUAL_PATH. |
| 43 | + """ |
| 44 | + self.config = config |
| 45 | + self.virtual_path = virtual_path |
| 46 | + self.skip_userid_check = True |
| 47 | + |
| 48 | + async def __call__(self, request: Request) -> AuthTuple: |
| 49 | + """Validate the proxy's SA token and extract forwarded user identity. |
| 50 | +
|
| 51 | + Parameters: |
| 52 | + ---------- |
| 53 | + request: The FastAPI request object. |
| 54 | +
|
| 55 | + Returns: |
| 56 | + ------- |
| 57 | + AuthTuple with the forwarded user identity. |
| 58 | +
|
| 59 | + Raises: |
| 60 | + ------ |
| 61 | + HTTPException: If authentication fails. |
| 62 | + """ |
| 63 | + if not request.headers.get("Authorization"): |
| 64 | + if configuration.authentication_configuration.skip_for_health_probes: |
| 65 | + if request.url.path in ("/readiness", "/liveness"): |
| 66 | + return NO_AUTH_TUPLE |
| 67 | + if configuration.authentication_configuration.skip_for_metrics: |
| 68 | + if request.url.path == "/metrics": |
| 69 | + return NO_AUTH_TUPLE |
| 70 | + response = UnauthorizedResponse(cause="Missing Authorization header") |
| 71 | + raise HTTPException(**response.model_dump()) |
| 72 | + |
| 73 | + token = extract_user_token(request.headers) |
| 74 | + user_info = get_user_info(token) |
| 75 | + |
| 76 | + if user_info is None: |
| 77 | + response = UnauthorizedResponse( |
| 78 | + cause="Invalid or expired proxy service account token" |
| 79 | + ) |
| 80 | + raise HTTPException(**response.model_dump()) |
| 81 | + |
| 82 | + user = cast(kubernetes.client.V1UserInfo, user_info.user) |
| 83 | + if not user or not hasattr(user, "username"): |
| 84 | + response = UnauthorizedResponse( |
| 85 | + cause="Invalid service account token: missing user information" |
| 86 | + ) |
| 87 | + raise HTTPException(**response.model_dump()) |
| 88 | + |
| 89 | + sa_username = cast(str, user.username) |
| 90 | + if not sa_username: |
| 91 | + response = UnauthorizedResponse( |
| 92 | + cause="Invalid service account token: missing username" |
| 93 | + ) |
| 94 | + raise HTTPException(**response.model_dump()) |
| 95 | + |
| 96 | + if self.config.allowed_service_accounts: |
| 97 | + allowed = { |
| 98 | + f"system:serviceaccount:{sa.namespace}:{sa.name}" |
| 99 | + for sa in self.config.allowed_service_accounts |
| 100 | + } |
| 101 | + if sa_username not in allowed: |
| 102 | + logger.warning( |
| 103 | + "Service account '%s' is not in the trusted-proxy allowlist", |
| 104 | + sa_username, |
| 105 | + ) |
| 106 | + response = ForbiddenResponse.endpoint(user_id=sa_username) |
| 107 | + raise HTTPException(**response.model_dump()) |
| 108 | + |
| 109 | + forwarded_user = (request.headers.get(self.config.user_header) or "").strip() |
| 110 | + if not forwarded_user: |
| 111 | + response = UnauthorizedResponse( |
| 112 | + cause=f"Missing required header '{self.config.user_header}'" |
| 113 | + ) |
| 114 | + raise HTTPException(**response.model_dump()) |
| 115 | + |
| 116 | + logger.debug( |
| 117 | + "Trusted-proxy auth: proxy='%s', forwarded_user='%s'", |
| 118 | + sa_username, |
| 119 | + forwarded_user, |
| 120 | + ) |
| 121 | + |
| 122 | + return ( |
| 123 | + forwarded_user, |
| 124 | + forwarded_user, |
| 125 | + self.skip_userid_check, |
| 126 | + NO_USER_TOKEN, |
| 127 | + ) |
0 commit comments