|
| 1 | +"""Basic Authentication Module.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | +import secrets |
| 6 | +from typing import Any, Dict |
| 7 | + |
| 8 | +from fastapi import Depends, HTTPException, Request, status |
| 9 | +from fastapi.routing import APIRoute |
| 10 | +from fastapi.security import HTTPBasic, HTTPBasicCredentials |
| 11 | +from typing_extensions import Annotated |
| 12 | + |
| 13 | +from stac_fastapi.api.app import StacApi |
| 14 | + |
| 15 | +security = HTTPBasic() |
| 16 | + |
| 17 | +_BASIC_AUTH: Dict[str, Any] = {} |
| 18 | + |
| 19 | + |
| 20 | +def has_access( |
| 21 | + request: Request, credentials: Annotated[HTTPBasicCredentials, Depends(security)] |
| 22 | +) -> str: |
| 23 | + """Check if the provided credentials match the expected \ |
| 24 | + username and password stored in environment variables for basic authentication. |
| 25 | +
|
| 26 | + Args: |
| 27 | + request (Request): The FastAPI request object. |
| 28 | + credentials (HTTPBasicCredentials): The HTTP basic authentication credentials. |
| 29 | +
|
| 30 | + Returns: |
| 31 | + str: The username if authentication is successful. |
| 32 | +
|
| 33 | + Raises: |
| 34 | + HTTPException: If authentication fails due to incorrect username or password. |
| 35 | + """ |
| 36 | + global _BASIC_AUTH |
| 37 | + |
| 38 | + users = _BASIC_AUTH.get("users") |
| 39 | + user: Dict[str, Any] = next( |
| 40 | + (u for u in users if u.get("username") == credentials.username), {} |
| 41 | + ) |
| 42 | + |
| 43 | + if not user: |
| 44 | + raise HTTPException( |
| 45 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 46 | + detail="Incorrect username or password", |
| 47 | + headers={"WWW-Authenticate": "Basic"}, |
| 48 | + ) |
| 49 | + |
| 50 | + # Compare the provided username and password with the correct ones using compare_digest |
| 51 | + if not secrets.compare_digest( |
| 52 | + credentials.username.encode("utf-8"), user.get("username").encode("utf-8") |
| 53 | + ) or not secrets.compare_digest( |
| 54 | + credentials.password.encode("utf-8"), user.get("password").encode("utf-8") |
| 55 | + ): |
| 56 | + raise HTTPException( |
| 57 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 58 | + detail="Incorrect username or password", |
| 59 | + headers={"WWW-Authenticate": "Basic"}, |
| 60 | + ) |
| 61 | + |
| 62 | + permissions = user.get("permissions", []) |
| 63 | + path = request.url.path |
| 64 | + method = request.method |
| 65 | + |
| 66 | + if permissions == "*": |
| 67 | + return credentials.username |
| 68 | + for permission in permissions: |
| 69 | + if permission["path"] == path and method in permission.get("method", []): |
| 70 | + return credentials.username |
| 71 | + |
| 72 | + raise HTTPException( |
| 73 | + status_code=status.HTTP_403_FORBIDDEN, |
| 74 | + detail=f"Insufficient permissions for [{method} {path}]", |
| 75 | + ) |
| 76 | + |
| 77 | + |
| 78 | +def apply_basic_auth(api: StacApi) -> None: |
| 79 | + """Apply basic authentication to the provided FastAPI application \ |
| 80 | + based on environment variables for username, password, and endpoints. |
| 81 | +
|
| 82 | + Args: |
| 83 | + api (StacApi): The FastAPI application. |
| 84 | +
|
| 85 | + Raises: |
| 86 | + HTTPException: If there are issues with the configuration or format |
| 87 | + of the environment variables. |
| 88 | + """ |
| 89 | + global _BASIC_AUTH |
| 90 | + |
| 91 | + basic_auth_json_str = os.environ.get("BASIC_AUTH") |
| 92 | + if not basic_auth_json_str: |
| 93 | + print("Basic authentication disabled.") |
| 94 | + return |
| 95 | + |
| 96 | + try: |
| 97 | + _BASIC_AUTH = json.loads(basic_auth_json_str) |
| 98 | + except json.JSONDecodeError as exception: |
| 99 | + print(f"Invalid JSON format for BASIC_AUTH. {exception=}") |
| 100 | + raise |
| 101 | + public_endpoints = _BASIC_AUTH.get("public_endpoints", []) |
| 102 | + users = _BASIC_AUTH.get("users") |
| 103 | + if not users: |
| 104 | + raise Exception("Invalid JSON format for BASIC_AUTH. Key 'users' undefined.") |
| 105 | + |
| 106 | + app = api.app |
| 107 | + for route in app.routes: |
| 108 | + if isinstance(route, APIRoute): |
| 109 | + for method in route.methods: |
| 110 | + endpoint = {"path": route.path, "method": method} |
| 111 | + if endpoint not in public_endpoints: |
| 112 | + api.add_route_dependencies([endpoint], [Depends(has_access)]) |
| 113 | + |
| 114 | + print("Basic authentication enabled.") |
0 commit comments