dap-engine 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dap_engine/__init__.py +3 -0
- dap_engine/__main__.py +80 -0
- dap_engine/api/__init__.py +0 -0
- dap_engine/api/agents.py +546 -0
- dap_engine/api/deps.py +60 -0
- dap_engine/api/health.py +20 -0
- dap_engine/api/pipelines.py +428 -0
- dap_engine/api/projects.py +191 -0
- dap_engine/api/runs.py +694 -0
- dap_engine/api/runtimes.py +29 -0
- dap_engine/api/schemas.py +331 -0
- dap_engine/api/settings.py +288 -0
- dap_engine/app.py +438 -0
- dap_engine/auth/__init__.py +23 -0
- dap_engine/auth/admin_users_routes.py +134 -0
- dap_engine/auth/api_token_routes.py +345 -0
- dap_engine/auth/api_tokens.py +147 -0
- dap_engine/auth/audit.py +91 -0
- dap_engine/auth/audit_routes.py +125 -0
- dap_engine/auth/db.py +135 -0
- dap_engine/auth/oauth.py +41 -0
- dap_engine/auth/policies.py +64 -0
- dap_engine/auth/schemas.py +37 -0
- dap_engine/auth/users.py +400 -0
- dap_engine/contracts.py +205 -0
- dap_engine/execution/__init__.py +30 -0
- dap_engine/execution/conditions.py +87 -0
- dap_engine/execution/node_executor.py +363 -0
- dap_engine/execution/output_parser.py +162 -0
- dap_engine/execution/run_orchestrator.py +213 -0
- dap_engine/execution/run_registry.py +158 -0
- dap_engine/execution/runner.py +422 -0
- dap_engine/execution/validator.py +580 -0
- dap_engine/persistence/__init__.py +0 -0
- dap_engine/persistence/_common.py +24 -0
- dap_engine/persistence/agents.py +410 -0
- dap_engine/persistence/db.py +179 -0
- dap_engine/persistence/migrations.py +739 -0
- dap_engine/persistence/models.py +569 -0
- dap_engine/persistence/pipelines.py +328 -0
- dap_engine/persistence/projects.py +256 -0
- dap_engine/persistence/repository.py +101 -0
- dap_engine/persistence/runs.py +482 -0
- dap_engine/py.typed +0 -0
- dap_engine-0.3.0.dist-info/METADATA +49 -0
- dap_engine-0.3.0.dist-info/RECORD +48 -0
- dap_engine-0.3.0.dist-info/WHEEL +4 -0
- dap_engine-0.3.0.dist-info/entry_points.txt +2 -0
dap_engine/app.py
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import logging
|
|
5
|
+
from collections.abc import AsyncIterator
|
|
6
|
+
from contextlib import AsyncExitStack, asynccontextmanager
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from dap_runtimes import create_default_registry
|
|
12
|
+
from fastapi import FastAPI
|
|
13
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
14
|
+
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
|
|
15
|
+
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
|
|
16
|
+
from psycopg import AsyncConnection
|
|
17
|
+
from psycopg.rows import DictRow, dict_row
|
|
18
|
+
from psycopg_pool import AsyncConnectionPool
|
|
19
|
+
|
|
20
|
+
from dap_engine.api.agents import router as agents_router
|
|
21
|
+
from dap_engine.api.health import router as health_router
|
|
22
|
+
from dap_engine.api.pipelines import router as pipelines_router
|
|
23
|
+
from dap_engine.api.projects import router as projects_router
|
|
24
|
+
from dap_engine.api.runs import router as runs_router
|
|
25
|
+
from dap_engine.api.runtimes import router as runtimes_router
|
|
26
|
+
from dap_engine.api.settings import router as settings_router
|
|
27
|
+
from dap_engine.auth import fastapi_users
|
|
28
|
+
from dap_engine.auth.admin_users_routes import router as admin_users_router
|
|
29
|
+
from dap_engine.auth.api_token_routes import router as api_token_router
|
|
30
|
+
from dap_engine.auth.audit_routes import router as audit_router
|
|
31
|
+
from dap_engine.auth.db import create_async_engine_for_url, make_async_session_factory
|
|
32
|
+
from dap_engine.auth.oauth import make_github_client, make_google_client
|
|
33
|
+
from dap_engine.auth.schemas import UserCreate, UserRead, UserUpdate
|
|
34
|
+
from dap_engine.auth.users import auth_backend, configure_jwt
|
|
35
|
+
from dap_engine.execution import RunRegistry
|
|
36
|
+
from dap_engine.persistence import repository as repo
|
|
37
|
+
from dap_engine.persistence.db import (
|
|
38
|
+
create_engine_for_postgresql,
|
|
39
|
+
create_engine_for_sqlite,
|
|
40
|
+
detect_dialect,
|
|
41
|
+
make_session_factory,
|
|
42
|
+
pg_conn_string,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
logger = logging.getLogger("dap.engine")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@asynccontextmanager
|
|
49
|
+
async def _pg_pooled_checkpointer(
|
|
50
|
+
conn_string: str,
|
|
51
|
+
*,
|
|
52
|
+
min_size: int,
|
|
53
|
+
max_size: int,
|
|
54
|
+
) -> AsyncIterator[AsyncPostgresSaver]:
|
|
55
|
+
"""Yield an AsyncPostgresSaver backed by a psycopg AsyncConnectionPool.
|
|
56
|
+
|
|
57
|
+
Replaces ``AsyncPostgresSaver.from_conn_string`` which opens a single
|
|
58
|
+
persistent AsyncConnection. (#187)
|
|
59
|
+
|
|
60
|
+
``AsyncPostgresSaver._cursor()`` acquires a per-saver ``asyncio.Lock``
|
|
61
|
+
before borrowing from the pool, so checkpoint reads/writes are serialised
|
|
62
|
+
across all concurrent runs sharing this saver instance — only one
|
|
63
|
+
connection is borrowed at a time. ``max_size`` therefore governs how many
|
|
64
|
+
*spare* connections stay open, not actual checkpoint parallelism.
|
|
65
|
+
``min_size`` is the more important knob: it controls how many warm
|
|
66
|
+
connections the pool keeps ready so a checkpoint write that arrives after a
|
|
67
|
+
long idle phase (Phase 1 ~10 min) doesn't have to create a new connection
|
|
68
|
+
through a potentially-stale k8s NodePort NAT. (#238)
|
|
69
|
+
|
|
70
|
+
The connection kwargs (autocommit / prepare_threshold / row_factory) mirror
|
|
71
|
+
what ``from_conn_string`` configures so AsyncPostgresSaver sees the same
|
|
72
|
+
DBAPI behavior whether it's holding one connection or borrowing from a pool.
|
|
73
|
+
"""
|
|
74
|
+
# Annotate as AsyncConnectionPool[AsyncConnection[DictRow]] so
|
|
75
|
+
# AsyncPostgresSaver (which expects DictRow connections) typechecks; the
|
|
76
|
+
# row_factory=dict_row in kwargs makes this true at runtime.
|
|
77
|
+
pool: AsyncConnectionPool[AsyncConnection[DictRow]] = AsyncConnectionPool(
|
|
78
|
+
conninfo=conn_string,
|
|
79
|
+
min_size=min_size,
|
|
80
|
+
max_size=max_size,
|
|
81
|
+
# psycopg_pool default max_idle=600s (10 min) matches Cortex Phase 1
|
|
82
|
+
# runtime exactly — the pool reaps idle connections just as the gate
|
|
83
|
+
# checkpoint write arrives, causing PoolTimeout (#238). Set to 1 h
|
|
84
|
+
# so connections survive the full pipeline (~40 min).
|
|
85
|
+
max_idle=3600.0,
|
|
86
|
+
kwargs={
|
|
87
|
+
"autocommit": True,
|
|
88
|
+
"prepare_threshold": 0,
|
|
89
|
+
"row_factory": dict_row,
|
|
90
|
+
# TCP keepalives so k8s NodePort NAT doesn't silently drop
|
|
91
|
+
# idle connections (causes "server closed connection unexpectedly"
|
|
92
|
+
# when the first checkpoint read hits a dead socket).
|
|
93
|
+
"keepalives": 1,
|
|
94
|
+
"keepalives_idle": 30,
|
|
95
|
+
"keepalives_interval": 10,
|
|
96
|
+
"keepalives_count": 5,
|
|
97
|
+
},
|
|
98
|
+
# Defer opening to the async-context-manager entry; avoids the
|
|
99
|
+
# "implicit pool open in __init__" deprecation warning.
|
|
100
|
+
open=False,
|
|
101
|
+
)
|
|
102
|
+
async with pool:
|
|
103
|
+
yield AsyncPostgresSaver(conn=pool)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# Local-dev defaults: dashboard on :3000, alt port :7332. Override at
|
|
107
|
+
# deploy time via ``EngineConfig.cors_origins`` or the ``DAP_CORS_ORIGINS``
|
|
108
|
+
# env var (#259).
|
|
109
|
+
DEFAULT_CORS_ORIGINS: list[str] = [
|
|
110
|
+
"http://localhost:3000",
|
|
111
|
+
"http://127.0.0.1:3000",
|
|
112
|
+
"http://localhost:7332",
|
|
113
|
+
"http://127.0.0.1:7332",
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def parse_cors_origins(raw: str | None) -> list[str] | None:
|
|
118
|
+
"""Parse ``DAP_CORS_ORIGINS`` (comma-separated origins) into a list.
|
|
119
|
+
|
|
120
|
+
Returns ``None`` when the env var is unset or empty after stripping —
|
|
121
|
+
callers treat that as "use the default local-dev list". Whitespace
|
|
122
|
+
around individual entries is trimmed; empty entries are dropped so a
|
|
123
|
+
trailing comma doesn't produce a bogus origin string.
|
|
124
|
+
"""
|
|
125
|
+
if not raw:
|
|
126
|
+
return None
|
|
127
|
+
parts = [p.strip() for p in raw.split(",")]
|
|
128
|
+
cleaned = [p for p in parts if p]
|
|
129
|
+
return cleaned or None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass
|
|
133
|
+
class EngineConfig:
|
|
134
|
+
db_path: str = "./.dap/state.db"
|
|
135
|
+
# When set, takes precedence over db_path. Prefix determines dialect:
|
|
136
|
+
# sqlite://… → SQLite (same as db_path)
|
|
137
|
+
# postgresql+asyncpg://… → PostgreSQL
|
|
138
|
+
database_url: str | None = None
|
|
139
|
+
host: str = "127.0.0.1"
|
|
140
|
+
port: int = 7333
|
|
141
|
+
# Hard cap for ``POST /agents/dry-run`` (#103). Each invocation pays
|
|
142
|
+
# real LLM tokens, so we refuse calls whose agent ``budget_limit_usd``
|
|
143
|
+
# (the top-level field on Agent / AgentDryRunDraft, not anything inside
|
|
144
|
+
# ``runtime_config``) exceeds this. Belt-and-suspenders against a runaway
|
|
145
|
+
# form value or a forgotten zero default in the UI.
|
|
146
|
+
dry_run_budget_usd: float = 0.50
|
|
147
|
+
# PostgreSQL checkpointer pool sizing (#187, #238).
|
|
148
|
+
# AsyncPostgresSaver serialises checkpoint ops behind a Lock, so only 1
|
|
149
|
+
# connection is in flight at a time — max_size governs burst concurrency
|
|
150
|
+
# across simultaneous runs, not within one. min_size=4 matches the
|
|
151
|
+
# psycopg_pool default and keeps enough warm connections for the gate
|
|
152
|
+
# checkpoint write that arrives after a long idle Phase 1.
|
|
153
|
+
pg_pool_min_size: int = 4
|
|
154
|
+
pg_pool_max_size: int = 10
|
|
155
|
+
# CORS origins permitted on the engine's REST API (#259). ``None``
|
|
156
|
+
# means "fall back to ``DEFAULT_CORS_ORIGINS``" — the local-dev list.
|
|
157
|
+
# Production deployments override via env var ``DAP_CORS_ORIGINS``
|
|
158
|
+
# (parsed in ``__main__``) or by passing ``cors_origins=[...]`` here.
|
|
159
|
+
cors_origins: list[str] | None = None
|
|
160
|
+
# Auth (v0.3, see #299).
|
|
161
|
+
# ``auth_jwt_secret``: required for any auth-protected route. Tests
|
|
162
|
+
# set a deterministic value; production reads ``DAP_AUTH_JWT_SECRET``
|
|
163
|
+
# in ``__main__`` and refuses to start with a default. We accept None
|
|
164
|
+
# here only to keep the dataclass default-constructible; the lifespan
|
|
165
|
+
# generates a per-process random secret in that case (sufficient for
|
|
166
|
+
# local dev where every restart invalidates outstanding tokens).
|
|
167
|
+
auth_jwt_secret: str | None = None
|
|
168
|
+
auth_access_ttl_seconds: int = 60 * 15
|
|
169
|
+
# Password-reset token logging (sub-B3 review).
|
|
170
|
+
#
|
|
171
|
+
# When ``True``, the ``UserManager.on_after_forgot_password`` hook
|
|
172
|
+
# logs the raw reset token at WARNING level. Useful for self-hosted
|
|
173
|
+
# dev / one-operator instances that have no email delivery yet —
|
|
174
|
+
# the operator copies the token out of stdout and hands it to the
|
|
175
|
+
# user. **Off by default** because reset tokens are credentials;
|
|
176
|
+
# production log aggregation would otherwise routinely contain
|
|
177
|
+
# account-takeover material. Set via ``DAP_AUTH_LOG_RESET_TOKENS``.
|
|
178
|
+
auth_log_reset_tokens: bool = False
|
|
179
|
+
# OAuth (v0.3, sub-A2). Each provider is opt-in: when both
|
|
180
|
+
# client_id and client_secret are set the corresponding /auth/<provider>
|
|
181
|
+
# router is mounted; otherwise nothing is exposed for that provider.
|
|
182
|
+
# Self-host installs can run with email+password only and add OAuth
|
|
183
|
+
# later by setting these env vars and restarting.
|
|
184
|
+
oauth_github_client_id: str | None = None
|
|
185
|
+
oauth_github_client_secret: str | None = None
|
|
186
|
+
oauth_google_client_id: str | None = None
|
|
187
|
+
oauth_google_client_secret: str | None = None
|
|
188
|
+
# Post-login redirect for OAuth callbacks (sub-B5).
|
|
189
|
+
#
|
|
190
|
+
# When set, fastapi-users' OAuth callback redirects the browser to
|
|
191
|
+
# this URL with the access token as a ``?token=<jwt>`` query
|
|
192
|
+
# parameter, instead of returning JSON. The dashboard's
|
|
193
|
+
# ``/api/auth/oauth/callback`` handler reads the token, sets the
|
|
194
|
+
# httpOnly cookie, and lands the user on the home page — turning
|
|
195
|
+
# the OAuth dance into the same cookie-only auth surface password
|
|
196
|
+
# login uses.
|
|
197
|
+
#
|
|
198
|
+
# In dev this points at the dashboard's local URL
|
|
199
|
+
# (``http://localhost:3000/api/auth/oauth/callback``); production
|
|
200
|
+
# operators set ``DAP_AUTH_OAUTH_REDIRECT_URL`` to the
|
|
201
|
+
# equivalent dashboard URL. When ``None`` (no dashboard wired)
|
|
202
|
+
# the callback falls back to returning JSON — useful for
|
|
203
|
+
# CLI-only deployments.
|
|
204
|
+
auth_oauth_redirect_url: str | None = None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _setup_auth(cfg: EngineConfig) -> tuple[Any, Any, str]:
|
|
208
|
+
"""Build the JWT-config + async engine + session factory for fastapi-users.
|
|
209
|
+
|
|
210
|
+
Returns ``(async_engine, async_session_factory, jwt_secret)``. The
|
|
211
|
+
async engine is owned by the caller, which must dispose it on shutdown.
|
|
212
|
+
``jwt_secret`` is returned so OAuth routers can reuse it as their
|
|
213
|
+
state-secret (CSRF protection of the OAuth flow); a separate secret
|
|
214
|
+
would force operators to manage two env vars without a security gain.
|
|
215
|
+
|
|
216
|
+
A ``None`` ``auth_jwt_secret`` is replaced with a per-process random,
|
|
217
|
+
which means outstanding tokens become invalid on the next restart.
|
|
218
|
+
That's the safer default for local dev / tests; production must set
|
|
219
|
+
``DAP_AUTH_JWT_SECRET`` explicitly.
|
|
220
|
+
"""
|
|
221
|
+
import secrets # noqa: PLC0415 — local to keep top of file uncluttered
|
|
222
|
+
|
|
223
|
+
jwt_secret = cfg.auth_jwt_secret or secrets.token_urlsafe(32)
|
|
224
|
+
configure_jwt(
|
|
225
|
+
jwt_secret,
|
|
226
|
+
cfg.auth_access_ttl_seconds,
|
|
227
|
+
log_reset_tokens=cfg.auth_log_reset_tokens,
|
|
228
|
+
)
|
|
229
|
+
async_engine = create_async_engine_for_url(cfg.database_url, cfg.db_path)
|
|
230
|
+
async_session_factory = make_async_session_factory(async_engine)
|
|
231
|
+
return async_engine, async_session_factory, jwt_secret
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def create_app(config: EngineConfig | None = None) -> FastAPI: # noqa: PLR0915
|
|
235
|
+
cfg = config or EngineConfig()
|
|
236
|
+
|
|
237
|
+
# Auth setup runs synchronously at app-construction time so the OAuth
|
|
238
|
+
# routers (mounted below at module scope, not in lifespan) have access
|
|
239
|
+
# to the same JWT/state secret. ``create_async_engine`` doesn't open
|
|
240
|
+
# connections until the first request, so this is safe to do here.
|
|
241
|
+
auth_async_engine, async_session_factory, oauth_state_secret = _setup_auth(cfg)
|
|
242
|
+
|
|
243
|
+
@asynccontextmanager
|
|
244
|
+
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
245
|
+
# Determine dialect from DAP_DATABASE_URL or fall back to SQLite path.
|
|
246
|
+
db_url = cfg.database_url
|
|
247
|
+
dialect = detect_dialect(db_url) if db_url else "sqlite"
|
|
248
|
+
|
|
249
|
+
checkpointer_ctx: Any
|
|
250
|
+
if dialect == "postgresql":
|
|
251
|
+
assert db_url is not None
|
|
252
|
+
engine = create_engine_for_postgresql(db_url)
|
|
253
|
+
# Pooled AsyncPostgresSaver — concurrent checkpoint ops parallelize
|
|
254
|
+
# across up to cfg.pg_pool_max_size psycopg connections instead of
|
|
255
|
+
# serializing through a single TCP socket. (#187)
|
|
256
|
+
checkpointer_ctx = _pg_pooled_checkpointer(
|
|
257
|
+
pg_conn_string(db_url),
|
|
258
|
+
min_size=cfg.pg_pool_min_size,
|
|
259
|
+
max_size=cfg.pg_pool_max_size,
|
|
260
|
+
)
|
|
261
|
+
db_label = db_url.split("@", 1)[-1] if "@" in db_url else db_url
|
|
262
|
+
else:
|
|
263
|
+
engine = create_engine_for_sqlite(cfg.db_path)
|
|
264
|
+
checkpoint_path = Path(cfg.db_path).with_suffix(".checkpoints.db")
|
|
265
|
+
checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
|
|
266
|
+
checkpointer_ctx = AsyncSqliteSaver.from_conn_string(str(checkpoint_path))
|
|
267
|
+
db_label = str(Path(cfg.db_path).resolve())
|
|
268
|
+
|
|
269
|
+
session_factory = make_session_factory(engine)
|
|
270
|
+
registry = create_default_registry()
|
|
271
|
+
run_registry = RunRegistry()
|
|
272
|
+
|
|
273
|
+
# Recover stale runs left by previous crashes
|
|
274
|
+
with session_factory() as cleanup_session:
|
|
275
|
+
stale_count = repo.mark_stale_running_runs_as_failed(
|
|
276
|
+
cleanup_session,
|
|
277
|
+
reason="engine restarted before run completed",
|
|
278
|
+
)
|
|
279
|
+
cleanup_session.commit()
|
|
280
|
+
if stale_count > 0:
|
|
281
|
+
logger.warning("marked %d stale running run(s) as failed", stale_count)
|
|
282
|
+
|
|
283
|
+
async with AsyncExitStack() as stack:
|
|
284
|
+
checkpointer = await stack.enter_async_context(checkpointer_ctx)
|
|
285
|
+
# Create checkpointer tables (checkpoints, checkpoint_blobs, etc.) on
|
|
286
|
+
# first start against a fresh DB. setup() is idempotent — no-op when
|
|
287
|
+
# tables already exist. Required for both SQLite and PostgreSQL backends.
|
|
288
|
+
await checkpointer.setup()
|
|
289
|
+
|
|
290
|
+
app.state.config = cfg
|
|
291
|
+
app.state.db_engine = engine
|
|
292
|
+
app.state.db_dialect = dialect
|
|
293
|
+
app.state.session_factory = session_factory
|
|
294
|
+
app.state.runtime_registry = registry
|
|
295
|
+
app.state.run_registry = run_registry
|
|
296
|
+
app.state.checkpointer = checkpointer
|
|
297
|
+
app.state.async_session_factory = async_session_factory
|
|
298
|
+
app.state.auth_async_engine = auth_async_engine
|
|
299
|
+
|
|
300
|
+
logger.info("dap-engine started — dialect=%s db=%s", dialect, db_label)
|
|
301
|
+
try:
|
|
302
|
+
yield
|
|
303
|
+
finally:
|
|
304
|
+
cancelled = await run_registry.shutdown(timeout=5.0)
|
|
305
|
+
if cancelled:
|
|
306
|
+
logger.info("aborted %d running run(s) on shutdown", len(cancelled))
|
|
307
|
+
with session_factory() as shutdown_session:
|
|
308
|
+
for run_id in cancelled:
|
|
309
|
+
with contextlib.suppress(repo.NotFoundError):
|
|
310
|
+
repo.finalize_run(
|
|
311
|
+
shutdown_session,
|
|
312
|
+
run_id,
|
|
313
|
+
final_status="aborted",
|
|
314
|
+
)
|
|
315
|
+
shutdown_session.commit()
|
|
316
|
+
|
|
317
|
+
await auth_async_engine.dispose()
|
|
318
|
+
engine.dispose()
|
|
319
|
+
logger.info("dap-engine stopped")
|
|
320
|
+
|
|
321
|
+
app = FastAPI(
|
|
322
|
+
title="dap-engine",
|
|
323
|
+
version="0.0.1",
|
|
324
|
+
lifespan=lifespan,
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
app.add_middleware(
|
|
328
|
+
CORSMiddleware,
|
|
329
|
+
allow_origins=cfg.cors_origins if cfg.cors_origins is not None else DEFAULT_CORS_ORIGINS,
|
|
330
|
+
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
|
|
331
|
+
allow_headers=["Content-Type", "Authorization"],
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
app.include_router(health_router)
|
|
335
|
+
app.include_router(runtimes_router)
|
|
336
|
+
app.include_router(agents_router)
|
|
337
|
+
app.include_router(pipelines_router)
|
|
338
|
+
app.include_router(projects_router)
|
|
339
|
+
app.include_router(runs_router)
|
|
340
|
+
app.include_router(settings_router)
|
|
341
|
+
|
|
342
|
+
# Auth routes (v0.3, see #299).
|
|
343
|
+
# Existing endpoints are NOT yet auth-protected — that lands in a
|
|
344
|
+
# follow-up PR alongside the user_id ownership columns. This PR only
|
|
345
|
+
# exposes the auth surface so dashboards / CLIs can register and log
|
|
346
|
+
# in; the full auth-and-ownership migration ships separately.
|
|
347
|
+
app.include_router(
|
|
348
|
+
fastapi_users.get_auth_router(auth_backend),
|
|
349
|
+
prefix="/auth/jwt",
|
|
350
|
+
tags=["auth"],
|
|
351
|
+
)
|
|
352
|
+
app.include_router(
|
|
353
|
+
fastapi_users.get_register_router(UserRead, UserCreate),
|
|
354
|
+
prefix="/auth",
|
|
355
|
+
tags=["auth"],
|
|
356
|
+
)
|
|
357
|
+
# Password reset (#300, sub-B3). Two endpoints:
|
|
358
|
+
#
|
|
359
|
+
# POST /auth/forgot-password — email-only body; engine emits a
|
|
360
|
+
# reset token via ``on_after_forgot_password``. Until email
|
|
361
|
+
# delivery lands, the hook logs the token at WARNING level
|
|
362
|
+
# so an operator can copy it for self-hosted resets.
|
|
363
|
+
# POST /auth/reset-password — accepts ``{token, password}``
|
|
364
|
+
# and rewrites the user's hashed_password if the token
|
|
365
|
+
# validates.
|
|
366
|
+
#
|
|
367
|
+
# Same behaviour as fastapi-users defaults; no custom wrapping
|
|
368
|
+
# beyond the logging hook on the UserManager. Mounted under
|
|
369
|
+
# ``/auth`` to match the register / users router conventions.
|
|
370
|
+
app.include_router(
|
|
371
|
+
fastapi_users.get_reset_password_router(),
|
|
372
|
+
prefix="/auth",
|
|
373
|
+
tags=["auth"],
|
|
374
|
+
)
|
|
375
|
+
app.include_router(
|
|
376
|
+
fastapi_users.get_users_router(UserRead, UserUpdate),
|
|
377
|
+
prefix="/users",
|
|
378
|
+
tags=["users"],
|
|
379
|
+
)
|
|
380
|
+
# Admin-only list endpoint that fastapi-users doesn't ship (#301,
|
|
381
|
+
# sub-C2). Same ``/users`` prefix as the fastapi-users router —
|
|
382
|
+
# FastAPI dispatches by exact path so ``GET /users`` lands here
|
|
383
|
+
# and ``GET /users/{id}`` keeps its fastapi-users handler.
|
|
384
|
+
app.include_router(admin_users_router)
|
|
385
|
+
|
|
386
|
+
# API tokens (CLI / scripts) — JWT-only management surface; the
|
|
387
|
+
# tokens themselves authenticate any other route via the api-token
|
|
388
|
+
# backend wired into ``fastapi_users``.
|
|
389
|
+
app.include_router(api_token_router)
|
|
390
|
+
|
|
391
|
+
# Audit log read surface (#301, sub-C3). Append-only events flow
|
|
392
|
+
# into ``audit_log`` from the auth subsystem + ownership repos;
|
|
393
|
+
# this router exposes them to the admin panel.
|
|
394
|
+
app.include_router(audit_router)
|
|
395
|
+
|
|
396
|
+
# OAuth routers — only mounted when both credentials are present.
|
|
397
|
+
# ``associate_by_email=True`` lets a user with an existing local
|
|
398
|
+
# password account link a GitHub/Google identity by logging in with
|
|
399
|
+
# the same email. ``is_verified_by_default=True`` flags OAuth-created
|
|
400
|
+
# users as verified — Google enforces verified emails server-side and
|
|
401
|
+
# GitHub returns the verified primary email when the ``user:email``
|
|
402
|
+
# scope is granted (see auth/oauth.py).
|
|
403
|
+
if cfg.oauth_github_client_id and cfg.oauth_github_client_secret:
|
|
404
|
+
github_client = make_github_client(
|
|
405
|
+
cfg.oauth_github_client_id,
|
|
406
|
+
cfg.oauth_github_client_secret,
|
|
407
|
+
)
|
|
408
|
+
app.include_router(
|
|
409
|
+
fastapi_users.get_oauth_router(
|
|
410
|
+
github_client,
|
|
411
|
+
auth_backend,
|
|
412
|
+
oauth_state_secret,
|
|
413
|
+
redirect_url=cfg.auth_oauth_redirect_url,
|
|
414
|
+
associate_by_email=True,
|
|
415
|
+
is_verified_by_default=True,
|
|
416
|
+
),
|
|
417
|
+
prefix="/auth/github",
|
|
418
|
+
tags=["auth"],
|
|
419
|
+
)
|
|
420
|
+
if cfg.oauth_google_client_id and cfg.oauth_google_client_secret:
|
|
421
|
+
google_client = make_google_client(
|
|
422
|
+
cfg.oauth_google_client_id,
|
|
423
|
+
cfg.oauth_google_client_secret,
|
|
424
|
+
)
|
|
425
|
+
app.include_router(
|
|
426
|
+
fastapi_users.get_oauth_router(
|
|
427
|
+
google_client,
|
|
428
|
+
auth_backend,
|
|
429
|
+
oauth_state_secret,
|
|
430
|
+
redirect_url=cfg.auth_oauth_redirect_url,
|
|
431
|
+
associate_by_email=True,
|
|
432
|
+
is_verified_by_default=True,
|
|
433
|
+
),
|
|
434
|
+
prefix="/auth/google",
|
|
435
|
+
tags=["auth"],
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
return app
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Authentication & user management (v0.3, see #299).
|
|
2
|
+
|
|
3
|
+
Public surface is intentionally minimal: callers should import
|
|
4
|
+
``current_active_user`` (FastAPI dependency) and ``fastapi_users`` (the
|
|
5
|
+
configured FastAPIUsers instance for mounting routers). Everything else
|
|
6
|
+
is implementation detail.
|
|
7
|
+
|
|
8
|
+
Architecture note: this module ships an async SQLAlchemy engine that
|
|
9
|
+
runs alongside the existing sync engine in ``persistence/db.py``. Both
|
|
10
|
+
share the same database file/URL but maintain independent pools. This
|
|
11
|
+
isolates the fastapi-users requirement (which is async-only) from the
|
|
12
|
+
rest of the engine's sync codebase, with the trade-off of running two
|
|
13
|
+
connection pools per process.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from dap_engine.auth.users import current_active_user, fastapi_users
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"current_active_user",
|
|
22
|
+
"fastapi_users",
|
|
23
|
+
]
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Admin-only user listing (#301, sub-C2).
|
|
2
|
+
|
|
3
|
+
fastapi-users' ``get_users_router`` exposes ``GET/PATCH/DELETE
|
|
4
|
+
/users/{id}`` and ``GET/PATCH /users/me`` but **not** a list endpoint.
|
|
5
|
+
The admin panel needs one to render its user table, so this module
|
|
6
|
+
adds it.
|
|
7
|
+
|
|
8
|
+
Per-user mutations (suspend, change role, soft-delete) reuse the
|
|
9
|
+
fastapi-users routes — they already enforce ``is_superuser`` on
|
|
10
|
+
non-self updates and our ``UserManager.delete`` override gives them
|
|
11
|
+
the soft-delete behaviour we want.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import uuid
|
|
17
|
+
from datetime import datetime
|
|
18
|
+
|
|
19
|
+
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
20
|
+
from pydantic import BaseModel
|
|
21
|
+
from sqlalchemy import func, select
|
|
22
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
23
|
+
from sqlalchemy.orm import noload
|
|
24
|
+
|
|
25
|
+
from dap_engine.auth.db import get_async_session
|
|
26
|
+
from dap_engine.auth.users import current_active_user
|
|
27
|
+
from dap_engine.persistence.models import UserORM
|
|
28
|
+
|
|
29
|
+
router = APIRouter(prefix="/users", tags=["users"])
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class AdminUserRead(BaseModel):
|
|
33
|
+
"""Public representation in the admin list.
|
|
34
|
+
|
|
35
|
+
Wider than fastapi-users' ``UserRead`` — exposes ``created_at`` /
|
|
36
|
+
``last_login_at`` / ``deleted_at`` so the admin table can show
|
|
37
|
+
"joined", "last active", and the soft-delete state at a glance.
|
|
38
|
+
The schema is intentionally not aliased to ``UserRead`` because
|
|
39
|
+
these fields are admin-only — surfacing ``deleted_at`` on the
|
|
40
|
+
public read endpoint would leak the soft-delete state to the
|
|
41
|
+
affected user.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
id: uuid.UUID
|
|
45
|
+
email: str
|
|
46
|
+
is_active: bool
|
|
47
|
+
is_superuser: bool
|
|
48
|
+
is_verified: bool
|
|
49
|
+
created_at: datetime | None
|
|
50
|
+
last_login_at: datetime | None
|
|
51
|
+
deleted_at: datetime | None
|
|
52
|
+
|
|
53
|
+
model_config = {"from_attributes": True}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class AdminUserList(BaseModel):
|
|
57
|
+
"""Paginated list response — matches the shape the dashboard uses
|
|
58
|
+
for other admin tables (``items`` + ``total`` + ``offset`` +
|
|
59
|
+
``limit``)."""
|
|
60
|
+
|
|
61
|
+
items: list[AdminUserRead]
|
|
62
|
+
total: int
|
|
63
|
+
offset: int
|
|
64
|
+
limit: int
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@router.get(
|
|
68
|
+
"",
|
|
69
|
+
response_model=AdminUserList,
|
|
70
|
+
summary="List all users (admin-only)",
|
|
71
|
+
)
|
|
72
|
+
async def list_users(
|
|
73
|
+
user: UserORM = Depends(current_active_user),
|
|
74
|
+
session: AsyncSession = Depends(get_async_session),
|
|
75
|
+
*,
|
|
76
|
+
include_deleted: bool = Query(
|
|
77
|
+
default=False,
|
|
78
|
+
description=(
|
|
79
|
+
"Include soft-deleted users (``deleted_at`` is not NULL). "
|
|
80
|
+
"Default false so the table mirrors the engine's notion of "
|
|
81
|
+
"active membership."
|
|
82
|
+
),
|
|
83
|
+
),
|
|
84
|
+
offset: int = Query(default=0, ge=0),
|
|
85
|
+
limit: int = Query(default=50, ge=1, le=500),
|
|
86
|
+
) -> AdminUserList:
|
|
87
|
+
"""Paginated user list.
|
|
88
|
+
|
|
89
|
+
Admin-only. Non-admins get ``404`` to match the anti-enumeration
|
|
90
|
+
rule the sub-A4b2 resource routes use — a normal user hitting
|
|
91
|
+
``/users`` must not learn that the endpoint exists. Anonymous
|
|
92
|
+
callers get ``401`` from the upstream ``current_active_user``
|
|
93
|
+
dependency before reaching this body.
|
|
94
|
+
"""
|
|
95
|
+
if not user.is_superuser:
|
|
96
|
+
raise HTTPException(
|
|
97
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
98
|
+
detail="Not Found",
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
where = [] if include_deleted else [UserORM.deleted_at.is_(None)]
|
|
102
|
+
total = (
|
|
103
|
+
await session.scalar(
|
|
104
|
+
select(func.count()).select_from(UserORM).where(*where),
|
|
105
|
+
)
|
|
106
|
+
) or 0
|
|
107
|
+
# ``noload(UserORM.oauth_accounts)`` overrides the model's
|
|
108
|
+
# ``lazy="joined"`` for this query specifically. Without it the
|
|
109
|
+
# OUTER JOIN would duplicate user rows per linked OAuth account,
|
|
110
|
+
# and ``offset`` / ``limit`` applied *before* ``.unique()`` would
|
|
111
|
+
# skip users or return fewer than ``limit`` — broken pagination
|
|
112
|
+
# (Copilot review on PR #328). The list view doesn't render
|
|
113
|
+
# oauth_accounts, so dropping them costs nothing.
|
|
114
|
+
rows = (
|
|
115
|
+
(
|
|
116
|
+
await session.execute(
|
|
117
|
+
select(UserORM)
|
|
118
|
+
.options(noload(UserORM.oauth_accounts))
|
|
119
|
+
.where(*where)
|
|
120
|
+
.order_by(UserORM.created_at.desc())
|
|
121
|
+
.offset(offset)
|
|
122
|
+
.limit(limit),
|
|
123
|
+
)
|
|
124
|
+
)
|
|
125
|
+
.scalars()
|
|
126
|
+
.all()
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
return AdminUserList(
|
|
130
|
+
items=[AdminUserRead.model_validate(row) for row in rows],
|
|
131
|
+
total=total,
|
|
132
|
+
offset=offset,
|
|
133
|
+
limit=limit,
|
|
134
|
+
)
|