Add API key authentication.

We don't have any sensitive data, but we do access the file system. On
the off chance that some phishing website decides to try to use
Liberation as an attack vector, prevent access to the API by
unauthorized applications. An API key is generated at each program start
and passed to the front end via the QWebChannel.
This commit is contained in:
Dan Albert
2022-02-19 14:41:39 -08:00
parent 09457d8aab
commit 77d29e314c
5 changed files with 36 additions and 5 deletions

View File

@@ -1,7 +1,8 @@
from fastapi import FastAPI
from fastapi import Depends, FastAPI
from . import debuggeometries, eventstream
from .security import ApiKeyManager
app = FastAPI()
app = FastAPI(dependencies=[Depends(ApiKeyManager.verify)])
app.include_router(debuggeometries.router)
app.include_router(eventstream.router)

15
game/server/security.py Normal file
View File

@@ -0,0 +1,15 @@
import secrets
from fastapi import HTTPException, Security, status
from fastapi.security import APIKeyHeader
API_KEY_HEADER = APIKeyHeader(name="X-API-Key")
class ApiKeyManager:
KEY = secrets.token_urlsafe()
@classmethod
def verify(cls, api_key_header: str = Security(API_KEY_HEADER)) -> None:
if api_key_header != cls.KEY:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)