feat: implement local KeyForge MVP with verified integration
This commit is contained in:
95
beispiele/beispieldienst/app.py
Normal file
95
beispiele/beispieldienst/app.py
Normal file
@ -0,0 +1,95 @@
|
||||
"""Zweck: Sprachunabhängige KeyForge-Referenzintegration; Version: 1.
|
||||
|
||||
Der lokale Rust-Client entscheidet über Tokens. Der Dienst setzt selbst Rechte
|
||||
durch. Selbsttest: python -m unittest discover -s beispiele/beispieldienst.
|
||||
Keine Aufrufdaten oder Geheimnisse protokollieren; uvicorn ohne Zugriffslog.
|
||||
"""
|
||||
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import httpx
|
||||
from fastapi import FastAPI, Header, HTTPException
|
||||
|
||||
|
||||
def anwendung_erstellen(pruefadresse=None, transport=None):
|
||||
"""Erstellt eine Anwendung mit ausschließlich lokaler Prüfstelle."""
|
||||
adresse = pruefadresse or os.environ.get(
|
||||
"KEYFORGE_PRUEFADRESSE", "http://127.0.0.1:8790"
|
||||
)
|
||||
teile = urlsplit(adresse)
|
||||
if (teile.scheme != "http" or teile.hostname not in
|
||||
{"127.0.0.1", "::1", "localhost"} or teile.username or
|
||||
teile.password or teile.query or teile.fragment or
|
||||
teile.path not in {"", "/"}):
|
||||
raise ValueError("Die Prüfstelle muss eine lokale HTTP-Adresse sein.")
|
||||
|
||||
@asynccontextmanager
|
||||
async def lebensdauer(app):
|
||||
async with httpx.AsyncClient(
|
||||
base_url=adresse, timeout=2, transport=transport, trust_env=False
|
||||
) as client:
|
||||
app.state.client = client
|
||||
yield
|
||||
|
||||
app = FastAPI(title="KeyForge-Beispieldienst", lifespan=lebensdauer)
|
||||
|
||||
async def pruefen(authorization, recht):
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(401, "Bearer-Token fehlt.")
|
||||
token = authorization[7:]
|
||||
if not token or len(token) > 4096 or any(c.isspace() for c in token):
|
||||
raise HTTPException(401, "Token ungültig.")
|
||||
try:
|
||||
antwort = await app.state.client.post(
|
||||
"/v1/pruefen", json={"token": token}
|
||||
)
|
||||
if antwort.status_code != 200:
|
||||
raise HTTPException(503, "Prüfstelle nicht bereit.")
|
||||
daten = antwort.json()
|
||||
if not isinstance(daten, dict):
|
||||
raise ValueError()
|
||||
if daten.get("gueltig") is False:
|
||||
raise HTTPException(401, "Token ungültig.")
|
||||
rechte = daten.get("berechtigungen")
|
||||
if (daten.get("gueltig") is not True or
|
||||
not isinstance(rechte, list) or
|
||||
not all(isinstance(r, str) for r in rechte) or
|
||||
not isinstance(daten.get("token_id"), str)):
|
||||
raise ValueError()
|
||||
if recht not in rechte:
|
||||
raise HTTPException(403, "Berechtigung fehlt.")
|
||||
return daten
|
||||
except (httpx.HTTPError, ValueError, TypeError):
|
||||
raise HTTPException(503, "Prüfstelle nicht bereit.") from None
|
||||
|
||||
@app.get("/lesen")
|
||||
async def lesen(authorization: str | None = Header(default=None)):
|
||||
daten = await pruefen(authorization, "lesen")
|
||||
return {"nachricht": "Lesen erlaubt.", "token_id": daten["token_id"]}
|
||||
|
||||
@app.post("/schreiben")
|
||||
async def schreiben(
|
||||
authorization: str | None = Header(default=None)
|
||||
):
|
||||
daten = await pruefen(authorization, "schreiben")
|
||||
return {
|
||||
"nachricht": "Schreiben erlaubt.", "token_id": daten["token_id"]
|
||||
}
|
||||
|
||||
@app.get("/v1/gesundheit")
|
||||
async def gesundheit():
|
||||
try:
|
||||
antwort = await app.state.client.get("/v1/status")
|
||||
if (antwort.status_code == 200 and
|
||||
antwort.json().get("bereit") is True):
|
||||
return {"status": "ok"}
|
||||
except (httpx.HTTPError, ValueError, AttributeError):
|
||||
pass
|
||||
raise HTTPException(503, "Prüfstelle nicht bereit.")
|
||||
|
||||
return app
|
||||
|
||||
|
||||
app = anwendung_erstellen()
|
||||
Reference in New Issue
Block a user