Skip to content

Commit

Permalink
X-API-key header introduced and users for all routes except for the…
Browse files Browse the repository at this point in the history
… health check

- `config.yaml` extended with `authentication > api_key`, which is mandatory to set!
- `CustomBaseModel` now uses string literal for `extra` with `forbid`
  • Loading branch information
bulletinmybeard committed Mar 30, 2024
1 parent 3b98176 commit 67a89bf
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 8 deletions.
19 changes: 14 additions & 5 deletions audit_logger/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
from contextlib import asynccontextmanager
from typing import Any, AsyncGenerator, Dict, List, Optional, cast

from fastapi import Body, FastAPI, HTTPException
from fastapi import Body, Depends, FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.security import APIKeyHeader

from audit_logger.config_manager import ConfigManager
from audit_logger.custom_logger import get_logger
Expand Down Expand Up @@ -63,12 +64,20 @@ async def lifespan(_: Any) -> AsyncGenerator[None, None]:
lifespan=lifespan,
)

api_key_header = APIKeyHeader(name="X-API-Key")

app.add_exception_handler(RequestValidationError, validation_exception_handler)

add_middleware(app, app_config)


@app.post("/create")
async def verify_api_key(api_key: str = Depends(api_key_header)):
if api_key != app_config.authentication.api_key:
raise HTTPException(status_code=401, detail="Invalid API-Key")
return api_key


@app.post("/create", dependencies=[Depends(verify_api_key)])
async def create_audit_log_entry(
audit_log: AuditLogEntry = Body(...),
) -> GenericResponse:
Expand All @@ -92,7 +101,7 @@ async def create_audit_log_entry(
)


@app.post("/create-bulk")
@app.post("/create-bulk", dependencies=[Depends(verify_api_key)])
async def create_bulk_audit_log_entries(
audit_logs: List[AuditLogEntry] = Body(...),
) -> GenericResponse:
Expand All @@ -119,7 +128,7 @@ async def create_bulk_audit_log_entries(
)


@app.post("/create/create-bulk-auto")
@app.post("/create/create-bulk-auto", dependencies=[Depends(verify_api_key)])
async def create_fake_audit_log_entries(
options: BulkAuditLogOptions,
) -> GenericResponse:
Expand All @@ -139,7 +148,7 @@ async def create_fake_audit_log_entries(
)


@app.post("/search")
@app.post("/search", dependencies=[Depends(verify_api_key)])
def search_audit_log_entries(
params: Optional[SearchParamsV2] = Body(default=None),
) -> SearchResults:
Expand Down
9 changes: 8 additions & 1 deletion audit_logger/models/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,14 @@ class APIMiddlewares(CustomBaseModel):
cors: CORSSettings = Field(description="CORS middleware settings")


class Authentication(CustomBaseModel):
api_key: str = Field(description="X-API Key")


class AppConfig(CustomBaseModel):
middlewares: Optional[APIMiddlewares] = Field(
description="API Middlewares settings",
description="API middlewares settings",
)
authentication: Authentication = Field(
description="API authentication settings",
)
4 changes: 2 additions & 2 deletions audit_logger/models/custom_base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Any

from pydantic import BaseModel, Extra
from pydantic import BaseModel


class CustomBaseModel(BaseModel):
Expand All @@ -9,4 +9,4 @@ def __init__(self, **kwargs: Any) -> None:

# Forbid extra fields and raise an exception if any are found.
class Config:
extra = Extra.forbid
extra = "forbid"
2 changes: 2 additions & 0 deletions config-sample.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
authentication:
api_key: "change-me-plz"
middlewares:
cors:
allow_origins:
Expand Down

0 comments on commit 67a89bf

Please sign in to comment.