Compare commits
21
Commits
b29fb2f538
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c547027f2 | ||
|
|
53047b6c16 | ||
|
|
f8af47d1d5 | ||
|
|
9e271a1954 | ||
|
|
39e8084b1a | ||
|
|
4069cb0e01 | ||
|
|
eaa0e25524 | ||
|
|
910b1d7e07 | ||
|
|
f9c207c4f6 | ||
|
|
f8b3ae3011 | ||
|
|
7a5da57bb8 | ||
|
|
88792eeb47 | ||
|
|
598677d343 | ||
|
|
7a6eb3abe8 | ||
|
|
2f631f419a | ||
|
|
101376540a | ||
|
|
45a108b4a0 | ||
|
|
25d3976226 | ||
|
|
564008be13 | ||
|
|
7b96bab1c9 | ||
|
|
b5efdbbc2e |
No files matched your search
@@ -8,6 +8,11 @@
|
|||||||
# APP_URL=https://dev.kairo.jinkendo.de
|
# APP_URL=https://dev.kairo.jinkendo.de
|
||||||
# ALLOWED_ORIGINS=https://dev.kairo.jinkendo.de,http://192.168.2.49:3097
|
# ALLOWED_ORIGINS=https://dev.kairo.jinkendo.de,http://192.168.2.49:3097
|
||||||
# ENVIRONMENT=development
|
# ENVIRONMENT=development
|
||||||
|
# SESSION_DAYS=30
|
||||||
|
# KAIRO_BOOTSTRAP_ADMIN_EMAIL=admin@kairo.local
|
||||||
|
# KAIRO_BOOTSTRAP_ADMIN_PASSWORD=change-me-in-dev-env
|
||||||
|
# KAIRO_BOOTSTRAP_TENANT_SLUG=default
|
||||||
|
# KAIRO_BOOTSTRAP_TENANT_NAME=Default Tenant
|
||||||
|
|
||||||
# ─── PROD (docker-compose.yml) ───────────────────────────────────────────────
|
# ─── PROD (docker-compose.yml) ───────────────────────────────────────────────
|
||||||
DB_NAME=kairo
|
DB_NAME=kairo
|
||||||
|
|||||||
@@ -25,10 +25,15 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
docker compose -f docker-compose.dev-env.yml build --no-cache backend frontend
|
docker compose -f docker-compose.dev-env.yml build --no-cache backend frontend
|
||||||
echo "✓ Backend + Frontend gebaut (Frontend: npm run build im Dockerfile)"
|
echo "✓ Backend + Frontend gebaut (Frontend: npm run build im Dockerfile)"
|
||||||
docker compose -f docker-compose.dev-env.yml up -d --wait
|
if ! docker compose -f docker-compose.dev-env.yml up -d --wait; then
|
||||||
|
echo "✗ compose up --wait fehlgeschlagen — Backend-Logs:"
|
||||||
|
docker compose -f docker-compose.dev-env.yml logs backend --tail 150 || true
|
||||||
|
docker compose -f docker-compose.dev-env.yml ps || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
if ! curl -sf http://localhost:8097/api/health; then
|
if ! curl -sf http://localhost:8097/api/health; then
|
||||||
echo "✗ DEV API nicht erreichbar — Backend-Logs:"
|
echo "✗ DEV API nicht erreichbar — Backend-Logs:"
|
||||||
docker compose -f docker-compose.dev-env.yml logs backend --tail 120 || true
|
docker compose -f docker-compose.dev-env.yml logs backend --tail 150 || true
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "✓ DEV API /api/health OK"
|
echo "✓ DEV API /api/health OK"
|
||||||
|
|||||||
@@ -25,7 +25,17 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
docker compose build --no-cache backend frontend
|
docker compose build --no-cache backend frontend
|
||||||
echo "✓ Backend + Frontend gebaut (Frontend: npm run build im Dockerfile)"
|
echo "✓ Backend + Frontend gebaut (Frontend: npm run build im Dockerfile)"
|
||||||
docker compose up -d --wait
|
if ! docker compose up -d --wait; then
|
||||||
curl -sf http://localhost:8004/api/health && echo "✓ PROD API /api/health OK"
|
echo "✗ compose up --wait fehlgeschlagen — Backend-Logs:"
|
||||||
|
docker compose logs backend --tail 150 || true
|
||||||
|
docker compose ps || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if ! curl -sf http://localhost:8004/api/health; then
|
||||||
|
echo "✗ PROD API nicht erreichbar — Backend-Logs:"
|
||||||
|
docker compose logs backend --tail 150 || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "✓ PROD API /api/health OK"
|
||||||
curl -sf http://localhost:3004/api/health && echo "✓ PROD Frontend-Proxy /api/health OK"
|
curl -sf http://localhost:3004/api/health && echo "✓ PROD Frontend-Proxy /api/health OK"
|
||||||
echo "=== Kairo PROD Deploy complete ==="
|
echo "=== Kairo PROD Deploy complete ==="
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
name: Test Suite
|
name: Test Suite
|
||||||
|
|
||||||
# develop: push/PR → Tests gegen deployte Dev-Instanz (wartet auf Container).
|
# develop: push/PR → Tests gegen deployte Dev-Instanz (wartet auf Container).
|
||||||
# main: kein push/PR — Prod-Tests via workflow_run nach Deploy Production.
|
# main: push → Prod-Tests gegen kairo (8004/3004), parallel zu deploy-prod.yml.
|
||||||
|
# workflow_run: optional (Gitea/act feuert oft nicht — push-Trigger ist maßgeblich).
|
||||||
# Frontend-Build: deploy-dev/prod (docker compose build backend frontend), nicht hier.
|
# Frontend-Build: deploy-dev/prod (docker compose build backend frontend), nicht hier.
|
||||||
# compose-smoke (PR): eigener Stack auf CI-Ports 18197/13197 (kein Konflikt mit kairo-dev).
|
# compose-smoke (PR): eigener Stack auf CI-Ports 18197/13197 (kein Konflikt mit kairo-dev).
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [develop]
|
branches: [develop, main]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [develop]
|
branches: [develop]
|
||||||
workflow_run:
|
workflow_run:
|
||||||
@@ -33,11 +34,16 @@ jobs:
|
|||||||
APP_DIR="/home/lars/docker/kairo-dev"
|
APP_DIR="/home/lars/docker/kairo-dev"
|
||||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||||
fi
|
fi
|
||||||
|
elif [ "$REF_NAME" = "main" ]; then
|
||||||
|
APP_DIR="/home/lars/docker/kairo"
|
||||||
|
COMPOSE_FILE="docker-compose.yml"
|
||||||
elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
elif [ "$REF_NAME" = "develop" ] || [ "$BASE_REF" = "develop" ]; then
|
||||||
APP_DIR="/home/lars/docker/kairo-dev"
|
APP_DIR="/home/lars/docker/kairo-dev"
|
||||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
echo "pytest gegen ${APP_DIR} (${COMPOSE_FILE})"
|
||||||
|
|
||||||
cd "$APP_DIR"
|
cd "$APP_DIR"
|
||||||
echo "Warte auf stabilen backend-Container …"
|
echo "Warte auf stabilen backend-Container …"
|
||||||
for i in $(seq 1 60); do
|
for i in $(seq 1 60); do
|
||||||
@@ -56,7 +62,8 @@ jobs:
|
|||||||
|
|
||||||
docker compose -f "$COMPOSE_FILE" exec -T backend sh -lc "
|
docker compose -f "$COMPOSE_FILE" exec -T backend sh -lc "
|
||||||
pip install -q -r requirements-dev.txt &&
|
pip install -q -r requirements-dev.txt &&
|
||||||
python -m pytest tests -ra -vv --tb=short
|
python -m pytest tests -ra -vv --tb=short &&
|
||||||
|
python run_seeds.py --only seed_001_cleanup_pytest_artifacts --force
|
||||||
"
|
"
|
||||||
echo "✓ pytest OK"
|
echo "✓ pytest OK"
|
||||||
|
|
||||||
@@ -127,8 +134,11 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
EVENT="${{ github.event_name }}"
|
EVENT="${{ github.event_name }}"
|
||||||
WF_NAME="${{ github.event.workflow_run.name }}"
|
WF_NAME="${{ github.event.workflow_run.name }}"
|
||||||
|
REF="${{ github.ref_name }}"
|
||||||
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
||||||
echo "base_url=http://localhost:8004" >> $GITHUB_OUTPUT
|
echo "base_url=http://localhost:8004" >> $GITHUB_OUTPUT
|
||||||
|
elif [ "$REF" = "main" ]; then
|
||||||
|
echo "base_url=http://localhost:8004" >> $GITHUB_OUTPUT
|
||||||
else
|
else
|
||||||
echo "base_url=http://localhost:8097" >> $GITHUB_OUTPUT
|
echo "base_url=http://localhost:8097" >> $GITHUB_OUTPUT
|
||||||
fi
|
fi
|
||||||
@@ -190,8 +200,11 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
EVENT="${{ github.event_name }}"
|
EVENT="${{ github.event_name }}"
|
||||||
WF_NAME="${{ github.event.workflow_run.name }}"
|
WF_NAME="${{ github.event.workflow_run.name }}"
|
||||||
|
REF="${{ github.ref_name }}"
|
||||||
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
if [ "$EVENT" = "workflow_run" ] && [ "$WF_NAME" = "Deploy Production" ]; then
|
||||||
echo "base_url=http://localhost:3004" >> $GITHUB_OUTPUT
|
echo "base_url=http://localhost:3004" >> $GITHUB_OUTPUT
|
||||||
|
elif [ "$REF" = "main" ]; then
|
||||||
|
echo "base_url=http://localhost:3004" >> $GITHUB_OUTPUT
|
||||||
else
|
else
|
||||||
echo "base_url=http://localhost:3097" >> $GITHUB_OUTPUT
|
echo "base_url=http://localhost:3097" >> $GITHUB_OUTPUT
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -99,6 +99,111 @@ docker compose -f docker-compose.dev-env.yml exec backend python -m pytest tests
|
|||||||
|
|
||||||
UI: http://localhost:3097 · API: http://localhost:8097
|
UI: http://localhost:3097 · API: http://localhost:8097
|
||||||
|
|
||||||
|
Interaktive API-Doku (Dev): http://localhost:8097/api/docs
|
||||||
|
|
||||||
|
### Auth (AP0.2)
|
||||||
|
|
||||||
|
**Ersteinrichtung Dev** (automatisch per Seed nach jedem Backend-Start):
|
||||||
|
|
||||||
|
| Feld | Wert |
|
||||||
|
|------|------|
|
||||||
|
| E-Mail | `lars@stommer.com` |
|
||||||
|
| Passwort | `12345678` |
|
||||||
|
|
||||||
|
Alternativ: UI-Registrierung (nur wenn DB leer und Dev-Seed deaktiviert) oder Bootstrap per `.env`:
|
||||||
|
|
||||||
|
```env
|
||||||
|
KAIRO_BOOTSTRAP_ADMIN_EMAIL=admin@kairo.local
|
||||||
|
KAIRO_BOOTSTRAP_ADMIN_PASSWORD=…
|
||||||
|
KAIRO_BOOTSTRAP_TENANT_SLUG=default
|
||||||
|
```
|
||||||
|
|
||||||
|
Migrationen & idempotente Data-Seeds: [docs/MIGRATIONS.md](docs/MIGRATIONS.md)
|
||||||
|
|
||||||
|
| Endpoint | Methode | Auth | Beschreibung |
|
||||||
|
|----------|---------|------|--------------|
|
||||||
|
| `/api/auth/setup-status` | GET | — | Ob Erstregistrierung offen ist |
|
||||||
|
| `/api/auth/register` | POST | — | Erster User → Portal-Admin + Tenant (nur wenn noch kein User) |
|
||||||
|
| `/api/auth/login` | POST | — | E-Mail + Passwort → Session-Token |
|
||||||
|
| `/api/auth/logout` | POST | `X-Auth-Token` | Session löschen |
|
||||||
|
| `/api/me` | GET | `X-Auth-Token` | Aktueller User + Tenant-Liste |
|
||||||
|
| `/api/me/context` | GET | `X-Auth-Token` | TenantContext (Tenant + Human Actor + Capabilities) |
|
||||||
|
| `/api/me/entitlements` | GET | `X-Auth-Token` | Entitlements-Snapshot (Rollen, Capabilities, Features-Platzhalter) |
|
||||||
|
| `/api/me/admin/demo` | GET | `X-Auth-Token` + `kairo.admin.access` | Beispiel-Endpoint mit `require_capability` |
|
||||||
|
| `/api/me/tenant` | POST | `X-Auth-Token` | Aktiven Tenant wechseln (nur Memberships) |
|
||||||
|
|
||||||
|
### Registries (AP0.4)
|
||||||
|
|
||||||
|
Feature-, Prompt-, Placeholder- und Config-Registry analog zur Rights Registry: Code-Registrierung → Startup-Sync → DB.
|
||||||
|
|
||||||
|
| Endpoint | Methode | Capability | Beschreibung |
|
||||||
|
|----------|---------|------------|--------------|
|
||||||
|
| `/api/features` | GET | `kairo.feature.registry.read` | Feature-Katalog |
|
||||||
|
| `/api/prompts` | GET | `kairo.prompt.registry.read` | Prompt-Definitionen |
|
||||||
|
| `/api/prompts/{key}` | GET | `kairo.prompt.registry.read` | Definition + aktive Version |
|
||||||
|
| `/api/prompts/{key}/render` | POST | `kairo.prompt.render` | Single-Mode Rendering (ohne LLM) |
|
||||||
|
| `/api/config` | GET | `kairo.config.registry.read` | Konfiguration (global/tenant) |
|
||||||
|
| `/api/config` | POST | `kairo.config.registry.manage` | Konfiguration setzen |
|
||||||
|
|
||||||
|
Startup: `sync_prompt_feature_config.py` nach Rights-Sync (`SKIP_REGISTRY_SYNC=1` zum Überspringen).
|
||||||
|
|
||||||
|
**Prompt-Modell:** `PromptDefinition` → `PromptVersion` → optional `PromptStep` (workflow-/pipeline-fähig; AP0.4 führt nur `execution_mode=single` aus).
|
||||||
|
|
||||||
|
**Beispiel-Prompts:** `kairo.system.health_summary`, `kairo.context.debug_summary`
|
||||||
|
|
||||||
|
**Features im Entitlements-Snapshot:** `kairo.prompt.registry`, `kairo.config.registry`, `kairo.feature.registry`
|
||||||
|
|
||||||
|
| Capability | Modul | Kurzbeschreibung |
|
||||||
|
|------------|-------|------------------|
|
||||||
|
| `kairo.feature.registry.read` | feature | Feature-Katalog lesen |
|
||||||
|
| `kairo.feature.registry.manage` | feature | Feature-Metadaten verwalten |
|
||||||
|
| `kairo.prompt.registry.read` | prompt | Prompt Registry lesen |
|
||||||
|
| `kairo.prompt.registry.manage` | prompt | Prompt Registry verwalten |
|
||||||
|
| `kairo.config.registry.read` | config | Config lesen |
|
||||||
|
| `kairo.config.registry.manage` | config | Config schreiben |
|
||||||
|
| `kairo.prompt.render` | prompt | Prompt rendern (Test/Preview) |
|
||||||
|
|
||||||
|
Zusätzlich AP0.3-Capabilities (siehe oben).
|
||||||
|
|
||||||
|
Enforcement: `CAPABILITY_ENFORCE=probe` (Default) oder `enforce`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s http://localhost:8097/api/me/entitlements -H "X-Auth-Token: TOKEN"
|
||||||
|
curl -s -X POST http://localhost:8097/api/prompts/kairo.system.health_summary/render \
|
||||||
|
-H "X-Auth-Token: TOKEN" -H "Content-Type: application/json" \
|
||||||
|
-d '{"values":{"debug_message":"OK","debug_level":"info"},"use_context":false}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### Capabilities (AP0.3)
|
||||||
|
|
||||||
|
Registry-first: Capabilities werden in `backend/rights_registrations/` registriert und beim Start via `sync_rights_registry.py` in die DB synchronisiert.
|
||||||
|
|
||||||
|
| Capability | Modul | Kurzbeschreibung |
|
||||||
|
|------------|-------|------------------|
|
||||||
|
| `kairo.admin.access` | platform | Portal-Administration |
|
||||||
|
| `kairo.tenant.manage` | tenant | Tenant-Verwaltung |
|
||||||
|
| `kairo.actor.manage` | tenant | Actor-Verwaltung |
|
||||||
|
| `kairo.context.read` | platform | TenantContext lesen |
|
||||||
|
| `kairo.entitlements.read` | platform | Entitlements lesen |
|
||||||
|
|
||||||
|
Enforcement: `CAPABILITY_ENFORCE=probe` (Default, loggt Verweigerungen) oder `enforce` (HTTP 403).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s http://localhost:8097/api/me/entitlements -H "X-Auth-Token: TOKEN"
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Login
|
||||||
|
curl -s -X POST http://localhost:8097/api/auth/login \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"email":"admin@kairo.local","password":"…"}'
|
||||||
|
|
||||||
|
# Geschützter Endpoint
|
||||||
|
curl -s http://localhost:8097/api/me -H "X-Auth-Token: TOKEN"
|
||||||
|
```
|
||||||
|
|
||||||
|
Regeln: `user_id` kommt aus der Session, nicht aus Client-Headern. Portalrolle (`portal_role`) und Tenantrolle (`tenant_role`) sind getrennt.
|
||||||
|
|
||||||
## AP0.1 – Stand Projektgrundlage
|
## AP0.1 – Stand Projektgrundlage
|
||||||
|
|
||||||
| Bereich | Status |
|
| Bereich | Status |
|
||||||
@@ -107,5 +212,5 @@ UI: http://localhost:3097 · API: http://localhost:8097
|
|||||||
| Docker Compose (Prod + Dev) | erledigt |
|
| Docker Compose (Prod + Dev) | erledigt |
|
||||||
| Backend (FastAPI, Migrationen, `/api/health`) | erledigt |
|
| Backend (FastAPI, Migrationen, `/api/health`) | erledigt |
|
||||||
| Frontend minimal (React + nginx Proxy) | erledigt |
|
| Frontend minimal (React + nginx Proxy) | erledigt |
|
||||||
| pytest (Health + Migrationen) | erledigt |
|
| pytest (Health + Migrationen + Auth/Tenant/Actor) | erledigt (AP0.2) |
|
||||||
| Gitea Actions (Deploy + Test) | erledigt |
|
| Gitea Actions (Deploy + Test) | erledigt |
|
||||||
@@ -10,7 +10,9 @@ ENV PIP_DEFAULT_TIMEOUT=120
|
|||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
RUN chmod +x /app/entrypoint.sh
|
||||||
|
|
||||||
EXPOSE 8000
|
EXPOSE 8000
|
||||||
|
|
||||||
|
ENTRYPOINT ["/app/entrypoint.sh"]
|
||||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||||
+243
@@ -0,0 +1,243 @@
|
|||||||
|
"""Authentication: bcrypt passwords, server-side sessions, FastAPI dependencies."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
import bcrypt
|
||||||
|
from fastapi import Depends, Header, HTTPException
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from services.audit import log_audit
|
||||||
|
|
||||||
|
AUTH_HEADER = "X-Auth-Token"
|
||||||
|
SESSION_DAYS = int(os.getenv("SESSION_DAYS", "30"))
|
||||||
|
|
||||||
|
|
||||||
|
def hash_password(password: str) -> str:
|
||||||
|
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(password: str, stored_hash: str) -> bool:
|
||||||
|
if not stored_hash:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return bcrypt.checkpw(password.encode("utf-8"), stored_hash.encode("utf-8"))
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def make_token() -> str:
|
||||||
|
return secrets.token_urlsafe(32)
|
||||||
|
|
||||||
|
|
||||||
|
def _session_expiry() -> datetime:
|
||||||
|
return datetime.now(timezone.utc) + timedelta(days=SESSION_DAYS)
|
||||||
|
|
||||||
|
|
||||||
|
def get_user_by_email(email: str) -> Optional[dict[str, Any]]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, email, password_hash, display_name, portal_role, is_active
|
||||||
|
FROM users
|
||||||
|
WHERE LOWER(email) = LOWER(%s)
|
||||||
|
""",
|
||||||
|
(email.strip(),),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_user_by_id(user_id: str) -> Optional[dict[str, Any]]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, email, display_name, portal_role, is_active, created_at
|
||||||
|
FROM users
|
||||||
|
WHERE id = %s
|
||||||
|
""",
|
||||||
|
(user_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_session(token: str) -> Optional[dict[str, Any]]:
|
||||||
|
if not token:
|
||||||
|
return None
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT
|
||||||
|
s.id AS session_id,
|
||||||
|
s.token,
|
||||||
|
s.user_id,
|
||||||
|
s.active_tenant_id,
|
||||||
|
s.expires_at,
|
||||||
|
u.email,
|
||||||
|
u.display_name,
|
||||||
|
u.portal_role,
|
||||||
|
u.is_active AS user_is_active
|
||||||
|
FROM sessions s
|
||||||
|
JOIN users u ON u.id = s.user_id
|
||||||
|
WHERE s.token = %s AND s.expires_at > NOW()
|
||||||
|
""",
|
||||||
|
(token,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
session = dict(row)
|
||||||
|
if not session.get("user_is_active"):
|
||||||
|
return None
|
||||||
|
return session
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _default_active_tenant(user_id: str) -> Optional[str]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT tm.tenant_id
|
||||||
|
FROM tenant_memberships tm
|
||||||
|
JOIN tenants t ON t.id = tm.tenant_id
|
||||||
|
WHERE tm.user_id = %s
|
||||||
|
AND tm.is_active = TRUE
|
||||||
|
AND t.is_active = TRUE
|
||||||
|
ORDER BY tm.created_at ASC
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
(user_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
return str(row[0]) if row else None
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def create_session(user_id: str, active_tenant_id: Optional[str] = None) -> dict[str, Any]:
|
||||||
|
token = make_token()
|
||||||
|
tenant_id = active_tenant_id or _default_active_tenant(user_id)
|
||||||
|
expires_at = _session_expiry()
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO sessions (token, user_id, active_tenant_id, expires_at)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
RETURNING token, expires_at, active_tenant_id
|
||||||
|
""",
|
||||||
|
(token, user_id, tenant_id, expires_at),
|
||||||
|
)
|
||||||
|
row = dict(cur.fetchone())
|
||||||
|
conn.commit()
|
||||||
|
row["user_id"] = user_id
|
||||||
|
return row
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def delete_session(token: str) -> None:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def set_session_active_tenant(token: str, tenant_id: str) -> bool:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE sessions s
|
||||||
|
SET active_tenant_id = %s
|
||||||
|
FROM users u
|
||||||
|
WHERE s.token = %s
|
||||||
|
AND s.user_id = u.id
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM tenant_memberships tm
|
||||||
|
JOIN tenants t ON t.id = tm.tenant_id
|
||||||
|
WHERE tm.user_id = s.user_id
|
||||||
|
AND tm.tenant_id = %s
|
||||||
|
AND tm.is_active = TRUE
|
||||||
|
AND t.is_active = TRUE
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
(tenant_id, token, tenant_id),
|
||||||
|
)
|
||||||
|
updated = cur.rowcount > 0
|
||||||
|
conn.commit()
|
||||||
|
return updated
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def login(email: str, password: str) -> dict[str, Any]:
|
||||||
|
user = get_user_by_email(email)
|
||||||
|
if not user or not user.get("is_active"):
|
||||||
|
log_audit("auth.login_failed", details={"email": email.strip().lower()})
|
||||||
|
raise HTTPException(status_code=401, detail="Ungültige Anmeldedaten")
|
||||||
|
|
||||||
|
if not verify_password(password, user["password_hash"]):
|
||||||
|
log_audit("auth.login_failed", user_id=str(user["id"]), details={"email": user["email"]})
|
||||||
|
raise HTTPException(status_code=401, detail="Ungültige Anmeldedaten")
|
||||||
|
|
||||||
|
session = create_session(str(user["id"]))
|
||||||
|
log_audit("auth.login", user_id=str(user["id"]), details={"email": user["email"]})
|
||||||
|
return {
|
||||||
|
"token": session["token"],
|
||||||
|
"expires_at": session["expires_at"].isoformat(),
|
||||||
|
"user": {
|
||||||
|
"id": str(user["id"]),
|
||||||
|
"email": user["email"],
|
||||||
|
"display_name": user["display_name"],
|
||||||
|
"portal_role": user["portal_role"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def logout(token: str) -> None:
|
||||||
|
session = get_session(token)
|
||||||
|
if session:
|
||||||
|
log_audit(
|
||||||
|
"auth.logout",
|
||||||
|
user_id=str(session["user_id"]),
|
||||||
|
tenant_id=str(session["active_tenant_id"]) if session.get("active_tenant_id") else None,
|
||||||
|
)
|
||||||
|
delete_session(token)
|
||||||
|
|
||||||
|
|
||||||
|
def require_auth(x_auth_token: Optional[str] = Header(default=None, alias=AUTH_HEADER)) -> dict[str, Any]:
|
||||||
|
session = get_session(x_auth_token or "")
|
||||||
|
if not session:
|
||||||
|
raise HTTPException(status_code=401, detail="Nicht eingeloggt")
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
def require_portal_admin(session: dict[str, Any] = Depends(require_auth)) -> dict[str, Any]:
|
||||||
|
if session.get("portal_role") != "admin":
|
||||||
|
raise HTTPException(status_code=403, detail="Nur für Portal-Admins")
|
||||||
|
return session
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Bootstrap first admin user from environment (optional alternative to UI registration)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
from services.registration import provision_system_admin, user_count
|
||||||
|
|
||||||
|
|
||||||
|
def _env(name: str) -> str:
|
||||||
|
return os.getenv(name, "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def bootstrap_admin_if_needed() -> None:
|
||||||
|
if _env("SKIP_BOOTSTRAP").lower() in ("1", "true", "yes"):
|
||||||
|
return
|
||||||
|
|
||||||
|
email = _env("KAIRO_BOOTSTRAP_ADMIN_EMAIL")
|
||||||
|
password = _env("KAIRO_BOOTSTRAP_ADMIN_PASSWORD")
|
||||||
|
if not email or not password:
|
||||||
|
return
|
||||||
|
|
||||||
|
if user_count() > 0:
|
||||||
|
return
|
||||||
|
|
||||||
|
tenant_slug = _env("KAIRO_BOOTSTRAP_TENANT_SLUG") or "default"
|
||||||
|
tenant_name = _env("KAIRO_BOOTSTRAP_TENANT_NAME") or "Default Tenant"
|
||||||
|
display_name = _env("KAIRO_BOOTSTRAP_ADMIN_NAME") or "Kairo Admin"
|
||||||
|
|
||||||
|
provision_system_admin(
|
||||||
|
email=email,
|
||||||
|
password=password,
|
||||||
|
display_name=display_name,
|
||||||
|
tenant_slug=tenant_slug,
|
||||||
|
tenant_name=tenant_name,
|
||||||
|
source="env_bootstrap",
|
||||||
|
)
|
||||||
|
print(f"[bootstrap] Systemadmin und Tenant '{tenant_slug}' angelegt")
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"""Central capability resolution and FastAPI enforcement dependencies."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from typing import Any, Callable
|
||||||
|
|
||||||
|
from fastapi import Depends, HTTPException
|
||||||
|
|
||||||
|
from rights_registry import load_grants_for_roles
|
||||||
|
from services.audit import log_audit
|
||||||
|
from tenant_context import TenantContext, get_tenant_context, require_tenant_context
|
||||||
|
|
||||||
|
CAPABILITY_ENFORCE_ENV = "CAPABILITY_ENFORCE"
|
||||||
|
|
||||||
|
|
||||||
|
def capability_enforcement_mode() -> str:
|
||||||
|
raw = os.getenv(CAPABILITY_ENFORCE_ENV, "probe").strip().lower()
|
||||||
|
return "enforce" if raw in ("1", "true", "enforce", "yes") else "probe"
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_capabilities(*, portal_role: str, tenant_role: str | None) -> frozenset[str]:
|
||||||
|
return frozenset(load_grants_for_roles(portal_role=portal_role, tenant_role=tenant_role))
|
||||||
|
|
||||||
|
|
||||||
|
def has_capability(ctx: TenantContext, capability_key: str) -> bool:
|
||||||
|
return capability_key in ctx.capabilities
|
||||||
|
|
||||||
|
|
||||||
|
def check_capability(ctx: TenantContext, capability_key: str) -> dict[str, Any]:
|
||||||
|
allowed = has_capability(ctx, capability_key)
|
||||||
|
return {
|
||||||
|
"capability_key": capability_key,
|
||||||
|
"allowed": allowed,
|
||||||
|
"reason": None if allowed else "missing_grant",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def require_capability(capability_key: str) -> Callable[..., TenantContext]:
|
||||||
|
"""FastAPI dependency — blocks in enforce mode, probes in probe mode."""
|
||||||
|
|
||||||
|
def _dependency(ctx: TenantContext = Depends(require_tenant_context)) -> TenantContext:
|
||||||
|
return _enforce_capability(ctx, capability_key)
|
||||||
|
|
||||||
|
return _dependency
|
||||||
|
|
||||||
|
|
||||||
|
def require_capability_ctx(capability_key: str) -> Callable[..., TenantContext]:
|
||||||
|
"""Like require_capability but allows portal context without active tenant."""
|
||||||
|
|
||||||
|
def _dependency(ctx: TenantContext = Depends(get_tenant_context)) -> TenantContext:
|
||||||
|
return _enforce_capability(ctx, capability_key)
|
||||||
|
|
||||||
|
return _dependency
|
||||||
|
|
||||||
|
|
||||||
|
def _enforce_capability(ctx: TenantContext, capability_key: str) -> TenantContext:
|
||||||
|
result = check_capability(ctx, capability_key)
|
||||||
|
if result["allowed"]:
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
log_audit(
|
||||||
|
"capability.denied",
|
||||||
|
user_id=ctx.user_id,
|
||||||
|
tenant_id=ctx.tenant_id,
|
||||||
|
details={
|
||||||
|
"capability_key": capability_key,
|
||||||
|
"mode": capability_enforcement_mode(),
|
||||||
|
"portal_role": ctx.portal_role,
|
||||||
|
"tenant_role": ctx.tenant_role,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
if capability_enforcement_mode() == "enforce":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail=f"Capability fehlt: {capability_key}",
|
||||||
|
)
|
||||||
|
return ctx
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
"""Central configuration service — no plaintext secrets."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from services.audit import log_audit
|
||||||
|
|
||||||
|
SECRET_VALUE_FORBIDDEN = (
|
||||||
|
"Configuration entries with is_secret=true must not store plaintext values; "
|
||||||
|
"use environment or secret management."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_secret_entry(*, is_secret: bool, value: Any) -> None:
|
||||||
|
if not is_secret:
|
||||||
|
return
|
||||||
|
if value not in (None, {}, "", {"ref": "env"}):
|
||||||
|
raise ValueError(SECRET_VALUE_FORBIDDEN)
|
||||||
|
|
||||||
|
|
||||||
|
def get_config(
|
||||||
|
config_key: str,
|
||||||
|
*,
|
||||||
|
scope: str = "global",
|
||||||
|
tenant_id: str | None = None,
|
||||||
|
) -> dict | None:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||||
|
FROM configuration_entries
|
||||||
|
WHERE config_key = %s AND scope = %s
|
||||||
|
AND (
|
||||||
|
(scope = 'global' AND tenant_id IS NULL)
|
||||||
|
OR (scope = 'tenant' AND tenant_id = %s::uuid)
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
(config_key, scope, tenant_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"config_key": row[0],
|
||||||
|
"scope": row[1],
|
||||||
|
"tenant_id": str(row[2]) if row[2] else None,
|
||||||
|
"value": row[3],
|
||||||
|
"value_type": row[4],
|
||||||
|
"description": row[5],
|
||||||
|
"is_secret": row[6],
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def list_configs(*, scope: str | None = None, tenant_id: str | None = None) -> list[dict]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
if scope == "global":
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||||
|
FROM configuration_entries
|
||||||
|
WHERE scope = 'global' AND tenant_id IS NULL
|
||||||
|
ORDER BY config_key
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
elif scope == "tenant" and tenant_id:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||||
|
FROM configuration_entries
|
||||||
|
WHERE scope = 'tenant' AND tenant_id = %s::uuid
|
||||||
|
ORDER BY config_key
|
||||||
|
""",
|
||||||
|
(tenant_id,),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||||
|
FROM configuration_entries
|
||||||
|
ORDER BY scope, config_key
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
rows = []
|
||||||
|
for row in cur.fetchall():
|
||||||
|
item = {
|
||||||
|
"config_key": row[0],
|
||||||
|
"scope": row[1],
|
||||||
|
"tenant_id": str(row[2]) if row[2] else None,
|
||||||
|
"value_type": row[4],
|
||||||
|
"description": row[5],
|
||||||
|
"is_secret": row[6],
|
||||||
|
}
|
||||||
|
if row[6]:
|
||||||
|
item["value"] = {"ref": "env"}
|
||||||
|
else:
|
||||||
|
item["value"] = row[3]
|
||||||
|
rows.append(item)
|
||||||
|
return rows
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def upsert_config(
|
||||||
|
*,
|
||||||
|
config_key: str,
|
||||||
|
scope: str,
|
||||||
|
value: Any,
|
||||||
|
value_type: str = "string",
|
||||||
|
description: str = "",
|
||||||
|
is_secret: bool = False,
|
||||||
|
tenant_id: str | None = None,
|
||||||
|
user_id: str | None = None,
|
||||||
|
) -> dict:
|
||||||
|
_validate_secret_entry(is_secret=is_secret, value=value)
|
||||||
|
if scope == "tenant" and not tenant_id:
|
||||||
|
raise ValueError("tenant_id required for tenant-scoped config")
|
||||||
|
if scope == "global":
|
||||||
|
tenant_id = None
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
if scope == "global":
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO configuration_entries (
|
||||||
|
config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||||
|
)
|
||||||
|
VALUES (%s, 'global', NULL, %s::jsonb, %s, %s, %s)
|
||||||
|
ON CONFLICT (config_key) WHERE scope = 'global' DO UPDATE SET
|
||||||
|
value = EXCLUDED.value,
|
||||||
|
value_type = EXCLUDED.value_type,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
is_secret = EXCLUDED.is_secret,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
config_key,
|
||||||
|
json.dumps(value if not is_secret else {"ref": "env"}),
|
||||||
|
value_type,
|
||||||
|
description,
|
||||||
|
is_secret,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO configuration_entries (
|
||||||
|
config_key, scope, tenant_id, value, value_type, description, is_secret
|
||||||
|
)
|
||||||
|
VALUES (%s, 'tenant', %s::uuid, %s::jsonb, %s, %s, %s)
|
||||||
|
ON CONFLICT (config_key, tenant_id) WHERE scope = 'tenant' DO UPDATE SET
|
||||||
|
value = EXCLUDED.value,
|
||||||
|
value_type = EXCLUDED.value_type,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
is_secret = EXCLUDED.is_secret,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
config_key,
|
||||||
|
tenant_id,
|
||||||
|
json.dumps(value if not is_secret else {"ref": "env"}),
|
||||||
|
value_type,
|
||||||
|
description,
|
||||||
|
is_secret,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
log_audit(
|
||||||
|
"config.entry.changed",
|
||||||
|
user_id=user_id,
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
details={"config_key": config_key, "scope": scope, "is_secret": is_secret},
|
||||||
|
)
|
||||||
|
result = get_config(config_key, scope=scope, tenant_id=tenant_id)
|
||||||
|
assert result is not None
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def sync_default_configs(defaults: list[dict]) -> int:
|
||||||
|
if not defaults:
|
||||||
|
return 0
|
||||||
|
for item in defaults:
|
||||||
|
existing = get_config(item["config_key"], scope=item.get("scope", "global"))
|
||||||
|
if existing:
|
||||||
|
continue
|
||||||
|
upsert_config(
|
||||||
|
config_key=item["config_key"],
|
||||||
|
scope=item.get("scope", "global"),
|
||||||
|
value=item["value"],
|
||||||
|
value_type=item.get("value_type", "string"),
|
||||||
|
description=item.get("description", ""),
|
||||||
|
is_secret=item.get("is_secret", False),
|
||||||
|
)
|
||||||
|
print(f"[config_service] Default configs ensured — {len(defaults)} item(s)")
|
||||||
|
return 0
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
"""PostgreSQL connection helpers."""
|
"""PostgreSQL connection helpers."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
import psycopg2
|
import psycopg2
|
||||||
from psycopg2.extensions import connection
|
from psycopg2.extensions import connection
|
||||||
@@ -27,6 +30,40 @@ def get_connection() -> connection:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def is_retryable_db_error(exc: Exception) -> bool:
|
||||||
|
"""Nur temporäre Verbindungsprobleme erneut versuchen (nicht Auth/Config)."""
|
||||||
|
msg = str(exc).lower()
|
||||||
|
if "password authentication failed" in msg:
|
||||||
|
return False
|
||||||
|
if "does not exist" in msg and any(token in msg for token in ("role", "database")):
|
||||||
|
return False
|
||||||
|
if "no pg_hba.conf entry" in msg:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def connect_with_retry(max_retries: int = 30, sleep_seconds: float = 2.0) -> connection:
|
||||||
|
p = db_params()
|
||||||
|
last_exc: Exception | None = None
|
||||||
|
for attempt in range(max_retries):
|
||||||
|
try:
|
||||||
|
conn = get_connection()
|
||||||
|
conn.autocommit = False
|
||||||
|
print(f"[OK] Connected to database: {p['dbname']}")
|
||||||
|
return conn
|
||||||
|
except psycopg2.OperationalError as exc:
|
||||||
|
last_exc = exc
|
||||||
|
if not is_retryable_db_error(exc):
|
||||||
|
raise
|
||||||
|
if attempt >= max_retries - 1:
|
||||||
|
raise
|
||||||
|
print(f"Waiting for database... ({attempt + 1}/{max_retries})")
|
||||||
|
time.sleep(sleep_seconds)
|
||||||
|
if last_exc:
|
||||||
|
raise last_exc
|
||||||
|
raise RuntimeError("database connection failed")
|
||||||
|
|
||||||
|
|
||||||
def check_db() -> bool:
|
def check_db() -> bool:
|
||||||
conn = get_connection()
|
conn = get_connection()
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""Entitlements snapshot for GET /api/me/entitlements."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from capabilities import capability_enforcement_mode, check_capability
|
||||||
|
from feature_registry import load_active_features
|
||||||
|
from rights_registry import get_registered_capabilities
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
|
||||||
|
def _capability_map(ctx: TenantContext) -> dict[str, dict[str, Any]]:
|
||||||
|
registered = {reg.key for reg in get_registered_capabilities()}
|
||||||
|
snapshot: dict[str, dict[str, Any]] = {}
|
||||||
|
for key in sorted(registered):
|
||||||
|
snapshot[key] = check_capability(ctx, key)
|
||||||
|
return snapshot
|
||||||
|
|
||||||
|
|
||||||
|
def _feature_snapshot() -> dict[str, dict[str, Any]]:
|
||||||
|
features = load_active_features()
|
||||||
|
return {
|
||||||
|
key: {
|
||||||
|
"enabled": meta["enabled"],
|
||||||
|
"module": meta["module"],
|
||||||
|
"name": meta["name"],
|
||||||
|
}
|
||||||
|
for key, meta in features.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_entitlements_snapshot(ctx: TenantContext) -> dict[str, Any]:
|
||||||
|
features = _feature_snapshot()
|
||||||
|
tenant_block = None
|
||||||
|
if ctx.tenant_id:
|
||||||
|
tenant_block = {
|
||||||
|
"tenant_id": ctx.tenant_id,
|
||||||
|
"slug": ctx.tenant_slug,
|
||||||
|
"name": ctx.tenant_name,
|
||||||
|
"role": ctx.tenant_role,
|
||||||
|
"capabilities": {
|
||||||
|
key: value
|
||||||
|
for key, value in _capability_map(ctx).items()
|
||||||
|
if key in ctx.capabilities
|
||||||
|
},
|
||||||
|
"features": features,
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"account": {
|
||||||
|
"user_id": ctx.user_id,
|
||||||
|
"email": ctx.email,
|
||||||
|
"display_name": ctx.display_name,
|
||||||
|
"portal_role": ctx.portal_role,
|
||||||
|
"capabilities": _capability_map(ctx),
|
||||||
|
"features": features,
|
||||||
|
},
|
||||||
|
"tenant": tenant_block,
|
||||||
|
"actor": (
|
||||||
|
{
|
||||||
|
"actor_id": ctx.actor_id,
|
||||||
|
"actor_type": ctx.actor_type,
|
||||||
|
}
|
||||||
|
if ctx.actor_id
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
"roles": {
|
||||||
|
"portal": ctx.portal_role,
|
||||||
|
"tenant": ctx.tenant_role,
|
||||||
|
},
|
||||||
|
"capabilities": sorted(ctx.capabilities),
|
||||||
|
"features": features,
|
||||||
|
"enforcement": {
|
||||||
|
"capabilities": capability_enforcement_mode(),
|
||||||
|
"features": "probe",
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
echo "=== Kairo Backend Startup ==="
|
||||||
|
|
||||||
|
if [ "${SKIP_DB_MIGRATE}" != "1" ] && [ "${SKIP_DB_MIGRATE}" != "true" ] && [ "${SKIP_DB_MIGRATE}" != "yes" ]; then
|
||||||
|
python run_migrations.py
|
||||||
|
else
|
||||||
|
echo "[SKIP_DB_MIGRATE] Migrationen übersprungen"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "${SKIP_SEEDS}" != "1" ] && [ "${SKIP_SEEDS}" != "true" ] && [ "${SKIP_SEEDS}" != "yes" ]; then
|
||||||
|
python run_seeds.py
|
||||||
|
else
|
||||||
|
echo "[SKIP_SEEDS] Data-Seeds übersprungen"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "${SKIP_RIGHTS_SYNC}" != "1" ] && [ "${SKIP_RIGHTS_SYNC}" != "true" ] && [ "${SKIP_RIGHTS_SYNC}" != "yes" ]; then
|
||||||
|
python sync_rights_registry.py
|
||||||
|
else
|
||||||
|
echo "[SKIP_RIGHTS_SYNC] Rights-Registry-Sync übersprungen"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "${SKIP_REGISTRY_SYNC}" != "1" ] && [ "${SKIP_REGISTRY_SYNC}" != "true" ] && [ "${SKIP_REGISTRY_SYNC}" != "yes" ]; then
|
||||||
|
python sync_prompt_feature_config.py
|
||||||
|
else
|
||||||
|
echo "[SKIP_REGISTRY_SYNC] Feature/Prompt/Config-Sync übersprungen"
|
||||||
|
fi
|
||||||
|
|
||||||
|
export KAIRO_DB_READY=1
|
||||||
|
echo "=== Starte Anwendung: $* ==="
|
||||||
|
exec "$@"
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""Side-effect imports for feature registrations."""
|
||||||
|
|
||||||
|
from feature_registrations import platform, prompt_ops # noqa: F401
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""Platform feature catalog entries."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from feature_registry import FeatureRegistration, register_feature
|
||||||
|
|
||||||
|
register_feature(
|
||||||
|
FeatureRegistration(
|
||||||
|
key="kairo.feature.registry",
|
||||||
|
module="platform",
|
||||||
|
name="Feature Registry",
|
||||||
|
description="Metadatenkatalog registrierter Kairo-Features",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_feature(
|
||||||
|
FeatureRegistration(
|
||||||
|
key="kairo.config.registry",
|
||||||
|
module="config",
|
||||||
|
name="Configuration Registry",
|
||||||
|
description="Zentrale fachliche Konfiguration (global/tenant)",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_feature(
|
||||||
|
FeatureRegistration(
|
||||||
|
key="kairo.prompt.registry",
|
||||||
|
module="prompt",
|
||||||
|
name="Prompt Registry",
|
||||||
|
description="Workflow-ready Prompt-Definitionen und Versionen",
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
"""Prompt-related feature metadata."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
# Reserved for future prompt-domain features beyond registry catalog.
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""In-memory feature registry with startup sync to PostgreSQL."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
|
||||||
|
VALID_CONTEXT_KINDS = frozenset(
|
||||||
|
{
|
||||||
|
"kairo.tenant_context",
|
||||||
|
"kairo.actor_context",
|
||||||
|
"kairo.debug_context",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
VALID_EXECUTION_MODES = frozenset({"single", "pipeline", "workflow"})
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class FeatureRegistration:
|
||||||
|
key: str
|
||||||
|
module: str
|
||||||
|
name: str
|
||||||
|
description: str
|
||||||
|
|
||||||
|
|
||||||
|
_REGISTRY: dict[str, FeatureRegistration] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def register_feature(registration: FeatureRegistration) -> None:
|
||||||
|
if not registration.key or not registration.key.strip():
|
||||||
|
raise ValueError("Feature key is required")
|
||||||
|
if not registration.module or not registration.module.strip():
|
||||||
|
raise ValueError("Feature module is required")
|
||||||
|
if not registration.name or not registration.name.strip():
|
||||||
|
raise ValueError("Feature name is required")
|
||||||
|
if not registration.description or not registration.description.strip():
|
||||||
|
raise ValueError("Feature description is required")
|
||||||
|
if registration.key in _REGISTRY:
|
||||||
|
raise ValueError(f"Feature already registered: {registration.key}")
|
||||||
|
_REGISTRY[registration.key] = registration
|
||||||
|
|
||||||
|
|
||||||
|
def get_registered_features() -> tuple[FeatureRegistration, ...]:
|
||||||
|
return tuple(_REGISTRY.values())
|
||||||
|
|
||||||
|
|
||||||
|
def clear_feature_registry_for_tests() -> None:
|
||||||
|
_REGISTRY.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def sync_features_to_db() -> int:
|
||||||
|
if not _REGISTRY:
|
||||||
|
print("[feature_registry] Keine Features registriert — Sync übersprungen")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
for reg in _REGISTRY.values():
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO features (feature_key, module, name, description, is_active)
|
||||||
|
VALUES (%s, %s, %s, %s, TRUE)
|
||||||
|
ON CONFLICT (feature_key) DO UPDATE SET
|
||||||
|
module = EXCLUDED.module,
|
||||||
|
name = EXCLUDED.name,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
is_active = TRUE,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(reg.key, reg.module, reg.name, reg.description),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
print(f"[feature_registry] Sync OK — {len(_REGISTRY)} Feature(s)")
|
||||||
|
return 0
|
||||||
|
except Exception as exc:
|
||||||
|
conn.rollback()
|
||||||
|
print(f"[feature_registry] Sync FAIL: {exc}")
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def load_active_features() -> dict[str, dict]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT feature_key, module, name, description
|
||||||
|
FROM features
|
||||||
|
WHERE is_active = TRUE
|
||||||
|
ORDER BY feature_key
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
row[0]: {
|
||||||
|
"enabled": True,
|
||||||
|
"module": row[1],
|
||||||
|
"name": row[2],
|
||||||
|
"description": row[3],
|
||||||
|
}
|
||||||
|
for row in cur.fetchall()
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
+27
-8
@@ -11,15 +11,26 @@ from fastapi.middleware.cors import CORSMiddleware
|
|||||||
from db import check_db
|
from db import check_db
|
||||||
from version import APP_NAME, APP_VERSION, DB_SCHEMA_VERSION
|
from version import APP_NAME, APP_VERSION, DB_SCHEMA_VERSION
|
||||||
|
|
||||||
if os.getenv("SKIP_DB_MIGRATE", "").strip().lower() in ("1", "true", "yes"):
|
if os.getenv("KAIRO_DB_READY") != "1":
|
||||||
print("[SKIP_DB_MIGRATE] Migrationen übersprungen")
|
if os.getenv("SKIP_DB_MIGRATE", "").strip().lower() not in ("1", "true", "yes"):
|
||||||
else:
|
import run_migrations
|
||||||
import run_migrations
|
|
||||||
|
|
||||||
exit_code = run_migrations.main()
|
exit_code = run_migrations.main()
|
||||||
if exit_code != 0:
|
if exit_code != 0:
|
||||||
print(f"[FAIL] Migrationen fehlgeschlagen (Exit {exit_code})")
|
print(f"[FAIL] Migrationen fehlgeschlagen (Exit {exit_code})")
|
||||||
sys.exit(exit_code)
|
sys.exit(exit_code)
|
||||||
|
else:
|
||||||
|
print("[SKIP_DB_MIGRATE] Migrationen übersprungen")
|
||||||
|
|
||||||
|
if os.getenv("SKIP_SEEDS", "").strip().lower() not in ("1", "true", "yes"):
|
||||||
|
import run_seeds
|
||||||
|
|
||||||
|
exit_code = run_seeds.main()
|
||||||
|
if exit_code != 0:
|
||||||
|
print(f"[FAIL] Seeds fehlgeschlagen (Exit {exit_code})")
|
||||||
|
sys.exit(exit_code)
|
||||||
|
else:
|
||||||
|
print("[SKIP_SEEDS] Data-Seeds übersprungen")
|
||||||
|
|
||||||
allowed_origins = [
|
allowed_origins = [
|
||||||
origin.strip()
|
origin.strip()
|
||||||
@@ -42,6 +53,14 @@ app.add_middleware(
|
|||||||
allow_headers=["*"],
|
allow_headers=["*"],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from routers import auth, config, features, me, prompts # noqa: E402
|
||||||
|
|
||||||
|
app.include_router(auth.router)
|
||||||
|
app.include_router(me.router)
|
||||||
|
app.include_router(features.router)
|
||||||
|
app.include_router(prompts.router)
|
||||||
|
app.include_router(config.router)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/health")
|
@app.get("/api/health")
|
||||||
def api_health():
|
def api_health():
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
-- AP0.2: Auth, Identity, Tenant & Actor Foundation
|
||||||
|
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||||
|
|
||||||
|
CREATE TABLE users (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
email VARCHAR(255) NOT NULL UNIQUE,
|
||||||
|
password_hash VARCHAR(255) NOT NULL,
|
||||||
|
display_name VARCHAR(255) NOT NULL,
|
||||||
|
portal_role VARCHAR(32) NOT NULL DEFAULT 'user'
|
||||||
|
CHECK (portal_role IN ('user', 'admin')),
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE tenants (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
slug VARCHAR(64) NOT NULL UNIQUE,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE tenant_memberships (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
tenant_role VARCHAR(32) NOT NULL DEFAULT 'member'
|
||||||
|
CHECK (tenant_role IN ('owner', 'admin', 'member')),
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (tenant_id, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_tenant_memberships_user ON tenant_memberships(user_id);
|
||||||
|
|
||||||
|
CREATE TABLE actors (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
actor_type VARCHAR(32) NOT NULL
|
||||||
|
CHECK (actor_type IN ('human', 'agent', 'working_group', 'external_system')),
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
user_id UUID NULL REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CHECK (
|
||||||
|
(actor_type = 'human' AND user_id IS NOT NULL)
|
||||||
|
OR (actor_type <> 'human' AND user_id IS NULL)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX idx_actors_human_user_tenant
|
||||||
|
ON actors(tenant_id, user_id)
|
||||||
|
WHERE actor_type = 'human';
|
||||||
|
|
||||||
|
CREATE INDEX idx_actors_tenant ON actors(tenant_id);
|
||||||
|
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
token VARCHAR(128) NOT NULL UNIQUE,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
active_tenant_id UUID NULL REFERENCES tenants(id) ON DELETE SET NULL,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_sessions_token ON sessions(token);
|
||||||
|
CREATE INDEX idx_sessions_user_id ON sessions(user_id);
|
||||||
|
|
||||||
|
CREATE TABLE audit_log (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
action VARCHAR(64) NOT NULL,
|
||||||
|
user_id UUID NULL REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
tenant_id UUID NULL REFERENCES tenants(id) ON DELETE SET NULL,
|
||||||
|
details JSONB NOT NULL DEFAULT '{}',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_audit_log_created ON audit_log(created_at DESC);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- Tracking für idempotente Data-Seeds (Checksum-basiert, bei Änderung erneut ausführbar)
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS data_seeds (
|
||||||
|
seed_name VARCHAR(255) PRIMARY KEY,
|
||||||
|
checksum VARCHAR(64) NOT NULL,
|
||||||
|
executed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
last_run_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
-- AP0.3: Capability catalog and role → capability grants
|
||||||
|
|
||||||
|
CREATE TABLE capabilities (
|
||||||
|
capability_key VARCHAR(128) PRIMARY KEY,
|
||||||
|
module VARCHAR(64) NOT NULL,
|
||||||
|
description TEXT NOT NULL,
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE role_capability_grants (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
role_scope VARCHAR(16) NOT NULL
|
||||||
|
CHECK (role_scope IN ('portal', 'tenant')),
|
||||||
|
role_code VARCHAR(32) NOT NULL,
|
||||||
|
capability_key VARCHAR(128) NOT NULL REFERENCES capabilities(capability_key) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (role_scope, role_code, capability_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_role_capability_grants_lookup
|
||||||
|
ON role_capability_grants(role_scope, role_code);
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
-- AP0.4: Feature, Prompt, Placeholder and Configuration registries
|
||||||
|
|
||||||
|
CREATE TABLE features (
|
||||||
|
feature_key VARCHAR(128) PRIMARY KEY,
|
||||||
|
module VARCHAR(64) NOT NULL,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE prompt_definitions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
prompt_key VARCHAR(128) NOT NULL UNIQUE,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
purpose TEXT NOT NULL DEFAULT '',
|
||||||
|
context_kind VARCHAR(64) NOT NULL,
|
||||||
|
execution_mode VARCHAR(32) NOT NULL DEFAULT 'single'
|
||||||
|
CHECK (execution_mode IN ('single', 'pipeline', 'workflow')),
|
||||||
|
status VARCHAR(32) NOT NULL DEFAULT 'active'
|
||||||
|
CHECK (status IN ('draft', 'active', 'archived')),
|
||||||
|
active_version_id UUID,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE prompt_versions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
prompt_definition_id UUID NOT NULL REFERENCES prompt_definitions(id) ON DELETE CASCADE,
|
||||||
|
version VARCHAR(64) NOT NULL,
|
||||||
|
body TEXT NOT NULL DEFAULT '',
|
||||||
|
input_schema JSONB,
|
||||||
|
output_schema JSONB,
|
||||||
|
model_policy_key VARCHAR(128),
|
||||||
|
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
changelog TEXT NOT NULL DEFAULT '',
|
||||||
|
UNIQUE (prompt_definition_id, version)
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE prompt_definitions
|
||||||
|
ADD CONSTRAINT fk_prompt_definitions_active_version
|
||||||
|
FOREIGN KEY (active_version_id) REFERENCES prompt_versions(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE TABLE prompt_steps (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
prompt_version_id UUID NOT NULL REFERENCES prompt_versions(id) ON DELETE CASCADE,
|
||||||
|
step_key VARCHAR(128) NOT NULL,
|
||||||
|
step_order INT NOT NULL DEFAULT 0,
|
||||||
|
step_type VARCHAR(32) NOT NULL DEFAULT 'template'
|
||||||
|
CHECK (step_type IN ('template', 'resolver', 'llm_call', 'postprocess', 'validation')),
|
||||||
|
template_body TEXT NOT NULL DEFAULT '',
|
||||||
|
input_mapping JSONB,
|
||||||
|
output_mapping JSONB,
|
||||||
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (prompt_version_id, step_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_prompt_steps_version_order
|
||||||
|
ON prompt_steps(prompt_version_id, step_order);
|
||||||
|
|
||||||
|
CREATE TABLE placeholder_definitions (
|
||||||
|
placeholder_key VARCHAR(128) NOT NULL,
|
||||||
|
context_kind VARCHAR(64) NOT NULL,
|
||||||
|
value_type VARCHAR(32) NOT NULL DEFAULT 'string'
|
||||||
|
CHECK (value_type IN ('string', 'number', 'boolean', 'object', 'array', 'json')),
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
required BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
source VARCHAR(64) NOT NULL DEFAULT 'input',
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
PRIMARY KEY (placeholder_key, context_kind)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE configuration_entries (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
config_key VARCHAR(128) NOT NULL,
|
||||||
|
scope VARCHAR(32) NOT NULL DEFAULT 'global'
|
||||||
|
CHECK (scope IN ('global', 'tenant')),
|
||||||
|
tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE,
|
||||||
|
value JSONB NOT NULL DEFAULT '{}',
|
||||||
|
value_type VARCHAR(32) NOT NULL DEFAULT 'string'
|
||||||
|
CHECK (value_type IN ('string', 'number', 'boolean', 'object', 'array', 'json')),
|
||||||
|
description TEXT NOT NULL DEFAULT '',
|
||||||
|
is_secret BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
CHECK (
|
||||||
|
(scope = 'global' AND tenant_id IS NULL)
|
||||||
|
OR (scope = 'tenant' AND tenant_id IS NOT NULL)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX uq_configuration_entries_global
|
||||||
|
ON configuration_entries (config_key)
|
||||||
|
WHERE scope = 'global';
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX uq_configuration_entries_tenant
|
||||||
|
ON configuration_entries (config_key, tenant_id)
|
||||||
|
WHERE scope = 'tenant';
|
||||||
|
|
||||||
|
CREATE TABLE prompt_execution_logs (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
prompt_definition_id UUID REFERENCES prompt_definitions(id) ON DELETE SET NULL,
|
||||||
|
prompt_version_id UUID REFERENCES prompt_versions(id) ON DELETE SET NULL,
|
||||||
|
execution_mode VARCHAR(32) NOT NULL,
|
||||||
|
status VARCHAR(32) NOT NULL
|
||||||
|
CHECK (status IN ('success', 'error', 'skipped')),
|
||||||
|
rendered_preview TEXT,
|
||||||
|
input_summary JSONB,
|
||||||
|
error_message TEXT,
|
||||||
|
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_prompt_execution_logs_created
|
||||||
|
ON prompt_execution_logs(created_at DESC);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""Side-effect imports for placeholder registrations."""
|
||||||
|
|
||||||
|
from placeholder_registrations import actor_context, debug, tenant_context # noqa: F401
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"""Actor context placeholders."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from placeholder_registry import PlaceholderRegistration, register_placeholder
|
||||||
|
|
||||||
|
_CTX = "kairo.actor_context"
|
||||||
|
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("actor_id", _CTX, "string", "UUID des Actors", required=True)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("actor_type", _CTX, "string", "Actor-Typ", required=True)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("tenant_id", _CTX, "string", "UUID des Tenants", required=True)
|
||||||
|
)
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
"""Debug context placeholders."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from placeholder_registry import PlaceholderRegistration, register_placeholder
|
||||||
|
|
||||||
|
_CTX = "kairo.debug_context"
|
||||||
|
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("debug_message", _CTX, "string", "Freier Debug-Text", required=True)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("debug_level", _CTX, "string", "Log-Level oder Kategorie", required=False)
|
||||||
|
)
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""TenantContext placeholders for prompt rendering."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from placeholder_registry import PlaceholderRegistration, register_placeholder
|
||||||
|
|
||||||
|
_CTX = "kairo.tenant_context"
|
||||||
|
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("tenant_name", _CTX, "string", "Name des aktiven Tenants", required=True)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("tenant_id", _CTX, "string", "UUID des aktiven Tenants", required=True)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("actor_name", _CTX, "string", "Anzeigename des Human Actors", required=False)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("actor_id", _CTX, "string", "UUID des Human Actors", required=False)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("actor_type", _CTX, "string", "Actor-Typ (z. B. human)", required=False)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("portal_role", _CTX, "string", "Portal-Rolle des Users", required=True)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration("tenant_role", _CTX, "string", "Tenant-Rolle in der Membership", required=False)
|
||||||
|
)
|
||||||
|
register_placeholder(
|
||||||
|
PlaceholderRegistration(
|
||||||
|
"capabilities",
|
||||||
|
_CTX,
|
||||||
|
"json",
|
||||||
|
"Aufgelöste Capability-Keys als JSON-Array",
|
||||||
|
required=False,
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
"""Placeholder definitions registry with DB sync."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from feature_registry import VALID_CONTEXT_KINDS
|
||||||
|
|
||||||
|
VALID_VALUE_TYPES = frozenset({"string", "number", "boolean", "object", "array", "json"})
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PlaceholderRegistration:
|
||||||
|
placeholder_key: str
|
||||||
|
context_kind: str
|
||||||
|
value_type: str
|
||||||
|
description: str
|
||||||
|
required: bool = False
|
||||||
|
source: str = "input"
|
||||||
|
|
||||||
|
|
||||||
|
_REGISTRY: list[PlaceholderRegistration] = []
|
||||||
|
|
||||||
|
|
||||||
|
def register_placeholder(registration: PlaceholderRegistration) -> None:
|
||||||
|
if not registration.placeholder_key or not registration.placeholder_key.strip():
|
||||||
|
raise ValueError("Placeholder key is required")
|
||||||
|
if registration.context_kind not in VALID_CONTEXT_KINDS:
|
||||||
|
raise ValueError(f"Unknown context_kind: {registration.context_kind}")
|
||||||
|
if registration.value_type not in VALID_VALUE_TYPES:
|
||||||
|
raise ValueError(f"Unknown value_type: {registration.value_type}")
|
||||||
|
if not registration.description or not registration.description.strip():
|
||||||
|
raise ValueError("Placeholder description is required")
|
||||||
|
key = (registration.placeholder_key, registration.context_kind)
|
||||||
|
if any((r.placeholder_key, r.context_kind) == key for r in _REGISTRY):
|
||||||
|
raise ValueError(f"Placeholder already registered: {key}")
|
||||||
|
_REGISTRY.append(registration)
|
||||||
|
|
||||||
|
|
||||||
|
def get_registered_placeholders() -> tuple[PlaceholderRegistration, ...]:
|
||||||
|
return tuple(_REGISTRY)
|
||||||
|
|
||||||
|
|
||||||
|
def clear_placeholder_registry_for_tests() -> None:
|
||||||
|
_REGISTRY.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def sync_placeholders_to_db() -> int:
|
||||||
|
if not _REGISTRY:
|
||||||
|
print("[placeholder_registry] Keine Placeholder registriert — Sync übersprungen")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
for reg in _REGISTRY:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO placeholder_definitions (
|
||||||
|
placeholder_key, context_kind, value_type, description,
|
||||||
|
required, source, is_active
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s, TRUE)
|
||||||
|
ON CONFLICT (placeholder_key, context_kind) DO UPDATE SET
|
||||||
|
value_type = EXCLUDED.value_type,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
required = EXCLUDED.required,
|
||||||
|
source = EXCLUDED.source,
|
||||||
|
is_active = TRUE,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
reg.placeholder_key,
|
||||||
|
reg.context_kind,
|
||||||
|
reg.value_type,
|
||||||
|
reg.description,
|
||||||
|
reg.required,
|
||||||
|
reg.source,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
print(f"[placeholder_registry] Sync OK — {len(_REGISTRY)} Placeholder(s)")
|
||||||
|
return 0
|
||||||
|
except Exception as exc:
|
||||||
|
conn.rollback()
|
||||||
|
print(f"[placeholder_registry] Sync FAIL: {exc}")
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def load_placeholders_for_context(context_kind: str) -> list[dict]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT placeholder_key, value_type, description, required, source
|
||||||
|
FROM placeholder_definitions
|
||||||
|
WHERE context_kind = %s AND is_active = TRUE
|
||||||
|
ORDER BY placeholder_key
|
||||||
|
""",
|
||||||
|
(context_kind,),
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"placeholder_key": row[0],
|
||||||
|
"value_type": row[1],
|
||||||
|
"description": row[2],
|
||||||
|
"required": row[3],
|
||||||
|
"source": row[4],
|
||||||
|
}
|
||||||
|
for row in cur.fetchall()
|
||||||
|
]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Build placeholder value maps from TenantContext."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
|
||||||
|
def build_tenant_context_values(ctx: TenantContext) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"tenant_name": ctx.tenant_name or "",
|
||||||
|
"tenant_id": ctx.tenant_id or "",
|
||||||
|
"actor_name": ctx.display_name,
|
||||||
|
"actor_id": ctx.actor_id or "",
|
||||||
|
"actor_type": ctx.actor_type or "",
|
||||||
|
"portal_role": ctx.portal_role,
|
||||||
|
"tenant_role": ctx.tenant_role or "",
|
||||||
|
"capabilities": sorted(ctx.capabilities),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_actor_context_values(ctx: TenantContext) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"actor_id": ctx.actor_id or "",
|
||||||
|
"actor_type": ctx.actor_type or "",
|
||||||
|
"tenant_id": ctx.tenant_id or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def merge_context_values(ctx: TenantContext, context_kind: str, extra: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
base: dict[str, Any] = {}
|
||||||
|
if context_kind == "kairo.tenant_context":
|
||||||
|
base = build_tenant_context_values(ctx)
|
||||||
|
elif context_kind == "kairo.actor_context":
|
||||||
|
base = build_actor_context_values(ctx)
|
||||||
|
merged = {**base, **extra}
|
||||||
|
for key, value in merged.items():
|
||||||
|
if key == "capabilities" and isinstance(value, list):
|
||||||
|
merged[key] = value
|
||||||
|
elif isinstance(value, (dict, list)) and key != "capabilities":
|
||||||
|
continue
|
||||||
|
return merged
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""Side-effect imports for prompt registrations."""
|
||||||
|
|
||||||
|
from prompt_registrations import debug, platform # noqa: F401
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""Debug prompts for actor context kind."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from prompt_registry import PromptRegistration, PromptVersionRegistration, register_prompt
|
||||||
|
|
||||||
|
register_prompt(
|
||||||
|
PromptRegistration(
|
||||||
|
prompt_key="kairo.actor.debug_summary",
|
||||||
|
name="Actor Context Debug",
|
||||||
|
purpose="Minimaler Prompt für kairo.actor_context",
|
||||||
|
context_kind="kairo.actor_context",
|
||||||
|
execution_mode="single",
|
||||||
|
active_version="1.0.0",
|
||||||
|
versions=(
|
||||||
|
PromptVersionRegistration(
|
||||||
|
version="1.0.0",
|
||||||
|
body="Actor {{actor_id}} ({{actor_type}}) in tenant {{tenant_id}}.",
|
||||||
|
changelog="Actor context smoke",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""Technical smoke-test prompts — no product logic."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from prompt_registry import (
|
||||||
|
PromptRegistration,
|
||||||
|
PromptStepRegistration,
|
||||||
|
PromptVersionRegistration,
|
||||||
|
register_prompt,
|
||||||
|
)
|
||||||
|
|
||||||
|
register_prompt(
|
||||||
|
PromptRegistration(
|
||||||
|
prompt_key="kairo.system.health_summary",
|
||||||
|
name="System Health Summary",
|
||||||
|
purpose="Smoke-Test für Registry, Versionierung und Rendering",
|
||||||
|
context_kind="kairo.debug_context",
|
||||||
|
execution_mode="single",
|
||||||
|
active_version="1.0.0",
|
||||||
|
versions=(
|
||||||
|
PromptVersionRegistration(
|
||||||
|
version="1.0.0",
|
||||||
|
body="",
|
||||||
|
changelog="Initial smoke prompt",
|
||||||
|
steps=(
|
||||||
|
PromptStepRegistration(
|
||||||
|
step_key="summary",
|
||||||
|
step_order=0,
|
||||||
|
step_type="template",
|
||||||
|
template_body=(
|
||||||
|
"Kairo Systemstatus: {{debug_message}} "
|
||||||
|
"(Level: {{debug_level}})"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_prompt(
|
||||||
|
PromptRegistration(
|
||||||
|
prompt_key="kairo.context.debug_summary",
|
||||||
|
name="Tenant Context Debug Summary",
|
||||||
|
purpose="Smoke-Test für TenantContext-Placeholder",
|
||||||
|
context_kind="kairo.tenant_context",
|
||||||
|
execution_mode="single",
|
||||||
|
active_version="1.0.0",
|
||||||
|
versions=(
|
||||||
|
PromptVersionRegistration(
|
||||||
|
version="1.0.0",
|
||||||
|
body=(
|
||||||
|
"Tenant {{tenant_name}} ({{tenant_id}}): "
|
||||||
|
"Portal={{portal_role}}, Tenant-Rolle={{tenant_role}}, "
|
||||||
|
"Actor={{actor_id}} ({{actor_type}})."
|
||||||
|
),
|
||||||
|
changelog="Initial tenant context prompt",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Pipeline/workflow structural sample — not executed in AP0.4
|
||||||
|
register_prompt(
|
||||||
|
PromptRegistration(
|
||||||
|
prompt_key="kairo.pipeline.placeholder",
|
||||||
|
name="Pipeline Placeholder",
|
||||||
|
purpose="Strukturelle Vorbereitung für pipeline execution_mode",
|
||||||
|
context_kind="kairo.debug_context",
|
||||||
|
execution_mode="pipeline",
|
||||||
|
active_version="0.1.0",
|
||||||
|
versions=(
|
||||||
|
PromptVersionRegistration(
|
||||||
|
version="0.1.0",
|
||||||
|
body="Pipeline placeholder: {{debug_message}}",
|
||||||
|
changelog="Not executed in AP0.4",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
"""Prompt definition registry with versioning and optional steps."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from feature_registry import VALID_CONTEXT_KINDS, VALID_EXECUTION_MODES
|
||||||
|
|
||||||
|
VALID_STEP_TYPES = frozenset(
|
||||||
|
{"template", "resolver", "llm_call", "postprocess", "validation"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PromptStepRegistration:
|
||||||
|
step_key: str
|
||||||
|
step_order: int
|
||||||
|
step_type: str
|
||||||
|
template_body: str
|
||||||
|
input_mapping: dict | None = None
|
||||||
|
output_mapping: dict | None = None
|
||||||
|
enabled: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PromptVersionRegistration:
|
||||||
|
version: str
|
||||||
|
body: str
|
||||||
|
input_schema: dict | None = None
|
||||||
|
output_schema: dict | None = None
|
||||||
|
model_policy_key: str | None = None
|
||||||
|
changelog: str = ""
|
||||||
|
steps: tuple[PromptStepRegistration, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PromptRegistration:
|
||||||
|
prompt_key: str
|
||||||
|
name: str
|
||||||
|
purpose: str
|
||||||
|
context_kind: str
|
||||||
|
execution_mode: str
|
||||||
|
active_version: str
|
||||||
|
versions: tuple[PromptVersionRegistration, ...]
|
||||||
|
|
||||||
|
|
||||||
|
_REGISTRY: dict[str, PromptRegistration] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def register_prompt(registration: PromptRegistration) -> None:
|
||||||
|
if not registration.prompt_key or not registration.prompt_key.strip():
|
||||||
|
raise ValueError("Prompt key is required")
|
||||||
|
if registration.context_kind not in VALID_CONTEXT_KINDS:
|
||||||
|
raise ValueError(f"Unknown context_kind: {registration.context_kind}")
|
||||||
|
if registration.execution_mode not in VALID_EXECUTION_MODES:
|
||||||
|
raise ValueError(f"Unknown execution_mode: {registration.execution_mode}")
|
||||||
|
if not registration.versions:
|
||||||
|
raise ValueError("At least one prompt version is required")
|
||||||
|
version_ids = {v.version for v in registration.versions}
|
||||||
|
if registration.active_version not in version_ids:
|
||||||
|
raise ValueError(f"active_version not found in versions: {registration.active_version}")
|
||||||
|
for step in _iter_steps(registration):
|
||||||
|
if step.step_type not in VALID_STEP_TYPES:
|
||||||
|
raise ValueError(f"Unknown step_type: {step.step_type}")
|
||||||
|
if registration.prompt_key in _REGISTRY:
|
||||||
|
raise ValueError(f"Prompt already registered: {registration.prompt_key}")
|
||||||
|
_REGISTRY[registration.prompt_key] = registration
|
||||||
|
|
||||||
|
|
||||||
|
def _iter_steps(registration: PromptRegistration):
|
||||||
|
for version in registration.versions:
|
||||||
|
yield from version.steps
|
||||||
|
|
||||||
|
|
||||||
|
def get_registered_prompts() -> tuple[PromptRegistration, ...]:
|
||||||
|
return tuple(_REGISTRY.values())
|
||||||
|
|
||||||
|
|
||||||
|
def clear_prompt_registry_for_tests() -> None:
|
||||||
|
_REGISTRY.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def sync_prompts_to_db() -> int:
|
||||||
|
if not _REGISTRY:
|
||||||
|
print("[prompt_registry] Keine Prompts registriert — Sync übersprungen")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
for reg in _REGISTRY.values():
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO prompt_definitions (
|
||||||
|
prompt_key, name, purpose, context_kind, execution_mode, status
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, 'active')
|
||||||
|
ON CONFLICT (prompt_key) DO UPDATE SET
|
||||||
|
name = EXCLUDED.name,
|
||||||
|
purpose = EXCLUDED.purpose,
|
||||||
|
context_kind = EXCLUDED.context_kind,
|
||||||
|
execution_mode = EXCLUDED.execution_mode,
|
||||||
|
status = 'active',
|
||||||
|
updated_at = NOW()
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
reg.prompt_key,
|
||||||
|
reg.name,
|
||||||
|
reg.purpose,
|
||||||
|
reg.context_kind,
|
||||||
|
reg.execution_mode,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
definition_id = cur.fetchone()[0]
|
||||||
|
|
||||||
|
active_version_id = None
|
||||||
|
for version in reg.versions:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO prompt_versions (
|
||||||
|
prompt_definition_id, version, body,
|
||||||
|
input_schema, output_schema, model_policy_key, changelog
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s::jsonb, %s::jsonb, %s, %s)
|
||||||
|
ON CONFLICT (prompt_definition_id, version) DO UPDATE SET
|
||||||
|
body = EXCLUDED.body,
|
||||||
|
input_schema = EXCLUDED.input_schema,
|
||||||
|
output_schema = EXCLUDED.output_schema,
|
||||||
|
model_policy_key = EXCLUDED.model_policy_key,
|
||||||
|
changelog = EXCLUDED.changelog
|
||||||
|
RETURNING id
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
definition_id,
|
||||||
|
version.version,
|
||||||
|
version.body,
|
||||||
|
json.dumps(version.input_schema) if version.input_schema else None,
|
||||||
|
json.dumps(version.output_schema) if version.output_schema else None,
|
||||||
|
version.model_policy_key,
|
||||||
|
version.changelog,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
version_id = cur.fetchone()[0]
|
||||||
|
if version.version == reg.active_version:
|
||||||
|
active_version_id = version_id
|
||||||
|
|
||||||
|
for step in version.steps:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO prompt_steps (
|
||||||
|
prompt_version_id, step_key, step_order, step_type,
|
||||||
|
template_body, input_mapping, output_mapping, enabled
|
||||||
|
)
|
||||||
|
VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s::jsonb, %s)
|
||||||
|
ON CONFLICT (prompt_version_id, step_key) DO UPDATE SET
|
||||||
|
step_order = EXCLUDED.step_order,
|
||||||
|
step_type = EXCLUDED.step_type,
|
||||||
|
template_body = EXCLUDED.template_body,
|
||||||
|
input_mapping = EXCLUDED.input_mapping,
|
||||||
|
output_mapping = EXCLUDED.output_mapping,
|
||||||
|
enabled = EXCLUDED.enabled,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
version_id,
|
||||||
|
step.step_key,
|
||||||
|
step.step_order,
|
||||||
|
step.step_type,
|
||||||
|
step.template_body,
|
||||||
|
json.dumps(step.input_mapping) if step.input_mapping else None,
|
||||||
|
json.dumps(step.output_mapping) if step.output_mapping else None,
|
||||||
|
step.enabled,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
if active_version_id:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE prompt_definitions
|
||||||
|
SET active_version_id = %s, updated_at = NOW()
|
||||||
|
WHERE id = %s
|
||||||
|
""",
|
||||||
|
(active_version_id, definition_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
print(f"[prompt_registry] Sync OK — {len(_REGISTRY)} Prompt(s)")
|
||||||
|
return 0
|
||||||
|
except Exception as exc:
|
||||||
|
conn.rollback()
|
||||||
|
print(f"[prompt_registry] Sync FAIL: {exc}")
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def load_prompt_definition(prompt_key: str) -> dict | None:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, prompt_key, name, purpose, context_kind, execution_mode,
|
||||||
|
status, active_version_id
|
||||||
|
FROM prompt_definitions
|
||||||
|
WHERE prompt_key = %s
|
||||||
|
""",
|
||||||
|
(prompt_key,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"id": str(row[0]),
|
||||||
|
"prompt_key": row[1],
|
||||||
|
"name": row[2],
|
||||||
|
"purpose": row[3],
|
||||||
|
"context_kind": row[4],
|
||||||
|
"execution_mode": row[5],
|
||||||
|
"status": row[6],
|
||||||
|
"active_version_id": str(row[7]) if row[7] else None,
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def load_active_prompt_version(definition: dict) -> dict | None:
|
||||||
|
version_id = definition.get("active_version_id")
|
||||||
|
if not version_id:
|
||||||
|
return None
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, version, body, input_schema, output_schema, model_policy_key
|
||||||
|
FROM prompt_versions
|
||||||
|
WHERE id = %s
|
||||||
|
""",
|
||||||
|
(version_id,),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"id": str(row[0]),
|
||||||
|
"version": row[1],
|
||||||
|
"body": row[2],
|
||||||
|
"input_schema": row[3],
|
||||||
|
"output_schema": row[4],
|
||||||
|
"model_policy_key": row[5],
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def load_template_steps(version_id: str) -> list[dict]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT step_key, step_order, step_type, template_body, enabled
|
||||||
|
FROM prompt_steps
|
||||||
|
WHERE prompt_version_id = %s AND enabled = TRUE
|
||||||
|
ORDER BY step_order, step_key
|
||||||
|
""",
|
||||||
|
(version_id,),
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"step_key": row[0],
|
||||||
|
"step_order": row[1],
|
||||||
|
"step_type": row[2],
|
||||||
|
"template_body": row[3],
|
||||||
|
"enabled": row[4],
|
||||||
|
}
|
||||||
|
for row in cur.fetchall()
|
||||||
|
]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def list_prompt_definitions() -> list[dict]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT prompt_key, name, purpose, context_kind, execution_mode, status
|
||||||
|
FROM prompt_definitions
|
||||||
|
ORDER BY prompt_key
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"prompt_key": row[0],
|
||||||
|
"name": row[1],
|
||||||
|
"purpose": row[2],
|
||||||
|
"context_kind": row[3],
|
||||||
|
"execution_mode": row[4],
|
||||||
|
"status": row[5],
|
||||||
|
}
|
||||||
|
for row in cur.fetchall()
|
||||||
|
]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
"""Single-mode prompt rendering without LLM execution."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
from prompt_registry import load_active_prompt_version, load_prompt_definition, load_template_steps
|
||||||
|
from prompt_validation import PLACEHOLDER_PATTERN, PlaceholderValidationError, validate_placeholder_input
|
||||||
|
from services.audit import log_audit
|
||||||
|
|
||||||
|
PLACEHOLDER_SUB = re.compile(r"\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}")
|
||||||
|
|
||||||
|
|
||||||
|
class PromptRenderError(Exception):
|
||||||
|
def __init__(self, message: str, *, code: str = "render_error"):
|
||||||
|
super().__init__(message)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
def _render_template(template: str, values: dict[str, Any]) -> str:
|
||||||
|
def replacer(match: re.Match[str]) -> str:
|
||||||
|
key = match.group(1)
|
||||||
|
if key not in values:
|
||||||
|
return match.group(0)
|
||||||
|
value = values[key]
|
||||||
|
if isinstance(value, (dict, list)):
|
||||||
|
return json.dumps(value, ensure_ascii=False)
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
return PLACEHOLDER_SUB.sub(replacer, template)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_template_body(version: dict) -> tuple[str, str]:
|
||||||
|
"""Return (template_body, source) where source is 'body' or 'step'."""
|
||||||
|
steps = load_template_steps(version["id"])
|
||||||
|
template_steps = [s for s in steps if s["step_type"] == "template" and s["template_body"]]
|
||||||
|
if template_steps:
|
||||||
|
step = template_steps[0]
|
||||||
|
return step["template_body"], f"step:{step['step_key']}"
|
||||||
|
if version.get("body"):
|
||||||
|
return version["body"], "body"
|
||||||
|
raise PromptRenderError("No template body or template step found", code="no_template")
|
||||||
|
|
||||||
|
|
||||||
|
def _write_execution_log(
|
||||||
|
*,
|
||||||
|
definition: dict,
|
||||||
|
version: dict,
|
||||||
|
status: str,
|
||||||
|
rendered_preview: str | None,
|
||||||
|
input_summary: dict | None,
|
||||||
|
error_message: str | None,
|
||||||
|
user_id: str | None,
|
||||||
|
) -> None:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO prompt_execution_logs (
|
||||||
|
prompt_definition_id, prompt_version_id, execution_mode,
|
||||||
|
status, rendered_preview, input_summary, error_message, created_by
|
||||||
|
)
|
||||||
|
VALUES (%s::uuid, %s::uuid, %s, %s, %s, %s::jsonb, %s, %s::uuid)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
definition["id"],
|
||||||
|
version["id"],
|
||||||
|
definition["execution_mode"],
|
||||||
|
status,
|
||||||
|
rendered_preview,
|
||||||
|
json.dumps(input_summary) if input_summary else None,
|
||||||
|
error_message,
|
||||||
|
user_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def render_prompt_single(
|
||||||
|
prompt_key: str,
|
||||||
|
*,
|
||||||
|
values: dict[str, Any],
|
||||||
|
user_id: str | None = None,
|
||||||
|
log_execution: bool = True,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
definition = load_prompt_definition(prompt_key)
|
||||||
|
if not definition:
|
||||||
|
raise PromptRenderError(f"Unknown prompt: {prompt_key}", code="not_found")
|
||||||
|
if definition["status"] != "active":
|
||||||
|
raise PromptRenderError(f"Prompt not active: {prompt_key}", code="inactive")
|
||||||
|
|
||||||
|
execution_mode = definition["execution_mode"]
|
||||||
|
if execution_mode in ("pipeline", "workflow"):
|
||||||
|
raise PromptRenderError(
|
||||||
|
f"execution_mode '{execution_mode}' is not implemented in AP0.4",
|
||||||
|
code="mode_not_implemented",
|
||||||
|
)
|
||||||
|
|
||||||
|
version = load_active_prompt_version(definition)
|
||||||
|
if not version:
|
||||||
|
raise PromptRenderError("No active prompt version", code="no_version")
|
||||||
|
|
||||||
|
template_body, template_source = _resolve_template_body(version)
|
||||||
|
|
||||||
|
try:
|
||||||
|
validation = validate_placeholder_input(
|
||||||
|
template=template_body,
|
||||||
|
context_kind=definition["context_kind"],
|
||||||
|
values=values,
|
||||||
|
)
|
||||||
|
rendered = _render_template(template_body, values)
|
||||||
|
result = {
|
||||||
|
"prompt_key": prompt_key,
|
||||||
|
"version": version["version"],
|
||||||
|
"execution_mode": execution_mode,
|
||||||
|
"template_source": template_source,
|
||||||
|
"rendered_text": rendered,
|
||||||
|
"validation": validation,
|
||||||
|
}
|
||||||
|
if log_execution:
|
||||||
|
_write_execution_log(
|
||||||
|
definition=definition,
|
||||||
|
version=version,
|
||||||
|
status="success",
|
||||||
|
rendered_preview=rendered[:2000],
|
||||||
|
input_summary={"keys": sorted(values.keys())},
|
||||||
|
error_message=None,
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
except PlaceholderValidationError as exc:
|
||||||
|
if log_execution:
|
||||||
|
_write_execution_log(
|
||||||
|
definition=definition,
|
||||||
|
version=version,
|
||||||
|
status="error",
|
||||||
|
rendered_preview=None,
|
||||||
|
input_summary={"keys": sorted(values.keys())},
|
||||||
|
error_message=str(exc),
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
log_audit(
|
||||||
|
"prompt.render.failed",
|
||||||
|
user_id=user_id,
|
||||||
|
details={
|
||||||
|
"prompt_key": prompt_key,
|
||||||
|
"missing": exc.missing,
|
||||||
|
"type_errors": exc.type_errors,
|
||||||
|
"unknown": exc.unknown,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
raise PromptRenderError(str(exc), code="validation_failed") from exc
|
||||||
|
except PromptRenderError:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
if log_execution:
|
||||||
|
_write_execution_log(
|
||||||
|
definition=definition,
|
||||||
|
version=version,
|
||||||
|
status="error",
|
||||||
|
rendered_preview=None,
|
||||||
|
input_summary={"keys": sorted(values.keys())},
|
||||||
|
error_message=str(exc),
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
raise PromptRenderError(str(exc), code="render_error") from exc
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"""Placeholder extraction and validation for prompt templates."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from placeholder_registry import load_placeholders_for_context
|
||||||
|
|
||||||
|
PLACEHOLDER_PATTERN = re.compile(r"\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}")
|
||||||
|
|
||||||
|
|
||||||
|
class PlaceholderValidationError(Exception):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str,
|
||||||
|
*,
|
||||||
|
missing: list[str] | None = None,
|
||||||
|
type_errors: list[str] | None = None,
|
||||||
|
unknown: list[str] | None = None,
|
||||||
|
):
|
||||||
|
super().__init__(message)
|
||||||
|
self.missing = missing or []
|
||||||
|
self.type_errors = type_errors or []
|
||||||
|
self.unknown = unknown or []
|
||||||
|
|
||||||
|
|
||||||
|
def extract_placeholders(template: str) -> set[str]:
|
||||||
|
return set(PLACEHOLDER_PATTERN.findall(template))
|
||||||
|
|
||||||
|
|
||||||
|
def _check_value_type(value: Any, value_type: str) -> bool:
|
||||||
|
if value_type == "string":
|
||||||
|
return isinstance(value, str)
|
||||||
|
if value_type == "number":
|
||||||
|
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
||||||
|
if value_type == "boolean":
|
||||||
|
return isinstance(value, bool)
|
||||||
|
if value_type == "object":
|
||||||
|
return isinstance(value, dict)
|
||||||
|
if value_type == "array":
|
||||||
|
return isinstance(value, list)
|
||||||
|
if value_type == "json":
|
||||||
|
return True
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def validate_placeholder_input(
|
||||||
|
*,
|
||||||
|
template: str,
|
||||||
|
context_kind: str,
|
||||||
|
values: dict[str, Any],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Validate input values against registry; return metadata including unknown placeholders."""
|
||||||
|
registry = {p["placeholder_key"]: p for p in load_placeholders_for_context(context_kind)}
|
||||||
|
used = extract_placeholders(template)
|
||||||
|
missing: list[str] = []
|
||||||
|
type_errors: list[str] = []
|
||||||
|
unknown = sorted(key for key in used if key not in registry)
|
||||||
|
|
||||||
|
for key, meta in registry.items():
|
||||||
|
if meta["required"] and key not in values:
|
||||||
|
missing.append(key)
|
||||||
|
if key in values and not _check_value_type(values[key], meta["value_type"]):
|
||||||
|
type_errors.append(f"{key}: expected {meta['value_type']}")
|
||||||
|
|
||||||
|
if missing or type_errors:
|
||||||
|
raise PlaceholderValidationError(
|
||||||
|
"Placeholder validation failed",
|
||||||
|
missing=missing,
|
||||||
|
type_errors=type_errors,
|
||||||
|
unknown=unknown,
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"used_placeholders": sorted(used),
|
||||||
|
"unknown_placeholders": unknown,
|
||||||
|
"optional_missing": sorted(
|
||||||
|
key for key in registry if not registry[key]["required"] and key not in values
|
||||||
|
),
|
||||||
|
}
|
||||||
@@ -3,3 +3,5 @@ uvicorn[standard]==0.29.0
|
|||||||
psycopg2-binary==2.9.9
|
psycopg2-binary==2.9.9
|
||||||
sqlparse>=0.5.0
|
sqlparse>=0.5.0
|
||||||
pydantic==2.7.1
|
pydantic==2.7.1
|
||||||
|
email-validator>=2.1.0
|
||||||
|
bcrypt>=4.1.0
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
"""Import all module registrations — side effect registers capabilities."""
|
||||||
|
|
||||||
|
from . import platform, registry_ops, tenant_ops # noqa: F401
|
||||||
|
|
||||||
|
__all__ = ["platform", "registry_ops", "tenant_ops"]
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Platform-level Kairo capabilities."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from rights_registry import CapabilityRegistration, register_capability
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.admin.access",
|
||||||
|
module="platform",
|
||||||
|
description="Zugriff auf Portal-Administration und Admin-Endpunkte",
|
||||||
|
default_grants=(("portal", "admin"),),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.context.read",
|
||||||
|
module="platform",
|
||||||
|
description="TenantContext und Session-Kontext lesen",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("portal", "user"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.entitlements.read",
|
||||||
|
module="platform",
|
||||||
|
description="Entitlements-Snapshot lesen",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("portal", "user"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""AP0.4 registry and prompt capabilities."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from rights_registry import CapabilityRegistration, register_capability
|
||||||
|
|
||||||
|
_TENANT_READ = (
|
||||||
|
("portal", "admin"),
|
||||||
|
("portal", "user"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
("tenant", "member"),
|
||||||
|
)
|
||||||
|
|
||||||
|
_TENANT_ADMIN = (
|
||||||
|
("portal", "admin"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.feature.registry.read",
|
||||||
|
module="feature",
|
||||||
|
description="Feature Registry lesen",
|
||||||
|
default_grants=_TENANT_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.feature.registry.manage",
|
||||||
|
module="feature",
|
||||||
|
description="Feature Registry verwalten (Sync/Metadaten)",
|
||||||
|
default_grants=(("portal", "admin"),),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.prompt.registry.read",
|
||||||
|
module="prompt",
|
||||||
|
description="Prompt Registry lesen",
|
||||||
|
default_grants=_TENANT_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.prompt.registry.manage",
|
||||||
|
module="prompt",
|
||||||
|
description="Prompt Registry verwalten",
|
||||||
|
default_grants=(("portal", "admin"),),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.config.registry.read",
|
||||||
|
module="config",
|
||||||
|
description="Configuration Registry lesen",
|
||||||
|
default_grants=_TENANT_ADMIN,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.config.registry.manage",
|
||||||
|
module="config",
|
||||||
|
description="Configuration Registry schreiben",
|
||||||
|
default_grants=_TENANT_ADMIN,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.prompt.render",
|
||||||
|
module="prompt",
|
||||||
|
description="Prompts rendern (ohne LLM)",
|
||||||
|
default_grants=_TENANT_READ,
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""Tenant and actor management capabilities."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from rights_registry import CapabilityRegistration, register_capability
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.tenant.manage",
|
||||||
|
module="tenant",
|
||||||
|
description="Tenant-Einstellungen und Mandantenverwaltung",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
register_capability(
|
||||||
|
CapabilityRegistration(
|
||||||
|
key="kairo.actor.manage",
|
||||||
|
module="tenant",
|
||||||
|
description="Actors im aktiven Tenant verwalten",
|
||||||
|
default_grants=(
|
||||||
|
("portal", "admin"),
|
||||||
|
("tenant", "owner"),
|
||||||
|
("tenant", "admin"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"""In-memory capability registry with startup sync to PostgreSQL."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
|
||||||
|
RoleGrant = tuple[str, str] # (role_scope, role_code)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CapabilityRegistration:
|
||||||
|
key: str
|
||||||
|
module: str
|
||||||
|
description: str
|
||||||
|
default_grants: tuple[RoleGrant, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
_REGISTRY: dict[str, CapabilityRegistration] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def register_capability(registration: CapabilityRegistration) -> None:
|
||||||
|
if not registration.key or not registration.key.strip():
|
||||||
|
raise ValueError("Capability key is required")
|
||||||
|
if not registration.module or not registration.module.strip():
|
||||||
|
raise ValueError("Capability module is required")
|
||||||
|
if not registration.description or not registration.description.strip():
|
||||||
|
raise ValueError("Capability description is required")
|
||||||
|
if registration.key in _REGISTRY:
|
||||||
|
raise ValueError(f"Capability already registered: {registration.key}")
|
||||||
|
_REGISTRY[registration.key] = registration
|
||||||
|
|
||||||
|
|
||||||
|
def get_registered_capabilities() -> tuple[CapabilityRegistration, ...]:
|
||||||
|
return tuple(_REGISTRY.values())
|
||||||
|
|
||||||
|
|
||||||
|
def clear_registry_for_tests() -> None:
|
||||||
|
"""Test helper — reset in-memory registry."""
|
||||||
|
_REGISTRY.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def sync_rights_registry_to_db() -> int:
|
||||||
|
"""Upsert capabilities and ensure default grants from registry."""
|
||||||
|
if not _REGISTRY:
|
||||||
|
print("[rights_registry] Keine Capabilities registriert — Sync übersprungen")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
for reg in _REGISTRY.values():
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO capabilities (capability_key, module, description, is_active)
|
||||||
|
VALUES (%s, %s, %s, TRUE)
|
||||||
|
ON CONFLICT (capability_key) DO UPDATE SET
|
||||||
|
module = EXCLUDED.module,
|
||||||
|
description = EXCLUDED.description,
|
||||||
|
is_active = TRUE,
|
||||||
|
updated_at = NOW()
|
||||||
|
""",
|
||||||
|
(reg.key, reg.module, reg.description),
|
||||||
|
)
|
||||||
|
for role_scope, role_code in reg.default_grants:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO role_capability_grants (role_scope, role_code, capability_key)
|
||||||
|
VALUES (%s, %s, %s)
|
||||||
|
ON CONFLICT (role_scope, role_code, capability_key) DO NOTHING
|
||||||
|
""",
|
||||||
|
(role_scope, role_code, reg.key),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
print(f"[rights_registry] Sync OK — {len(_REGISTRY)} Capability(s)")
|
||||||
|
return 0
|
||||||
|
except Exception as exc:
|
||||||
|
conn.rollback()
|
||||||
|
print(f"[rights_registry] Sync FAIL: {exc}")
|
||||||
|
return 1
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def load_grants_for_roles(
|
||||||
|
*,
|
||||||
|
portal_role: str,
|
||||||
|
tenant_role: str | None,
|
||||||
|
) -> set[str]:
|
||||||
|
"""Resolve capability keys granted by portal and optional tenant role."""
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
keys: set[str] = set()
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT c.capability_key
|
||||||
|
FROM role_capability_grants g
|
||||||
|
JOIN capabilities c ON c.capability_key = g.capability_key
|
||||||
|
WHERE g.role_scope = 'portal'
|
||||||
|
AND g.role_code = %s
|
||||||
|
AND c.is_active = TRUE
|
||||||
|
""",
|
||||||
|
(portal_role,),
|
||||||
|
)
|
||||||
|
keys.update(row[0] for row in cur.fetchall())
|
||||||
|
|
||||||
|
if tenant_role:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT c.capability_key
|
||||||
|
FROM role_capability_grants g
|
||||||
|
JOIN capabilities c ON c.capability_key = g.capability_key
|
||||||
|
WHERE g.role_scope = 'tenant'
|
||||||
|
AND g.role_code = %s
|
||||||
|
AND c.is_active = TRUE
|
||||||
|
""",
|
||||||
|
(tenant_role,),
|
||||||
|
)
|
||||||
|
keys.update(row[0] for row in cur.fetchall())
|
||||||
|
return keys
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
Whitespace-only changes.
@@ -0,0 +1,51 @@
|
|||||||
|
"""Auth endpoints: login, logout, registration."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from auth import login, logout, require_auth
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from services.registration import register_system_admin, setup_status
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||||
|
|
||||||
|
|
||||||
|
class LoginRequest(BaseModel):
|
||||||
|
email: str = Field(min_length=3, max_length=255)
|
||||||
|
password: str = Field(min_length=8, max_length=256)
|
||||||
|
|
||||||
|
|
||||||
|
class RegisterRequest(BaseModel):
|
||||||
|
email: str = Field(min_length=3, max_length=255)
|
||||||
|
password: str = Field(min_length=8, max_length=256)
|
||||||
|
display_name: str = Field(min_length=1, max_length=255)
|
||||||
|
organization_name: str | None = Field(default=None, max_length=255)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/setup-status")
|
||||||
|
def auth_setup_status():
|
||||||
|
return setup_status()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/register")
|
||||||
|
def auth_register(body: RegisterRequest):
|
||||||
|
"""Erster User wird Portal-Systemadmin inkl. Default-Tenant."""
|
||||||
|
return register_system_admin(
|
||||||
|
email=body.email,
|
||||||
|
password=body.password,
|
||||||
|
display_name=body.display_name,
|
||||||
|
organization_name=body.organization_name,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login")
|
||||||
|
def auth_login(body: LoginRequest):
|
||||||
|
return login(body.email, body.password)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/logout")
|
||||||
|
def auth_logout(session: dict = Depends(require_auth)):
|
||||||
|
token = session.get("token")
|
||||||
|
if token:
|
||||||
|
logout(token)
|
||||||
|
return {"ok": True}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"""Configuration registry API."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from capabilities import require_capability_ctx
|
||||||
|
from config_service import SECRET_VALUE_FORBIDDEN, list_configs, upsert_config
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/config", tags=["config"])
|
||||||
|
|
||||||
|
|
||||||
|
class ConfigUpsertRequest(BaseModel):
|
||||||
|
config_key: str
|
||||||
|
scope: str = "global"
|
||||||
|
value: Any = None
|
||||||
|
value_type: str = "string"
|
||||||
|
description: str = ""
|
||||||
|
is_secret: bool = False
|
||||||
|
tenant_id: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def get_configs(
|
||||||
|
scope: str | None = None,
|
||||||
|
ctx: TenantContext = Depends(require_capability_ctx("kairo.config.registry.read")),
|
||||||
|
):
|
||||||
|
tenant_id = ctx.tenant_id if scope == "tenant" else None
|
||||||
|
if scope == "tenant" and not tenant_id:
|
||||||
|
raise HTTPException(status_code=400, detail="Aktiver Tenant erforderlich für tenant-scope")
|
||||||
|
return list_configs(scope=scope, tenant_id=tenant_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
def post_config(
|
||||||
|
body: ConfigUpsertRequest,
|
||||||
|
ctx: TenantContext = Depends(require_capability_ctx("kairo.config.registry.manage")),
|
||||||
|
):
|
||||||
|
tenant_id = body.tenant_id
|
||||||
|
if body.scope == "tenant":
|
||||||
|
tenant_id = tenant_id or ctx.tenant_id
|
||||||
|
if not tenant_id:
|
||||||
|
raise HTTPException(status_code=400, detail="tenant_id erforderlich")
|
||||||
|
try:
|
||||||
|
return upsert_config(
|
||||||
|
config_key=body.config_key,
|
||||||
|
scope=body.scope,
|
||||||
|
value=body.value,
|
||||||
|
value_type=body.value_type,
|
||||||
|
description=body.description,
|
||||||
|
is_secret=body.is_secret,
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
user_id=ctx.user_id,
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
if str(exc) == SECRET_VALUE_FORBIDDEN:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Feature registry API."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from capabilities import require_capability_ctx
|
||||||
|
from db import get_connection
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/features", tags=["features"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_features(_ctx=Depends(require_capability_ctx("kairo.feature.registry.read"))):
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT feature_key, module, name, description, is_active
|
||||||
|
FROM features
|
||||||
|
ORDER BY feature_key
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"feature_key": row[0],
|
||||||
|
"module": row[1],
|
||||||
|
"name": row[2],
|
||||||
|
"description": row[3],
|
||||||
|
"is_active": row[4],
|
||||||
|
}
|
||||||
|
for row in cur.fetchall()
|
||||||
|
]
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"""Current user, tenant context and entitlements endpoints."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from auth import get_session, require_auth, set_session_active_tenant
|
||||||
|
from capabilities import require_capability
|
||||||
|
from entitlements import build_entitlements_snapshot
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from tenant_context import TenantContext, get_tenant_context, list_user_tenants, require_tenant_context, resolve_tenant_context
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/me", tags=["me"])
|
||||||
|
|
||||||
|
|
||||||
|
class SwitchTenantRequest(BaseModel):
|
||||||
|
tenant_id: str
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def get_me(session: dict = Depends(require_auth)):
|
||||||
|
tenants = list_user_tenants(str(session["user_id"]))
|
||||||
|
return {
|
||||||
|
"id": str(session["user_id"]),
|
||||||
|
"email": session["email"],
|
||||||
|
"display_name": session["display_name"],
|
||||||
|
"portal_role": session["portal_role"],
|
||||||
|
"active_tenant_id": str(session["active_tenant_id"]) if session.get("active_tenant_id") else None,
|
||||||
|
"tenants": tenants,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/context")
|
||||||
|
def get_my_context(ctx: TenantContext = Depends(get_tenant_context)):
|
||||||
|
return ctx.to_dict()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/context/required")
|
||||||
|
def get_my_context_with_tenant(ctx: TenantContext = Depends(require_tenant_context)):
|
||||||
|
"""Endpoint requiring an active tenant."""
|
||||||
|
return ctx.to_dict()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/entitlements")
|
||||||
|
def get_my_entitlements(ctx: TenantContext = Depends(get_tenant_context)):
|
||||||
|
return build_entitlements_snapshot(ctx)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/admin/demo")
|
||||||
|
def admin_demo(ctx: TenantContext = Depends(require_capability("kairo.admin.access"))):
|
||||||
|
"""Example endpoint protected by require_capability."""
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"message": "Portal-Admin Capability bestätigt",
|
||||||
|
"user_id": ctx.user_id,
|
||||||
|
"tenant_id": ctx.tenant_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/tenant")
|
||||||
|
def switch_tenant(body: SwitchTenantRequest, session: dict = Depends(require_auth)):
|
||||||
|
ok = set_session_active_tenant(session["token"], body.tenant_id)
|
||||||
|
if not ok:
|
||||||
|
raise HTTPException(status_code=403, detail="Tenant nicht erlaubt")
|
||||||
|
fresh = get_session(session["token"])
|
||||||
|
if not fresh:
|
||||||
|
raise HTTPException(status_code=401, detail="Session ungültig")
|
||||||
|
return resolve_tenant_context(fresh).to_dict()
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Prompt registry and rendering API."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from capabilities import require_capability_ctx
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from prompt_context import merge_context_values
|
||||||
|
from prompt_registry import list_prompt_definitions, load_active_prompt_version, load_prompt_definition
|
||||||
|
from prompt_rendering import PromptRenderError, render_prompt_single
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from tenant_context import TenantContext
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/prompts", tags=["prompts"])
|
||||||
|
|
||||||
|
|
||||||
|
class RenderPromptRequest(BaseModel):
|
||||||
|
values: dict[str, Any] = Field(default_factory=dict)
|
||||||
|
use_context: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
def list_prompts(_ctx=Depends(require_capability_ctx("kairo.prompt.registry.read"))):
|
||||||
|
return list_prompt_definitions()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{prompt_key}")
|
||||||
|
def get_prompt(prompt_key: str, _ctx=Depends(require_capability_ctx("kairo.prompt.registry.read"))):
|
||||||
|
definition = load_prompt_definition(prompt_key)
|
||||||
|
if not definition:
|
||||||
|
raise HTTPException(status_code=404, detail="Prompt nicht gefunden")
|
||||||
|
version = load_active_prompt_version(definition)
|
||||||
|
return {
|
||||||
|
"definition": definition,
|
||||||
|
"active_version": version,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{prompt_key}/render")
|
||||||
|
def render_prompt(
|
||||||
|
prompt_key: str,
|
||||||
|
body: RenderPromptRequest,
|
||||||
|
ctx: TenantContext = Depends(require_capability_ctx("kairo.prompt.render")),
|
||||||
|
):
|
||||||
|
definition = load_prompt_definition(prompt_key)
|
||||||
|
if not definition:
|
||||||
|
raise HTTPException(status_code=404, detail="Prompt nicht gefunden")
|
||||||
|
|
||||||
|
if body.use_context and definition["context_kind"] in (
|
||||||
|
"kairo.tenant_context",
|
||||||
|
"kairo.actor_context",
|
||||||
|
):
|
||||||
|
if not ctx.tenant_id:
|
||||||
|
raise HTTPException(status_code=403, detail="Aktiver Tenant erforderlich für diesen Prompt")
|
||||||
|
|
||||||
|
values = body.values
|
||||||
|
if body.use_context:
|
||||||
|
values = merge_context_values(ctx, definition["context_kind"], body.values)
|
||||||
|
|
||||||
|
try:
|
||||||
|
return render_prompt_single(
|
||||||
|
prompt_key,
|
||||||
|
values=values,
|
||||||
|
user_id=ctx.user_id,
|
||||||
|
log_execution=True,
|
||||||
|
)
|
||||||
|
except PromptRenderError as exc:
|
||||||
|
status = 400
|
||||||
|
if exc.code == "not_found":
|
||||||
|
status = 404
|
||||||
|
elif exc.code == "mode_not_implemented":
|
||||||
|
status = 501
|
||||||
|
raise HTTPException(status_code=status, detail=str(exc)) from exc
|
||||||
@@ -8,13 +8,12 @@ import re
|
|||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import time
|
|
||||||
from typing import List, Tuple
|
from typing import List, Tuple
|
||||||
|
|
||||||
import psycopg2
|
import psycopg2
|
||||||
import sqlparse
|
import sqlparse
|
||||||
|
|
||||||
from db import db_params, get_connection
|
from db import check_db, connect_with_retry, db_params, get_connection
|
||||||
|
|
||||||
_LEADING_DIGITS = re.compile(r"^(\d+)")
|
_LEADING_DIGITS = re.compile(r"^(\d+)")
|
||||||
|
|
||||||
@@ -135,21 +134,6 @@ def run_migration(conn, migration_name: str, filepath: str) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def connect_with_retry(max_retries: int = 30):
|
|
||||||
p = db_params()
|
|
||||||
for attempt in range(max_retries):
|
|
||||||
try:
|
|
||||||
conn = get_connection()
|
|
||||||
conn.autocommit = False
|
|
||||||
print(f"[OK] Connected to database: {p['dbname']}")
|
|
||||||
return conn
|
|
||||||
except psycopg2.OperationalError:
|
|
||||||
if attempt >= max_retries - 1:
|
|
||||||
raise
|
|
||||||
print(f"Waiting for database... ({attempt + 1}/{max_retries})")
|
|
||||||
time.sleep(2)
|
|
||||||
|
|
||||||
|
|
||||||
def migrations_directory() -> str:
|
def migrations_directory() -> str:
|
||||||
docker_path = "/app/migrations"
|
docker_path = "/app/migrations"
|
||||||
if os.path.isdir(docker_path):
|
if os.path.isdir(docker_path):
|
||||||
|
|||||||
@@ -0,0 +1,260 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Apply idempotent data seeds with checksum-based tracking and re-run on change."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import importlib.util
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from typing import Callable, List, Optional, Tuple
|
||||||
|
|
||||||
|
import psycopg2
|
||||||
|
import sqlparse
|
||||||
|
|
||||||
|
from db import connect_with_retry, db_params, get_connection
|
||||||
|
|
||||||
|
_SEED_PREFIX = re.compile(r"^seed_(\d+)_(.+)$")
|
||||||
|
_DEV_MARKER = ".dev."
|
||||||
|
|
||||||
|
|
||||||
|
def is_production() -> bool:
|
||||||
|
return os.getenv("ENVIRONMENT", "development").strip().lower() == "production"
|
||||||
|
|
||||||
|
|
||||||
|
def seeds_directory() -> str:
|
||||||
|
docker_path = "/app/seeds"
|
||||||
|
if os.path.isdir(docker_path):
|
||||||
|
return docker_path
|
||||||
|
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "seeds")
|
||||||
|
|
||||||
|
|
||||||
|
def init_data_seeds_table(conn) -> None:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS data_seeds (
|
||||||
|
seed_name VARCHAR(255) PRIMARY KEY,
|
||||||
|
checksum VARCHAR(64) NOT NULL,
|
||||||
|
executed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
last_run_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_sort_key(filename: str) -> Tuple[int, str]:
|
||||||
|
stem = filename
|
||||||
|
for suffix in (".sql", ".py"):
|
||||||
|
if stem.endswith(suffix):
|
||||||
|
stem = stem[: -len(suffix)]
|
||||||
|
break
|
||||||
|
match = _SEED_PREFIX.match(stem)
|
||||||
|
if match:
|
||||||
|
return (int(match.group(1)), stem)
|
||||||
|
return (0, stem)
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_stem(filename: str) -> str:
|
||||||
|
if filename.endswith(".dev.sql"):
|
||||||
|
return filename[: -len(".dev.sql")]
|
||||||
|
if filename.endswith(".sql"):
|
||||||
|
return filename[: -len(".sql")]
|
||||||
|
if filename.endswith(".py"):
|
||||||
|
return filename[: -len(".py")]
|
||||||
|
return filename
|
||||||
|
|
||||||
|
|
||||||
|
def seed_files(seeds_dir: str) -> List[Tuple[str, str, str]]:
|
||||||
|
"""Return (seed_name, filepath, kind) sorted by numeric prefix."""
|
||||||
|
rows: List[Tuple[str, str, str]] = []
|
||||||
|
if not os.path.isdir(seeds_dir):
|
||||||
|
return rows
|
||||||
|
|
||||||
|
for filename in os.listdir(seeds_dir):
|
||||||
|
if filename.startswith("_") or not filename.startswith("seed_"):
|
||||||
|
continue
|
||||||
|
if filename.endswith(".sql"):
|
||||||
|
kind = "sql"
|
||||||
|
elif filename.endswith(".py"):
|
||||||
|
kind = "py"
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
stem = _seed_stem(filename)
|
||||||
|
rows.append((stem, os.path.join(seeds_dir, filename), kind))
|
||||||
|
|
||||||
|
rows.sort(key=lambda item: _seed_sort_key(item[0]))
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def seed_applies_in_environment(filename: str) -> bool:
|
||||||
|
if _DEV_MARKER in filename and is_production():
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def file_checksum(filepath: str) -> str:
|
||||||
|
digest = hashlib.sha256()
|
||||||
|
with open(filepath, "rb") as handle:
|
||||||
|
for chunk in iter(lambda: handle.read(65536), b""):
|
||||||
|
digest.update(chunk)
|
||||||
|
return digest.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def applied_seed_checksum(conn, seed_name: str) -> Optional[str]:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT checksum FROM data_seeds WHERE seed_name = %s", (seed_name,))
|
||||||
|
row = cur.fetchone()
|
||||||
|
return row[0] if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def record_seed(conn, seed_name: str, checksum: str) -> None:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO data_seeds (seed_name, checksum, executed_at, last_run_at)
|
||||||
|
VALUES (%s, %s, NOW(), NOW())
|
||||||
|
ON CONFLICT (seed_name) DO UPDATE SET
|
||||||
|
checksum = EXCLUDED.checksum,
|
||||||
|
last_run_at = NOW()
|
||||||
|
""",
|
||||||
|
(seed_name, checksum),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _split_statements(sql_text: str) -> List[str]:
|
||||||
|
parts = sqlparse.split(sql_text.strip())
|
||||||
|
return [part.strip() for part in parts if part and part.strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def run_sql_seed(conn, filepath: str) -> None:
|
||||||
|
with open(filepath, "r", encoding="utf-8") as handle:
|
||||||
|
body = handle.read()
|
||||||
|
statements = _split_statements(body)
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
for stmt in statements:
|
||||||
|
cur.execute(stmt)
|
||||||
|
|
||||||
|
|
||||||
|
def run_python_seed(filepath: str) -> None:
|
||||||
|
module_name = f"kairo_seed_{hashlib.md5(filepath.encode()).hexdigest()[:12]}"
|
||||||
|
spec = importlib.util.spec_from_file_location(module_name, filepath)
|
||||||
|
if spec is None or spec.loader is None:
|
||||||
|
raise RuntimeError(f"Seed-Modul nicht ladbar: {filepath}")
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
run_fn: Callable[[], None] | None = getattr(module, "run", None)
|
||||||
|
if run_fn is None:
|
||||||
|
raise RuntimeError(f"Seed {filepath} hat keine run()-Funktion")
|
||||||
|
run_fn()
|
||||||
|
|
||||||
|
|
||||||
|
def run_seed(conn, seed_name: str, filepath: str, kind: str) -> tuple[bool, object]:
|
||||||
|
print(f"Running seed: {seed_name}")
|
||||||
|
try:
|
||||||
|
if kind == "sql":
|
||||||
|
run_sql_seed(conn, filepath)
|
||||||
|
else:
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
run_python_seed(filepath)
|
||||||
|
conn = connect_with_retry(max_retries=5)
|
||||||
|
|
||||||
|
checksum = file_checksum(filepath)
|
||||||
|
record_seed(conn, seed_name, checksum)
|
||||||
|
conn.commit()
|
||||||
|
print(f" [OK] {seed_name}")
|
||||||
|
return True, conn
|
||||||
|
except Exception as exc:
|
||||||
|
try:
|
||||||
|
conn.rollback()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
print(f" [FAIL] {seed_name}: {exc}")
|
||||||
|
return False, conn
|
||||||
|
|
||||||
|
|
||||||
|
def pending_seeds(
|
||||||
|
conn,
|
||||||
|
seeds_dir: str,
|
||||||
|
*,
|
||||||
|
only: Optional[List[str]] = None,
|
||||||
|
force: bool = False,
|
||||||
|
) -> List[Tuple[str, str, str]]:
|
||||||
|
selected: List[Tuple[str, str, str]] = []
|
||||||
|
for seed_name, filepath, kind in seed_files(seeds_dir):
|
||||||
|
filename = os.path.basename(filepath)
|
||||||
|
if not seed_applies_in_environment(filename):
|
||||||
|
print(f" [SKIP] {seed_name} (nur Nicht-Prod)")
|
||||||
|
continue
|
||||||
|
if only and seed_name not in only:
|
||||||
|
continue
|
||||||
|
checksum = file_checksum(filepath)
|
||||||
|
is_dev_seed = _DEV_MARKER in filename
|
||||||
|
always_run = is_dev_seed and not is_production()
|
||||||
|
if force or always_run or applied_seed_checksum(conn, seed_name) != checksum:
|
||||||
|
selected.append((seed_name, filepath, kind))
|
||||||
|
return selected
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: Optional[List[str]] = None) -> int:
|
||||||
|
argv = argv if argv is not None else sys.argv[1:]
|
||||||
|
only: Optional[List[str]] = None
|
||||||
|
force = False
|
||||||
|
|
||||||
|
idx = 0
|
||||||
|
while idx < len(argv):
|
||||||
|
arg = argv[idx]
|
||||||
|
if arg == "--only" and idx + 1 < len(argv):
|
||||||
|
only = [part.strip() for part in argv[idx + 1].split(",") if part.strip()]
|
||||||
|
idx += 2
|
||||||
|
continue
|
||||||
|
if arg == "--force":
|
||||||
|
force = True
|
||||||
|
idx += 1
|
||||||
|
continue
|
||||||
|
print(f"[FAIL] Unbekanntes Argument: {arg}")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
print("=" * 60)
|
||||||
|
print("Jinkendo Kairo — Data Seeds")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
seeds_dir = seeds_directory()
|
||||||
|
if not os.path.isdir(seeds_dir):
|
||||||
|
print(f"[OK] Kein seeds-Verzeichnis ({seeds_dir}) — nichts zu tun.")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn = connect_with_retry()
|
||||||
|
init_data_seeds_table(conn)
|
||||||
|
to_run = pending_seeds(conn, seeds_dir, only=only, force=force)
|
||||||
|
|
||||||
|
if not to_run:
|
||||||
|
print("[OK] Alle Seeds aktuell — nichts auszuführen.")
|
||||||
|
conn.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
print(f"{len(to_run)} Seed(s) ausstehend:")
|
||||||
|
for seed_name, _, _ in to_run:
|
||||||
|
print(f" - {seed_name}")
|
||||||
|
|
||||||
|
for seed_name, filepath, kind in to_run:
|
||||||
|
ok, conn = run_seed(conn, seed_name, filepath, kind)
|
||||||
|
if not ok:
|
||||||
|
conn.close()
|
||||||
|
return 1
|
||||||
|
|
||||||
|
conn.close()
|
||||||
|
print("[OK] Seeds abgeschlossen.")
|
||||||
|
return 0
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[FAIL] {exc}")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
-- Dev/CI: pytest-Artefakte entfernen (idempotent, sicher mehrfach ausführbar).
|
||||||
|
-- Nur in Nicht-Prod-Umgebungen (Dateiname *.dev.sql).
|
||||||
|
|
||||||
|
-- Reparatur: ungültige Human-Actors (user_id NULL verletzt CHECK constraint)
|
||||||
|
DELETE FROM actors WHERE actor_type = 'human' AND user_id IS NULL;
|
||||||
|
|
||||||
|
-- Abhängigkeiten vor User-Löschung (human actors: user_id NOT NULL constraint)
|
||||||
|
DELETE FROM actors
|
||||||
|
WHERE user_id IN (SELECT id FROM users WHERE email ~* '@example\.com$');
|
||||||
|
|
||||||
|
DELETE FROM tenant_memberships
|
||||||
|
WHERE user_id IN (SELECT id FROM users WHERE email ~* '@example\.com$');
|
||||||
|
|
||||||
|
DELETE FROM sessions
|
||||||
|
WHERE user_id IN (SELECT id FROM users WHERE email ~* '@example\.com$');
|
||||||
|
|
||||||
|
DELETE FROM audit_log
|
||||||
|
WHERE user_id IN (SELECT id FROM users WHERE email ~* '@example\.com$');
|
||||||
|
|
||||||
|
DELETE FROM users WHERE email ~* '@example\.com$';
|
||||||
|
|
||||||
|
-- Verwaiste pytest-Tenants (Factory-Slug t-{10 hex}), ohne Memberships
|
||||||
|
DELETE FROM actors a
|
||||||
|
USING tenants t
|
||||||
|
WHERE a.tenant_id = t.id
|
||||||
|
AND t.slug ~ '^t-[a-f0-9]{10}$'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM tenant_memberships tm WHERE tm.tenant_id = t.id
|
||||||
|
);
|
||||||
|
|
||||||
|
DELETE FROM tenants t
|
||||||
|
WHERE t.slug ~ '^t-[a-f0-9]{10}$'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM tenant_memberships tm WHERE tm.tenant_id = t.id
|
||||||
|
);
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
"""Bootstrap portal admin from KAIRO_BOOTSTRAP_* when no users exist."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
def run() -> None:
|
||||||
|
from bootstrap import bootstrap_admin_if_needed
|
||||||
|
|
||||||
|
bootstrap_admin_if_needed()
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
"""Dev: Portal-Admin lars@stommer.com sicherstellen (läuft bei jedem Start in Dev)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
def run() -> None:
|
||||||
|
from services.dev_admin import ensure_dev_admin
|
||||||
|
|
||||||
|
ensure_dev_admin()
|
||||||
Whitespace-only changes.
@@ -0,0 +1,68 @@
|
|||||||
|
"""Actor creation helpers — User and Actor remain separate concepts."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Literal, Optional
|
||||||
|
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
|
||||||
|
ActorType = Literal["human", "agent", "working_group", "external_system"]
|
||||||
|
|
||||||
|
|
||||||
|
def create_actor(
|
||||||
|
*,
|
||||||
|
tenant_id: str,
|
||||||
|
actor_type: ActorType,
|
||||||
|
name: str,
|
||||||
|
user_id: Optional[str] = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if actor_type == "human" and not user_id:
|
||||||
|
raise ValueError("Human actors require user_id")
|
||||||
|
if actor_type != "human" and user_id:
|
||||||
|
raise ValueError("Non-human actors must not have user_id")
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO actors (tenant_id, actor_type, name, user_id)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
RETURNING id, tenant_id, actor_type, name, user_id, is_active, created_at
|
||||||
|
""",
|
||||||
|
(tenant_id, actor_type, name, user_id),
|
||||||
|
)
|
||||||
|
row = dict(cur.fetchone())
|
||||||
|
conn.commit()
|
||||||
|
for key in ("id", "tenant_id", "user_id"):
|
||||||
|
if row.get(key):
|
||||||
|
row[key] = str(row[key])
|
||||||
|
return row
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_human_actor(tenant_id: str, user_id: str) -> Optional[dict[str, Any]]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, tenant_id, actor_type, name, user_id, is_active, created_at
|
||||||
|
FROM actors
|
||||||
|
WHERE tenant_id = %s AND user_id = %s AND actor_type = 'human'
|
||||||
|
""",
|
||||||
|
(tenant_id, user_id),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
result = dict(row)
|
||||||
|
for key in ("id", "tenant_id", "user_id"):
|
||||||
|
if result.get(key):
|
||||||
|
result[key] = str(result[key])
|
||||||
|
return result
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Minimal audit logging for critical auth actions (AP0.2)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
|
||||||
|
|
||||||
|
def log_audit(
|
||||||
|
action: str,
|
||||||
|
*,
|
||||||
|
user_id: Optional[str] = None,
|
||||||
|
tenant_id: Optional[str] = None,
|
||||||
|
details: Optional[dict[str, Any]] = None,
|
||||||
|
) -> None:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO audit_log (action, user_id, tenant_id, details)
|
||||||
|
VALUES (%s, %s, %s, %s::jsonb)
|
||||||
|
""",
|
||||||
|
(action, user_id, tenant_id, json.dumps(details or {})),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
"""Dev-only admin seed — ensures a known portal admin exists."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from typing import Iterable
|
||||||
|
|
||||||
|
from auth import hash_password
|
||||||
|
from db import get_connection
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
|
||||||
|
from services.actors import create_actor, get_human_actor
|
||||||
|
from services.audit import log_audit
|
||||||
|
from services.registration import provision_system_admin, user_count
|
||||||
|
|
||||||
|
DEV_ADMIN_EMAIL = "lars@stommer.com"
|
||||||
|
DEV_ADMIN_PASSWORD = "12345678"
|
||||||
|
DEV_ADMIN_NAME = "Lars Stommer"
|
||||||
|
DEV_TENANT_SLUG = "stommer"
|
||||||
|
DEV_TENANT_NAME = "Stommer"
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_emails(emails: Iterable[str]) -> tuple[str, ...]:
|
||||||
|
return tuple(sorted({email.strip().lower() for email in emails if email.strip()}))
|
||||||
|
|
||||||
|
|
||||||
|
def delete_users_except(keep_emails: Iterable[str]) -> int:
|
||||||
|
"""Remove all users not in keep_emails (with FK-safe order). Returns deleted count."""
|
||||||
|
keep = _normalize_emails(keep_emails)
|
||||||
|
if not keep:
|
||||||
|
raise ValueError("keep_emails must not be empty")
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("DELETE FROM actors WHERE actor_type = 'human' AND user_id IS NULL")
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
DELETE FROM actors
|
||||||
|
WHERE user_id IN (
|
||||||
|
SELECT id FROM users WHERE lower(email) <> ALL(%s)
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
(list(keep),),
|
||||||
|
)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
DELETE FROM tenant_memberships
|
||||||
|
WHERE user_id IN (
|
||||||
|
SELECT id FROM users WHERE lower(email) <> ALL(%s)
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
(list(keep),),
|
||||||
|
)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
DELETE FROM sessions
|
||||||
|
WHERE user_id IN (
|
||||||
|
SELECT id FROM users WHERE lower(email) <> ALL(%s)
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
(list(keep),),
|
||||||
|
)
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
DELETE FROM audit_log
|
||||||
|
WHERE user_id IN (
|
||||||
|
SELECT id FROM users WHERE lower(email) <> ALL(%s)
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
(list(keep),),
|
||||||
|
)
|
||||||
|
cur.execute(
|
||||||
|
"DELETE FROM users WHERE lower(email) <> ALL(%s) RETURNING email",
|
||||||
|
(list(keep),),
|
||||||
|
)
|
||||||
|
removed = cur.fetchall()
|
||||||
|
conn.commit()
|
||||||
|
return len(removed)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_tenant(conn, *, slug: str, name: str) -> dict:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO tenants (slug, name)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
ON CONFLICT (slug) DO UPDATE SET name = EXCLUDED.name
|
||||||
|
RETURNING id, slug, name
|
||||||
|
""",
|
||||||
|
(slug, name),
|
||||||
|
)
|
||||||
|
return dict(cur.fetchone())
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_dev_admin(
|
||||||
|
*,
|
||||||
|
email: str = DEV_ADMIN_EMAIL,
|
||||||
|
password: str = DEV_ADMIN_PASSWORD,
|
||||||
|
display_name: str = DEV_ADMIN_NAME,
|
||||||
|
tenant_slug: str = DEV_TENANT_SLUG,
|
||||||
|
tenant_name: str = DEV_TENANT_NAME,
|
||||||
|
) -> dict:
|
||||||
|
"""Dev seed: remove other users, ensure portal admin + tenant + human actor."""
|
||||||
|
if os.getenv("ENVIRONMENT", "development").strip().lower() == "production":
|
||||||
|
raise RuntimeError("ensure_dev_admin darf nicht in Production laufen")
|
||||||
|
|
||||||
|
normalized_email = email.strip().lower()
|
||||||
|
removed = delete_users_except([normalized_email])
|
||||||
|
if removed:
|
||||||
|
print(f"[dev_admin] {removed} fremde User entfernt")
|
||||||
|
|
||||||
|
if user_count() == 0:
|
||||||
|
result = provision_system_admin(
|
||||||
|
email=normalized_email,
|
||||||
|
password=password,
|
||||||
|
display_name=display_name,
|
||||||
|
tenant_slug=tenant_slug,
|
||||||
|
tenant_name=tenant_name,
|
||||||
|
source="dev_seed",
|
||||||
|
)
|
||||||
|
print(f"[dev_admin] Portal-Admin angelegt: {normalized_email}")
|
||||||
|
return result
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
tenant = _ensure_tenant(conn, slug=tenant_slug, name=tenant_name)
|
||||||
|
tenant_id = str(tenant["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
UPDATE users
|
||||||
|
SET password_hash = %s,
|
||||||
|
display_name = %s,
|
||||||
|
portal_role = 'admin',
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE lower(email) = %s
|
||||||
|
RETURNING id, email, display_name, portal_role
|
||||||
|
""",
|
||||||
|
(hash_password(password), display_name.strip(), normalized_email),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise RuntimeError(f"Dev-Admin {normalized_email} fehlt nach Bereinigung")
|
||||||
|
user = dict(row)
|
||||||
|
user_id = str(user["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO tenant_memberships (tenant_id, user_id, tenant_role)
|
||||||
|
VALUES (%s, %s, 'owner')
|
||||||
|
ON CONFLICT (tenant_id, user_id) DO UPDATE SET tenant_role = 'owner'
|
||||||
|
""",
|
||||||
|
(tenant_id, user_id),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
if not get_human_actor(tenant_id, user_id):
|
||||||
|
create_actor(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
actor_type="human",
|
||||||
|
name=display_name.strip(),
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
log_audit(
|
||||||
|
"auth.dev_admin_ensure",
|
||||||
|
user_id=user_id,
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
details={"email": normalized_email, "removed_users": removed},
|
||||||
|
)
|
||||||
|
print(f"[dev_admin] Portal-Admin bestätigt: {normalized_email}")
|
||||||
|
return {
|
||||||
|
"user": {
|
||||||
|
"id": user_id,
|
||||||
|
"email": user["email"],
|
||||||
|
"display_name": user["display_name"],
|
||||||
|
"portal_role": user["portal_role"],
|
||||||
|
},
|
||||||
|
"tenant": {"id": tenant_id, "slug": tenant["slug"], "name": tenant["name"]},
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
"""First-user / system-admin provisioning (bootstrap + registration)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from auth import create_session, get_user_by_email, hash_password
|
||||||
|
from db import get_connection
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from services.actors import create_actor
|
||||||
|
from services.audit import log_audit
|
||||||
|
|
||||||
|
|
||||||
|
def user_count() -> int:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT COUNT(*) FROM users")
|
||||||
|
return int(cur.fetchone()[0])
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def registration_open() -> bool:
|
||||||
|
return user_count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def setup_status() -> dict[str, Any]:
|
||||||
|
count = user_count()
|
||||||
|
return {
|
||||||
|
"has_users": count > 0,
|
||||||
|
"registration_open": count == 0,
|
||||||
|
"user_count": count,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _slugify(value: str) -> str:
|
||||||
|
slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
|
||||||
|
return (slug[:48] or "default")
|
||||||
|
|
||||||
|
|
||||||
|
def provision_system_admin(
|
||||||
|
*,
|
||||||
|
email: str,
|
||||||
|
password: str,
|
||||||
|
display_name: str,
|
||||||
|
tenant_slug: str | None = None,
|
||||||
|
tenant_name: str | None = None,
|
||||||
|
source: str = "bootstrap",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Create portal admin, default tenant, owner membership and human actor."""
|
||||||
|
if user_count() > 0:
|
||||||
|
raise ValueError("users_already_exist")
|
||||||
|
|
||||||
|
normalized_email = email.strip().lower()
|
||||||
|
slug = tenant_slug or os.getenv("KAIRO_BOOTSTRAP_TENANT_SLUG") or "default"
|
||||||
|
name = tenant_name or os.getenv("KAIRO_BOOTSTRAP_TENANT_NAME") or "Default Tenant"
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO tenants (slug, name)
|
||||||
|
VALUES (%s, %s)
|
||||||
|
ON CONFLICT (slug) DO UPDATE SET name = EXCLUDED.name
|
||||||
|
RETURNING id, slug, name
|
||||||
|
""",
|
||||||
|
(slug, name),
|
||||||
|
)
|
||||||
|
tenant = dict(cur.fetchone())
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO users (email, password_hash, display_name, portal_role)
|
||||||
|
VALUES (%s, %s, %s, 'admin')
|
||||||
|
RETURNING id, email, display_name, portal_role
|
||||||
|
""",
|
||||||
|
(normalized_email, hash_password(password), display_name.strip()),
|
||||||
|
)
|
||||||
|
user = dict(cur.fetchone())
|
||||||
|
user_id = str(user["id"])
|
||||||
|
tenant_id = str(tenant["id"])
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO tenant_memberships (tenant_id, user_id, tenant_role)
|
||||||
|
VALUES (%s, %s, 'owner')
|
||||||
|
""",
|
||||||
|
(tenant_id, user_id),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
create_actor(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
actor_type="human",
|
||||||
|
name=display_name.strip(),
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
log_audit(
|
||||||
|
"auth.register_system_admin",
|
||||||
|
user_id=user_id,
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
details={"email": normalized_email, "source": source, "tenant_slug": slug},
|
||||||
|
)
|
||||||
|
|
||||||
|
session = create_session(user_id, tenant_id)
|
||||||
|
return {
|
||||||
|
"token": session["token"],
|
||||||
|
"expires_at": session["expires_at"].isoformat(),
|
||||||
|
"user": {
|
||||||
|
"id": user_id,
|
||||||
|
"email": user["email"],
|
||||||
|
"display_name": user["display_name"],
|
||||||
|
"portal_role": user["portal_role"],
|
||||||
|
},
|
||||||
|
"tenant": {"id": tenant_id, "slug": tenant["slug"], "name": tenant["name"]},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def register_system_admin(
|
||||||
|
*,
|
||||||
|
email: str,
|
||||||
|
password: str,
|
||||||
|
display_name: str,
|
||||||
|
organization_name: str | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if get_user_by_email(email):
|
||||||
|
raise HTTPException(status_code=409, detail="E-Mail bereits registriert")
|
||||||
|
|
||||||
|
if not registration_open():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Registrierung geschlossen — Systemadministrator ist bereits eingerichtet",
|
||||||
|
)
|
||||||
|
|
||||||
|
org = (organization_name or display_name or "Default Tenant").strip()
|
||||||
|
slug = _slugify(org)
|
||||||
|
|
||||||
|
return provision_system_admin(
|
||||||
|
email=email,
|
||||||
|
password=password,
|
||||||
|
display_name=display_name.strip(),
|
||||||
|
tenant_slug=slug,
|
||||||
|
tenant_name=org,
|
||||||
|
source="registration",
|
||||||
|
)
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""Startup sync for feature, prompt, placeholder and default config registries."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import feature_registrations # noqa: F401
|
||||||
|
import placeholder_registrations # noqa: F401
|
||||||
|
import prompt_registrations # noqa: F401
|
||||||
|
from config_service import sync_default_configs
|
||||||
|
from feature_registry import sync_features_to_db
|
||||||
|
from placeholder_registry import sync_placeholders_to_db
|
||||||
|
from prompt_registry import sync_prompts_to_db
|
||||||
|
from services.audit import log_audit
|
||||||
|
|
||||||
|
DEFAULT_CONFIGS = [
|
||||||
|
{
|
||||||
|
"config_key": "prompt.default_execution_mode",
|
||||||
|
"scope": "global",
|
||||||
|
"value": "single",
|
||||||
|
"value_type": "string",
|
||||||
|
"description": "Default execution mode for prompt rendering",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"config_key": "prompt.render_logging_enabled",
|
||||||
|
"scope": "global",
|
||||||
|
"value": True,
|
||||||
|
"value_type": "boolean",
|
||||||
|
"description": "Write prompt_execution_logs on render",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"config_key": "features.registry_sync_enabled",
|
||||||
|
"scope": "global",
|
||||||
|
"value": True,
|
||||||
|
"value_type": "boolean",
|
||||||
|
"description": "Enable registry sync on startup",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
results = [
|
||||||
|
sync_features_to_db(),
|
||||||
|
sync_placeholders_to_db(),
|
||||||
|
sync_prompts_to_db(),
|
||||||
|
]
|
||||||
|
sync_default_configs(DEFAULT_CONFIGS)
|
||||||
|
log_audit(
|
||||||
|
"registry.sync.completed",
|
||||||
|
details={
|
||||||
|
"features": results[0] == 0,
|
||||||
|
"placeholders": results[1] == 0,
|
||||||
|
"prompts": results[2] == 0,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return 0 if all(code == 0 for code in results) else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Sync in-memory rights registry to PostgreSQL."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
import rights_registrations # noqa: F401 — side-effect registration
|
||||||
|
from rights_registry import sync_rights_registry_to_db
|
||||||
|
|
||||||
|
return sync_rights_registry_to_db()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
"""TenantContext resolution — single layer, not scattered header logic in routers."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from fastapi import Depends, HTTPException
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
|
||||||
|
from auth import require_auth
|
||||||
|
from db import get_connection
|
||||||
|
from rights_registry import load_grants_for_roles
|
||||||
|
from services.actors import get_human_actor
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class TenantContext:
|
||||||
|
user_id: str
|
||||||
|
email: str
|
||||||
|
display_name: str
|
||||||
|
portal_role: str
|
||||||
|
tenant_id: Optional[str]
|
||||||
|
tenant_slug: Optional[str]
|
||||||
|
tenant_name: Optional[str]
|
||||||
|
tenant_role: Optional[str]
|
||||||
|
actor_id: Optional[str]
|
||||||
|
actor_type: Optional[str]
|
||||||
|
session_token: str
|
||||||
|
capabilities: frozenset[str]
|
||||||
|
|
||||||
|
def to_dict(self) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"user_id": self.user_id,
|
||||||
|
"email": self.email,
|
||||||
|
"display_name": self.display_name,
|
||||||
|
"portal_role": self.portal_role,
|
||||||
|
"capabilities": sorted(self.capabilities),
|
||||||
|
"tenant": (
|
||||||
|
{
|
||||||
|
"id": self.tenant_id,
|
||||||
|
"slug": self.tenant_slug,
|
||||||
|
"name": self.tenant_name,
|
||||||
|
"role": self.tenant_role,
|
||||||
|
}
|
||||||
|
if self.tenant_id
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
"actor": (
|
||||||
|
{
|
||||||
|
"id": self.actor_id,
|
||||||
|
"type": self.actor_type,
|
||||||
|
}
|
||||||
|
if self.actor_id
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def list_user_tenants(user_id: str) -> list[dict[str, Any]]:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT
|
||||||
|
t.id,
|
||||||
|
t.slug,
|
||||||
|
t.name,
|
||||||
|
tm.tenant_role,
|
||||||
|
tm.is_active AS membership_active
|
||||||
|
FROM tenant_memberships tm
|
||||||
|
JOIN tenants t ON t.id = tm.tenant_id
|
||||||
|
WHERE tm.user_id = %s AND tm.is_active = TRUE AND t.is_active = TRUE
|
||||||
|
ORDER BY t.name
|
||||||
|
""",
|
||||||
|
(user_id,),
|
||||||
|
)
|
||||||
|
rows = []
|
||||||
|
for row in cur.fetchall():
|
||||||
|
item = dict(row)
|
||||||
|
item["id"] = str(item["id"])
|
||||||
|
rows.append(item)
|
||||||
|
return rows
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_tenant_context(session: dict[str, Any]) -> TenantContext:
|
||||||
|
user_id = str(session["user_id"])
|
||||||
|
tenant_id = session.get("active_tenant_id")
|
||||||
|
portal_role = session["portal_role"]
|
||||||
|
|
||||||
|
if not tenant_id:
|
||||||
|
caps = frozenset(load_grants_for_roles(portal_role=portal_role, tenant_role=None))
|
||||||
|
return TenantContext(
|
||||||
|
user_id=user_id,
|
||||||
|
email=session["email"],
|
||||||
|
display_name=session["display_name"],
|
||||||
|
portal_role=portal_role,
|
||||||
|
tenant_id=None,
|
||||||
|
tenant_slug=None,
|
||||||
|
tenant_name=None,
|
||||||
|
tenant_role=None,
|
||||||
|
actor_id=None,
|
||||||
|
actor_type=None,
|
||||||
|
session_token=session["token"],
|
||||||
|
capabilities=caps,
|
||||||
|
)
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
SELECT t.id, t.slug, t.name, tm.tenant_role
|
||||||
|
FROM tenant_memberships tm
|
||||||
|
JOIN tenants t ON t.id = tm.tenant_id
|
||||||
|
WHERE tm.user_id = %s
|
||||||
|
AND tm.tenant_id = %s
|
||||||
|
AND tm.is_active = TRUE
|
||||||
|
AND t.is_active = TRUE
|
||||||
|
""",
|
||||||
|
(user_id, tenant_id),
|
||||||
|
)
|
||||||
|
membership = cur.fetchone()
|
||||||
|
if not membership:
|
||||||
|
raise HTTPException(status_code=403, detail="Keine gültige Tenant-Mitgliedschaft")
|
||||||
|
|
||||||
|
tenant_id_str = str(membership["id"])
|
||||||
|
tenant_role = membership["tenant_role"]
|
||||||
|
human = get_human_actor(tenant_id_str, user_id)
|
||||||
|
caps = frozenset(
|
||||||
|
load_grants_for_roles(portal_role=portal_role, tenant_role=tenant_role)
|
||||||
|
)
|
||||||
|
return TenantContext(
|
||||||
|
user_id=user_id,
|
||||||
|
email=session["email"],
|
||||||
|
display_name=session["display_name"],
|
||||||
|
portal_role=portal_role,
|
||||||
|
tenant_id=tenant_id_str,
|
||||||
|
tenant_slug=membership["slug"],
|
||||||
|
tenant_name=membership["name"],
|
||||||
|
tenant_role=tenant_role,
|
||||||
|
actor_id=human["id"] if human else None,
|
||||||
|
actor_type=human["actor_type"] if human else None,
|
||||||
|
session_token=session["token"],
|
||||||
|
capabilities=caps,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_tenant_context(session: dict[str, Any] = Depends(require_auth)) -> TenantContext:
|
||||||
|
return resolve_tenant_context(session)
|
||||||
|
|
||||||
|
|
||||||
|
def require_tenant_context(session: dict[str, Any] = Depends(require_auth)) -> TenantContext:
|
||||||
|
ctx = resolve_tenant_context(session)
|
||||||
|
if not ctx.tenant_id:
|
||||||
|
raise HTTPException(status_code=403, detail="Kein aktiver Tenant — Tenant wählen")
|
||||||
|
return ctx
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""Shared pytest fixtures for AP0.2 auth tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
||||||
|
os.environ.setdefault("SKIP_SEEDS", "1")
|
||||||
|
os.environ.setdefault("SKIP_BOOTSTRAP", "1")
|
||||||
|
os.environ.setdefault("SKIP_RIGHTS_SYNC", "1")
|
||||||
|
os.environ.setdefault("SKIP_REGISTRY_SYNC", "1")
|
||||||
|
|
||||||
|
|
||||||
|
def _db_available() -> bool:
|
||||||
|
try:
|
||||||
|
import psycopg2
|
||||||
|
|
||||||
|
conn = psycopg2.connect(
|
||||||
|
host=os.getenv("DB_HOST", "localhost"),
|
||||||
|
port=os.getenv("DB_PORT", "5432"),
|
||||||
|
dbname=os.getenv("DB_NAME", "kairo_dev"),
|
||||||
|
user=os.getenv("DB_USER", "kairo_dev"),
|
||||||
|
password=os.getenv("DB_PASSWORD", "dev_password"),
|
||||||
|
)
|
||||||
|
conn.close()
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.skipif(not _db_available(), reason="PostgreSQL nicht erreichbar")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session", autouse=True)
|
||||||
|
def _run_migrations():
|
||||||
|
import run_migrations
|
||||||
|
|
||||||
|
assert run_migrations.main() == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session", autouse=True)
|
||||||
|
def _seed_hygiene():
|
||||||
|
"""Vor/nach Tests pytest-Artefakte aus der geteilten Dev-DB entfernen."""
|
||||||
|
import run_seeds
|
||||||
|
|
||||||
|
run_seeds.main(["--only", "seed_001_cleanup_pytest_artifacts"])
|
||||||
|
yield
|
||||||
|
run_seeds.main(["--only", "seed_001_cleanup_pytest_artifacts"])
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session", autouse=True)
|
||||||
|
def _sync_rights_registry():
|
||||||
|
import rights_registrations # noqa: F401
|
||||||
|
from rights_registry import sync_rights_registry_to_db
|
||||||
|
|
||||||
|
assert sync_rights_registry_to_db() == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="session", autouse=True)
|
||||||
|
def _sync_prompt_feature_config():
|
||||||
|
import feature_registrations # noqa: F401
|
||||||
|
import placeholder_registrations # noqa: F401
|
||||||
|
import prompt_registrations # noqa: F401
|
||||||
|
from sync_prompt_feature_config import main as sync_registries
|
||||||
|
|
||||||
|
assert sync_registries() == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def client():
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
import main as main_module
|
||||||
|
|
||||||
|
importlib.reload(main_module)
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
return TestClient(main_module.app)
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""Test data factories (PostgreSQL required)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from auth import hash_password
|
||||||
|
from db import get_connection
|
||||||
|
from services.actors import create_actor
|
||||||
|
|
||||||
|
|
||||||
|
def create_tenant(*, slug: str | None = None, name: str = "Test Tenant") -> str:
|
||||||
|
slug = slug or f"t-{uuid.uuid4().hex[:10]}"
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO tenants (slug, name) VALUES (%s, %s) RETURNING id",
|
||||||
|
(slug, name),
|
||||||
|
)
|
||||||
|
tenant_id = str(cur.fetchone()[0])
|
||||||
|
conn.commit()
|
||||||
|
return tenant_id
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def create_user(
|
||||||
|
*,
|
||||||
|
email: str | None = None,
|
||||||
|
password: str = "test-password-123",
|
||||||
|
display_name: str = "Test User",
|
||||||
|
portal_role: str = "user",
|
||||||
|
) -> dict:
|
||||||
|
email = email or f"user-{uuid.uuid4().hex[:8]}@example.com"
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO users (email, password_hash, display_name, portal_role)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
RETURNING id, email, display_name, portal_role
|
||||||
|
""",
|
||||||
|
(email, hash_password(password), display_name, portal_role),
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
conn.commit()
|
||||||
|
return {
|
||||||
|
"id": str(row[0]),
|
||||||
|
"email": row[1],
|
||||||
|
"display_name": row[2],
|
||||||
|
"portal_role": row[3],
|
||||||
|
"password": password,
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def add_membership(*, tenant_id: str, user_id: str, tenant_role: str = "member") -> None:
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO tenant_memberships (tenant_id, user_id, tenant_role)
|
||||||
|
VALUES (%s, %s, %s)
|
||||||
|
ON CONFLICT (tenant_id, user_id) DO UPDATE SET tenant_role = EXCLUDED.tenant_role
|
||||||
|
""",
|
||||||
|
(tenant_id, user_id, tenant_role),
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def provision_user_in_tenant(
|
||||||
|
*,
|
||||||
|
tenant_role: str = "member",
|
||||||
|
portal_role: str = "user",
|
||||||
|
) -> dict:
|
||||||
|
tenant_id = create_tenant()
|
||||||
|
user = create_user(portal_role=portal_role)
|
||||||
|
add_membership(tenant_id=tenant_id, user_id=user["id"], tenant_role=tenant_role)
|
||||||
|
actor = create_actor(
|
||||||
|
tenant_id=tenant_id,
|
||||||
|
actor_type="human",
|
||||||
|
name=user["display_name"],
|
||||||
|
user_id=user["id"],
|
||||||
|
)
|
||||||
|
return {**user, "tenant_id": tenant_id, "actor_id": actor["id"]}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""Auth endpoint and session tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from auth import AUTH_HEADER, get_session
|
||||||
|
from tests.factories import provision_user_in_tenant
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_logout_and_session(client):
|
||||||
|
user = provision_user_in_tenant()
|
||||||
|
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user["email"], "password": user["password"]},
|
||||||
|
)
|
||||||
|
assert login.status_code == 200
|
||||||
|
payload = login.json()
|
||||||
|
assert "token" in payload
|
||||||
|
assert payload["user"]["email"] == user["email"]
|
||||||
|
token = payload["token"]
|
||||||
|
|
||||||
|
me = client.get("/api/me", headers={AUTH_HEADER: token})
|
||||||
|
assert me.status_code == 200
|
||||||
|
assert me.json()["email"] == user["email"]
|
||||||
|
assert me.json()["active_tenant_id"] == user["tenant_id"]
|
||||||
|
|
||||||
|
logout = client.post("/api/auth/logout", headers={AUTH_HEADER: token})
|
||||||
|
assert logout.status_code == 200
|
||||||
|
assert get_session(token) is None
|
||||||
|
|
||||||
|
me_after = client.get("/api/me", headers={AUTH_HEADER: token})
|
||||||
|
assert me_after.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_login_invalid_password(client):
|
||||||
|
user = provision_user_in_tenant()
|
||||||
|
response = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user["email"], "password": "wrong-password"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_me_requires_auth(client):
|
||||||
|
assert client.get("/api/me").status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
def test_me_context_returns_tenant_and_actor(client):
|
||||||
|
user = provision_user_in_tenant(tenant_role="admin")
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user["email"], "password": user["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
|
||||||
|
ctx = client.get("/api/me/context", headers={AUTH_HEADER: token})
|
||||||
|
assert ctx.status_code == 200
|
||||||
|
body = ctx.json()
|
||||||
|
assert body["tenant"]["id"] == user["tenant_id"]
|
||||||
|
assert body["tenant"]["role"] == "admin"
|
||||||
|
assert body["actor"]["id"] == user["actor_id"]
|
||||||
|
assert body["actor"]["type"] == "human"
|
||||||
|
|
||||||
|
|
||||||
|
def test_tenant_switch_rejects_invalid_membership(client):
|
||||||
|
user = provision_user_in_tenant()
|
||||||
|
other = provision_user_in_tenant()
|
||||||
|
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user["email"], "password": user["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
|
||||||
|
switch = client.post(
|
||||||
|
"/api/me/tenant",
|
||||||
|
headers={AUTH_HEADER: token},
|
||||||
|
json={"tenant_id": other["tenant_id"]},
|
||||||
|
)
|
||||||
|
assert switch.status_code == 403
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""Capability resolution and require_capability tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from auth import AUTH_HEADER
|
||||||
|
from tests.factories import provision_user_in_tenant
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture()
|
||||||
|
def enforce_capabilities(monkeypatch):
|
||||||
|
monkeypatch.setenv("CAPABILITY_ENFORCE", "enforce")
|
||||||
|
|
||||||
|
|
||||||
|
def test_portal_admin_has_admin_capability(client, enforce_capabilities):
|
||||||
|
admin = provision_user_in_tenant(tenant_role="member", portal_role="admin")
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": admin["email"], "password": admin["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
|
||||||
|
res = client.get("/api/me/admin/demo", headers={AUTH_HEADER: token})
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert res.json()["ok"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_tenant_member_denied_admin_capability(client, enforce_capabilities):
|
||||||
|
member = provision_user_in_tenant(tenant_role="member", portal_role="user")
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": member["email"], "password": member["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
|
||||||
|
res = client.get("/api/me/admin/demo", headers={AUTH_HEADER: token})
|
||||||
|
assert res.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_tenant_owner_has_manage_capabilities(client, enforce_capabilities):
|
||||||
|
owner = provision_user_in_tenant(tenant_role="owner", portal_role="user")
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": owner["email"], "password": owner["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
ctx = client.get("/api/me/context", headers={AUTH_HEADER: token}).json()
|
||||||
|
|
||||||
|
assert "kairo.tenant.manage" in ctx["capabilities"]
|
||||||
|
assert "kairo.actor.manage" in ctx["capabilities"]
|
||||||
|
assert "kairo.admin.access" not in ctx["capabilities"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_probe_mode_allows_without_capability(client, monkeypatch):
|
||||||
|
monkeypatch.setenv("CAPABILITY_ENFORCE", "probe")
|
||||||
|
member = provision_user_in_tenant(tenant_role="member", portal_role="user")
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": member["email"], "password": member["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
|
||||||
|
res = client.get("/api/me/admin/demo", headers={AUTH_HEADER: token})
|
||||||
|
assert res.status_code == 200
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
"""Configuration registry tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from auth import AUTH_HEADER
|
||||||
|
from config_service import SECRET_VALUE_FORBIDDEN, get_config, list_configs, upsert_config
|
||||||
|
from tests.factories import provision_user_in_tenant
|
||||||
|
|
||||||
|
|
||||||
|
def test_global_config_upsert_and_read():
|
||||||
|
upsert_config(
|
||||||
|
config_key="test.ap0.config",
|
||||||
|
scope="global",
|
||||||
|
value="enabled",
|
||||||
|
value_type="string",
|
||||||
|
description="pytest config",
|
||||||
|
)
|
||||||
|
item = get_config("test.ap0.config", scope="global")
|
||||||
|
assert item is not None
|
||||||
|
assert item["value"] == "enabled"
|
||||||
|
|
||||||
|
|
||||||
|
def test_secret_config_rejects_plaintext():
|
||||||
|
with pytest.raises(ValueError, match=SECRET_VALUE_FORBIDDEN):
|
||||||
|
upsert_config(
|
||||||
|
config_key="test.secret",
|
||||||
|
scope="global",
|
||||||
|
value="super-secret-token",
|
||||||
|
is_secret=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_api(client):
|
||||||
|
user = provision_user_in_tenant(portal_role="admin", tenant_role="owner")
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user["email"], "password": user["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
res = client.get("/api/config", headers={AUTH_HEADER: token})
|
||||||
|
assert res.status_code == 200
|
||||||
|
keys = {item["config_key"] for item in res.json()}
|
||||||
|
assert "prompt.default_execution_mode" in keys
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_post_api(client):
|
||||||
|
user = provision_user_in_tenant(portal_role="admin", tenant_role="owner")
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user["email"], "password": user["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
res = client.post(
|
||||||
|
"/api/config",
|
||||||
|
json={
|
||||||
|
"config_key": "test.api.config",
|
||||||
|
"scope": "global",
|
||||||
|
"value": True,
|
||||||
|
"value_type": "boolean",
|
||||||
|
"description": "via api",
|
||||||
|
},
|
||||||
|
headers={AUTH_HEADER: token},
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert res.json()["config_key"] == "test.api.config"
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""Entitlements snapshot tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from auth import AUTH_HEADER
|
||||||
|
from tests.factories import provision_user_in_tenant
|
||||||
|
|
||||||
|
|
||||||
|
def test_entitlements_snapshot_shape(client):
|
||||||
|
user = provision_user_in_tenant(tenant_role="owner", portal_role="admin")
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user["email"], "password": user["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
|
||||||
|
res = client.get("/api/me/entitlements", headers={AUTH_HEADER: token})
|
||||||
|
assert res.status_code == 200
|
||||||
|
body = res.json()
|
||||||
|
|
||||||
|
assert "account" in body
|
||||||
|
assert body["account"]["portal_role"] == "admin"
|
||||||
|
assert "capabilities" in body["account"]
|
||||||
|
assert body["tenant"]["tenant_id"] == user["tenant_id"]
|
||||||
|
assert body["actor"]["actor_id"] == user["actor_id"]
|
||||||
|
assert body["roles"]["portal"] == "admin"
|
||||||
|
assert body["roles"]["tenant"] == "owner"
|
||||||
|
assert "kairo.admin.access" in body["capabilities"]
|
||||||
|
assert body["enforcement"]["capabilities"] in ("probe", "enforce")
|
||||||
|
assert body["enforcement"]["features"] == "probe"
|
||||||
|
assert "kairo.prompt.registry" in body["features"]
|
||||||
|
assert body["features"]["kairo.prompt.registry"]["enabled"] is True
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""Feature registry tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import feature_registrations # noqa: F401
|
||||||
|
from auth import AUTH_HEADER
|
||||||
|
from db import get_connection
|
||||||
|
from feature_registry import get_registered_features, sync_features_to_db
|
||||||
|
from tests.factories import provision_user_in_tenant
|
||||||
|
|
||||||
|
|
||||||
|
def test_feature_registration_required_fields():
|
||||||
|
keys = {f.key for f in get_registered_features()}
|
||||||
|
assert keys == {
|
||||||
|
"kairo.feature.registry",
|
||||||
|
"kairo.config.registry",
|
||||||
|
"kairo.prompt.registry",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_feature_sync_idempotent():
|
||||||
|
assert sync_features_to_db() == 0
|
||||||
|
assert sync_features_to_db() == 0
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT COUNT(*) FROM features WHERE is_active = TRUE")
|
||||||
|
assert cur.fetchone()[0] == 3
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_features_in_entitlements(client):
|
||||||
|
user = provision_user_in_tenant(tenant_role="member", portal_role="user")
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user["email"], "password": user["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
res = client.get("/api/me/entitlements", headers={AUTH_HEADER: token})
|
||||||
|
features = res.json()["features"]
|
||||||
|
assert "kairo.prompt.registry" in features
|
||||||
|
assert features["kairo.prompt.registry"]["enabled"] is True
|
||||||
|
assert features["kairo.prompt.registry"]["module"] == "prompt"
|
||||||
|
|
||||||
|
|
||||||
|
def test_features_api_requires_auth(client):
|
||||||
|
assert client.get("/api/features").status_code == 401
|
||||||
@@ -7,6 +7,7 @@ from fastapi.testclient import TestClient
|
|||||||
@pytest.fixture()
|
@pytest.fixture()
|
||||||
def client(monkeypatch):
|
def client(monkeypatch):
|
||||||
monkeypatch.setenv("SKIP_DB_MIGRATE", "1")
|
monkeypatch.setenv("SKIP_DB_MIGRATE", "1")
|
||||||
|
monkeypatch.setenv("SKIP_BOOTSTRAP", "1")
|
||||||
import importlib
|
import importlib
|
||||||
|
|
||||||
import main as main_module
|
import main as main_module
|
||||||
|
|||||||
@@ -32,6 +32,10 @@ def test_migration_runner_finds_migrations():
|
|||||||
files = run_migrations.migration_files(migrations_dir)
|
files = run_migrations.migration_files(migrations_dir)
|
||||||
names = [name for name, _ in files]
|
names = [name for name, _ in files]
|
||||||
assert "001_init_core" in names
|
assert "001_init_core" in names
|
||||||
|
assert "002_auth_identity_tenant_actor" in names
|
||||||
|
assert "003_data_seeds_tracking" in names
|
||||||
|
assert "004_capabilities_registry" in names
|
||||||
|
assert "005_prompt_feature_config_registry" in names
|
||||||
|
|
||||||
|
|
||||||
def test_migration_runner_is_idempotent():
|
def test_migration_runner_is_idempotent():
|
||||||
@@ -42,6 +46,10 @@ def test_migration_runner_is_idempotent():
|
|||||||
executed = run_migrations.executed_migrations(conn)
|
executed = run_migrations.executed_migrations(conn)
|
||||||
conn.close()
|
conn.close()
|
||||||
assert "001_init_core" in executed
|
assert "001_init_core" in executed
|
||||||
|
assert "002_auth_identity_tenant_actor" in executed
|
||||||
|
assert "003_data_seeds_tracking" in executed
|
||||||
|
assert "004_capabilities_registry" in executed
|
||||||
|
assert "005_prompt_feature_config_registry" in executed
|
||||||
|
|
||||||
|
|
||||||
def test_core_table_exists():
|
def test_core_table_exists():
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
"""Prompt registry and rendering tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import prompt_registrations # noqa: F401
|
||||||
|
from auth import AUTH_HEADER
|
||||||
|
from db import get_connection
|
||||||
|
from prompt_registry import get_registered_prompts, sync_prompts_to_db
|
||||||
|
from prompt_rendering import PromptRenderError, render_prompt_single
|
||||||
|
from prompt_validation import PlaceholderValidationError, validate_placeholder_input
|
||||||
|
from tests.factories import provision_user_in_tenant
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_registry_contains_smoke_prompts():
|
||||||
|
keys = {p.prompt_key for p in get_registered_prompts()}
|
||||||
|
assert "kairo.system.health_summary" in keys
|
||||||
|
assert "kairo.context.debug_summary" in keys
|
||||||
|
assert "kairo.pipeline.placeholder" in keys
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_sync_idempotent():
|
||||||
|
assert sync_prompts_to_db() == 0
|
||||||
|
assert sync_prompts_to_db() == 0
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT COUNT(*) FROM prompt_definitions")
|
||||||
|
assert cur.fetchone()[0] >= 4
|
||||||
|
cur.execute("SELECT COUNT(*) FROM prompt_steps")
|
||||||
|
assert cur.fetchone()[0] >= 1
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_placeholder_required_missing():
|
||||||
|
try:
|
||||||
|
validate_placeholder_input(
|
||||||
|
template="Hello {{debug_message}}",
|
||||||
|
context_kind="kairo.debug_context",
|
||||||
|
values={},
|
||||||
|
)
|
||||||
|
assert False, "expected validation error"
|
||||||
|
except PlaceholderValidationError as exc:
|
||||||
|
assert "debug_message" in exc.missing
|
||||||
|
|
||||||
|
|
||||||
|
def test_placeholder_optional_ok():
|
||||||
|
meta = validate_placeholder_input(
|
||||||
|
template="Level {{debug_level}}",
|
||||||
|
context_kind="kairo.debug_context",
|
||||||
|
values={"debug_message": "ok"},
|
||||||
|
)
|
||||||
|
assert "debug_level" in meta["optional_missing"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_debug_prompt():
|
||||||
|
result = render_prompt_single(
|
||||||
|
"kairo.system.health_summary",
|
||||||
|
values={"debug_message": "All systems nominal", "debug_level": "info"},
|
||||||
|
log_execution=False,
|
||||||
|
)
|
||||||
|
assert "All systems nominal" in result["rendered_text"]
|
||||||
|
assert result["template_source"].startswith("step:")
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_pipeline_mode_rejected():
|
||||||
|
try:
|
||||||
|
render_prompt_single(
|
||||||
|
"kairo.pipeline.placeholder",
|
||||||
|
values={"debug_message": "x"},
|
||||||
|
log_execution=False,
|
||||||
|
)
|
||||||
|
assert False, "expected error"
|
||||||
|
except PromptRenderError as exc:
|
||||||
|
assert exc.code == "mode_not_implemented"
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_api(client):
|
||||||
|
user = provision_user_in_tenant(tenant_role="owner", portal_role="admin")
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user["email"], "password": user["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
client.post(
|
||||||
|
"/api/me/tenant",
|
||||||
|
json={"tenant_id": user["tenant_id"]},
|
||||||
|
headers={AUTH_HEADER: token},
|
||||||
|
)
|
||||||
|
res = client.post(
|
||||||
|
"/api/prompts/kairo.context.debug_summary/render",
|
||||||
|
json={"values": {}, "use_context": True},
|
||||||
|
headers={AUTH_HEADER: token},
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
assert user["tenant_id"] in res.json()["rendered_text"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompts_list_api(client):
|
||||||
|
user = provision_user_in_tenant(portal_role="admin", tenant_role="owner")
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user["email"], "password": user["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
res = client.get("/api/prompts", headers={AUTH_HEADER: token})
|
||||||
|
assert res.status_code == 200
|
||||||
|
keys = {item["prompt_key"] for item in res.json()}
|
||||||
|
assert "kairo.system.health_summary" in keys
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
"""Registration and first system-admin tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from auth import AUTH_HEADER, get_session
|
||||||
|
from db import get_connection
|
||||||
|
from services.registration import user_count
|
||||||
|
|
||||||
|
|
||||||
|
def test_setup_status_open_without_users(client):
|
||||||
|
if user_count() > 0:
|
||||||
|
return
|
||||||
|
res = client.get("/api/auth/setup-status")
|
||||||
|
assert res.status_code == 200
|
||||||
|
body = res.json()
|
||||||
|
assert body["registration_open"] is True
|
||||||
|
assert body["has_users"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_register_first_user_becomes_portal_admin(client):
|
||||||
|
if user_count() > 0:
|
||||||
|
return
|
||||||
|
|
||||||
|
suffix = uuid.uuid4().hex[:8]
|
||||||
|
email = f"admin-{suffix}@example.com"
|
||||||
|
res = client.post(
|
||||||
|
"/api/auth/register",
|
||||||
|
json={
|
||||||
|
"email": email,
|
||||||
|
"password": "secure-pass-123",
|
||||||
|
"display_name": "System Admin",
|
||||||
|
"organization_name": "Kairo Org",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
body = res.json()
|
||||||
|
assert body["user"]["portal_role"] == "admin"
|
||||||
|
assert body["token"]
|
||||||
|
assert get_session(body["token"]) is not None
|
||||||
|
|
||||||
|
me = client.get("/api/me", headers={AUTH_HEADER: body["token"]})
|
||||||
|
assert me.status_code == 200
|
||||||
|
assert me.json()["portal_role"] == "admin"
|
||||||
|
|
||||||
|
ctx = client.get("/api/me/context", headers={AUTH_HEADER: body["token"]})
|
||||||
|
assert ctx.status_code == 200
|
||||||
|
assert ctx.json()["tenant"]["role"] == "owner"
|
||||||
|
assert ctx.json()["actor"]["type"] == "human"
|
||||||
|
|
||||||
|
# cleanup: allow re-run in isolated env — skip delete in shared CI DB
|
||||||
|
closed = client.get("/api/auth/setup-status")
|
||||||
|
assert closed.json()["registration_open"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_register_closed_when_users_exist(client):
|
||||||
|
if user_count() == 0:
|
||||||
|
return
|
||||||
|
|
||||||
|
res = client.post(
|
||||||
|
"/api/auth/register",
|
||||||
|
json={
|
||||||
|
"email": f"other-{uuid.uuid4().hex[:8]}@example.com",
|
||||||
|
"password": "secure-pass-123",
|
||||||
|
"display_name": "Other User",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert res.status_code == 403
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""Rights registry and DB sync tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import rights_registrations # noqa: F401
|
||||||
|
from db import get_connection
|
||||||
|
from rights_registry import get_registered_capabilities, sync_rights_registry_to_db
|
||||||
|
|
||||||
|
|
||||||
|
def test_registry_contains_initial_capabilities():
|
||||||
|
keys = {reg.key for reg in get_registered_capabilities()}
|
||||||
|
assert keys == {
|
||||||
|
"kairo.admin.access",
|
||||||
|
"kairo.tenant.manage",
|
||||||
|
"kairo.actor.manage",
|
||||||
|
"kairo.context.read",
|
||||||
|
"kairo.entitlements.read",
|
||||||
|
"kairo.feature.registry.read",
|
||||||
|
"kairo.feature.registry.manage",
|
||||||
|
"kairo.prompt.registry.read",
|
||||||
|
"kairo.prompt.registry.manage",
|
||||||
|
"kairo.config.registry.read",
|
||||||
|
"kairo.config.registry.manage",
|
||||||
|
"kairo.prompt.render",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_is_idempotent():
|
||||||
|
assert sync_rights_registry_to_db() == 0
|
||||||
|
assert sync_rights_registry_to_db() == 0
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT COUNT(*) FROM capabilities")
|
||||||
|
assert cur.fetchone()[0] == 12
|
||||||
|
cur.execute("SELECT COUNT(*) FROM role_capability_grants")
|
||||||
|
assert cur.fetchone()[0] >= 5
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""Data seed runner tests (require PostgreSQL)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import run_seeds
|
||||||
|
from tests.factories import create_user
|
||||||
|
|
||||||
|
|
||||||
|
def test_seed_runner_finds_seeds():
|
||||||
|
seeds_dir = run_seeds.seeds_directory()
|
||||||
|
names = [name for name, _, _ in run_seeds.seed_files(seeds_dir)]
|
||||||
|
assert "seed_001_cleanup_pytest_artifacts" in names
|
||||||
|
assert "seed_002_bootstrap_admin" in names
|
||||||
|
|
||||||
|
|
||||||
|
def test_cleanup_seed_removes_example_com_users():
|
||||||
|
suffix = uuid.uuid4().hex[:8]
|
||||||
|
user = create_user(email=f"seed-test-{suffix}@example.com")
|
||||||
|
|
||||||
|
assert run_seeds.main(["--only", "seed_001_cleanup_pytest_artifacts", "--force"]) == 0
|
||||||
|
|
||||||
|
from db import get_connection
|
||||||
|
|
||||||
|
conn = get_connection()
|
||||||
|
try:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute("SELECT COUNT(*) FROM users WHERE id = %s", (user["id"],))
|
||||||
|
assert cur.fetchone()[0] == 0
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_cleanup_seed_is_idempotent():
|
||||||
|
assert run_seeds.main(["--only", "seed_001_cleanup_pytest_artifacts"]) == 0
|
||||||
|
assert run_seeds.main(["--only", "seed_001_cleanup_pytest_artifacts"]) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_dev_admin_seed_ensures_lars():
|
||||||
|
import os
|
||||||
|
|
||||||
|
if os.getenv("ENVIRONMENT", "development").strip().lower() == "production":
|
||||||
|
return
|
||||||
|
|
||||||
|
from auth import get_user_by_email, verify_password
|
||||||
|
from services.dev_admin import DEV_ADMIN_EMAIL, DEV_ADMIN_PASSWORD
|
||||||
|
|
||||||
|
assert run_seeds.main(["--only", "seed_003_ensure_dev_admin"]) == 0
|
||||||
|
|
||||||
|
user = get_user_by_email(DEV_ADMIN_EMAIL)
|
||||||
|
assert user is not None
|
||||||
|
assert user["portal_role"] == "admin"
|
||||||
|
assert verify_password(DEV_ADMIN_PASSWORD, user["password_hash"])
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""Actor and TenantContext tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from auth import AUTH_HEADER
|
||||||
|
from services.actors import create_actor
|
||||||
|
from tests.factories import create_tenant, provision_user_in_tenant
|
||||||
|
|
||||||
|
|
||||||
|
def test_human_actor_linked_to_user(client):
|
||||||
|
user = provision_user_in_tenant()
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user["email"], "password": user["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
ctx = client.get("/api/me/context", headers={AUTH_HEADER: token}).json()
|
||||||
|
assert ctx["actor"]["type"] == "human"
|
||||||
|
assert ctx["actor"]["id"] == user["actor_id"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_agent_actor_without_user(client):
|
||||||
|
tenant_id = create_tenant()
|
||||||
|
agent = create_actor(tenant_id=tenant_id, actor_type="agent", name="Planner Agent")
|
||||||
|
assert agent["user_id"] is None
|
||||||
|
assert agent["actor_type"] == "agent"
|
||||||
|
|
||||||
|
|
||||||
|
def test_working_group_and_external_system_actors(client):
|
||||||
|
tenant_id = create_tenant()
|
||||||
|
wg = create_actor(tenant_id=tenant_id, actor_type="working_group", name="Steering Group")
|
||||||
|
ext = create_actor(tenant_id=tenant_id, actor_type="external_system", name="Jira")
|
||||||
|
assert wg["actor_type"] == "working_group"
|
||||||
|
assert ext["actor_type"] == "external_system"
|
||||||
|
|
||||||
|
|
||||||
|
def test_portal_role_separate_from_tenant_role(client):
|
||||||
|
user = provision_user_in_tenant(tenant_role="member", portal_role="admin")
|
||||||
|
login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user["email"], "password": user["password"]},
|
||||||
|
)
|
||||||
|
token = login.json()["token"]
|
||||||
|
ctx = client.get("/api/me/context", headers={AUTH_HEADER: token}).json()
|
||||||
|
assert ctx["portal_role"] == "admin"
|
||||||
|
assert ctx["tenant"]["role"] == "member"
|
||||||
+2
-2
@@ -1,3 +1,3 @@
|
|||||||
APP_VERSION = "0.1.0-ap0.1"
|
APP_VERSION = "0.4.0-ap0.4"
|
||||||
DB_SCHEMA_VERSION = "001"
|
DB_SCHEMA_VERSION = "005"
|
||||||
APP_NAME = "jinkendo-kairo"
|
APP_NAME = "jinkendo-kairo"
|
||||||
@@ -34,6 +34,11 @@ services:
|
|||||||
APP_URL: "${APP_URL:-https://dev.kairo.jinkendo.de}"
|
APP_URL: "${APP_URL:-https://dev.kairo.jinkendo.de}"
|
||||||
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.kairo.jinkendo.de,http://192.168.2.49:3097,http://localhost:3097}"
|
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.kairo.jinkendo.de,http://192.168.2.49:3097,http://localhost:3097}"
|
||||||
ENVIRONMENT: "${ENVIRONMENT:-development}"
|
ENVIRONMENT: "${ENVIRONMENT:-development}"
|
||||||
|
SESSION_DAYS: "${SESSION_DAYS:-30}"
|
||||||
|
KAIRO_BOOTSTRAP_ADMIN_EMAIL: "${KAIRO_BOOTSTRAP_ADMIN_EMAIL:-}"
|
||||||
|
KAIRO_BOOTSTRAP_ADMIN_PASSWORD: "${KAIRO_BOOTSTRAP_ADMIN_PASSWORD:-}"
|
||||||
|
KAIRO_BOOTSTRAP_TENANT_SLUG: "${KAIRO_BOOTSTRAP_TENANT_SLUG:-default}"
|
||||||
|
KAIRO_BOOTSTRAP_TENANT_NAME: "${KAIRO_BOOTSTRAP_TENANT_NAME:-Default Tenant}"
|
||||||
ports:
|
ports:
|
||||||
- "${KAIRO_BACKEND_PORT:-8097}:8000"
|
- "${KAIRO_BACKEND_PORT:-8097}:8000"
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -49,8 +54,8 @@ services:
|
|||||||
]
|
]
|
||||||
interval: 10s
|
interval: 10s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 12
|
retries: 18
|
||||||
start_period: 30s
|
start_period: 90s
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
networks:
|
networks:
|
||||||
- dev-kairo-network
|
- dev-kairo-network
|
||||||
|
|||||||
@@ -35,6 +35,9 @@ services:
|
|||||||
APP_URL: "${APP_URL:-https://kairo.jinkendo.de}"
|
APP_URL: "${APP_URL:-https://kairo.jinkendo.de}"
|
||||||
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://kairo.jinkendo.de}"
|
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://kairo.jinkendo.de}"
|
||||||
ENVIRONMENT: "${ENVIRONMENT:-production}"
|
ENVIRONMENT: "${ENVIRONMENT:-production}"
|
||||||
|
SESSION_DAYS: "${SESSION_DAYS:-30}"
|
||||||
|
KAIRO_BOOTSTRAP_ADMIN_EMAIL: "${KAIRO_BOOTSTRAP_ADMIN_EMAIL:-}"
|
||||||
|
KAIRO_BOOTSTRAP_ADMIN_PASSWORD: "${KAIRO_BOOTSTRAP_ADMIN_PASSWORD:-}"
|
||||||
ports:
|
ports:
|
||||||
- "${KAIRO_BACKEND_PORT:-8004}:8000"
|
- "${KAIRO_BACKEND_PORT:-8004}:8000"
|
||||||
depends_on:
|
depends_on:
|
||||||
|
|||||||
+34
-3
@@ -45,18 +45,18 @@ cp .env.example .env
|
|||||||
2. **Pi-Runner registriert** — derselbe wie Shinkan/Mitai (`ubuntu-latest`)
|
2. **Pi-Runner registriert** — derselbe wie Shinkan/Mitai (`ubuntu-latest`)
|
||||||
3. Push `develop` → `deploy-dev.yml` → `curl http://localhost:8097/api/health`
|
3. Push `develop` → `deploy-dev.yml` → `curl http://localhost:8097/api/health`
|
||||||
4. Merge `main` → `deploy-prod.yml` → `curl http://localhost:8004/api/health`
|
4. Merge `main` → `deploy-prod.yml` → `curl http://localhost:8004/api/health`
|
||||||
5. Nach Deploy: `test.yml` (workflow_run) — pytest, k6, Playwright smoke gegen **localhost**
|
5. Push `main` → `deploy-prod.yml` + `test.yml` (Prod pytest/k6/Playwright auf localhost 8004/3004)
|
||||||
|
|
||||||
| Workflow | Trigger | Zweck |
|
| Workflow | Trigger | Zweck |
|
||||||
|----------|---------|--------|
|
|----------|---------|--------|
|
||||||
| `deploy-dev.yml` | Push `develop` | Deploy nach `/home/lars/docker/kairo-dev` |
|
| `deploy-dev.yml` | Push `develop` | Deploy nach `/home/lars/docker/kairo-dev` |
|
||||||
| `deploy-prod.yml` | Push `main` | Deploy nach `/home/lars/docker/kairo` |
|
| `deploy-prod.yml` | Push `main` | Deploy nach `/home/lars/docker/kairo` |
|
||||||
| `test.yml` | Push/PR `develop`, nach Deploy | lint, pytest, k6, Playwright (Frontend-Build läuft im Deploy via Docker) |
|
| `test.yml` | Push `develop`/`main`, PR `develop` | lint, pytest, k6, Playwright gegen deployte Instanz |
|
||||||
| `test.yml` → `compose-smoke` | Pull Request | Eigener Stack auf **CI-Ports 18197/13197** |
|
| `test.yml` → `compose-smoke` | Pull Request | Eigener Stack auf **CI-Ports 18197/13197** |
|
||||||
|
|
||||||
Struktur wie Shinkan: **Deploy** und **Test Suite** sind getrennte Workflows in Gitea.
|
Struktur wie Shinkan: **Deploy** und **Test Suite** sind getrennte Workflows in Gitea.
|
||||||
|
|
||||||
Bei Push auf `develop` starten Deploy und Test Suite parallel; pytest wartet auf den Backend-Container der deployten Instanz (Ports 8097/3097). Nach Deploy Production feuert `workflow_run` die Prod-Tests (Ports 8004/3004).
|
Bei Push auf `develop` oder `main` starten Deploy und Test Suite parallel; pytest wartet auf den Backend-Container (Dev: 8097/3097, Prod: 8004/3004).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -75,6 +75,37 @@ Aktuell keine Medien-Speicherung. Bei Bedarf: NAS-Mount + `docker-compose.overri
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Datenbank-Passwort (Dev & Prod)
|
||||||
|
|
||||||
|
PostgreSQL im Compose-Stack initialisiert User/Passwort **nur beim ersten Start** des Volumes.
|
||||||
|
Wenn `DB_PASSWORD` in `.env` nicht mehr zum Volume passt, scheitert das Backend mit
|
||||||
|
`password authentication failed for user "kairo_user"` — der Container bleibt `unhealthy`.
|
||||||
|
|
||||||
|
**Prod (Daten behalten):** Passwort in der laufenden DB an `.env` anpassen:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /home/lars/docker/kairo
|
||||||
|
set -a && source .env && set +a
|
||||||
|
docker compose exec -T postgres psql -U kairo_user -d kairo \
|
||||||
|
-c "ALTER USER kairo_user WITH PASSWORD '${DB_PASSWORD}';"
|
||||||
|
docker compose restart backend
|
||||||
|
curl -sf http://localhost:8004/api/health
|
||||||
|
```
|
||||||
|
|
||||||
|
**Dev (Volume neu, inkl. Testdaten):** Volume löschen und neu starten (`dev-kairo-db-data`).
|
||||||
|
Wenn du `DB_NAME`, `DB_USER` oder `DB_PASSWORD` in `.env` änderst, muss das Volume neu angelegt werden:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /home/lars/docker/kairo-dev
|
||||||
|
docker compose -f docker-compose.dev-env.yml down -v
|
||||||
|
docker compose -f docker-compose.dev-env.yml up -d --wait
|
||||||
|
curl -sf http://localhost:8097/api/health
|
||||||
|
```
|
||||||
|
|
||||||
|
Danach laufen Migrationen und Dev-Seeds automatisch (u. a. `lars@stommer.com`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Manuelles Deploy
|
## Manuelles Deploy
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Migrationen & Data-Seeds
|
||||||
|
|
||||||
|
Kairo trennt **Schema-Migrationen** (einmalig) von **Data-Seeds** (idempotent, bei Änderung erneut ausführbar).
|
||||||
|
|
||||||
|
## Schema-Migrationen
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| **Pfad** | `backend/migrations/NNN_beschreibung.sql` |
|
||||||
|
| **Tracking** | Tabelle `schema_migrations` |
|
||||||
|
| **Ausführung** | Beim Backend-Start (`run_migrations.py`), überspringbar via `SKIP_DB_MIGRATE=1` |
|
||||||
|
| **Regel** | Jede Datei wird **genau einmal** angewendet. Änderungen → neue nummerierte Datei. |
|
||||||
|
|
||||||
|
## Data-Seeds
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| **Pfad** | `backend/seeds/seed_NNN_beschreibung.sql` oder `.py` |
|
||||||
|
| **Tracking** | Tabelle `data_seeds` (Name + SHA256-Checksum) |
|
||||||
|
| **Ausführung** | Nach Schema-Migrationen (`run_seeds.py`), überspringbar via `SKIP_SEEDS=1` |
|
||||||
|
| **Regel** | Seed läuft erneut, wenn die Datei **geändert** wurde (Checksum abweicht) oder `--force` gesetzt ist. |
|
||||||
|
|
||||||
|
### Umgebungsfilter
|
||||||
|
|
||||||
|
Dateien mit **`.dev.`** im Namen (z. B. `seed_001_….dev.sql`) laufen **nicht in Production** (`ENVIRONMENT=production`).
|
||||||
|
|
||||||
|
### Seeds manuell ausführen
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.dev-env.yml exec backend python run_seeds.py
|
||||||
|
docker compose -f docker-compose.dev-env.yml exec backend python run_seeds.py --only seed_001_cleanup_pytest_artifacts --force
|
||||||
|
```
|
||||||
|
|
||||||
|
## Aktuelle Seeds
|
||||||
|
|
||||||
|
| Seed | Typ | Zweck |
|
||||||
|
|------|-----|--------|
|
||||||
|
| `seed_001_cleanup_pytest_artifacts` | SQL (dev) | Entfernt pytest/CI-User (`*@example.com`) und verwaiste Test-Tenants |
|
||||||
|
| `seed_002_bootstrap_admin` | Python | Legt Systemadmin aus `KAIRO_BOOTSTRAP_*` an, wenn noch kein User existiert |
|
||||||
|
| `seed_003_ensure_dev_admin` | Python (dev) | Entfernt fremde Dev-User, stellt `lars@stommer.com` als Portal-Admin sicher (jeder Start) |
|
||||||
|
|
||||||
|
Dev-Seeds (`.dev.*`) werden in Nicht-Prod-Umgebungen **bei jedem Backend-Start** erneut ausgeführt.
|
||||||
|
|
||||||
|
## Neuen Seed anlegen
|
||||||
|
|
||||||
|
1. Datei `backend/seeds/seed_NNN_kurzname.sql` oder `.py` anlegen (Python: `def run() -> None:`).
|
||||||
|
2. SQL idempotent halten (`DELETE … WHERE …`, `INSERT … ON CONFLICT`, etc.).
|
||||||
|
3. Nur Dev/CI: `.dev.sql` / `.dev.py` Suffix verwenden.
|
||||||
|
4. Nach Deploy prüfen: `python run_seeds.py` — bei geänderter Datei wird der Seed automatisch erneut ausgeführt.
|
||||||
|
|
||||||
|
## Tests & CI
|
||||||
|
|
||||||
|
- pytest setzt `SKIP_SEEDS=1` beim App-Import; Cleanup läuft über Fixture + nach CI-pytest.
|
||||||
|
- Geteilte Dev-DB wird nach jedem Test-Lauf bereinigt (`run_seeds.py --only seed_001_cleanup_pytest_artifacts --force`).
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
# AP0.1 – Abschlussbericht Projektgrundlage
|
||||||
|
|
||||||
|
**Status:** abgeschlossen
|
||||||
|
**Stand:** 2026-07-04
|
||||||
|
**Branch:** `develop` (`b5efdbb`) · Prod-Stand identisch (`main` `7b96bab`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Umgesetzt
|
||||||
|
|
||||||
|
| Anforderung (AP0.1) | Umsetzung |
|
||||||
|
|---------------------|-----------|
|
||||||
|
| Backend-Skeleton + FastAPI | `backend/main.py`, `backend/Dockerfile` |
|
||||||
|
| Health Endpoint `GET /api/health` | Liefert `status`, `app`, `db` (+ `version`, `schema`) |
|
||||||
|
| PostgreSQL-Anbindung | `backend/db.py`, Compose-Services |
|
||||||
|
| Docker Compose lokal | `docker-compose.dev-env.yml`, `docker-compose.yml` |
|
||||||
|
| Migrationsverzeichnis | `backend/migrations/` |
|
||||||
|
| Migration Runner + `schema_migrations` | `backend/run_migrations.py` |
|
||||||
|
| Erste Migration `001_init_core.sql` | `kairo_app_meta` (Schema-Phase AP0.1) |
|
||||||
|
| Testbasis | `backend/tests/` (pytest) |
|
||||||
|
| Frontend optional minimal | React/Vite-SPA + nginx-Proxy (`frontend/`) |
|
||||||
|
| Verzeichnisse `infra/`, `scripts/`, `tests/` | vorhanden |
|
||||||
|
| README „Local Development“ | `README.md` § Local Development |
|
||||||
|
| Kein Sprint-1-Fachscope | Keine Tenant/User/Actor-Logik, nur Meta-Tabelle |
|
||||||
|
|
||||||
|
**Zusätzlich (über AP0.1-Minimum, bewusst Sprint-0-Infrastruktur):**
|
||||||
|
|
||||||
|
- Gitea Actions: `deploy-dev.yml`, `deploy-prod.yml`, `test.yml`
|
||||||
|
- CI: pytest im Container, compose-smoke (PR), k6-Baseline, Playwright smoke
|
||||||
|
- Deployment-Doku: `docs/DEPLOYMENT.md`
|
||||||
|
- Dev/Prod auf Raspberry Pi (Ports 8097/3097 bzw. 8004/3004)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
### Unit / Integration (pytest)
|
||||||
|
|
||||||
|
| Test | Datei | Status |
|
||||||
|
|------|-------|--------|
|
||||||
|
| App importierbar | `test_health.py::test_app_importable` | ✓ |
|
||||||
|
| Health Endpoint | `test_health.py::test_health_endpoint` | ✓ |
|
||||||
|
| Runner findet Migrationen | `test_migrations.py::test_migration_runner_finds_migrations` | ✓ |
|
||||||
|
| Runner trägt Migration ein + idempotent | `test_migrations.py::test_migration_runner_is_idempotent` | ✓ |
|
||||||
|
| Core-Tabelle existiert | `test_migrations.py::test_core_table_exists` | ✓ |
|
||||||
|
|
||||||
|
### CI (Self-hosted Runner, Dev)
|
||||||
|
|
||||||
|
| Job | Status (2026-07-04) |
|
||||||
|
|-----|---------------------|
|
||||||
|
| pytest-backend | ✓ |
|
||||||
|
| k6 /api/health Baseline | ✓ (nach K6_CI-Anpassung) |
|
||||||
|
| playwright-smoke | ✓ |
|
||||||
|
| lint-backend | ✓ |
|
||||||
|
| compose-smoke | ✓ (PR, isolierte CI-Ports) |
|
||||||
|
|
||||||
|
### Prod
|
||||||
|
|
||||||
|
| Schritt | Status |
|
||||||
|
|---------|--------|
|
||||||
|
| Deploy Production (manueller Merge `develop` → `main`) | ✓ |
|
||||||
|
| Test Suite Prod-Trigger | Fix auf `develop` (`b5efdbb`): Push auf `main` startet Tests |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Lokaler Start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout develop
|
||||||
|
docker compose -f docker-compose.dev-env.yml up --build
|
||||||
|
|
||||||
|
curl http://localhost:8097/api/health
|
||||||
|
curl http://localhost:3097/api/health
|
||||||
|
|
||||||
|
docker compose -f docker-compose.dev-env.yml exec backend pip install -r requirements-dev.txt
|
||||||
|
docker compose -f docker-compose.dev-env.yml exec backend python -m pytest tests -ra -vv
|
||||||
|
```
|
||||||
|
|
||||||
|
Migrationen laufen beim Backend-Start automatisch (`run_migrations.main()` in `main.py`, überspringbar via `SKIP_DB_MIGRATE=1` für Tests).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Offene Fragen
|
||||||
|
|
||||||
|
1. **Reverse Proxy** — Domains `kairo.jinkendo.de` / `dev.kairo.jinkendo.de` noch nicht eingerichtet; CI und Deploy nutzen localhost (bewusst ausreichend für AP0.1).
|
||||||
|
2. **Prod `.env`** — Muss auf dem Pi unter `/home/lars/docker/kairo/.env` mit sicherem `DB_PASSWORD` liegen (Deploy klont Repo, erzeugt `.env` nicht).
|
||||||
|
3. **README „Startzustand“** — Abschnitt oben in `README.md` beschreibt noch „kein Anwendungscode“; AP0.1-Tabelle unten ist aktuell — Kosmetik-Update empfohlen.
|
||||||
|
4. **`workflow_run`-Trigger** — In Gitea/act unzuverlässig; Prod-Tests hängen an Push `main` (Fix `b5efdbb`). Merge/Deploy bleibt manuell durch Product Owner.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Abweichungen von der Spezifikation
|
||||||
|
|
||||||
|
| Spezifikation | Ist | Bewertung |
|
||||||
|
|---------------|-----|-----------|
|
||||||
|
| Health nur `status`, `app`, `db` | zusätzlich `version`, `schema` | Erweiterung, abwärtskompatibel |
|
||||||
|
| `db: "ok"` | auch `"error"` bei DB-Ausfall, dann `status: "degraded"` | sinnvoller Betriebszustand |
|
||||||
|
| Frontend optional | minimal umgesetzt (Health-Anzeige + nginx `/api`-Proxy) | im Scope |
|
||||||
|
| Offene Entscheidungen dokumentiert | in diesem Bericht + `docs/DEPLOYMENT.md`, kein separates ADR für AP0.1 | ausreichend für Abschluss |
|
||||||
|
|
||||||
|
Keine fachliche Sprint-1-Logik vorgezogen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Empfehlung für AP0.2
|
||||||
|
|
||||||
|
**Nächster Auftrag:** AP0.2 – Tenant, User, Actor (`Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md` § AP0.2)
|
||||||
|
|
||||||
|
Vorgehen:
|
||||||
|
|
||||||
|
1. Migration `002_tenant_user_actor.sql` — Tabellen laut Foundation, weiterhin ohne Vorhaben/Projekt-Domäne.
|
||||||
|
2. Seed für lokalen Admin-User (Dev only).
|
||||||
|
3. pytest für Migration + minimale Repository/Model-Schicht.
|
||||||
|
4. Health/version bei Schema-Bump (`DB_SCHEMA_VERSION` → `002`).
|
||||||
|
5. README-Startzustand bereinigen; optional Reverse Proxy parallel (nicht blockierend).
|
||||||
|
|
||||||
|
AP0.1 nicht erneut anfassen, außer README-Kosmetik oder Proxy-Wunsch.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Erstellt im Rahmen Sprint 0 – AP0.1 Akzeptanz.*
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
# AP0.2 – Abschlussbericht Auth, Identity, Tenant & Actor Foundation
|
||||||
|
|
||||||
|
**Status:** abgeschlossen
|
||||||
|
**Stand:** 2026-07-04 (final)
|
||||||
|
**Branch:** `develop` · Prod-Deploy auf `main` erfolgt und stabil
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Scope und Einordnung
|
||||||
|
|
||||||
|
AP0.2 liefert die **Auth-, Identity-, Tenant- und Actor-Grundlage** für Kairo. Gegenüber dem ursprünglichen Foundation-Dokument (`Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md`) wurde der für AP0.3 vorgesehene **Auth-/TenantContext-Teil bereits in AP0.2** umgesetzt.
|
||||||
|
|
||||||
|
| Anforderung (AP0.2 / erweitert) | Status |
|
||||||
|
|----------------------------------|--------|
|
||||||
|
| Tenant, User, Membership | ✓ |
|
||||||
|
| Actor (human, agent, working_group, external_system) | ✓ |
|
||||||
|
| Server-Sessions, Login/Logout | ✓ |
|
||||||
|
| TenantContext + Tenant-Wechsel | ✓ |
|
||||||
|
| Portal-Rolle vs. Tenant-Rolle getrennt | ✓ |
|
||||||
|
| Seed für Admin (Env + Erstregistrierung + Dev-Seed) | ✓ |
|
||||||
|
| Audit bei Auth-Aktionen | ✓ |
|
||||||
|
| Frontend Login/Register (minimal) | ✓ |
|
||||||
|
| Idempotentes Data-Seed-System | ✓ (Erweiterung) |
|
||||||
|
|
||||||
|
**Bewusst nicht in AP0.2:** Capabilities/Rights Registry, Rate-Limiting, Tenant-Admin-API, Passwort-Reset.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Umgesetzte Artefakte
|
||||||
|
|
||||||
|
### Backend – Schema & Migrationen
|
||||||
|
|
||||||
|
| Datei | Zweck |
|
||||||
|
|-------|--------|
|
||||||
|
| `backend/migrations/002_auth_identity_tenant_actor.sql` | User, Session, Tenant, Membership, Actor, Audit |
|
||||||
|
| `backend/migrations/003_data_seeds_tracking.sql` | Tabelle `data_seeds` für Seed-Tracking |
|
||||||
|
| `backend/run_migrations.py` | Schema-Migrationen (`schema_migrations`) |
|
||||||
|
| `backend/run_seeds.py` | Data-Seeds (Checksum, Dev-Seeds bei jedem Start) |
|
||||||
|
| `backend/entrypoint.sh` | Migrationen + Seeds vor Uvicorn-Start |
|
||||||
|
|
||||||
|
### Backend – Domäne & Services
|
||||||
|
|
||||||
|
| Datei | Zweck |
|
||||||
|
|-------|--------|
|
||||||
|
| `backend/auth.py` | bcrypt, Sessions, `require_auth`, `require_portal_admin` |
|
||||||
|
| `backend/tenant_context.py` | `TenantContext`, `get_tenant_context`, `require_tenant_context` |
|
||||||
|
| `backend/bootstrap.py` | Env-Bootstrap (`KAIRO_BOOTSTRAP_*`) |
|
||||||
|
| `backend/services/registration.py` | Erstregistrierung, `provision_system_admin` |
|
||||||
|
| `backend/services/dev_admin.py` | Dev-Admin sicherstellen (nur Nicht-Prod) |
|
||||||
|
| `backend/services/actors.py` | Actor-Erzeugung, Human-Lookup |
|
||||||
|
| `backend/services/audit.py` | Audit-Log |
|
||||||
|
|
||||||
|
### Backend – API
|
||||||
|
|
||||||
|
| Datei | Zweck |
|
||||||
|
|-------|--------|
|
||||||
|
| `backend/routers/auth.py` | Login, Logout, Register, Setup-Status |
|
||||||
|
| `backend/routers/me.py` | `/api/me`, `/api/me/context`, Tenant-Wechsel |
|
||||||
|
| `backend/main.py` | Router, Startup (Fallback ohne Entrypoint) |
|
||||||
|
|
||||||
|
### Data-Seeds
|
||||||
|
|
||||||
|
| Seed | Umgebung | Zweck |
|
||||||
|
|------|----------|--------|
|
||||||
|
| `seed_001_cleanup_pytest_artifacts.dev.sql` | Dev | Entfernt `*@example.com`, verwaiste Test-Tenants |
|
||||||
|
| `seed_002_bootstrap_admin.py` | Dev + Prod | Admin aus `KAIRO_BOOTSTRAP_*` wenn DB leer |
|
||||||
|
| `seed_003_ensure_dev_admin.dev.py` | Dev | Stellt `lars@stommer.com` als Portal-Admin sicher |
|
||||||
|
|
||||||
|
Doku: `docs/MIGRATIONS.md`
|
||||||
|
|
||||||
|
### Frontend
|
||||||
|
|
||||||
|
| Datei | Zweck |
|
||||||
|
|-------|--------|
|
||||||
|
| `frontend/src/App.jsx` | Login/Register-Tabs, Session-Anzeige, Setup-Status |
|
||||||
|
| `frontend/src/app.css` | Auth-UI, Tabs, Hinweise |
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
|
||||||
|
| Datei | Abdeckung |
|
||||||
|
|-------|-----------|
|
||||||
|
| `test_auth.py` | Login, Logout, Session, `/api/me`, Context, Tenant-Wechsel |
|
||||||
|
| `test_tenant_actor.py` | Actor-Typen, Portal- vs. Tenant-Rolle |
|
||||||
|
| `test_registration.py` | Erstregistrierung, Setup-Status |
|
||||||
|
| `test_seeds.py` | Seed-Runner, Cleanup, Dev-Admin |
|
||||||
|
| `test_migrations.py` | Migrationen 001–003, Idempotenz |
|
||||||
|
|
||||||
|
### Infrastruktur & Doku
|
||||||
|
|
||||||
|
| Datei | Zweck |
|
||||||
|
|-------|--------|
|
||||||
|
| `docker-compose.dev-env.yml`, `docker-compose.yml` | Postgres pro Stack, Bootstrap/Session-Env, Healthcheck |
|
||||||
|
| `backend/Dockerfile` | Entrypoint für Startup-Reihenfolge |
|
||||||
|
| `.gitea/workflows/deploy-dev.yml` | Deploy Dev + Logs bei Fehler |
|
||||||
|
| `.gitea/workflows/test.yml` | pytest + Seed-Cleanup nach CI |
|
||||||
|
| `README.md`, `docs/DEPLOYMENT.md` | Local Dev, Auth, DB-Volume-Wechsel |
|
||||||
|
|
||||||
|
**Version:** `APP_VERSION = 0.2.0-ap0.2`, `DB_SCHEMA_VERSION = 003`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Datenmodell (Migration 002)
|
||||||
|
|
||||||
|
- **`users`** — E-Mail, bcrypt-Hash, `portal_role` (`user` \| `admin`)
|
||||||
|
- **`sessions`** — opaque Token, `user_id`, `active_tenant_id`, Ablauf
|
||||||
|
- **`tenants`** — Slug (unique), Name, aktiv
|
||||||
|
- **`tenant_memberships`** — `tenant_role` (`owner` \| `admin` \| `member`)
|
||||||
|
- **`actors`** — `human`, `agent`, `working_group`, `external_system`; Human verknüpft mit `user_id`
|
||||||
|
- **`audit_log`** — Auth-Ereignisse (JSONB-Details)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. API-Endpunkte
|
||||||
|
|
||||||
|
| Endpoint | Methode | Auth | Beschreibung |
|
||||||
|
|----------|---------|------|--------------|
|
||||||
|
| `/api/auth/setup-status` | GET | — | `registration_open`, `has_users`, `user_count` |
|
||||||
|
| `/api/auth/register` | POST | — | Erster User → Portal-Admin (nur leere DB) |
|
||||||
|
| `/api/auth/login` | POST | — | E-Mail + Passwort → Session-Token |
|
||||||
|
| `/api/auth/logout` | POST | `X-Auth-Token` | Session löschen |
|
||||||
|
| `/api/me` | GET | `X-Auth-Token` | User + Tenant-Liste |
|
||||||
|
| `/api/me/context` | GET | `X-Auth-Token` | TenantContext (Tenant + Human Actor) |
|
||||||
|
| `/api/me/context/required` | GET | `X-Auth-Token` | Wie Context, 403 ohne aktiven Tenant |
|
||||||
|
| `/api/me/tenant` | POST | `X-Auth-Token` | Aktiven Tenant wechseln (nur Memberships) |
|
||||||
|
|
||||||
|
OpenAPI (Dev): `/api/docs`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Auth-Fluss
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /api/auth/login { email, password }
|
||||||
|
→ bcrypt verify
|
||||||
|
→ INSERT sessions (token, expires_at, active_tenant_id = erste Membership)
|
||||||
|
→ audit: auth.login
|
||||||
|
→ Response: { token, expires_at, user }
|
||||||
|
|
||||||
|
Request mit Header X-Auth-Token
|
||||||
|
→ get_session(token) JOIN users
|
||||||
|
→ require_auth → session (user_id aus DB, nie aus Client-Body)
|
||||||
|
|
||||||
|
POST /api/auth/logout → DELETE session → audit: auth.logout
|
||||||
|
```
|
||||||
|
|
||||||
|
**Ersteinrichtung (Priorität):**
|
||||||
|
|
||||||
|
1. **Dev:** Seed `seed_003` — `lars@stommer.com` (Portal-Admin, bei jedem Start)
|
||||||
|
2. **Prod/Dev:** Seed `seed_002` — `KAIRO_BOOTSTRAP_*` wenn DB leer
|
||||||
|
3. **UI:** `POST /api/auth/register` — nur wenn `user_count == 0`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. TenantContext
|
||||||
|
|
||||||
|
```
|
||||||
|
require_auth → session (user_id, active_tenant_id, portal_role)
|
||||||
|
→ tenant_memberships + tenants (nur aktiv)
|
||||||
|
→ human actor: actors WHERE tenant_id + user_id + type = human
|
||||||
|
→ TenantContext(portal_role, tenant_role, tenant, actor)
|
||||||
|
```
|
||||||
|
|
||||||
|
Tenant-Wechsel: `POST /api/me/tenant { tenant_id }` — nur bei gültiger Membership.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Deployment & Betrieb
|
||||||
|
|
||||||
|
| | Development | Production |
|
||||||
|
|---|-------------|------------|
|
||||||
|
| Verzeichnis | `/home/lars/docker/kairo-dev` | `/home/lars/docker/kairo` |
|
||||||
|
| Ports | 3097 / 8097 | 3004 / 8004 |
|
||||||
|
| Postgres | Eigener Container + Volume pro Stack | Eigener Container + Volume |
|
||||||
|
| Dev-Seeds | Ja (Cleanup + Dev-Admin) | Nein (`.dev.*` übersprungen) |
|
||||||
|
| Admin-Zugang | `lars@stommer.com` (Seed) | `KAIRO_BOOTSTRAP_*` in `.env` |
|
||||||
|
|
||||||
|
**Startup-Reihenfolge:** Entrypoint → Schema-Migrationen → Data-Seeds → Uvicorn.
|
||||||
|
|
||||||
|
**DB-Zugangsdaten ändern:** Volume neu anlegen (`docker compose down -v`) — siehe `docs/DEPLOYMENT.md`.
|
||||||
|
|
||||||
|
**Verifikation (2026-07-04):** Dev und Prod stabil nach Deploy; Dev-DB-Wechsel mit frischem Volume erfolgreich.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Tests & CI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.dev-env.yml exec backend pip install -r requirements-dev.txt
|
||||||
|
docker compose -f docker-compose.dev-env.yml exec backend python -m pytest tests -ra -vv
|
||||||
|
```
|
||||||
|
|
||||||
|
| Bereich | Status |
|
||||||
|
|---------|--------|
|
||||||
|
| pytest-backend (Dev/Prod im Container) | ✓ |
|
||||||
|
| compose-smoke (PR, isolierte Ports) | ✓ |
|
||||||
|
| k6 Health-Baseline | ✓ |
|
||||||
|
| Playwright smoke | ✓ |
|
||||||
|
| Seed-Cleanup nach pytest (Dev) | ✓ |
|
||||||
|
|
||||||
|
**Hinweis Betrieb:** pytest gegen deployte Instanz erzeugt `*@example.com`-User. Dev-Seed räumt auf; auf Prod bleiben Test-User bestehen (Cleanup-Seed läuft dort nicht). Prod-DB bei Bedarf manuell prüfen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Abweichungen von Designprinzipien
|
||||||
|
|
||||||
|
| Thema | Kairo AP0.2 | Begründung |
|
||||||
|
|-------|-------------|------------|
|
||||||
|
| Mitai `profiles` | `users` + separate `actors` | User ≠ Actor, kein Multi-Profil-Legacy |
|
||||||
|
| Passwort-Hash | nur bcrypt | Grüne Wiese |
|
||||||
|
| Query-Token / SSE | nicht implementiert | Später |
|
||||||
|
| Capabilities in TenantContext | fehlen | AP0.3 |
|
||||||
|
| Zentrale Postgres-Instanz | je Stack eigener Container | Isolation wie Shinkan/Mitai |
|
||||||
|
|
||||||
|
**Eingehalten:** Server-Sessions, `X-Auth-Token`, `Depends(require_auth)`, Portal- vs. Tenant-Rolle, TenantContext-Schicht, nummerierte Migrationen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Offene Punkte (nach AP0.2)
|
||||||
|
|
||||||
|
1. **Rate-Limiting / Passwort-Policy** für Login
|
||||||
|
2. **Passwort-Reset** + Session-Invalidierung
|
||||||
|
3. **Tenant-/User-Verwaltung per API** (Admin-Routen)
|
||||||
|
4. **Prod-pytest-Cleanup** — optional Seed für `*@example.com` auch in Prod
|
||||||
|
5. **Frontend** — produktive Shell statt Debug-JSON (UX, AP0.3+)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Empfehlung AP0.3
|
||||||
|
|
||||||
|
Gemäß Foundation-Dokument:
|
||||||
|
|
||||||
|
- **Capability / Rights Registry** (DB + Runtime-Sync)
|
||||||
|
- **`require_capability()`** als FastAPI-Dependency
|
||||||
|
- **TenantContext** um `capabilities: list[str]` erweitern
|
||||||
|
- Keine Feature-Limits / Billing in Sprint 0
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Referenzen
|
||||||
|
|
||||||
|
- Assignment-Kontext: `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md` § AP0.2
|
||||||
|
- Vorgänger: `docs/sprints/Sprint0_AP0_1_Completion_Report_v0.1.md`
|
||||||
|
- Migrationen/Seeds: `docs/MIGRATIONS.md`
|
||||||
|
- Deployment: `docs/DEPLOYMENT.md`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Abgeschlossen im Rahmen Sprint 0 – AP0.2. Ersetzt `Sprint0_AP0_2_Completion_Report_v0.1.md`.*
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
# AP0.3 – Abschlussbericht Capability / Rights Registry & Entitlements Snapshot
|
||||||
|
|
||||||
|
**Status:** abgeschlossen
|
||||||
|
**Stand:** 2026-07-04 (final)
|
||||||
|
**Branch:** `develop` · Dev-Deploy und Test Suite grün · Prod stabil (Stand Nutzer)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Scope und Einordnung
|
||||||
|
|
||||||
|
AP0.3 liefert die **minimale Capability-/Rights-Grundlage** und den **Entitlements-Snapshot** für Sprint 0. Auth, TenantContext und Sessions stammen aus AP0.2; AP0.3 ergänzt Registry, DB-Sync, zentrale Capability-Prüfung und `/api/me/entitlements`.
|
||||||
|
|
||||||
|
| Anforderung (AP0.3) | Status |
|
||||||
|
|---------------------|--------|
|
||||||
|
| Migration Capabilities + Role-Grants | ✓ |
|
||||||
|
| Runtime Registry + Modul-Registrierungen | ✓ |
|
||||||
|
| Startup-Sync Registry → DB | ✓ |
|
||||||
|
| TenantContext.capabilities | ✓ |
|
||||||
|
| `require_capability()` Dependency | ✓ |
|
||||||
|
| `GET /api/me/entitlements` | ✓ |
|
||||||
|
| Beispiel-Endpoint mit Capability-Gate | ✓ |
|
||||||
|
| Tests (Registry, Sync, Auflösung, Enforce/Probe) | ✓ |
|
||||||
|
| Trennung Auth / Capability / Feature | ✓ |
|
||||||
|
|
||||||
|
**Bewusst nicht in AP0.3:** Feature-Limits, Billing, Usage-Zähler, Prompt Registry, produktive Admin-UI, Governance/Object-ACL.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Umgesetzte Dateien
|
||||||
|
|
||||||
|
| Datei | Zweck |
|
||||||
|
|-------|--------|
|
||||||
|
| `backend/migrations/004_capabilities_registry.sql` | Tabellen `capabilities`, `role_capability_grants` |
|
||||||
|
| `backend/rights_registry.py` | In-Memory-Registry, Validierung, DB-Sync, Grant-Lookup |
|
||||||
|
| `backend/rights_registrations/__init__.py` | Side-Effect-Import aller Modul-Registrierungen |
|
||||||
|
| `backend/rights_registrations/platform.py` | Platform-Capabilities |
|
||||||
|
| `backend/rights_registrations/tenant_ops.py` | Tenant-/Actor-Capabilities |
|
||||||
|
| `backend/capabilities.py` | Auflösung, `check_capability`, `require_capability` |
|
||||||
|
| `backend/entitlements.py` | Entitlements-Snapshot-Builder |
|
||||||
|
| `backend/sync_rights_registry.py` | CLI-Sync beim Container-Start |
|
||||||
|
| `backend/tenant_context.py` | `TenantContext.capabilities` |
|
||||||
|
| `backend/routers/me.py` | `/entitlements`, `/admin/demo` |
|
||||||
|
| `backend/entrypoint.sh` | Rights-Sync nach Seeds |
|
||||||
|
| `backend/version.py` | `0.3.0-ap0.3`, Schema `004` |
|
||||||
|
| `backend/tests/test_rights_registry.py` | Registry + Sync |
|
||||||
|
| `backend/tests/test_capabilities.py` | Grants, enforce/probe, Demo-Endpoint |
|
||||||
|
| `backend/tests/test_entitlements.py` | Snapshot-Form |
|
||||||
|
| `backend/tests/conftest.py` | Registry-Sync in Test-Session |
|
||||||
|
| `frontend/src/App.jsx` | Header AP0.3; `/api/me/context` zeigt Capabilities |
|
||||||
|
| `README.md` | API-Doku AP0.3 |
|
||||||
|
|
||||||
|
**Wesentliche Commits:** `910b1d7` (Implementierung), `eaa0e25` (pytest-Fix), `4069cb0` (GUI-Sprint-Label).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Neue Migrationen
|
||||||
|
|
||||||
|
**`004_capabilities_registry.sql`**
|
||||||
|
|
||||||
|
- **`capabilities`** — `capability_key`, `module`, `description`, `is_active`
|
||||||
|
- **`role_capability_grants`** — `role_scope` (`portal` \| `tenant`), `role_code`, `capability_key`
|
||||||
|
|
||||||
|
Kein Feature-/Limit-Schema (Vorbereitung AP0.4).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Registry-Struktur
|
||||||
|
|
||||||
|
```
|
||||||
|
backend/
|
||||||
|
├── rights_registry.py
|
||||||
|
├── rights_registrations/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ ├── platform.py # admin, context, entitlements
|
||||||
|
│ └── tenant_ops.py # tenant.manage, actor.manage
|
||||||
|
└── sync_rights_registry.py
|
||||||
|
```
|
||||||
|
|
||||||
|
**Modell:** `@dataclass(frozen=True) CapabilityRegistration` mit `key`, `module`, `description`, `default_grants`.
|
||||||
|
|
||||||
|
**Startup:** `entrypoint.sh` → `python sync_rights_registry.py` (`SKIP_RIGHTS_SYNC=1` zum Überspringen).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Endpoints
|
||||||
|
|
||||||
|
| Endpoint | Methode | Auth / Gate | Status |
|
||||||
|
|----------|---------|-------------|--------|
|
||||||
|
| `/api/me/context` | GET | Session | geändert — `capabilities[]` |
|
||||||
|
| `/api/me/entitlements` | GET | Session | neu |
|
||||||
|
| `/api/me/admin/demo` | GET | Session + `kairo.admin.access` | neu (Beispiel `require_capability`) |
|
||||||
|
|
||||||
|
OpenAPI (Dev): `/api/docs`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Capability-Auflösungslogik
|
||||||
|
|
||||||
|
```
|
||||||
|
Session (portal_role, active_tenant_id)
|
||||||
|
→ tenant_role aus Membership (optional)
|
||||||
|
→ load_grants_for_roles(portal_role, tenant_role)
|
||||||
|
→ Union Portal-Grants + Tenant-Grants
|
||||||
|
→ TenantContext.capabilities (frozenset)
|
||||||
|
```
|
||||||
|
|
||||||
|
**`require_capability(key)`:** prüft Mitgliedschaft in `ctx.capabilities`.
|
||||||
|
|
||||||
|
| Modus | Env | Verhalten |
|
||||||
|
|-------|-----|-----------|
|
||||||
|
| probe | `CAPABILITY_ENFORCE=probe` (Default) | Zugriff erlaubt; Verweigerung → Audit `capability.denied` |
|
||||||
|
| enforce | `CAPABILITY_ENFORCE=enforce` | HTTP 403 ohne Grant |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Initiale Capabilities
|
||||||
|
|
||||||
|
| Capability | Portal admin | Portal user | Tenant owner | Tenant admin | Tenant member |
|
||||||
|
|------------|:------------:|:-----------:|:------------:|:------------:|:-------------:|
|
||||||
|
| `kairo.admin.access` | ✓ | | | | |
|
||||||
|
| `kairo.tenant.manage` | ✓ | | ✓ | ✓ | |
|
||||||
|
| `kairo.actor.manage` | ✓ | | ✓ | ✓ | |
|
||||||
|
| `kairo.context.read` | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| `kairo.entitlements.read` | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Tests und Verifikation
|
||||||
|
|
||||||
|
### pytest (CI, Dev-Container)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.dev-env.yml exec backend python -m pytest tests -ra -vv
|
||||||
|
```
|
||||||
|
|
||||||
|
| Testdatei | Abdeckung | Status |
|
||||||
|
|-----------|-----------|--------|
|
||||||
|
| `test_rights_registry.py` | 5 Capabilities, Sync idempotent | ✓ |
|
||||||
|
| `test_capabilities.py` | Admin/Member enforce, Owner-Grants, probe | ✓ |
|
||||||
|
| `test_entitlements.py` | Snapshot-Struktur | ✓ |
|
||||||
|
| `test_migrations.py` | Migration 004 | ✓ |
|
||||||
|
| Gesamt Test Suite (Gitea) | nach Push `develop` | ✓ (Nutzer bestätigt) |
|
||||||
|
|
||||||
|
### Manuell (Dev-GUI)
|
||||||
|
|
||||||
|
| Prüfung | Ergebnis |
|
||||||
|
|---------|----------|
|
||||||
|
| Login `lars@stommer.com` | ✓ |
|
||||||
|
| `/api/me/context` → `capabilities` sichtbar | ✓ |
|
||||||
|
| API Health → `"schema": "004"` | ✓ |
|
||||||
|
| Header Sprint-Anzeige AP0.3 | ✓ (nach `4069cb0`) |
|
||||||
|
|
||||||
|
**Hinweis:** Entitlements und Admin-Demo sind in der GUI noch nicht als eigene Karten — prüfbar über Swagger (`/api/docs`) oder DevTools.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Übernommene Muster aus Shinkan
|
||||||
|
|
||||||
|
| Muster | Kairo-Umsetzung |
|
||||||
|
|--------|-----------------|
|
||||||
|
| Registry-first | `rights_registry.py` + `rights_registrations/` |
|
||||||
|
| `register_capability()` mit Validierung | Pflichtfelder `key`, `module`, `description` |
|
||||||
|
| Frozen Dataclass-Definitionen | `CapabilityRegistration` |
|
||||||
|
| Startup-Sync Registry → DB | `sync_rights_registry_to_db()` |
|
||||||
|
| Modul-Ownership | `platform`, `tenant` |
|
||||||
|
| Default Grants in Code | `default_grants` pro Capability |
|
||||||
|
| `require_capability` Dependency | `capabilities.py` |
|
||||||
|
| `/api/me/entitlements` Snapshot | `entitlements.py` |
|
||||||
|
| Probe vs. Enforce | `CAPABILITY_ENFORCE` |
|
||||||
|
|
||||||
|
**Nicht übernommen:** `club_id`, Vereinsrollen, Übungs-/Trainingsrechte, Club-Feature-Kontingente.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Übernommene Muster aus Mitai
|
||||||
|
|
||||||
|
| Muster | Kairo-Umsetzung |
|
||||||
|
|--------|-----------------|
|
||||||
|
| Entitlements als zentrale Schicht | `build_entitlements_snapshot()` |
|
||||||
|
| Probe-vs-Enforce-Denken | Default `probe`, optional `enforce` |
|
||||||
|
| Feature-Registry vorbereitet | `features: {}` im Snapshot |
|
||||||
|
|
||||||
|
**Nicht übernommen:** Tier/Subscription, Usage-Zähler, Billing, Legacy `check_feature_access`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Bewusst nicht übernommen
|
||||||
|
|
||||||
|
- Shinkan-/Mitai-Domänenbegriffe (`club`, `profile`, Tier)
|
||||||
|
- Feature-Limits, Billing, Coupons
|
||||||
|
- Prompt Registry, Vorhaben-/Projektlogik
|
||||||
|
- MCP, produktive Admin-UI (nur Debug-JSON + Swagger)
|
||||||
|
- Capabilities nur in SQL pflegen
|
||||||
|
- Governance/Object-ACL
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Abweichungen von Designprinzipien
|
||||||
|
|
||||||
|
| Thema | Abweichung | Begründung |
|
||||||
|
|-------|------------|------------|
|
||||||
|
| Entitlements-Struktur | Account- + Tenant-Block | Kairo Hybrid laut Family Entitlement Model |
|
||||||
|
| Feature-Registry | leeres Objekt | AP0.4 |
|
||||||
|
| Grant-Overrides | Sync nur additive Grants | Sprint-0-Minimal |
|
||||||
|
| `linked_feature_id` | nicht modelliert | Keine Limits in AP0.3 |
|
||||||
|
| Frontend | kein Entitlements-Panel | Minimal-UI; AP0.4/UX optional |
|
||||||
|
|
||||||
|
**Eingehalten:** zentrale Capability-Prüfung; Portal- vs. Tenant-Rolle getrennt; TenantContext als Auflösungsschicht.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. Offene Entscheidungen
|
||||||
|
|
||||||
|
1. **Prod `CAPABILITY_ENFORCE=enforce`** — wann umstellen?
|
||||||
|
2. **Grant-Overrides in DB** vs. reiner Code-Kanon
|
||||||
|
3. **Prod-pytest-Cleanup** (`*@example.com`) — aus AP0.2 offen
|
||||||
|
4. **Frontend:** Entitlements-Karte + Admin-Demo-Button
|
||||||
|
5. **Feature-Registry** — AP0.4
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 14. Empfehlung für AP0.4
|
||||||
|
|
||||||
|
Laut Foundation **AP0.4 – Prompt, Feature, Config Registry**:
|
||||||
|
|
||||||
|
- Feature Registry (Metadaten, ohne Billing-Limits in Sprint 0)
|
||||||
|
- PromptTemplate / PromptVersion / Placeholder
|
||||||
|
- ConfigurationEntry
|
||||||
|
- Prompt-Rendering mit Placeholder-Validation
|
||||||
|
- `features`-Block in Entitlements mit Registry-Sync
|
||||||
|
|
||||||
|
Optional vor AP0.4: Prod-Cleanup-Seed; GUI-Entitlements; `CAPABILITY_ENFORCE=enforce` in Prod nach Kalibrierung.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Referenzen
|
||||||
|
|
||||||
|
- `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md` § AP0.3, §9
|
||||||
|
- `docs/reference/design-principles/shinkan/RIGHTS_REGISTRY_DESIGN_PRINCIPLES.md`
|
||||||
|
- `docs/reference/design-principles/shinkan/CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md`
|
||||||
|
- `docs/reference/design-principles/alignment/FAMILY_ENTITLEMENT_MODEL.md`
|
||||||
|
- Vorgänger: `docs/sprints/Sprint0_AP0_2_Completion_Report_v0.2.md`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Abgeschlossen im Rahmen Sprint 0 – AP0.3. Ersetzt `Sprint0_AP0_3_Completion_Report_v0.1.md`.*
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
# AP0.3 – Abschlussbericht Capability / Rights Registry & Entitlements Snapshot
|
||||||
|
|
||||||
|
**Status:** abgeschlossen
|
||||||
|
**Stand:** 2026-07-04 (final inkl. Prod-Deploy-Nacharbeit)
|
||||||
|
**Branch:** `develop` · Dev-Deploy und Test Suite grün · **Prod verifiziert** (Schema `004`, Health ok)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Scope und Einordnung
|
||||||
|
|
||||||
|
AP0.3 liefert die **minimale Capability-/Rights-Grundlage** und den **Entitlements-Snapshot** für Sprint 0. Auth, TenantContext und Sessions stammen aus AP0.2; AP0.3 ergänzt Registry, DB-Sync, zentrale Capability-Prüfung und `/api/me/entitlements`.
|
||||||
|
|
||||||
|
| Anforderung (AP0.3) | Status |
|
||||||
|
|---------------------|--------|
|
||||||
|
| Migration Capabilities + Role-Grants | ✓ |
|
||||||
|
| Runtime Registry + Modul-Registrierungen | ✓ |
|
||||||
|
| Startup-Sync Registry → DB | ✓ |
|
||||||
|
| TenantContext.capabilities | ✓ |
|
||||||
|
| `require_capability()` Dependency | ✓ |
|
||||||
|
| `GET /api/me/entitlements` | ✓ |
|
||||||
|
| Beispiel-Endpoint mit Capability-Gate | ✓ |
|
||||||
|
| Tests (Registry, Sync, Auflösung, Enforce/Probe) | ✓ |
|
||||||
|
| Trennung Auth / Capability / Feature | ✓ |
|
||||||
|
|
||||||
|
**Bewusst nicht in AP0.3:** Feature-Limits, Billing, Usage-Zähler, Prompt Registry, produktive Admin-UI, Governance/Object-ACL.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Umgesetzte Dateien
|
||||||
|
|
||||||
|
| Datei | Zweck |
|
||||||
|
|-------|--------|
|
||||||
|
| `backend/migrations/004_capabilities_registry.sql` | Tabellen `capabilities`, `role_capability_grants` |
|
||||||
|
| `backend/rights_registry.py` | In-Memory-Registry, Validierung, DB-Sync, Grant-Lookup |
|
||||||
|
| `backend/rights_registrations/__init__.py` | Side-Effect-Import aller Modul-Registrierungen |
|
||||||
|
| `backend/rights_registrations/platform.py` | Platform-Capabilities |
|
||||||
|
| `backend/rights_registrations/tenant_ops.py` | Tenant-/Actor-Capabilities |
|
||||||
|
| `backend/capabilities.py` | Auflösung, `check_capability`, `require_capability` |
|
||||||
|
| `backend/entitlements.py` | Entitlements-Snapshot-Builder |
|
||||||
|
| `backend/sync_rights_registry.py` | CLI-Sync beim Container-Start |
|
||||||
|
| `backend/tenant_context.py` | `TenantContext.capabilities` |
|
||||||
|
| `backend/routers/me.py` | `/entitlements`, `/admin/demo` |
|
||||||
|
| `backend/entrypoint.sh` | Rights-Sync nach Seeds |
|
||||||
|
| `backend/version.py` | `0.3.0-ap0.3`, Schema `004` |
|
||||||
|
| `backend/tests/test_rights_registry.py` | Registry + Sync |
|
||||||
|
| `backend/tests/test_capabilities.py` | Grants, enforce/probe, Demo-Endpoint |
|
||||||
|
| `backend/tests/test_entitlements.py` | Snapshot-Form |
|
||||||
|
| `backend/tests/conftest.py` | Registry-Sync in Test-Session |
|
||||||
|
| `frontend/src/App.jsx` | Header AP0.3; `/api/me/context` zeigt Capabilities |
|
||||||
|
| `README.md` | API-Doku AP0.3 |
|
||||||
|
| `.gitea/workflows/deploy-prod.yml` | Backend-Logs bei `--wait`-Fehler (Parität zu Dev) |
|
||||||
|
| `docs/DEPLOYMENT.md` | Abschnitt DB-Passwort Dev/Prod inkl. `ALTER USER`-Fix |
|
||||||
|
|
||||||
|
**Wesentliche Commits:** `910b1d7` (Implementierung), `eaa0e25` (pytest-Fix), `4069cb0` (GUI-Sprint-Label), `39e8084` (Abschlussbericht v0.2).
|
||||||
|
|
||||||
|
**Nacharbeit (noch auf `develop`):** `deploy-prod.yml`, `DEPLOYMENT.md`, dieser Bericht v0.3.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Neue Migrationen
|
||||||
|
|
||||||
|
**`004_capabilities_registry.sql`**
|
||||||
|
|
||||||
|
- **`capabilities`** — `capability_key`, `module`, `description`, `is_active`
|
||||||
|
- **`role_capability_grants`** — `role_scope` (`portal` \| `tenant`), `role_code`, `capability_key`
|
||||||
|
|
||||||
|
Kein Feature-/Limit-Schema (Vorbereitung AP0.4).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Registry-Struktur
|
||||||
|
|
||||||
|
```
|
||||||
|
backend/
|
||||||
|
├── rights_registry.py
|
||||||
|
├── rights_registrations/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ ├── platform.py # admin, context, entitlements
|
||||||
|
│ └── tenant_ops.py # tenant.manage, actor.manage
|
||||||
|
└── sync_rights_registry.py
|
||||||
|
```
|
||||||
|
|
||||||
|
**Modell:** `@dataclass(frozen=True) CapabilityRegistration` mit `key`, `module`, `description`, `default_grants`.
|
||||||
|
|
||||||
|
**Startup:** `entrypoint.sh` → Migrationen → Seeds → `python sync_rights_registry.py` → Uvicorn (`SKIP_RIGHTS_SYNC=1` zum Überspringen).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Endpoints
|
||||||
|
|
||||||
|
| Endpoint | Methode | Auth / Gate | Status |
|
||||||
|
|----------|---------|-------------|--------|
|
||||||
|
| `/api/me/context` | GET | Session | geändert — `capabilities[]` |
|
||||||
|
| `/api/me/entitlements` | GET | Session | neu |
|
||||||
|
| `/api/me/admin/demo` | GET | Session + `kairo.admin.access` | neu (Beispiel `require_capability`) |
|
||||||
|
|
||||||
|
OpenAPI (Dev): `/api/docs`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Capability-Auflösungslogik
|
||||||
|
|
||||||
|
```
|
||||||
|
Session (portal_role, active_tenant_id)
|
||||||
|
→ tenant_role aus Membership (optional)
|
||||||
|
→ load_grants_for_roles(portal_role, tenant_role)
|
||||||
|
→ Union Portal-Grants + Tenant-Grants
|
||||||
|
→ TenantContext.capabilities (frozenset)
|
||||||
|
```
|
||||||
|
|
||||||
|
**`require_capability(key)`:** prüft Mitgliedschaft in `ctx.capabilities`.
|
||||||
|
|
||||||
|
| Modus | Env | Verhalten |
|
||||||
|
|-------|-----|-----------|
|
||||||
|
| probe | `CAPABILITY_ENFORCE=probe` (Default) | Zugriff erlaubt; Verweigerung → Audit `capability.denied` |
|
||||||
|
| enforce | `CAPABILITY_ENFORCE=enforce` | HTTP 403 ohne Grant |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Initiale Capabilities
|
||||||
|
|
||||||
|
| Capability | Portal admin | Portal user | Tenant owner | Tenant admin | Tenant member |
|
||||||
|
|------------|:------------:|:-----------:|:------------:|:------------:|:-------------:|
|
||||||
|
| `kairo.admin.access` | ✓ | | | | |
|
||||||
|
| `kairo.tenant.manage` | ✓ | | ✓ | ✓ | |
|
||||||
|
| `kairo.actor.manage` | ✓ | | ✓ | ✓ | |
|
||||||
|
| `kairo.context.read` | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
| `kairo.entitlements.read` | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Tests und Verifikation
|
||||||
|
|
||||||
|
### pytest (CI, Dev-Container)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.dev-env.yml exec backend python -m pytest tests -ra -vv
|
||||||
|
```
|
||||||
|
|
||||||
|
| Testdatei | Abdeckung | Status |
|
||||||
|
|-----------|-----------|--------|
|
||||||
|
| `test_rights_registry.py` | 5 Capabilities, Sync idempotent | ✓ |
|
||||||
|
| `test_capabilities.py` | Admin/Member enforce, Owner-Grants, probe | ✓ |
|
||||||
|
| `test_entitlements.py` | Snapshot-Struktur | ✓ |
|
||||||
|
| `test_migrations.py` | Migration 004 | ✓ |
|
||||||
|
| Gesamt Test Suite (Gitea) | nach Push `develop` | ✓ |
|
||||||
|
|
||||||
|
### Manuell (Dev-GUI)
|
||||||
|
|
||||||
|
| Prüfung | Ergebnis |
|
||||||
|
|---------|----------|
|
||||||
|
| Login `lars@stommer.com` | ✓ |
|
||||||
|
| `/api/me/context` → `capabilities` sichtbar | ✓ |
|
||||||
|
| API Health → `"schema": "004"` | ✓ |
|
||||||
|
| Header Sprint-Anzeige AP0.3 | ✓ |
|
||||||
|
|
||||||
|
**Hinweis:** Entitlements und Admin-Demo sind in der GUI noch nicht als eigene Karten — prüfbar über Swagger (`/api/docs`) oder DevTools.
|
||||||
|
|
||||||
|
### Production (nach Nacharbeit 2026-07-04)
|
||||||
|
|
||||||
|
| Prüfung | Ergebnis |
|
||||||
|
|---------|----------|
|
||||||
|
| `curl http://localhost:8004/api/health` | ✓ — `0.3.0-ap0.3`, Schema `004`, `db: ok` |
|
||||||
|
| `curl http://localhost:3004/api/health` | ✓ |
|
||||||
|
| Migration 004 auf Prod-Volume | ✓ (nach DB-Reconnect) |
|
||||||
|
| Rights-Sync beim Start | ✓ |
|
||||||
|
| Bootstrap-Admin (`.env`) | unverändert nutzbar |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Prod-Deploy-Nacharbeit (Gitea `deploy-prod` #7154)
|
||||||
|
|
||||||
|
### Symptom
|
||||||
|
|
||||||
|
Push auf `main` → Workflow `deploy-prod` schlug fehl:
|
||||||
|
|
||||||
|
```
|
||||||
|
dependency failed to start: container kairo-api is unhealthy
|
||||||
|
```
|
||||||
|
|
||||||
|
Backend-Logs (Pi):
|
||||||
|
|
||||||
|
```
|
||||||
|
[FAIL] ... FATAL: password authentication failed for user "kairo_user"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Ursache
|
||||||
|
|
||||||
|
**Kein AP0.3-Codefehler.** PostgreSQL initialisiert User/Passwort nur beim **ersten Start** des Volumes (`kairo-db-data`). Das Passwort in `/home/lars/docker/kairo/.env` wich vom in der DB gespeicherten Passwort ab — identisches Muster wie beim Dev-Deploy (#7100).
|
||||||
|
|
||||||
|
Der Entrypoint bricht bei DB-Auth-Fehlern fail-fast ab (seit AP0.2/`f8b3ae3`); Uvicorn startet nicht → Healthcheck scheitert nach wenigen Sekunden.
|
||||||
|
|
||||||
|
### Behebung (Prod, ohne Datenverlust)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /home/lars/docker/kairo
|
||||||
|
set -a && source .env && set +a
|
||||||
|
docker compose exec -T postgres psql -U kairo_user -d kairo \
|
||||||
|
-c "ALTER USER kairo_user WITH PASSWORD '${DB_PASSWORD}';"
|
||||||
|
docker compose restart backend
|
||||||
|
docker compose up -d --wait
|
||||||
|
```
|
||||||
|
|
||||||
|
Danach: alle Container `healthy`, API und Frontend-Proxy antworten.
|
||||||
|
|
||||||
|
### Prävention / Doku
|
||||||
|
|
||||||
|
| Maßnahme | Datei |
|
||||||
|
|----------|-------|
|
||||||
|
| Prod-Fix ohne Volume-Löschung dokumentiert | `docs/DEPLOYMENT.md` § Datenbank-Passwort |
|
||||||
|
| Backend-Logs bei `compose up --wait`-Fehler | `.gitea/workflows/deploy-prod.yml` (wie Dev) |
|
||||||
|
|
||||||
|
**Wichtig:** `docker compose down -v` auf Prod löscht alle Anwendungsdaten. Bei Passwort-Wechsel in `.env` bevorzugt `ALTER USER` verwenden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Deployment & Betrieb
|
||||||
|
|
||||||
|
| | Development | Production |
|
||||||
|
|---|-------------|------------|
|
||||||
|
| Verzeichnis | `/home/lars/docker/kairo-dev` | `/home/lars/docker/kairo` |
|
||||||
|
| Ports | 3097 / 8097 | 3004 / 8004 |
|
||||||
|
| Postgres | eigener Container + Volume | eigener Container + Volume (`kairo-db-data`) |
|
||||||
|
| Dev-Seeds | ja | nein |
|
||||||
|
| Admin | `lars@stommer.com` (Seed) | `KAIRO_BOOTSTRAP_*` in `.env` |
|
||||||
|
| Schema nach AP0.3 | `004` | `004` |
|
||||||
|
|
||||||
|
**Startup-Reihenfolge:** Entrypoint → Schema-Migrationen → Data-Seeds → Rights-Sync → Uvicorn.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Übernommene Muster aus Shinkan
|
||||||
|
|
||||||
|
| Muster | Kairo-Umsetzung |
|
||||||
|
|--------|-----------------|
|
||||||
|
| Registry-first | `rights_registry.py` + `rights_registrations/` |
|
||||||
|
| `register_capability()` mit Validierung | Pflichtfelder `key`, `module`, `description` |
|
||||||
|
| Frozen Dataclass-Definitionen | `CapabilityRegistration` |
|
||||||
|
| Startup-Sync Registry → DB | `sync_rights_registry_to_db()` |
|
||||||
|
| Modul-Ownership | `platform`, `tenant` |
|
||||||
|
| Default Grants in Code | `default_grants` pro Capability |
|
||||||
|
| `require_capability` Dependency | `capabilities.py` |
|
||||||
|
| `/api/me/entitlements` Snapshot | `entitlements.py` |
|
||||||
|
| Probe vs. Enforce | `CAPABILITY_ENFORCE` |
|
||||||
|
|
||||||
|
**Nicht übernommen:** `club_id`, Vereinsrollen, Übungs-/Trainingsrechte, Club-Feature-Kontingente.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Übernommene Muster aus Mitai
|
||||||
|
|
||||||
|
| Muster | Kairo-Umsetzung |
|
||||||
|
|--------|-----------------|
|
||||||
|
| Entitlements als zentrale Schicht | `build_entitlements_snapshot()` |
|
||||||
|
| Probe-vs-Enforce-Denken | Default `probe`, optional `enforce` |
|
||||||
|
| Feature-Registry vorbereitet | `features: {}` im Snapshot |
|
||||||
|
|
||||||
|
**Nicht übernommen:** Tier/Subscription, Usage-Zähler, Billing, Legacy `check_feature_access`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. Bewusst nicht übernommen
|
||||||
|
|
||||||
|
- Shinkan-/Mitai-Domänenbegriffe (`club`, `profile`, Tier)
|
||||||
|
- Feature-Limits, Billing, Coupons
|
||||||
|
- Prompt Registry, Vorhaben-/Projektlogik
|
||||||
|
- MCP, produktive Admin-UI (nur Debug-JSON + Swagger)
|
||||||
|
- Capabilities nur in SQL pflegen
|
||||||
|
- Governance/Object-ACL
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 14. Abweichungen von Designprinzipien
|
||||||
|
|
||||||
|
| Thema | Abweichung | Begründung |
|
||||||
|
|-------|------------|------------|
|
||||||
|
| Entitlements-Struktur | Account- + Tenant-Block | Kairo Hybrid laut Family Entitlement Model |
|
||||||
|
| Feature-Registry | leeres Objekt | AP0.4 |
|
||||||
|
| Grant-Overrides | Sync nur additive Grants | Sprint-0-Minimal |
|
||||||
|
| `linked_feature_id` | nicht modelliert | Keine Limits in AP0.3 |
|
||||||
|
| Frontend | kein Entitlements-Panel | Minimal-UI; AP0.4/UX optional |
|
||||||
|
|
||||||
|
**Eingehalten:** zentrale Capability-Prüfung; Portal- vs. Tenant-Rolle getrennt; TenantContext als Auflösungsschicht.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 15. Offene Entscheidungen
|
||||||
|
|
||||||
|
1. **Prod `CAPABILITY_ENFORCE=enforce`** — wann umstellen?
|
||||||
|
2. **Grant-Overrides in DB** vs. reiner Code-Kanon
|
||||||
|
3. **Prod-pytest-Cleanup** (`*@example.com`) — aus AP0.2 offen
|
||||||
|
4. **Frontend:** Entitlements-Karte + Admin-Demo-Button
|
||||||
|
5. **Feature-Registry** — AP0.4
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 16. Empfehlung für AP0.4
|
||||||
|
|
||||||
|
Laut Foundation **AP0.4 – Prompt, Feature, Config Registry**:
|
||||||
|
|
||||||
|
- Feature Registry (Metadaten, ohne Billing-Limits in Sprint 0)
|
||||||
|
- PromptTemplate / PromptVersion / Placeholder
|
||||||
|
- ConfigurationEntry
|
||||||
|
- Prompt-Rendering mit Placeholder-Validation
|
||||||
|
- `features`-Block in Entitlements mit Registry-Sync
|
||||||
|
|
||||||
|
Optional vor AP0.4: Prod-Cleanup-Seed; GUI-Entitlements; `CAPABILITY_ENFORCE=enforce` in Prod nach Kalibrierung.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Referenzen
|
||||||
|
|
||||||
|
- `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md` § AP0.3, §9
|
||||||
|
- `docs/reference/design-principles/shinkan/RIGHTS_REGISTRY_DESIGN_PRINCIPLES.md`
|
||||||
|
- `docs/reference/design-principles/shinkan/CAPABILITY_ENTITLEMENT_DESIGN_PRINCIPLES.md`
|
||||||
|
- `docs/reference/design-principles/alignment/FAMILY_ENTITLEMENT_MODEL.md`
|
||||||
|
- `docs/DEPLOYMENT.md` — DB-Passwort Dev/Prod
|
||||||
|
- Vorgänger: `docs/sprints/Sprint0_AP0_2_Completion_Report_v0.2.md`, `Sprint0_AP0_3_Completion_Report_v0.2.md`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Abgeschlossen im Rahmen Sprint 0 – AP0.3. Ersetzt `Sprint0_AP0_3_Completion_Report_v0.2.md`.*
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
# AP0.4 – Abschlussbericht Workflow-ready Prompt, Feature & Config Registry
|
||||||
|
|
||||||
|
**Status:** abgeschlossen
|
||||||
|
**Stand:** 2026-07-04
|
||||||
|
**Branch:** `develop` · Schema `005` · Version `0.4.0-ap0.4`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Scope und Einordnung
|
||||||
|
|
||||||
|
AP0.4 liefert die **minimale, workflow-ready Grundlage** für Feature-, Prompt-, Placeholder- und Configuration-Registry in Kairo — ohne LLM-Aufrufe, ohne Workflow Engine, ohne Billing.
|
||||||
|
|
||||||
|
| Anforderung (AP0.4) | Status |
|
||||||
|
|---------------------|--------|
|
||||||
|
| Migration Feature/Prompt/Placeholder/Config/ExecutionLog | ✓ |
|
||||||
|
| Feature Registry + DB-Sync | ✓ |
|
||||||
|
| PromptDefinition / PromptVersion / PromptStep | ✓ |
|
||||||
|
| PlaceholderDefinition + Validation | ✓ |
|
||||||
|
| ConfigurationEntry + Config Service | ✓ |
|
||||||
|
| Single Prompt Rendering | ✓ |
|
||||||
|
| `features`-Block in Entitlements | ✓ |
|
||||||
|
| Capability-geschützte API | ✓ |
|
||||||
|
| Audit bei Sync/Config/Fehler-Render | ✓ |
|
||||||
|
| Tests | ✓ (lokal; CI nach Push) |
|
||||||
|
|
||||||
|
**Bewusst nicht in AP0.4:** Workflow/Pipeline-Ausführung, LLM, MCP, Tool Calling, Feature-Limits, Admin-UI, zentrale Jinkendo Prompt Engine.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Umgesetzte Dateien
|
||||||
|
|
||||||
|
| Datei | Zweck |
|
||||||
|
|-------|--------|
|
||||||
|
| `backend/migrations/005_prompt_feature_config_registry.sql` | Tabellen Feature/Prompt/Placeholder/Config/ExecutionLog |
|
||||||
|
| `backend/feature_registry.py` | Feature-Registry + DB-Sync |
|
||||||
|
| `backend/feature_registrations/` | Initiale Features |
|
||||||
|
| `backend/prompt_registry.py` | Prompt-Registry + Version/Step-Sync |
|
||||||
|
| `backend/prompt_registrations/` | Smoke-Prompts |
|
||||||
|
| `backend/placeholder_registry.py` | Placeholder-Registry + Sync |
|
||||||
|
| `backend/placeholder_registrations/` | Tenant-/Actor-/Debug-Placeholder |
|
||||||
|
| `backend/config_service.py` | Config lesen/schreiben, Secret-Schutz |
|
||||||
|
| `backend/prompt_validation.py` | Placeholder-Extraktion + Validierung |
|
||||||
|
| `backend/prompt_rendering.py` | Single-Mode Render + ExecutionLog |
|
||||||
|
| `backend/prompt_context.py` | TenantContext → Placeholder-Werte |
|
||||||
|
| `backend/sync_prompt_feature_config.py` | Startup-Sync + Default-Configs |
|
||||||
|
| `backend/rights_registrations/registry_ops.py` | 7 neue Capabilities |
|
||||||
|
| `backend/routers/features.py` | `GET /api/features` |
|
||||||
|
| `backend/routers/prompts.py` | Prompt-Liste, Detail, Render |
|
||||||
|
| `backend/routers/config.py` | Config GET/POST |
|
||||||
|
| `backend/entitlements.py` | `features`-Block aus DB |
|
||||||
|
| `backend/capabilities.py` | `require_capability_ctx` (ohne Tenant-Zwang) |
|
||||||
|
| `backend/entrypoint.sh` | Registry-Sync nach Rights-Sync |
|
||||||
|
| `backend/version.py` | `0.4.0-ap0.4`, Schema `005` |
|
||||||
|
| `backend/tests/test_feature_registry.py` | Feature-Tests |
|
||||||
|
| `backend/tests/test_prompt_registry.py` | Prompt/Validation/Render-Tests |
|
||||||
|
| `backend/tests/test_config_registry.py` | Config-Tests |
|
||||||
|
| `frontend/src/App.jsx` | Header AP0.4 |
|
||||||
|
| `README.md` | API-Doku AP0.4 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Neue Migrationen
|
||||||
|
|
||||||
|
**`005_prompt_feature_config_registry.sql`**
|
||||||
|
|
||||||
|
| Tabelle | Zweck |
|
||||||
|
|---------|--------|
|
||||||
|
| `features` | Feature-Metadatenkatalog |
|
||||||
|
| `prompt_definitions` | PromptDefinition inkl. `execution_mode`, `active_version_id` |
|
||||||
|
| `prompt_versions` | Versionierter Body + JSON-Schemas + `model_policy_key` |
|
||||||
|
| `prompt_steps` | Workflow-/Pipeline-Schritte (AP0.4: nur `template` genutzt) |
|
||||||
|
| `placeholder_definitions` | Typisierte Placeholder pro `context_kind` |
|
||||||
|
| `configuration_entries` | Global/tenant Config (kein Secret-Klartext) |
|
||||||
|
| `prompt_execution_logs` | Render-/Test-Läufe |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Datenmodell
|
||||||
|
|
||||||
|
```
|
||||||
|
features
|
||||||
|
prompt_definitions ──< prompt_versions ──< prompt_steps
|
||||||
|
└── active_version_id → prompt_versions
|
||||||
|
|
||||||
|
placeholder_definitions (key + context_kind)
|
||||||
|
|
||||||
|
configuration_entries (global | tenant)
|
||||||
|
|
||||||
|
prompt_execution_logs → definition/version/user
|
||||||
|
```
|
||||||
|
|
||||||
|
**ExecutionMode:** `single` | `pipeline` | `workflow` (nur `single` ausführbar)
|
||||||
|
**ContextKind:** `kairo.tenant_context`, `kairo.actor_context`, `kairo.debug_context`
|
||||||
|
**StepType:** `template`, `resolver`, `llm_call`, `postprocess`, `validation` (nur `template` ausführbar)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Registry-Strukturen
|
||||||
|
|
||||||
|
Analog AP0.3 Rights Registry:
|
||||||
|
|
||||||
|
```
|
||||||
|
backend/
|
||||||
|
├── feature_registry.py + feature_registrations/
|
||||||
|
├── prompt_registry.py + prompt_registrations/
|
||||||
|
├── placeholder_registry.py + placeholder_registrations/
|
||||||
|
├── config_service.py
|
||||||
|
├── prompt_validation.py
|
||||||
|
├── prompt_rendering.py
|
||||||
|
└── sync_prompt_feature_config.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Startup-Reihenfolge: Migrationen → Seeds → Rights-Sync → **Registry-Sync** → Uvicorn.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Feature Registry
|
||||||
|
|
||||||
|
Registrierte Features:
|
||||||
|
|
||||||
|
| Feature Key | Modul |
|
||||||
|
|-------------|-------|
|
||||||
|
| `kairo.feature.registry` | platform |
|
||||||
|
| `kairo.config.registry` | config |
|
||||||
|
| `kairo.prompt.registry` | prompt |
|
||||||
|
|
||||||
|
Keine Limits, Quotas oder Billing — reiner Metadatenkatalog im Entitlements-Snapshot (`enabled: true`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Prompt-Modell
|
||||||
|
|
||||||
|
**Kernel-Konzepte (lokal in Kairo, extrahierbar):**
|
||||||
|
|
||||||
|
| Konzept | Umsetzung |
|
||||||
|
|---------|-----------|
|
||||||
|
| PromptDefinition | `prompt_definitions` + `PromptRegistration` |
|
||||||
|
| PromptVersion | `prompt_versions` |
|
||||||
|
| PromptStep | `prompt_steps` |
|
||||||
|
| PlaceholderDefinition | `placeholder_definitions` |
|
||||||
|
| ContextKind | Code-Konstanten + Spalte `context_kind` |
|
||||||
|
| ExecutionMode | Spalte `execution_mode` |
|
||||||
|
| InputSchema / OutputSchema | JSONB auf Version |
|
||||||
|
| ModelPolicyKey | Spalte (Vorbereitung, kein LLM) |
|
||||||
|
| PromptRenderService | `prompt_rendering.render_prompt_single` |
|
||||||
|
| PromptValidationService | `prompt_validation.validate_placeholder_input` |
|
||||||
|
| PromptExecutionLog | `prompt_execution_logs` |
|
||||||
|
|
||||||
|
**Smoke-Prompts:**
|
||||||
|
|
||||||
|
- `kairo.system.health_summary` — Debug-Context, Template via `PromptStep`
|
||||||
|
- `kairo.context.debug_summary` — TenantContext-Placeholder
|
||||||
|
- `kairo.actor.debug_summary` — Actor-Context
|
||||||
|
- `kairo.pipeline.placeholder` — `execution_mode=pipeline` (strukturell, nicht ausführbar)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Workflow-/Pipeline-Fähigkeit
|
||||||
|
|
||||||
|
| Vorbereitet | AP0.4 Verhalten |
|
||||||
|
|-------------|-----------------|
|
||||||
|
| `execution_mode=pipeline/workflow` | In DB/Registry akzeptiert; Render → HTTP 501 / `mode_not_implemented` |
|
||||||
|
| `prompt_steps` mit diversen `step_type` | Gespeichert; Single-Render nutzt ersten aktiven `template`-Step oder `version.body` |
|
||||||
|
| `input_mapping` / `output_mapping` | JSONB-Spalten, noch nicht ausgewertet |
|
||||||
|
|
||||||
|
**Spätere Pipeline:** Schritte der aktiven Version in `step_order` ausführen; pro `step_type` Handler registrieren (analog Rights-Registrations).
|
||||||
|
**Spätere Workflow:** `execution_mode=workflow` + Step-Graph/Orchestrator oberhalb des Render-Services — Tabellen müssen nicht migriert werden.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Placeholder Validation
|
||||||
|
|
||||||
|
- Mustache-Style: `{{placeholder_key}}`
|
||||||
|
- Required Placeholder aus Registry → kontrollierter `PlaceholderValidationError`
|
||||||
|
- Optionale Placeholder fehlen → kein Fehler
|
||||||
|
- Unbekannte Keys im Template → in `validation.unknown_placeholders` dokumentiert
|
||||||
|
- Typ-Prüfung basic (`string`, `number`, `boolean`, `object`, `array`, `json`)
|
||||||
|
- Template und Kontext getrennt (`use_context` + `prompt_context.py`)
|
||||||
|
|
||||||
|
Initial-Placeholder (Tenant): `tenant_name`, `tenant_id`, `actor_*`, `portal_role`, `tenant_role`, `capabilities`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Configuration Registry
|
||||||
|
|
||||||
|
Default-Configs beim Sync:
|
||||||
|
|
||||||
|
| Key | Wert |
|
||||||
|
|-----|------|
|
||||||
|
| `prompt.default_execution_mode` | `single` |
|
||||||
|
| `prompt.render_logging_enabled` | `true` |
|
||||||
|
| `features.registry_sync_enabled` | `true` |
|
||||||
|
|
||||||
|
- Scopes: `global`, `tenant`
|
||||||
|
- `is_secret=true` → kein Klartext; nur `{"ref": "env"}` erlaubt
|
||||||
|
- Zugriff zentral über `config_service.py`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Entitlements-Erweiterung
|
||||||
|
|
||||||
|
`/api/me/entitlements` liefert nun `features` auf Root-, Account- und Tenant-Ebene:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"features": {
|
||||||
|
"kairo.prompt.registry": {
|
||||||
|
"enabled": true,
|
||||||
|
"module": "prompt",
|
||||||
|
"name": "Prompt Registry"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Keine Usage-Zähler. Feature-Enforcement bleibt `probe`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Neue/geänderte API-Endpunkte
|
||||||
|
|
||||||
|
| Endpoint | Auth | Capability |
|
||||||
|
|----------|------|------------|
|
||||||
|
| `GET /api/features` | Session | `kairo.feature.registry.read` |
|
||||||
|
| `GET /api/prompts` | Session | `kairo.prompt.registry.read` |
|
||||||
|
| `GET /api/prompts/{key}` | Session | `kairo.prompt.registry.read` |
|
||||||
|
| `POST /api/prompts/{key}/render` | Session | `kairo.prompt.render` |
|
||||||
|
| `GET /api/config` | Session | `kairo.config.registry.read` |
|
||||||
|
| `POST /api/config` | Session | `kairo.config.registry.manage` |
|
||||||
|
|
||||||
|
`require_capability_ctx` erlaubt Lese-Endpunkte ohne aktiven Tenant (Portal-Admin/User).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. Audit
|
||||||
|
|
||||||
|
| Aktion | Event |
|
||||||
|
|--------|-------|
|
||||||
|
| Registry-Sync Startup | `registry.sync.completed` |
|
||||||
|
| Config geändert | `config.entry.changed` |
|
||||||
|
| Render fehlgeschlagen | `prompt.render.failed` |
|
||||||
|
| Capability verweigert | `capability.denied` (bestehend) |
|
||||||
|
|
||||||
|
Prompt-Definition-CRUD über API ist in AP0.4 nicht exponiert (nur Code-Registry + Sync) — Audit bei manuellem DB-Write wäre Lücke; AP0.5 Admin-Routen können CRUD + Audit ergänzen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 14. Tests und Verifikation
|
||||||
|
|
||||||
|
| Testdatei | Abdeckung |
|
||||||
|
|-----------|-----------|
|
||||||
|
| `test_feature_registry.py` | Registrierung, Sync, Entitlements, Auth |
|
||||||
|
| `test_prompt_registry.py` | Sync, Validation, Render, Pipeline-Ablehnung, API |
|
||||||
|
| `test_config_registry.py` | Global Config, Secret-Schutz, API |
|
||||||
|
| `test_entitlements.py` | Features im Snapshot |
|
||||||
|
| `test_migrations.py` | Migration 005 |
|
||||||
|
| `test_rights_registry.py` | 12 Capabilities |
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f docker-compose.dev-env.yml exec backend python -m pytest tests -ra -vv
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 15. Übernommene Muster aus Mitai
|
||||||
|
|
||||||
|
| Muster | Kairo |
|
||||||
|
|--------|-------|
|
||||||
|
| Prompt Template + Version | `PromptRegistration` / `prompt_versions` |
|
||||||
|
| Placeholder-Handling | Registry + Validation |
|
||||||
|
| Feature Registry Metadaten | `features` + Entitlements |
|
||||||
|
| Entitlements zentrale Schicht | `features`-Block ergänzt |
|
||||||
|
| Registry-Sync | Startup-Sync analog Rights |
|
||||||
|
| Preview/Testbarkeit | Render-Endpoint + ExecutionLog |
|
||||||
|
|
||||||
|
**Nicht übernommen:** Pipeline-Graphen, Gesundheits-Prompts, Tier/Billing, Usage-Zähler.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 16. Übernommene Muster aus Shinkan
|
||||||
|
|
||||||
|
| Muster | Kairo |
|
||||||
|
|--------|-------|
|
||||||
|
| Mustache-Template-Prinzip | `{{key}}`-Rendering |
|
||||||
|
| Kontextarten | `context_kind` |
|
||||||
|
| Registry-first | Code → DB-Sync |
|
||||||
|
| Schlanke Runtime ohne Overengineering | nur Single-Render |
|
||||||
|
| Capability-Gates | `require_capability*` |
|
||||||
|
|
||||||
|
**Nicht übernommen:** Trainings-Prompts, Club-Logik, Übungsrechte.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 17. Bewusst nicht übernommene Muster
|
||||||
|
|
||||||
|
- Vollständige Mitai Prompt Engine / Workflow-Graphen
|
||||||
|
- LLM Provider Routing, Tool Calling, MCP
|
||||||
|
- Shinkan-/Mitai-Domänenprompts
|
||||||
|
- Feature-Limits, Billing, Coupons
|
||||||
|
- Produktive Admin-UI
|
||||||
|
- Secrets in `configuration_entries`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 18. Abweichungen von Designprinzipien
|
||||||
|
|
||||||
|
| Thema | Abweichung | Begründung |
|
||||||
|
|-------|------------|------------|
|
||||||
|
| Prompt-CRUD API | nur Code-Registry + Sync | Sprint-0-Minimal; Swagger-Read/Render reicht |
|
||||||
|
| Feature-Enforcement | immer `probe` | Limits erst später |
|
||||||
|
| Output-Validation | nicht implementiert | Spec: nicht erforderlich in AP0.4 |
|
||||||
|
| ContextKind | Code-Konstanten, keine eigene Tabelle | Ausreichend für 3 Kindes |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 19. Offene Entscheidungen
|
||||||
|
|
||||||
|
1. **Wann Prompt/Feature-CRUD über Admin-API** (AP0.5)?
|
||||||
|
2. **Extraktion `jinkendo_prompt_kernel`** — Package-Grenze und Migrations-Ownership
|
||||||
|
3. **Pipeline-Executor** — Step-Handler-Registry vs. feste Kette
|
||||||
|
4. **Feature-Enforcement** — wann über reine Metadaten hinaus?
|
||||||
|
5. **Render-Logging in Prod** — `prompt.render_logging_enabled` Default?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 20. Empfehlung für AP0.5
|
||||||
|
|
||||||
|
Laut Foundation **AP0.5 – Audit und minimale Admin-Prüfbarkeit**:
|
||||||
|
|
||||||
|
- AuditLog für Registry-/Prompt-Änderungen erweitern
|
||||||
|
- Minimale Admin-Routen oder Admin-Seite
|
||||||
|
- Optional: Entitlements-/Feature-Panel in GUI
|
||||||
|
- Prod-pytest-Cleanup (`*@example.com`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Extraktion `jinkendo_prompt_kernel` — Einschätzung
|
||||||
|
|
||||||
|
**Realistisch:** Die Module `prompt_registry`, `placeholder_registry`, `prompt_validation`, `prompt_rendering` und die Tabellen `prompt_*` / `placeholder_definitions` sind produktneutral genug (`kairo.*`-Keys nur in Registrations). Extraktion als Shared Python-Package mit injizierbarem DB-Layer und Audit-Hook ist ohne Schema-Bruch möglich.
|
||||||
|
|
||||||
|
**Risiken im aktuellen Zuschnitt:**
|
||||||
|
|
||||||
|
- Config und Feature Registry noch eng an Kairo-Entitlements gekoppelt
|
||||||
|
- Kein generischer Step-Executor — Pipeline-Integration erfordert noch Designarbeit
|
||||||
|
- `require_capability_ctx` vs. `require_capability` — zwei Patterns für Tenant-Pflicht
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Referenzen
|
||||||
|
|
||||||
|
- `docs/sprints/Jinkendo_Kairo_04_Sprint0_Foundation_v0.3.md` § AP0.4
|
||||||
|
- Vorgänger: `docs/sprints/Sprint0_AP0_3_Completion_Report_v0.3.md`
|
||||||
|
- Designprinzipien: Mitai Prompt/Registry/Feature, Shinkan AI Prompt Runtime
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Abgeschlossen im Rahmen Sprint 0 – AP0.4.*
|
||||||
+368
-10
@@ -1,8 +1,39 @@
|
|||||||
import { useEffect, useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
|
|
||||||
|
const TOKEN_KEY = 'kairo_auth_token'
|
||||||
|
|
||||||
|
function apiHeaders(token) {
|
||||||
|
const headers = { 'Content-Type': 'application/json' }
|
||||||
|
if (token) headers['X-Auth-Token'] = token
|
||||||
|
return headers
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseError(body, fallback) {
|
||||||
|
if (!body) return fallback
|
||||||
|
if (typeof body.detail === 'string') return body.detail
|
||||||
|
if (Array.isArray(body.detail)) {
|
||||||
|
return body.detail.map((d) => d.msg || JSON.stringify(d)).join(', ')
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const [health, setHealth] = useState(null)
|
const [health, setHealth] = useState(null)
|
||||||
const [error, setError] = useState(null)
|
const [healthError, setHealthError] = useState(null)
|
||||||
|
const [setup, setSetup] = useState(null)
|
||||||
|
const [setupLoading, setSetupLoading] = useState(true)
|
||||||
|
const [setupError, setSetupError] = useState(null)
|
||||||
|
const [authMode, setAuthMode] = useState('login')
|
||||||
|
const [token, setToken] = useState(() => localStorage.getItem(TOKEN_KEY) || '')
|
||||||
|
const [email, setEmail] = useState('')
|
||||||
|
const [password, setPassword] = useState('')
|
||||||
|
const [displayName, setDisplayName] = useState('')
|
||||||
|
const [organizationName, setOrganizationName] = useState('')
|
||||||
|
const [passwordConfirm, setPasswordConfirm] = useState('')
|
||||||
|
const [authError, setAuthError] = useState(null)
|
||||||
|
const [authBusy, setAuthBusy] = useState(false)
|
||||||
|
const [me, setMe] = useState(null)
|
||||||
|
const [context, setContext] = useState(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetch('/api/health')
|
fetch('/api/health')
|
||||||
@@ -11,21 +42,348 @@ export default function App() {
|
|||||||
return res.json()
|
return res.json()
|
||||||
})
|
})
|
||||||
.then(setHealth)
|
.then(setHealth)
|
||||||
.catch((err) => setError(err.message))
|
.catch((err) => setHealthError(err.message))
|
||||||
|
|
||||||
|
async function loadSetupStatus() {
|
||||||
|
setSetupLoading(true)
|
||||||
|
setSetupError(null)
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/auth/setup-status')
|
||||||
|
const body = await res.json().catch(() => ({}))
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(
|
||||||
|
res.status === 404
|
||||||
|
? 'Endpoint /api/auth/setup-status nicht gefunden — Backend neu deployen?'
|
||||||
|
: parseError(body, `Setup-Status fehlgeschlagen (HTTP ${res.status})`),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (typeof body.registration_open !== 'boolean') {
|
||||||
|
throw new Error('Ungültige Antwort vom Setup-Status — Backend-Version prüfen')
|
||||||
|
}
|
||||||
|
setSetup(body)
|
||||||
|
if (body.registration_open) setAuthMode('register')
|
||||||
|
} catch (err) {
|
||||||
|
setSetup(null)
|
||||||
|
setSetupError(err.message)
|
||||||
|
} finally {
|
||||||
|
setSetupLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loadSetupStatus()
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
const loadSession = useCallback(async (activeToken) => {
|
||||||
|
if (!activeToken) {
|
||||||
|
setMe(null)
|
||||||
|
setContext(null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const meRes = await fetch('/api/me', { headers: apiHeaders(activeToken) })
|
||||||
|
if (!meRes.ok) {
|
||||||
|
localStorage.removeItem(TOKEN_KEY)
|
||||||
|
setToken('')
|
||||||
|
setMe(null)
|
||||||
|
setContext(null)
|
||||||
|
throw new Error(meRes.status === 401 ? 'Session abgelaufen' : `HTTP ${meRes.status}`)
|
||||||
|
}
|
||||||
|
setMe(await meRes.json())
|
||||||
|
const ctxRes = await fetch('/api/me/context', { headers: apiHeaders(activeToken) })
|
||||||
|
if (ctxRes.ok) setContext(await ctxRes.json())
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!token) return
|
||||||
|
loadSession(token).catch((err) => setAuthError(err.message))
|
||||||
|
}, [token, loadSession])
|
||||||
|
|
||||||
|
function applyLogin(data) {
|
||||||
|
localStorage.setItem(TOKEN_KEY, data.token)
|
||||||
|
setToken(data.token)
|
||||||
|
setPassword('')
|
||||||
|
setPasswordConfirm('')
|
||||||
|
setSetup({ registration_open: false, has_users: true, user_count: 1 })
|
||||||
|
setAuthMode('login')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleLogin(event) {
|
||||||
|
event.preventDefault()
|
||||||
|
setAuthBusy(true)
|
||||||
|
setAuthError(null)
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: apiHeaders(),
|
||||||
|
body: JSON.stringify({ email, password }),
|
||||||
|
})
|
||||||
|
const body = await res.json().catch(() => ({}))
|
||||||
|
if (!res.ok) throw new Error(parseError(body, `Login fehlgeschlagen (${res.status})`))
|
||||||
|
applyLogin(body)
|
||||||
|
} catch (err) {
|
||||||
|
setAuthError(err.message)
|
||||||
|
} finally {
|
||||||
|
setAuthBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRegister(event) {
|
||||||
|
event.preventDefault()
|
||||||
|
if (password !== passwordConfirm) {
|
||||||
|
setAuthError('Passwörter stimmen nicht überein')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setAuthBusy(true)
|
||||||
|
setAuthError(null)
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/auth/register', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: apiHeaders(),
|
||||||
|
body: JSON.stringify({
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
display_name: displayName,
|
||||||
|
organization_name: organizationName || undefined,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
const body = await res.json().catch(() => ({}))
|
||||||
|
if (!res.ok) throw new Error(parseError(body, `Registrierung fehlgeschlagen (${res.status})`))
|
||||||
|
applyLogin(body)
|
||||||
|
} catch (err) {
|
||||||
|
setAuthError(err.message)
|
||||||
|
} finally {
|
||||||
|
setAuthBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleLogout() {
|
||||||
|
setAuthBusy(true)
|
||||||
|
setAuthError(null)
|
||||||
|
try {
|
||||||
|
if (token) {
|
||||||
|
await fetch('/api/auth/logout', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: apiHeaders(token),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* lokal entfernen */
|
||||||
|
} finally {
|
||||||
|
localStorage.removeItem(TOKEN_KEY)
|
||||||
|
setToken('')
|
||||||
|
setMe(null)
|
||||||
|
setContext(null)
|
||||||
|
setAuthBusy(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const registrationOpen = setup?.registration_open === true
|
||||||
|
const registrationClosedBecauseUsersExist = setup?.has_users === true && !registrationOpen
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="shell">
|
<main className="shell">
|
||||||
<h1>Jinkendo Kairo</h1>
|
<header className="hero">
|
||||||
<p>Operativer Program Director — Sprint 0 / AP0.1</p>
|
<h1>Jinkendo Kairo</h1>
|
||||||
|
<p>Operativer Program Director — Sprint 0 / AP0.4</p>
|
||||||
|
<p className="muted">Capability Registry & Entitlements</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section className="card auth-card">
|
||||||
|
<h2>{token ? 'Session' : registrationOpen ? 'Ersteinrichtung' : 'Anmeldung'}</h2>
|
||||||
|
|
||||||
|
{!token && registrationOpen && (
|
||||||
|
<p className="setup-hint">
|
||||||
|
Noch kein Systemadministrator. Der erste Account wird automatisch{' '}
|
||||||
|
<strong>Portal-Admin</strong> und erhält einen Default-Tenant.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!token && setupLoading && (
|
||||||
|
<p className="muted">Prüfe Ersteinrichtung …</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!token && setupError && (
|
||||||
|
<p className="error">{setupError}</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!token && registrationClosedBecauseUsersExist && (
|
||||||
|
<p className="setup-hint setup-hint-muted">
|
||||||
|
Es existiert bereits mindestens ein Benutzer ({setup.user_count ?? '≥1'}).
|
||||||
|
Registrierung ist nur für die Ersteinrichtung vorgesehen — bitte anmelden.
|
||||||
|
Falls der Admin per <code>KAIRO_BOOTSTRAP_*</code> in der <code>.env</code> angelegt
|
||||||
|
wurde, nutzen Sie diese Zugangsdaten.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!token && !setupLoading && !setupError && (
|
||||||
|
<>
|
||||||
|
<div className="tabs" role="tablist">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="tab"
|
||||||
|
className={authMode === 'login' ? 'tab active' : 'tab'}
|
||||||
|
aria-selected={authMode === 'login'}
|
||||||
|
onClick={() => { setAuthMode('login'); setAuthError(null) }}
|
||||||
|
>
|
||||||
|
Anmelden
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="tab"
|
||||||
|
className={authMode === 'register' ? 'tab active' : 'tab'}
|
||||||
|
aria-selected={authMode === 'register'}
|
||||||
|
disabled={!registrationOpen}
|
||||||
|
onClick={() => { setAuthMode('register'); setAuthError(null) }}
|
||||||
|
>
|
||||||
|
Registrieren
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{authMode === 'login' && (
|
||||||
|
<form className="form" onSubmit={handleLogin}>
|
||||||
|
<label>
|
||||||
|
E-Mail
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
autoComplete="username"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Passwort
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
minLength={8}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button type="submit" disabled={authBusy}>
|
||||||
|
{authBusy ? 'Anmelden …' : 'Anmelden'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{authMode === 'register' && registrationOpen && (
|
||||||
|
<form className="form" onSubmit={handleRegister}>
|
||||||
|
<label>
|
||||||
|
Anzeigename
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
autoComplete="name"
|
||||||
|
value={displayName}
|
||||||
|
onChange={(e) => setDisplayName(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Organisation / Tenant (optional)
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={organizationName}
|
||||||
|
onChange={(e) => setOrganizationName(e.target.value)}
|
||||||
|
placeholder="z. B. Mein Programm-Team"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
E-Mail
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
autoComplete="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Passwort
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
minLength={8}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Passwort bestätigen
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
value={passwordConfirm}
|
||||||
|
onChange={(e) => setPasswordConfirm(e.target.value)}
|
||||||
|
minLength={8}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button type="submit" disabled={authBusy}>
|
||||||
|
{authBusy ? 'Registrieren …' : 'Systemadmin anlegen'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{authMode === 'register' && !registrationOpen && (
|
||||||
|
<p className="muted">
|
||||||
|
Registrierung ist geschlossen. Bitte melden Sie sich an oder wenden Sie sich an
|
||||||
|
den Administrator.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{token && me && (
|
||||||
|
<div className="session">
|
||||||
|
<p>
|
||||||
|
Eingeloggt als <strong>{me.display_name}</strong> ({me.email})
|
||||||
|
</p>
|
||||||
|
<p className="muted">
|
||||||
|
{me.portal_role === 'admin' ? 'Portal-Systemadmin' : `Portal-Rolle: ${me.portal_role}`}
|
||||||
|
{context?.tenant?.name && ` · ${context.tenant.name}`}
|
||||||
|
</p>
|
||||||
|
<button type="button" className="secondary" onClick={handleLogout} disabled={authBusy}>
|
||||||
|
Abmelden
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{authError && <p className="error">{authError}</p>}
|
||||||
|
</section>
|
||||||
|
|
||||||
<section className="card">
|
<section className="card">
|
||||||
<h2>API Health</h2>
|
<h2>Ersteinrichtung</h2>
|
||||||
{error && <p className="error">Fehler: {error}</p>}
|
{setupLoading && <p className="muted">Lade …</p>}
|
||||||
{!error && !health && <p>Lade …</p>}
|
{setupError && <p className="error">{setupError}</p>}
|
||||||
{health && (
|
{setup && <pre>{JSON.stringify(setup, null, 2)}</pre>}
|
||||||
<pre>{JSON.stringify(health, null, 2)}</pre>
|
{!setupLoading && !setup && !setupError && (
|
||||||
|
<p className="muted">Kein Setup-Status verfügbar.</p>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section className="card">
|
||||||
|
<h2>API Health</h2>
|
||||||
|
{healthError && <p className="error">Fehler: {healthError}</p>}
|
||||||
|
{!healthError && !health && <p>Lade …</p>}
|
||||||
|
{health && <pre>{JSON.stringify(health, null, 2)}</pre>}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{token && me && (
|
||||||
|
<>
|
||||||
|
<section className="card">
|
||||||
|
<h2>/api/me</h2>
|
||||||
|
<pre>{JSON.stringify(me, null, 2)}</pre>
|
||||||
|
</section>
|
||||||
|
{context && (
|
||||||
|
<section className="card">
|
||||||
|
<h2>/api/me/context</h2>
|
||||||
|
<pre>{JSON.stringify(context, null, 2)}</pre>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</main>
|
</main>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
+103
-1
@@ -11,7 +11,16 @@ body {
|
|||||||
.shell {
|
.shell {
|
||||||
max-width: 720px;
|
max-width: 720px;
|
||||||
margin: 2rem auto;
|
margin: 2rem auto;
|
||||||
padding: 0 1rem;
|
padding: 0 1rem 3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hero h1 {
|
||||||
|
margin-bottom: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.muted {
|
||||||
|
color: #555;
|
||||||
|
font-size: 0.95rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.card {
|
.card {
|
||||||
@@ -19,6 +28,54 @@ body {
|
|||||||
border: 1px solid #ddd;
|
border: 1px solid #ddd;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auth-card {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setup-hint {
|
||||||
|
background: #eef4fc;
|
||||||
|
border: 1px solid #c5d9f0;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0.75rem;
|
||||||
|
font-size: 0.92rem;
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setup-hint-muted {
|
||||||
|
background: #f3f3f3;
|
||||||
|
border-color: #ddd;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tabs {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.35rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab {
|
||||||
|
background: #eee;
|
||||||
|
color: #333;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
padding: 0.45rem 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab.active {
|
||||||
|
background: #1a4d8f;
|
||||||
|
color: #fff;
|
||||||
|
border-color: #1a4d8f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab:disabled {
|
||||||
|
opacity: 0.45;
|
||||||
|
cursor: not-allowed;
|
||||||
}
|
}
|
||||||
|
|
||||||
.error {
|
.error {
|
||||||
@@ -27,4 +84,49 @@ body {
|
|||||||
|
|
||||||
pre {
|
pre {
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form label {
|
||||||
|
display: grid;
|
||||||
|
gap: 0.25rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form input {
|
||||||
|
padding: 0.5rem 0.6rem;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
border-radius: 6px;
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
padding: 0.55rem 1rem;
|
||||||
|
border: none;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: #1a4d8f;
|
||||||
|
color: #fff;
|
||||||
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
width: fit-content;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: wait;
|
||||||
|
}
|
||||||
|
|
||||||
|
button.secondary {
|
||||||
|
background: #eee;
|
||||||
|
color: #222;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.session p {
|
||||||
|
margin: 0.35rem 0;
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user