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/auth/users.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
"""UserManager + auth backends + FastAPIUsers instance.
|
|
2
|
+
|
|
3
|
+
The JWT secret is configured once from the engine lifespan via
|
|
4
|
+
``configure_jwt`` and lives on a module-level holder; ``get_jwt_strategy``
|
|
5
|
+
reads it on every login. ``UserManager`` instances pull the same value
|
|
6
|
+
into ``reset_password_token_secret`` and ``verification_token_secret``
|
|
7
|
+
on construction so fastapi-users' password-reset / verification routers
|
|
8
|
+
work end-to-end without per-request indirection.
|
|
9
|
+
|
|
10
|
+
Two authentication backends are wired into the ``FastAPIUsers`` instance:
|
|
11
|
+
- ``auth_backend`` — JWT bearer (``/auth/jwt/login`` flow)
|
|
12
|
+
- ``api_token_backend`` — opaque ``dap_*`` tokens (``/auth/api-tokens``,
|
|
13
|
+
see ``api_tokens.py``)
|
|
14
|
+
|
|
15
|
+
Both share the standard ``Authorization: Bearer <token>`` header.
|
|
16
|
+
``current_user(active=True)`` accepts whichever backend reads the token
|
|
17
|
+
successfully — JWT is tried first because its decode is purely
|
|
18
|
+
in-process (no DB hit) for non-API-token requests.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import logging
|
|
24
|
+
import uuid
|
|
25
|
+
from collections.abc import AsyncGenerator
|
|
26
|
+
from datetime import UTC, datetime
|
|
27
|
+
|
|
28
|
+
from fastapi import Depends, Request, Response
|
|
29
|
+
from fastapi_users import (
|
|
30
|
+
BaseUserManager,
|
|
31
|
+
FastAPIUsers,
|
|
32
|
+
InvalidPasswordException,
|
|
33
|
+
UUIDIDMixin,
|
|
34
|
+
)
|
|
35
|
+
from fastapi_users import schemas as fa_users_schemas
|
|
36
|
+
from fastapi_users.authentication import (
|
|
37
|
+
AuthenticationBackend,
|
|
38
|
+
BearerTransport,
|
|
39
|
+
JWTStrategy,
|
|
40
|
+
Strategy,
|
|
41
|
+
)
|
|
42
|
+
from fastapi_users.db import SQLAlchemyUserDatabase
|
|
43
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
44
|
+
|
|
45
|
+
from dap_engine.auth.api_tokens import looks_like_api_token, verify_api_token
|
|
46
|
+
from dap_engine.auth.audit import record_audit_event_async
|
|
47
|
+
from dap_engine.auth.db import get_async_session, get_user_db
|
|
48
|
+
from dap_engine.persistence.models import UserORM
|
|
49
|
+
|
|
50
|
+
# 15 minutes by default — short enough that revocation latency stays
|
|
51
|
+
# bounded even without a token blacklist (we don't ship one yet).
|
|
52
|
+
# Override via ``DAP_AUTH_ACCESS_TTL`` env var → ``EngineConfig``.
|
|
53
|
+
DEFAULT_ACCESS_TTL_SECONDS = 60 * 15
|
|
54
|
+
|
|
55
|
+
# Server-side password policy — must stay aligned with the dashboard's
|
|
56
|
+
# Zod rule (see ``apps/dashboard/src/app/(auth)/signup/page.tsx``).
|
|
57
|
+
MIN_PASSWORD_LENGTH = 8
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# In-process holder for the JWT secret. The engine lifespan writes here
|
|
61
|
+
# at startup; ``get_jwt_strategy`` reads it on every login. A module-level
|
|
62
|
+
# attribute (not app.state) mirrors fastapi-users' expectation that the
|
|
63
|
+
# strategy factory takes no arguments.
|
|
64
|
+
_JWT_SECRET: str | None = None
|
|
65
|
+
_ACCESS_TTL_SECONDS: int = DEFAULT_ACCESS_TTL_SECONDS
|
|
66
|
+
_LOG_RESET_TOKENS: bool = False
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def configure_jwt(
|
|
70
|
+
secret: str,
|
|
71
|
+
access_ttl_seconds: int = DEFAULT_ACCESS_TTL_SECONDS,
|
|
72
|
+
*,
|
|
73
|
+
log_reset_tokens: bool = False,
|
|
74
|
+
) -> None:
|
|
75
|
+
"""Set the JWT secret + lifetime — called once from the engine lifespan.
|
|
76
|
+
|
|
77
|
+
Empty secret raises immediately so misconfig fails on startup, not on
|
|
78
|
+
the first login attempt.
|
|
79
|
+
|
|
80
|
+
``log_reset_tokens`` is a developer convenience for self-hosted
|
|
81
|
+
setups without email delivery. **Off by default** because reset
|
|
82
|
+
tokens are credentials — leaking them into log aggregation would
|
|
83
|
+
hand attackers account-takeover material. See ``EngineConfig.
|
|
84
|
+
auth_log_reset_tokens`` for the public knob.
|
|
85
|
+
"""
|
|
86
|
+
if not secret:
|
|
87
|
+
raise ValueError("DAP_AUTH_JWT_SECRET must be a non-empty string")
|
|
88
|
+
global _JWT_SECRET, _ACCESS_TTL_SECONDS, _LOG_RESET_TOKENS # noqa: PLW0603 — module-level by design
|
|
89
|
+
_JWT_SECRET = secret
|
|
90
|
+
_ACCESS_TTL_SECONDS = access_ttl_seconds
|
|
91
|
+
_LOG_RESET_TOKENS = log_reset_tokens
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _resolve_jwt_secret_or_raise() -> str:
|
|
95
|
+
if _JWT_SECRET is None:
|
|
96
|
+
raise RuntimeError(
|
|
97
|
+
"JWT secret not configured — call dap_engine.auth.users.configure_jwt() "
|
|
98
|
+
"from the engine lifespan before serving auth routes"
|
|
99
|
+
)
|
|
100
|
+
return _JWT_SECRET
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class UserManager(UUIDIDMixin, BaseUserManager[UserORM, uuid.UUID]):
|
|
104
|
+
"""Hooks for register / login / password-reset events.
|
|
105
|
+
|
|
106
|
+
Reads the configured JWT secret on construction so password-reset
|
|
107
|
+
and verification flows (Phase E) sign their tokens with the same
|
|
108
|
+
key the JWT login uses. UserManager instances are short-lived
|
|
109
|
+
(one per request via the ``get_user_manager`` dependency), so this
|
|
110
|
+
pulls the current secret value cleanly without a class-level cache.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
def __init__(
|
|
114
|
+
self,
|
|
115
|
+
user_db: SQLAlchemyUserDatabase[UserORM, uuid.UUID],
|
|
116
|
+
) -> None:
|
|
117
|
+
super().__init__(user_db)
|
|
118
|
+
secret = _resolve_jwt_secret_or_raise()
|
|
119
|
+
self.reset_password_token_secret = secret
|
|
120
|
+
self.verification_token_secret = secret
|
|
121
|
+
|
|
122
|
+
async def validate_password(
|
|
123
|
+
self,
|
|
124
|
+
password: str,
|
|
125
|
+
user: fa_users_schemas.BaseUserCreate | UserORM,
|
|
126
|
+
) -> None:
|
|
127
|
+
"""Server-side password policy — runs on register, reset, and
|
|
128
|
+
admin-set paths. Matches the dashboard's Zod rule (min 8 chars)
|
|
129
|
+
so the policy is the same regardless of which client wrote
|
|
130
|
+
the field (#300, sub-B3).
|
|
131
|
+
|
|
132
|
+
Keeps the validator deliberately minimal: complexity rules
|
|
133
|
+
(mixed-case, digits) tend to push users toward predictable
|
|
134
|
+
substitutions; length is the cheap and effective gate.
|
|
135
|
+
"""
|
|
136
|
+
if len(password) < MIN_PASSWORD_LENGTH:
|
|
137
|
+
raise InvalidPasswordException(
|
|
138
|
+
reason=f"Password must be at least {MIN_PASSWORD_LENGTH} characters",
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
async def on_after_register(
|
|
142
|
+
self,
|
|
143
|
+
user: UserORM,
|
|
144
|
+
request: Request | None = None,
|
|
145
|
+
) -> None:
|
|
146
|
+
logging.getLogger("dap.engine.auth").info(
|
|
147
|
+
"user.registered",
|
|
148
|
+
extra={"user_id": str(user.id), "email": user.email},
|
|
149
|
+
)
|
|
150
|
+
await record_audit_event_async(
|
|
151
|
+
self.user_db.session, # type: ignore[attr-defined]
|
|
152
|
+
user_id=user.id,
|
|
153
|
+
event_type="user.registered",
|
|
154
|
+
event_data={"email": user.email},
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
async def on_after_login(
|
|
158
|
+
self,
|
|
159
|
+
user: UserORM,
|
|
160
|
+
request: Request | None = None,
|
|
161
|
+
response: Response | None = None,
|
|
162
|
+
) -> None:
|
|
163
|
+
logging.getLogger("dap.engine.auth").info(
|
|
164
|
+
"user.logged_in",
|
|
165
|
+
extra={"user_id": str(user.id)},
|
|
166
|
+
)
|
|
167
|
+
await record_audit_event_async(
|
|
168
|
+
self.user_db.session, # type: ignore[attr-defined]
|
|
169
|
+
user_id=user.id,
|
|
170
|
+
event_type="user.logged_in",
|
|
171
|
+
event_data={"email": user.email},
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
async def on_after_forgot_password(
|
|
175
|
+
self,
|
|
176
|
+
user: UserORM,
|
|
177
|
+
token: str,
|
|
178
|
+
request: Request | None = None,
|
|
179
|
+
) -> None:
|
|
180
|
+
"""Forgot-password hook (#300, sub-B3).
|
|
181
|
+
|
|
182
|
+
v0.3 doesn't have email delivery yet — Phase E ships that.
|
|
183
|
+
For self-hosted setups without email, an operator can opt in
|
|
184
|
+
to **token logging** via ``DAP_AUTH_LOG_RESET_TOKENS=1`` and
|
|
185
|
+
copy the token out of stdout. **Default is off** because
|
|
186
|
+
reset tokens are credentials; production log aggregation
|
|
187
|
+
would otherwise routinely contain account-takeover material.
|
|
188
|
+
The audit log always captures the *event* (no token) so
|
|
189
|
+
admins can observe reset attempts.
|
|
190
|
+
|
|
191
|
+
fastapi-users only invokes this hook when a user matches the
|
|
192
|
+
submitted email — unknown emails get a 202 from the endpoint
|
|
193
|
+
without firing the hook (anti-enumeration is enforced
|
|
194
|
+
upstream, not here).
|
|
195
|
+
"""
|
|
196
|
+
logger = logging.getLogger("dap.engine.auth")
|
|
197
|
+
if _LOG_RESET_TOKENS:
|
|
198
|
+
logger.warning(
|
|
199
|
+
"user.forgot_password (token issued, email delivery TODO): "
|
|
200
|
+
"user_id=%s reset_token=%s",
|
|
201
|
+
user.id,
|
|
202
|
+
token,
|
|
203
|
+
)
|
|
204
|
+
else:
|
|
205
|
+
logger.info(
|
|
206
|
+
"user.forgot_password (token issued, not logged — "
|
|
207
|
+
"set DAP_AUTH_LOG_RESET_TOKENS=1 for dev): user_id=%s",
|
|
208
|
+
user.id,
|
|
209
|
+
)
|
|
210
|
+
await record_audit_event_async(
|
|
211
|
+
self.user_db.session, # type: ignore[attr-defined]
|
|
212
|
+
user_id=user.id,
|
|
213
|
+
event_type="user.forgot_password",
|
|
214
|
+
event_data={"email": user.email},
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
async def on_after_reset_password(
|
|
218
|
+
self,
|
|
219
|
+
user: UserORM,
|
|
220
|
+
request: Request | None = None,
|
|
221
|
+
) -> None:
|
|
222
|
+
"""Audit successful password resets — no token in the event data
|
|
223
|
+
(token already burned by the time this fires)."""
|
|
224
|
+
logging.getLogger("dap.engine.auth").info(
|
|
225
|
+
"user.password_reset", extra={"user_id": str(user.id)}
|
|
226
|
+
)
|
|
227
|
+
await record_audit_event_async(
|
|
228
|
+
self.user_db.session, # type: ignore[attr-defined]
|
|
229
|
+
user_id=user.id,
|
|
230
|
+
event_type="user.password_reset",
|
|
231
|
+
event_data={"email": user.email},
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
async def delete(
|
|
235
|
+
self,
|
|
236
|
+
user: UserORM,
|
|
237
|
+
request: Request | None = None,
|
|
238
|
+
) -> None:
|
|
239
|
+
"""Soft-delete the user: stamp ``deleted_at`` + flip ``is_active``.
|
|
240
|
+
|
|
241
|
+
fastapi-users' default ``delete()`` calls ``user_db.delete(user)``
|
|
242
|
+
which is a hard ``DELETE FROM users``. We override so the row stays
|
|
243
|
+
in the table — that keeps any FK referencing this user (introduced
|
|
244
|
+
in a follow-up sub-PR for ``agents`` / ``pipelines`` / etc.) valid
|
|
245
|
+
without cascading data loss. ``is_active=False`` makes the
|
|
246
|
+
``current_user(active=True)`` dependency reject any future request
|
|
247
|
+
from this user, so soft-deleted accounts can no longer authenticate
|
|
248
|
+
even if they hold a valid JWT.
|
|
249
|
+
|
|
250
|
+
Hard delete (audit-driven, admin-initiated, GDPR right-to-erasure)
|
|
251
|
+
lands as a separate admin endpoint in Phase C/E.
|
|
252
|
+
"""
|
|
253
|
+
await self.on_before_delete(user, request)
|
|
254
|
+
await self.user_db.update(
|
|
255
|
+
user,
|
|
256
|
+
{"deleted_at": datetime.now(UTC), "is_active": False},
|
|
257
|
+
)
|
|
258
|
+
await record_audit_event_async(
|
|
259
|
+
self.user_db.session, # type: ignore[attr-defined]
|
|
260
|
+
user_id=user.id,
|
|
261
|
+
event_type="user.deleted",
|
|
262
|
+
event_data={"email": user.email, "soft": True},
|
|
263
|
+
)
|
|
264
|
+
await self.on_after_delete(user, request)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
# ---------------------------------------------------------------------------
|
|
268
|
+
# JWT strategy + auth backend
|
|
269
|
+
# ---------------------------------------------------------------------------
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def get_jwt_strategy() -> JWTStrategy[UserORM, uuid.UUID]:
|
|
273
|
+
return JWTStrategy(
|
|
274
|
+
secret=_resolve_jwt_secret_or_raise(),
|
|
275
|
+
lifetime_seconds=_ACCESS_TTL_SECONDS,
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
_bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
|
|
280
|
+
|
|
281
|
+
auth_backend = AuthenticationBackend(
|
|
282
|
+
name="jwt",
|
|
283
|
+
transport=_bearer_transport,
|
|
284
|
+
get_strategy=get_jwt_strategy,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
# ---------------------------------------------------------------------------
|
|
289
|
+
# API token strategy — long-lived tokens for CLI / scripts (sub-A3).
|
|
290
|
+
# ---------------------------------------------------------------------------
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
class ApiTokenStrategy(Strategy[UserORM, uuid.UUID]):
|
|
294
|
+
"""fastapi-users Strategy that resolves ``dap_*`` opaque tokens.
|
|
295
|
+
|
|
296
|
+
The strategy receives the bearer token from ``BearerTransport``; if
|
|
297
|
+
the value doesn't start with the API-token prefix it returns
|
|
298
|
+
``None`` (lets the JWT strategy try). Otherwise it does the DB
|
|
299
|
+
lookup defined in ``api_tokens.verify_api_token``.
|
|
300
|
+
|
|
301
|
+
``write_token`` raises — API tokens are created via the dedicated
|
|
302
|
+
``POST /auth/api-tokens`` endpoint, not via the standard login
|
|
303
|
+
flow. ``destroy_token`` is a no-op for the same reason: revocation
|
|
304
|
+
goes through ``DELETE /auth/api-tokens/{id}``.
|
|
305
|
+
"""
|
|
306
|
+
|
|
307
|
+
def __init__(self, session: AsyncSession) -> None:
|
|
308
|
+
self.session = session
|
|
309
|
+
|
|
310
|
+
async def read_token(
|
|
311
|
+
self,
|
|
312
|
+
token: str | None,
|
|
313
|
+
user_manager: BaseUserManager[UserORM, uuid.UUID],
|
|
314
|
+
) -> UserORM | None:
|
|
315
|
+
if not token or not looks_like_api_token(token):
|
|
316
|
+
return None
|
|
317
|
+
result = await verify_api_token(token, self.session)
|
|
318
|
+
if result is None:
|
|
319
|
+
return None
|
|
320
|
+
user, _ = result
|
|
321
|
+
return user
|
|
322
|
+
|
|
323
|
+
async def write_token(self, user: UserORM) -> str:
|
|
324
|
+
raise NotImplementedError(
|
|
325
|
+
"API tokens are minted via POST /auth/api-tokens, not the standard login flow"
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
async def destroy_token(self, token: str, user: UserORM) -> None:
|
|
329
|
+
# Revocation goes through DELETE /auth/api-tokens/{id}; this hook
|
|
330
|
+
# exists only because the AuthenticationBackend interface requires it.
|
|
331
|
+
return None
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def get_api_token_strategy(
|
|
335
|
+
session: AsyncSession = Depends(get_async_session),
|
|
336
|
+
) -> ApiTokenStrategy:
|
|
337
|
+
return ApiTokenStrategy(session)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
api_token_backend = AuthenticationBackend(
|
|
341
|
+
name="api-token",
|
|
342
|
+
# Same Authorization: Bearer header as JWT — strategy disambiguates
|
|
343
|
+
# by token shape ("dap_*" vs JWT). tokenUrl is OpenAPI metadata only.
|
|
344
|
+
transport=BearerTransport(tokenUrl="auth/api-tokens"),
|
|
345
|
+
get_strategy=get_api_token_strategy,
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
# ---------------------------------------------------------------------------
|
|
350
|
+
# UserManager dependency + FastAPIUsers instance
|
|
351
|
+
# ---------------------------------------------------------------------------
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
async def get_user_manager(
|
|
355
|
+
user_db: SQLAlchemyUserDatabase[UserORM, uuid.UUID] = Depends(get_user_db),
|
|
356
|
+
) -> AsyncGenerator[UserManager]:
|
|
357
|
+
yield UserManager(user_db)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
fastapi_users: FastAPIUsers[UserORM, uuid.UUID] = FastAPIUsers[UserORM, uuid.UUID](
|
|
361
|
+
get_user_manager,
|
|
362
|
+
[auth_backend, api_token_backend],
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
# Convenience dependency for protected routes — kept here so callers
|
|
367
|
+
# don't need to know about the underlying ``fastapi_users.current_user``
|
|
368
|
+
# factory. ``active=True`` rejects users where ``is_active=False`` —
|
|
369
|
+
# which includes soft-deleted users (``UserManager.delete`` flips the
|
|
370
|
+
# flag) and admin-suspended users (Phase C will add suspend/unsuspend
|
|
371
|
+
# endpoints that toggle the same column).
|
|
372
|
+
#
|
|
373
|
+
# Accepts both JWT bearer tokens (regular dashboard sessions) AND
|
|
374
|
+
# ``dap_*`` API tokens (CLI / scripts) — see the multi-backend
|
|
375
|
+
# ``FastAPIUsers`` instance above.
|
|
376
|
+
current_active_user = fastapi_users.current_user(active=True)
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
async def _jwt_only_backends(
|
|
380
|
+
request: Request,
|
|
381
|
+
) -> list[AuthenticationBackend[UserORM, uuid.UUID]]:
|
|
382
|
+
"""Restrict an endpoint to JWT auth — used by API-token CRUD itself.
|
|
383
|
+
|
|
384
|
+
Issuing or revoking an API token via *another* API token would let
|
|
385
|
+
a leaked CLI credential silently mint long-lived siblings (or
|
|
386
|
+
revoke the user's other tokens). Forcing JWT here means the
|
|
387
|
+
operator must have an active password / OAuth session — same trust
|
|
388
|
+
boundary as managing the user's profile.
|
|
389
|
+
|
|
390
|
+
The signature mirrors what fastapi-users' ``get_enabled_backends``
|
|
391
|
+
expects (async callable accepting ``Request``), even though we
|
|
392
|
+
don't dispatch on the request — the contract is what matters.
|
|
393
|
+
"""
|
|
394
|
+
return [auth_backend]
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
current_active_user_jwt_only = fastapi_users.current_user(
|
|
398
|
+
active=True,
|
|
399
|
+
get_enabled_backends=_jwt_only_backends,
|
|
400
|
+
)
|
dap_engine/contracts.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Cross-layer request contracts (#252).
|
|
2
|
+
|
|
3
|
+
Persistence and execution layers consume these models when accepting
|
|
4
|
+
mutations from the API; keeping them at the package level instead of
|
|
5
|
+
under ``api/`` prevents the layer-inversion smell of
|
|
6
|
+
``persistence -> api`` and ``execution -> api`` imports.
|
|
7
|
+
|
|
8
|
+
Strictly request-side: response shapes, exports, dry-run payloads,
|
|
9
|
+
pagination wrappers, and other API-only types live in
|
|
10
|
+
:mod:`dap_engine.api.schemas`.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Any, Literal
|
|
16
|
+
|
|
17
|
+
from dap_types.agent import coerce_legacy_field_list, validate_field_list
|
|
18
|
+
from dap_types.pipeline import PipelineDefaults, PipelineEdge, PipelineNode
|
|
19
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _validate_pipeline_bindings_dict(value: dict[str, str]) -> dict[str, str]:
|
|
23
|
+
"""Reject blank workflow kinds and blank pipeline ids in a binding dict.
|
|
24
|
+
|
|
25
|
+
Empty/whitespace strings on either side of the binding lead to
|
|
26
|
+
invalid project state that fails later when triggering a run —
|
|
27
|
+
fail fast at request time with a clear 422 instead.
|
|
28
|
+
"""
|
|
29
|
+
blank_kinds = sorted({k for k in value if not k.strip()})
|
|
30
|
+
if blank_kinds:
|
|
31
|
+
msg = (
|
|
32
|
+
"pipelines: workflow kind keys must be non-blank "
|
|
33
|
+
f"(got {len(blank_kinds)} blank entries)"
|
|
34
|
+
)
|
|
35
|
+
raise ValueError(msg)
|
|
36
|
+
blank_ids = sorted({k for k, v in value.items() if not v.strip()})
|
|
37
|
+
if blank_ids:
|
|
38
|
+
msg = (
|
|
39
|
+
"pipelines: pipeline ids must be non-blank — blank values "
|
|
40
|
+
f"for kind(s): {', '.join(blank_ids)}"
|
|
41
|
+
)
|
|
42
|
+
raise ValueError(msg)
|
|
43
|
+
return value
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class AgentCreate(BaseModel):
|
|
47
|
+
"""POST /agents body — server generates id, version=1, timestamps."""
|
|
48
|
+
|
|
49
|
+
model_config = ConfigDict(extra="forbid")
|
|
50
|
+
|
|
51
|
+
name: str = Field(min_length=1, max_length=200)
|
|
52
|
+
role: str = Field(min_length=1, max_length=100)
|
|
53
|
+
|
|
54
|
+
runtime_id: str
|
|
55
|
+
runtime_config: dict[str, Any] = Field(default_factory=dict)
|
|
56
|
+
prompt_template: str
|
|
57
|
+
|
|
58
|
+
input_schema: list[str] = Field(default_factory=list)
|
|
59
|
+
output_schema: list[str] = Field(default_factory=list)
|
|
60
|
+
constraints: list[str] = Field(default_factory=list)
|
|
61
|
+
|
|
62
|
+
budget_limit_usd: float | None = None
|
|
63
|
+
timeout_ms: int = Field(default=60_000, gt=0)
|
|
64
|
+
|
|
65
|
+
@field_validator("input_schema", "output_schema", mode="before")
|
|
66
|
+
@classmethod
|
|
67
|
+
def _coerce_legacy_dict_schema(cls, value: Any) -> Any:
|
|
68
|
+
return coerce_legacy_field_list(value)
|
|
69
|
+
|
|
70
|
+
@field_validator("input_schema", "output_schema")
|
|
71
|
+
@classmethod
|
|
72
|
+
def _check_known_fields(cls, value: list[str]) -> list[str]:
|
|
73
|
+
return validate_field_list(value)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class AgentUpdate(BaseModel):
|
|
77
|
+
"""PUT /agents/{id} body — creates a new immutable version."""
|
|
78
|
+
|
|
79
|
+
model_config = ConfigDict(extra="forbid")
|
|
80
|
+
|
|
81
|
+
name: str | None = Field(default=None, min_length=1, max_length=200)
|
|
82
|
+
|
|
83
|
+
runtime_id: str
|
|
84
|
+
runtime_config: dict[str, Any] = Field(default_factory=dict)
|
|
85
|
+
prompt_template: str
|
|
86
|
+
|
|
87
|
+
input_schema: list[str] = Field(default_factory=list)
|
|
88
|
+
output_schema: list[str] = Field(default_factory=list)
|
|
89
|
+
constraints: list[str] = Field(default_factory=list)
|
|
90
|
+
|
|
91
|
+
budget_limit_usd: float | None = None
|
|
92
|
+
timeout_ms: int = Field(default=60_000, gt=0)
|
|
93
|
+
|
|
94
|
+
@field_validator("input_schema", "output_schema", mode="before")
|
|
95
|
+
@classmethod
|
|
96
|
+
def _coerce_legacy_dict_schema(cls, value: Any) -> Any:
|
|
97
|
+
return coerce_legacy_field_list(value)
|
|
98
|
+
|
|
99
|
+
@field_validator("input_schema", "output_schema")
|
|
100
|
+
@classmethod
|
|
101
|
+
def _check_known_fields(cls, value: list[str]) -> list[str]:
|
|
102
|
+
return validate_field_list(value)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class PipelineCreate(BaseModel):
|
|
106
|
+
"""POST /pipelines body."""
|
|
107
|
+
|
|
108
|
+
model_config = ConfigDict(extra="forbid")
|
|
109
|
+
|
|
110
|
+
name: str = Field(min_length=1, max_length=200)
|
|
111
|
+
description: str = ""
|
|
112
|
+
|
|
113
|
+
schema_version: Literal["langgraph/1.0"] = "langgraph/1.0"
|
|
114
|
+
state_schema_ref: str = Field(min_length=1)
|
|
115
|
+
entry_point: str = Field(min_length=1)
|
|
116
|
+
|
|
117
|
+
nodes: list[PipelineNode]
|
|
118
|
+
edges: list[PipelineEdge]
|
|
119
|
+
defaults: PipelineDefaults = Field(default_factory=PipelineDefaults)
|
|
120
|
+
ui_metadata: dict[str, Any] | None = None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class PipelineUpdate(BaseModel):
|
|
124
|
+
"""PUT /pipelines/{id} body — creates a new version."""
|
|
125
|
+
|
|
126
|
+
model_config = ConfigDict(extra="forbid")
|
|
127
|
+
|
|
128
|
+
name: str | None = Field(default=None, min_length=1, max_length=200)
|
|
129
|
+
description: str | None = None
|
|
130
|
+
|
|
131
|
+
schema_version: Literal["langgraph/1.0"] = "langgraph/1.0"
|
|
132
|
+
state_schema_ref: str = Field(min_length=1)
|
|
133
|
+
entry_point: str = Field(min_length=1)
|
|
134
|
+
|
|
135
|
+
nodes: list[PipelineNode]
|
|
136
|
+
edges: list[PipelineEdge]
|
|
137
|
+
defaults: PipelineDefaults = Field(default_factory=PipelineDefaults)
|
|
138
|
+
ui_metadata: dict[str, Any] | None = None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class ProjectCreate(BaseModel):
|
|
142
|
+
"""POST /projects body — server generates id + timestamps.
|
|
143
|
+
|
|
144
|
+
``pipelines`` values must reference existing non-archived pipelines;
|
|
145
|
+
repository validates and raises ``ValueError`` (mapped to 422) if not.
|
|
146
|
+
"""
|
|
147
|
+
|
|
148
|
+
model_config = ConfigDict(extra="forbid")
|
|
149
|
+
|
|
150
|
+
name: str = Field(min_length=1, max_length=200)
|
|
151
|
+
description: str = ""
|
|
152
|
+
|
|
153
|
+
working_directory: str | None = None
|
|
154
|
+
repo_url: str | None = None
|
|
155
|
+
default_branch: str = Field(default="main", min_length=1, max_length=200)
|
|
156
|
+
|
|
157
|
+
pipelines: dict[str, str] = Field(default_factory=dict)
|
|
158
|
+
env_vars: dict[str, str] = Field(default_factory=dict)
|
|
159
|
+
|
|
160
|
+
@field_validator("pipelines")
|
|
161
|
+
@classmethod
|
|
162
|
+
def _check_pipeline_bindings(cls, value: dict[str, str]) -> dict[str, str]:
|
|
163
|
+
return _validate_pipeline_bindings_dict(value)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class ProjectUpdate(BaseModel):
|
|
167
|
+
"""PUT /projects/{id} body — full replacement (no versioning for projects).
|
|
168
|
+
|
|
169
|
+
Same shape as ``ProjectCreate`` minus the auto fields.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
model_config = ConfigDict(extra="forbid")
|
|
173
|
+
|
|
174
|
+
name: str = Field(min_length=1, max_length=200)
|
|
175
|
+
description: str = ""
|
|
176
|
+
|
|
177
|
+
working_directory: str | None = None
|
|
178
|
+
repo_url: str | None = None
|
|
179
|
+
default_branch: str = Field(default="main", min_length=1, max_length=200)
|
|
180
|
+
|
|
181
|
+
pipelines: dict[str, str] = Field(default_factory=dict)
|
|
182
|
+
env_vars: dict[str, str] = Field(default_factory=dict)
|
|
183
|
+
|
|
184
|
+
@field_validator("pipelines")
|
|
185
|
+
@classmethod
|
|
186
|
+
def _check_pipeline_bindings(cls, value: dict[str, str]) -> dict[str, str]:
|
|
187
|
+
return _validate_pipeline_bindings_dict(value)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class RunCreateRequest(BaseModel):
|
|
191
|
+
"""POST /runs body — trigger pipeline execution.
|
|
192
|
+
|
|
193
|
+
`initial_state` is a partial PipelineState dict; missing fields use defaults.
|
|
194
|
+
`pipeline_version` is optional — defaults to current_version when omitted.
|
|
195
|
+
`project_id` is optional (#64) — when set, the engine validates the
|
|
196
|
+
project exists and stamps it on ``Run.project_id``. ``None`` keeps
|
|
197
|
+
the run ad-hoc, matching pre-v0.6 behaviour.
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
model_config = ConfigDict(extra="forbid")
|
|
201
|
+
|
|
202
|
+
pipeline_id: str = Field(min_length=1)
|
|
203
|
+
pipeline_version: int | None = None
|
|
204
|
+
project_id: str | None = None
|
|
205
|
+
initial_state: dict[str, Any] = Field(default_factory=dict)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from dap_engine.execution.conditions import evaluate_condition
|
|
2
|
+
from dap_engine.execution.run_orchestrator import (
|
|
3
|
+
execute_rewind_background,
|
|
4
|
+
execute_run_background,
|
|
5
|
+
)
|
|
6
|
+
from dap_engine.execution.run_registry import RunRegistry
|
|
7
|
+
from dap_engine.execution.runner import (
|
|
8
|
+
REWIND_RETRY,
|
|
9
|
+
REWIND_SKIP,
|
|
10
|
+
CheckpointNotFoundError,
|
|
11
|
+
PipelineRunner,
|
|
12
|
+
RunnerError,
|
|
13
|
+
RunnerInterrupt,
|
|
14
|
+
)
|
|
15
|
+
from dap_engine.execution.validator import ValidationResult, validate_pipeline_dag
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"REWIND_RETRY",
|
|
19
|
+
"REWIND_SKIP",
|
|
20
|
+
"CheckpointNotFoundError",
|
|
21
|
+
"PipelineRunner",
|
|
22
|
+
"RunRegistry",
|
|
23
|
+
"RunnerError",
|
|
24
|
+
"RunnerInterrupt",
|
|
25
|
+
"ValidationResult",
|
|
26
|
+
"evaluate_condition",
|
|
27
|
+
"execute_rewind_background",
|
|
28
|
+
"execute_run_background",
|
|
29
|
+
"validate_pipeline_dag",
|
|
30
|
+
]
|