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
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
"""CRUD endpoints for API tokens (#299, sub-A3).
|
|
2
|
+
|
|
3
|
+
All routes require **JWT** auth (``current_active_user_jwt_only``) —
|
|
4
|
+
not API-token auth. Letting an API token mint or revoke other API
|
|
5
|
+
tokens would mean a single leaked CLI credential could silently
|
|
6
|
+
escalate (creating siblings without a TTL) or sabotage the user
|
|
7
|
+
(revoking their other tokens). Forcing JWT here means the operator
|
|
8
|
+
must have an active password / OAuth session, which gates the action
|
|
9
|
+
to a "real" login event.
|
|
10
|
+
|
|
11
|
+
The raw token value is returned exactly once — at creation. The DB
|
|
12
|
+
stores only its SHA-256 hash and the indexed ``token_prefix`` (see
|
|
13
|
+
``api_tokens.py`` and ``ApiTokenORM`` for the rationale).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import uuid
|
|
19
|
+
from datetime import UTC, datetime, timedelta
|
|
20
|
+
|
|
21
|
+
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
22
|
+
from pydantic import BaseModel, Field
|
|
23
|
+
from sqlalchemy import ColumnElement, select
|
|
24
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
25
|
+
|
|
26
|
+
from dap_engine.auth.api_tokens import generate_token
|
|
27
|
+
from dap_engine.auth.audit import record_audit_event_async
|
|
28
|
+
from dap_engine.auth.db import get_async_session
|
|
29
|
+
from dap_engine.auth.users import current_active_user_jwt_only
|
|
30
|
+
from dap_engine.persistence.models import ApiTokenORM, UserORM
|
|
31
|
+
|
|
32
|
+
router = APIRouter(prefix="/auth/api-tokens", tags=["auth"])
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ApiTokenCreateRequest(BaseModel):
|
|
36
|
+
"""Payload for ``POST /auth/api-tokens``."""
|
|
37
|
+
|
|
38
|
+
name: str = Field(min_length=1, max_length=255)
|
|
39
|
+
expires_in_days: int | None = Field(default=None, ge=1, le=3650)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ApiTokenRead(BaseModel):
|
|
43
|
+
"""Public representation in list responses — no raw token here."""
|
|
44
|
+
|
|
45
|
+
id: uuid.UUID
|
|
46
|
+
name: str
|
|
47
|
+
prefix: str
|
|
48
|
+
created_at: datetime
|
|
49
|
+
expires_at: datetime | None
|
|
50
|
+
last_used_at: datetime | None
|
|
51
|
+
revoked_at: datetime | None
|
|
52
|
+
|
|
53
|
+
model_config = {"from_attributes": True}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class ApiTokenCreateResponse(ApiTokenRead):
|
|
57
|
+
"""Returned only by the create endpoint — includes the raw value."""
|
|
58
|
+
|
|
59
|
+
token: str
|
|
60
|
+
"""Raw ``dap_<...>`` token. Shown ONCE, not retrievable later."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@router.post(
|
|
64
|
+
"",
|
|
65
|
+
response_model=ApiTokenCreateResponse,
|
|
66
|
+
status_code=status.HTTP_201_CREATED,
|
|
67
|
+
)
|
|
68
|
+
async def create_api_token(
|
|
69
|
+
payload: ApiTokenCreateRequest,
|
|
70
|
+
user: UserORM = Depends(current_active_user_jwt_only),
|
|
71
|
+
session: AsyncSession = Depends(get_async_session),
|
|
72
|
+
) -> ApiTokenCreateResponse:
|
|
73
|
+
"""Mint a new API token for the authenticated user.
|
|
74
|
+
|
|
75
|
+
The raw token is returned in the response body and never persisted;
|
|
76
|
+
callers must capture it on receipt or generate a new one.
|
|
77
|
+
"""
|
|
78
|
+
generated = generate_token()
|
|
79
|
+
expires_at: datetime | None = None
|
|
80
|
+
if payload.expires_in_days is not None:
|
|
81
|
+
expires_at = datetime.now(UTC) + timedelta(days=payload.expires_in_days)
|
|
82
|
+
|
|
83
|
+
row = ApiTokenORM(
|
|
84
|
+
user_id=user.id,
|
|
85
|
+
name=payload.name,
|
|
86
|
+
token_prefix=generated.prefix,
|
|
87
|
+
token_hash=generated.sha256_hash,
|
|
88
|
+
expires_at=expires_at,
|
|
89
|
+
)
|
|
90
|
+
session.add(row)
|
|
91
|
+
await session.flush() # populate row.id before audit refers to it
|
|
92
|
+
await record_audit_event_async(
|
|
93
|
+
session,
|
|
94
|
+
user_id=user.id,
|
|
95
|
+
event_type="api_token.created",
|
|
96
|
+
event_data={
|
|
97
|
+
"token_id": str(row.id),
|
|
98
|
+
"name": row.name,
|
|
99
|
+
"expires_at": row.expires_at.isoformat() if row.expires_at else None,
|
|
100
|
+
},
|
|
101
|
+
)
|
|
102
|
+
await session.commit()
|
|
103
|
+
await session.refresh(row)
|
|
104
|
+
|
|
105
|
+
return ApiTokenCreateResponse(
|
|
106
|
+
id=row.id,
|
|
107
|
+
name=row.name,
|
|
108
|
+
prefix=row.token_prefix,
|
|
109
|
+
created_at=row.created_at,
|
|
110
|
+
expires_at=row.expires_at,
|
|
111
|
+
last_used_at=row.last_used_at,
|
|
112
|
+
revoked_at=row.revoked_at,
|
|
113
|
+
token=generated.raw,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@router.get("", response_model=list[ApiTokenRead])
|
|
118
|
+
async def list_api_tokens(
|
|
119
|
+
user: UserORM = Depends(current_active_user_jwt_only),
|
|
120
|
+
session: AsyncSession = Depends(get_async_session),
|
|
121
|
+
) -> list[ApiTokenRead]:
|
|
122
|
+
"""List the caller's tokens.
|
|
123
|
+
|
|
124
|
+
Returns metadata only — never the raw value (which exists only in
|
|
125
|
+
the create response and the user's clipboard).
|
|
126
|
+
"""
|
|
127
|
+
stmt = (
|
|
128
|
+
select(ApiTokenORM)
|
|
129
|
+
.where(ApiTokenORM.user_id == user.id)
|
|
130
|
+
.order_by(ApiTokenORM.created_at.desc())
|
|
131
|
+
)
|
|
132
|
+
rows = (await session.execute(stmt)).scalars().all()
|
|
133
|
+
return [
|
|
134
|
+
ApiTokenRead(
|
|
135
|
+
id=r.id,
|
|
136
|
+
name=r.name,
|
|
137
|
+
prefix=r.token_prefix,
|
|
138
|
+
created_at=r.created_at,
|
|
139
|
+
expires_at=r.expires_at,
|
|
140
|
+
last_used_at=r.last_used_at,
|
|
141
|
+
revoked_at=r.revoked_at,
|
|
142
|
+
)
|
|
143
|
+
for r in rows
|
|
144
|
+
]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@router.delete("/{token_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
148
|
+
async def revoke_api_token(
|
|
149
|
+
token_id: uuid.UUID,
|
|
150
|
+
user: UserORM = Depends(current_active_user_jwt_only),
|
|
151
|
+
session: AsyncSession = Depends(get_async_session),
|
|
152
|
+
) -> None:
|
|
153
|
+
"""Soft-revoke a token (sets ``revoked_at`` to now).
|
|
154
|
+
|
|
155
|
+
Returns 404 when the token doesn't exist OR belongs to another
|
|
156
|
+
user — the two responses are deliberately indistinguishable so the
|
|
157
|
+
endpoint can't be used to enumerate other users' token IDs.
|
|
158
|
+
"""
|
|
159
|
+
stmt = select(ApiTokenORM).where(
|
|
160
|
+
ApiTokenORM.id == token_id,
|
|
161
|
+
ApiTokenORM.user_id == user.id,
|
|
162
|
+
)
|
|
163
|
+
row = (await session.execute(stmt)).scalars().one_or_none()
|
|
164
|
+
if row is None:
|
|
165
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Token not found")
|
|
166
|
+
if row.revoked_at is None:
|
|
167
|
+
row.revoked_at = datetime.now(UTC)
|
|
168
|
+
await record_audit_event_async(
|
|
169
|
+
session,
|
|
170
|
+
user_id=user.id,
|
|
171
|
+
event_type="api_token.revoked",
|
|
172
|
+
event_data={"token_id": str(row.id), "name": row.name},
|
|
173
|
+
)
|
|
174
|
+
# record_audit_event_async commits — second commit is a no-op
|
|
175
|
+
# but harmless; left in for defensive symmetry with the
|
|
176
|
+
# pre-audit shape.
|
|
177
|
+
await session.commit()
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# ---------------------------------------------------------------------------
|
|
181
|
+
# Admin-wide views (#301, sub-C4)
|
|
182
|
+
# ---------------------------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class AdminApiTokenRead(ApiTokenRead):
|
|
186
|
+
"""Admin list row — same shape as ``ApiTokenRead`` plus owner info.
|
|
187
|
+
|
|
188
|
+
Wider than the user-scoped view so the admin can identify whose
|
|
189
|
+
token is whose without a second round-trip. ``owner_email`` lives
|
|
190
|
+
on the wire as a plain string (admin already has the right to
|
|
191
|
+
enumerate users via ``/users``, so no new info disclosure).
|
|
192
|
+
"""
|
|
193
|
+
|
|
194
|
+
owner_id: uuid.UUID
|
|
195
|
+
owner_email: str
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class AdminApiTokenList(BaseModel):
|
|
199
|
+
"""Paginated list — same shape as the rest of the admin surface."""
|
|
200
|
+
|
|
201
|
+
items: list[AdminApiTokenRead]
|
|
202
|
+
total: int
|
|
203
|
+
offset: int
|
|
204
|
+
limit: int
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@router.get(
|
|
208
|
+
"/admin",
|
|
209
|
+
response_model=AdminApiTokenList,
|
|
210
|
+
summary="List every user's API tokens (admin-only)",
|
|
211
|
+
)
|
|
212
|
+
async def list_all_api_tokens(
|
|
213
|
+
user: UserORM = Depends(current_active_user_jwt_only),
|
|
214
|
+
session: AsyncSession = Depends(get_async_session),
|
|
215
|
+
*,
|
|
216
|
+
include_revoked: bool = Query(
|
|
217
|
+
default=True,
|
|
218
|
+
description=(
|
|
219
|
+
"Include tokens that are no longer usable — either "
|
|
220
|
+
"explicitly revoked (``revoked_at`` set) or past their "
|
|
221
|
+
"``expires_at``. Default true so the admin can see the "
|
|
222
|
+
"full lifecycle; flip to false for the currently-valid "
|
|
223
|
+
"view."
|
|
224
|
+
),
|
|
225
|
+
),
|
|
226
|
+
offset: int = Query(default=0, ge=0),
|
|
227
|
+
limit: int = Query(default=50, ge=1, le=500),
|
|
228
|
+
) -> AdminApiTokenList:
|
|
229
|
+
"""Paginated list of every user's tokens.
|
|
230
|
+
|
|
231
|
+
Admin-only — JWT-protected (same as the user-scoped routes here
|
|
232
|
+
so an API token can't enumerate other API tokens). Non-admin gets
|
|
233
|
+
``404`` (anti-enumeration, mirrors the rest of the admin surface).
|
|
234
|
+
Anonymous gets ``401`` from the JWT-only dependency.
|
|
235
|
+
"""
|
|
236
|
+
if not user.is_superuser:
|
|
237
|
+
raise HTTPException(
|
|
238
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
239
|
+
detail="Not Found",
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
where: list[ColumnElement[bool]] = []
|
|
243
|
+
if not include_revoked:
|
|
244
|
+
# "Currently valid" = not revoked AND not expired. Without the
|
|
245
|
+
# expires_at clause the filter only hides explicitly-revoked
|
|
246
|
+
# rows, leaving expired ones in — which contradicts the
|
|
247
|
+
# docstring's promise (Copilot review on PR #330).
|
|
248
|
+
now = datetime.now(UTC)
|
|
249
|
+
where.append(ApiTokenORM.revoked_at.is_(None))
|
|
250
|
+
where.append(
|
|
251
|
+
(ApiTokenORM.expires_at.is_(None)) | (ApiTokenORM.expires_at > now),
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
from sqlalchemy import func as sql_func # noqa: PLC0415 — narrow scope
|
|
255
|
+
|
|
256
|
+
total = (
|
|
257
|
+
await session.scalar(
|
|
258
|
+
select(sql_func.count()).select_from(ApiTokenORM).where(*where),
|
|
259
|
+
)
|
|
260
|
+
) or 0
|
|
261
|
+
|
|
262
|
+
# JOIN on owner so we can ship the email in the same response —
|
|
263
|
+
# avoids the dashboard needing a second round-trip per row.
|
|
264
|
+
# ``select(ApiTokenORM, UserORM.email)`` returns ``tuple[ApiTokenORM, str]``
|
|
265
|
+
# rows; SQLAlchemy's generic ``select`` overloads support the
|
|
266
|
+
# mixed-entity shape but mypy needs the explicit annotation below.
|
|
267
|
+
rows = (
|
|
268
|
+
await session.execute(
|
|
269
|
+
select(ApiTokenORM, UserORM.email) # type: ignore[call-overload]
|
|
270
|
+
.join(UserORM, UserORM.id == ApiTokenORM.user_id)
|
|
271
|
+
.where(*where)
|
|
272
|
+
.order_by(ApiTokenORM.created_at.desc())
|
|
273
|
+
.offset(offset)
|
|
274
|
+
.limit(limit),
|
|
275
|
+
)
|
|
276
|
+
).all()
|
|
277
|
+
|
|
278
|
+
return AdminApiTokenList(
|
|
279
|
+
items=[
|
|
280
|
+
AdminApiTokenRead(
|
|
281
|
+
id=token.id,
|
|
282
|
+
name=token.name,
|
|
283
|
+
prefix=token.token_prefix,
|
|
284
|
+
created_at=token.created_at,
|
|
285
|
+
expires_at=token.expires_at,
|
|
286
|
+
last_used_at=token.last_used_at,
|
|
287
|
+
revoked_at=token.revoked_at,
|
|
288
|
+
owner_id=token.user_id,
|
|
289
|
+
owner_email=email,
|
|
290
|
+
)
|
|
291
|
+
for token, email in rows
|
|
292
|
+
],
|
|
293
|
+
total=total,
|
|
294
|
+
offset=offset,
|
|
295
|
+
limit=limit,
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
@router.delete(
|
|
300
|
+
"/admin/{token_id}",
|
|
301
|
+
status_code=status.HTTP_204_NO_CONTENT,
|
|
302
|
+
summary="Revoke any user's API token (admin-only)",
|
|
303
|
+
)
|
|
304
|
+
async def admin_revoke_api_token(
|
|
305
|
+
token_id: uuid.UUID,
|
|
306
|
+
user: UserORM = Depends(current_active_user_jwt_only),
|
|
307
|
+
session: AsyncSession = Depends(get_async_session),
|
|
308
|
+
) -> None:
|
|
309
|
+
"""Soft-revoke any token, regardless of owner.
|
|
310
|
+
|
|
311
|
+
Audit row carries both the *acting* admin's ``user_id`` and the
|
|
312
|
+
*target* token's owner in ``event_data.target_user_id`` so the
|
|
313
|
+
log clearly distinguishes self-revocations from admin
|
|
314
|
+
interventions.
|
|
315
|
+
|
|
316
|
+
Non-admin → ``404`` (anti-enumeration). Anonymous → ``401``.
|
|
317
|
+
"""
|
|
318
|
+
if not user.is_superuser:
|
|
319
|
+
raise HTTPException(
|
|
320
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
|
321
|
+
detail="Not Found",
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
stmt = select(ApiTokenORM).where(ApiTokenORM.id == token_id)
|
|
325
|
+
row = (await session.execute(stmt)).scalars().one_or_none()
|
|
326
|
+
if row is None:
|
|
327
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Token not found")
|
|
328
|
+
|
|
329
|
+
if row.revoked_at is None:
|
|
330
|
+
row.revoked_at = datetime.now(UTC)
|
|
331
|
+
await record_audit_event_async(
|
|
332
|
+
session,
|
|
333
|
+
# Admin is the acting user — ``user_id`` on the audit row.
|
|
334
|
+
user_id=user.id,
|
|
335
|
+
event_type="api_token.revoked",
|
|
336
|
+
event_data={
|
|
337
|
+
"token_id": str(row.id),
|
|
338
|
+
"name": row.name,
|
|
339
|
+
# Separate field so log filters can group by who *owned*
|
|
340
|
+
# the token vs. who *triggered* the revocation.
|
|
341
|
+
"target_user_id": str(row.user_id),
|
|
342
|
+
"by_admin": True,
|
|
343
|
+
},
|
|
344
|
+
)
|
|
345
|
+
await session.commit()
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""API tokens for CLI / scripts (#299, sub-A3).
|
|
2
|
+
|
|
3
|
+
Tokens are opaque strings of the form ``dap_<43-char-base64>``:
|
|
4
|
+
- ``dap_`` prefix lets log filters / git-secret-scanners match the
|
|
5
|
+
format unambiguously
|
|
6
|
+
- 32 bytes of OS randomness encoded as URL-safe base64 → 43 chars
|
|
7
|
+
after the prefix (entropy 256 bits)
|
|
8
|
+
- The first 8 chars after the prefix become the indexed ``token_prefix``
|
|
9
|
+
for fast DB lookup; the full token is hashed with SHA-256 (storing
|
|
10
|
+
raw would defeat the point, but bcrypt-style KDFs are unnecessary
|
|
11
|
+
here — see ``ApiTokenORM`` docstring for the calculus)
|
|
12
|
+
|
|
13
|
+
Verification:
|
|
14
|
+
- Authorization header ``Authorization: Bearer dap_*`` is the trigger
|
|
15
|
+
- DB lookup by prefix narrows the candidate set (almost always 1)
|
|
16
|
+
- ``hmac.compare_digest`` on the SHA-256 hash defeats timing attacks
|
|
17
|
+
- ``revoked_at`` non-NULL or ``expires_at`` past now → reject
|
|
18
|
+
- ``last_used_at`` is touched best-effort (separate UPDATE, no rollback
|
|
19
|
+
on conflict — slightly stale ``last_used_at`` is acceptable, race
|
|
20
|
+
conditions on the hot path are not worth a serialized transaction)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import hashlib
|
|
26
|
+
import hmac
|
|
27
|
+
import logging
|
|
28
|
+
import secrets
|
|
29
|
+
import uuid
|
|
30
|
+
from datetime import UTC, datetime
|
|
31
|
+
from typing import NamedTuple
|
|
32
|
+
|
|
33
|
+
from sqlalchemy import select
|
|
34
|
+
from sqlalchemy.exc import SQLAlchemyError
|
|
35
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
36
|
+
|
|
37
|
+
from dap_engine.persistence.models import ApiTokenORM, UserORM
|
|
38
|
+
|
|
39
|
+
logger = logging.getLogger("dap.engine.auth.api_tokens")
|
|
40
|
+
|
|
41
|
+
TOKEN_PREFIX = "dap_"
|
|
42
|
+
TOKEN_RANDOM_BYTES = 32 # → 43 base64-url chars
|
|
43
|
+
TOKEN_INDEX_PREFIX_LEN = 8
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class GeneratedToken(NamedTuple):
|
|
47
|
+
"""Returned by ``generate_token`` — caller stores prefix+hash, shows raw once."""
|
|
48
|
+
|
|
49
|
+
raw: str
|
|
50
|
+
"""Full ``dap_<...>`` token. Show to the user once at create time."""
|
|
51
|
+
|
|
52
|
+
prefix: str
|
|
53
|
+
"""First ``TOKEN_INDEX_PREFIX_LEN`` chars after ``dap_`` — DB indexed."""
|
|
54
|
+
|
|
55
|
+
sha256_hash: str
|
|
56
|
+
"""Hex-encoded SHA-256 of ``raw``. DB stores this, not the raw value."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def generate_token() -> GeneratedToken:
|
|
60
|
+
"""Generate a new opaque API token.
|
|
61
|
+
|
|
62
|
+
Returns the raw form, the prefix used for indexed DB lookup, and
|
|
63
|
+
the SHA-256 hash that the DB row should hold. The caller is
|
|
64
|
+
expected to pair (prefix, hash) into an ``ApiTokenORM`` row, then
|
|
65
|
+
return ``raw`` to the user — the token is irrecoverable afterwards.
|
|
66
|
+
"""
|
|
67
|
+
random_part = secrets.token_urlsafe(TOKEN_RANDOM_BYTES)
|
|
68
|
+
raw = f"{TOKEN_PREFIX}{random_part}"
|
|
69
|
+
prefix = random_part[:TOKEN_INDEX_PREFIX_LEN]
|
|
70
|
+
sha256_hash = hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
|
71
|
+
return GeneratedToken(raw=raw, prefix=prefix, sha256_hash=sha256_hash)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def looks_like_api_token(value: str) -> bool:
|
|
75
|
+
"""True iff ``value`` has the API-token shape — used to route auth."""
|
|
76
|
+
return value.startswith(TOKEN_PREFIX)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
async def verify_api_token( # noqa: PLR0911 — early-return matrix per failure mode keeps logic readable
|
|
80
|
+
raw_token: str,
|
|
81
|
+
session: AsyncSession,
|
|
82
|
+
) -> tuple[UserORM, ApiTokenORM] | None:
|
|
83
|
+
"""Look up + verify an API token. Returns ``(user, token)`` or ``None``.
|
|
84
|
+
|
|
85
|
+
Touches ``last_used_at`` on success (best-effort; not transactional
|
|
86
|
+
with the hit so a concurrent revoke / verify race won't roll back
|
|
87
|
+
the actual auth result).
|
|
88
|
+
"""
|
|
89
|
+
if not raw_token.startswith(TOKEN_PREFIX):
|
|
90
|
+
return None
|
|
91
|
+
random_part = raw_token[len(TOKEN_PREFIX) :]
|
|
92
|
+
if len(random_part) < TOKEN_INDEX_PREFIX_LEN:
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
prefix = random_part[:TOKEN_INDEX_PREFIX_LEN]
|
|
96
|
+
candidate_hash = hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
|
|
97
|
+
|
|
98
|
+
# Lookup by indexed prefix; almost always 1 row, but iterate to
|
|
99
|
+
# tolerate the (astronomically unlikely) collision case.
|
|
100
|
+
stmt = select(ApiTokenORM).where(ApiTokenORM.token_prefix == prefix)
|
|
101
|
+
rows = (await session.execute(stmt)).scalars().all()
|
|
102
|
+
now = datetime.now(UTC)
|
|
103
|
+
|
|
104
|
+
for token in rows:
|
|
105
|
+
if not hmac.compare_digest(token.token_hash, candidate_hash):
|
|
106
|
+
continue
|
|
107
|
+
if token.revoked_at is not None:
|
|
108
|
+
return None
|
|
109
|
+
# SQLite strips tzinfo on roundtrip even with `DateTime(timezone=True)`,
|
|
110
|
+
# so an expires_at read back is naive. Treat naive timestamps as UTC
|
|
111
|
+
# — the writer always uses datetime.now(UTC) so this is safe.
|
|
112
|
+
expires_at = token.expires_at
|
|
113
|
+
if expires_at is not None:
|
|
114
|
+
if expires_at.tzinfo is None:
|
|
115
|
+
expires_at = expires_at.replace(tzinfo=UTC)
|
|
116
|
+
if expires_at <= now:
|
|
117
|
+
return None
|
|
118
|
+
# Found a live match — fetch the user.
|
|
119
|
+
user_stmt = select(UserORM).where(UserORM.id == token.user_id) # type: ignore[arg-type]
|
|
120
|
+
user = (await session.execute(user_stmt)).scalars().unique().one_or_none()
|
|
121
|
+
if user is None or not user.is_active:
|
|
122
|
+
return None
|
|
123
|
+
|
|
124
|
+
# Touch last_used_at — best-effort. Wrap in try/except so a
|
|
125
|
+
# transient write failure (SQLite busy, lost FK to a
|
|
126
|
+
# just-deleted user, etc.) doesn't promote a successful auth
|
|
127
|
+
# to a 500. The token already passed all integrity checks
|
|
128
|
+
# above; the only thing left is the audit-style timestamp,
|
|
129
|
+
# which we'd rather lose than fail the request over.
|
|
130
|
+
token.last_used_at = now
|
|
131
|
+
try:
|
|
132
|
+
await session.commit()
|
|
133
|
+
except SQLAlchemyError:
|
|
134
|
+
await session.rollback()
|
|
135
|
+
logger.warning(
|
|
136
|
+
"auth.api_token.last_used_touch_failed",
|
|
137
|
+
extra={"token_id": str(token.id), "user_id": str(user.id)},
|
|
138
|
+
exc_info=True,
|
|
139
|
+
)
|
|
140
|
+
return user, token
|
|
141
|
+
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def generate_token_uuid() -> uuid.UUID:
|
|
146
|
+
"""Convenience for callers that need a row id alongside the raw token."""
|
|
147
|
+
return uuid.uuid4()
|
dap_engine/auth/audit.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Audit log helpers (#299, sub-A4b).
|
|
2
|
+
|
|
3
|
+
Two flavours of the same helper — sync for resource routes (which use
|
|
4
|
+
``Session`` from ``persistence/db.py``) and async for fastapi-users
|
|
5
|
+
hooks (UserManager.on_after_login etc., where the session lives in the
|
|
6
|
+
auth subsystem). Both append a row to ``audit_log`` without committing
|
|
7
|
+
— the caller's transaction boundary owns the commit so the audit row
|
|
8
|
+
either lands together with the action it describes or rolls back with
|
|
9
|
+
it.
|
|
10
|
+
|
|
11
|
+
Event-type vocabulary (stable string keys):
|
|
12
|
+
- ``user.registered``
|
|
13
|
+
- ``user.logged_in``
|
|
14
|
+
- ``user.password_reset_requested`` / ``user.password_reset``
|
|
15
|
+
- ``user.deleted`` — soft delete via UserManager
|
|
16
|
+
- ``api_token.created``
|
|
17
|
+
- ``api_token.revoked``
|
|
18
|
+
- ``agent.created`` / ``agent.updated`` / ``agent.archived``
|
|
19
|
+
- ``pipeline.created`` / ``pipeline.updated`` / ``pipeline.archived``
|
|
20
|
+
- ``project.created`` / ``project.updated`` / ``project.archived``
|
|
21
|
+
- ``run.created`` — start trigger only; lifecycle
|
|
22
|
+
transitions are noisy and stay
|
|
23
|
+
in node_execution_logs
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import uuid
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
32
|
+
from sqlalchemy.orm import Session
|
|
33
|
+
|
|
34
|
+
from dap_engine.persistence.models import AuditLogORM
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"record_audit_event",
|
|
38
|
+
"record_audit_event_async",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def record_audit_event(
|
|
43
|
+
session: Session,
|
|
44
|
+
*,
|
|
45
|
+
user_id: uuid.UUID | None,
|
|
46
|
+
event_type: str,
|
|
47
|
+
event_data: dict[str, Any] | None = None,
|
|
48
|
+
) -> None:
|
|
49
|
+
"""Append an audit row using the sync session.
|
|
50
|
+
|
|
51
|
+
The row is added to the session but not committed — the caller's
|
|
52
|
+
request-scoped transaction (``api/deps.get_session``) commits on
|
|
53
|
+
success / rolls back on error. That ties the audit entry to the
|
|
54
|
+
action it describes: an agent-create that crashes after writing
|
|
55
|
+
its own row will roll back the audit row too, keeping the trail
|
|
56
|
+
consistent with the actual data state.
|
|
57
|
+
"""
|
|
58
|
+
session.add(
|
|
59
|
+
AuditLogORM(
|
|
60
|
+
user_id=user_id,
|
|
61
|
+
event_type=event_type,
|
|
62
|
+
event_data=event_data,
|
|
63
|
+
)
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
async def record_audit_event_async(
|
|
68
|
+
session: AsyncSession,
|
|
69
|
+
*,
|
|
70
|
+
user_id: uuid.UUID | None,
|
|
71
|
+
event_type: str,
|
|
72
|
+
event_data: dict[str, Any] | None = None,
|
|
73
|
+
) -> None:
|
|
74
|
+
"""Async counterpart for fastapi-users hooks (and any other async caller).
|
|
75
|
+
|
|
76
|
+
Commits eagerly. fastapi-users invokes its ``on_after_*`` hooks
|
|
77
|
+
*after* the action's transaction has already committed, so the
|
|
78
|
+
session passed in is no longer holding an open tx — adding to it
|
|
79
|
+
without a commit would leave the audit row orphaned in the unit
|
|
80
|
+
of work and lost on session close. The eager commit here is
|
|
81
|
+
self-contained: only the audit row is in flight, so it's
|
|
82
|
+
semantically equivalent to a separate audit-log session.
|
|
83
|
+
"""
|
|
84
|
+
session.add(
|
|
85
|
+
AuditLogORM(
|
|
86
|
+
user_id=user_id,
|
|
87
|
+
event_type=event_type,
|
|
88
|
+
event_data=event_data,
|
|
89
|
+
)
|
|
90
|
+
)
|
|
91
|
+
await session.commit()
|