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()
|
||||
3
beispiele/beispieldienst/requirements.txt
Normal file
3
beispiele/beispieldienst/requirements.txt
Normal file
@ -0,0 +1,3 @@
|
||||
fastapi>=0.115,<1
|
||||
httpx>=0.27,<1
|
||||
uvicorn>=0.30,<1
|
||||
69
beispiele/beispieldienst/test_app.py
Normal file
69
beispiele/beispieldienst/test_app.py
Normal file
@ -0,0 +1,69 @@
|
||||
"""Zweck: Prüfstelle und Rechte der Referenzintegration testen; Version: 1.
|
||||
Selbsttest: python -m unittest discover -s beispiele/beispieldienst.
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
import httpx
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import anwendung_erstellen
|
||||
|
||||
|
||||
class PruefstelleTest(unittest.TestCase):
|
||||
"""Prüft echte HTTP-Grenzen mit kontrollierter Client-Antwort."""
|
||||
|
||||
def test_rechte_und_tokenweitergabe(self):
|
||||
def antwort(anfrage):
|
||||
self.assertEqual(anfrage.url.path, "/v1/pruefen")
|
||||
self.assertEqual(anfrage.content, b'{"token":"nur-im-test"}')
|
||||
return httpx.Response(200, json={
|
||||
"gueltig": True, "token_id": "t1", "bezeichnung": "Test",
|
||||
"berechtigungen": ["lesen"],
|
||||
})
|
||||
app = anwendung_erstellen(transport=httpx.MockTransport(antwort))
|
||||
with TestClient(app) as client:
|
||||
kopf = {"Authorization": "Bearer nur-im-test"}
|
||||
self.assertEqual(
|
||||
client.get("/lesen", headers=kopf).status_code, 200)
|
||||
self.assertEqual(
|
||||
client.post("/schreiben", headers=kopf).status_code, 403)
|
||||
self.assertEqual(client.get("/lesen").status_code, 401)
|
||||
|
||||
def test_ausfall_und_ungueltige_antwort(self):
|
||||
for status, daten, erwartet in [
|
||||
(503, {}, 503), (200, {"gueltig": False}, 401),
|
||||
(200, {"gueltig": True}, 503), (200, [], 503),
|
||||
]:
|
||||
with self.subTest(status=status, daten=daten):
|
||||
app = anwendung_erstellen(transport=httpx.MockTransport(
|
||||
lambda r: httpx.Response(status, json=daten)))
|
||||
with TestClient(app) as client:
|
||||
ergebnis = client.get("/lesen", headers={
|
||||
"Authorization": "Bearer geheim"})
|
||||
self.assertEqual(ergebnis.status_code, erwartet)
|
||||
self.assertNotIn("geheim", ergebnis.text)
|
||||
|
||||
def test_netzfehler(self):
|
||||
def antwort(anfrage):
|
||||
raise httpx.ConnectError("geheim", request=anfrage)
|
||||
app = anwendung_erstellen(transport=httpx.MockTransport(antwort))
|
||||
with TestClient(app) as client:
|
||||
ergebnis = client.get("/lesen", headers={
|
||||
"Authorization": "Bearer geheim"})
|
||||
self.assertEqual(ergebnis.status_code, 503)
|
||||
self.assertNotIn("geheim", ergebnis.text)
|
||||
|
||||
def test_gesundheit(self):
|
||||
app = anwendung_erstellen(transport=httpx.MockTransport(
|
||||
lambda r: httpx.Response(200, json={"bereit": True})))
|
||||
with TestClient(app) as client:
|
||||
self.assertEqual(client.get("/v1/gesundheit").status_code, 200)
|
||||
|
||||
def test_nur_lokale_pruefstelle(self):
|
||||
with self.assertRaises(ValueError):
|
||||
anwendung_erstellen("http://fremder-rechner:8790")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user