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.
Files changed (48) hide show
  1. dap_engine/__init__.py +3 -0
  2. dap_engine/__main__.py +80 -0
  3. dap_engine/api/__init__.py +0 -0
  4. dap_engine/api/agents.py +546 -0
  5. dap_engine/api/deps.py +60 -0
  6. dap_engine/api/health.py +20 -0
  7. dap_engine/api/pipelines.py +428 -0
  8. dap_engine/api/projects.py +191 -0
  9. dap_engine/api/runs.py +694 -0
  10. dap_engine/api/runtimes.py +29 -0
  11. dap_engine/api/schemas.py +331 -0
  12. dap_engine/api/settings.py +288 -0
  13. dap_engine/app.py +438 -0
  14. dap_engine/auth/__init__.py +23 -0
  15. dap_engine/auth/admin_users_routes.py +134 -0
  16. dap_engine/auth/api_token_routes.py +345 -0
  17. dap_engine/auth/api_tokens.py +147 -0
  18. dap_engine/auth/audit.py +91 -0
  19. dap_engine/auth/audit_routes.py +125 -0
  20. dap_engine/auth/db.py +135 -0
  21. dap_engine/auth/oauth.py +41 -0
  22. dap_engine/auth/policies.py +64 -0
  23. dap_engine/auth/schemas.py +37 -0
  24. dap_engine/auth/users.py +400 -0
  25. dap_engine/contracts.py +205 -0
  26. dap_engine/execution/__init__.py +30 -0
  27. dap_engine/execution/conditions.py +87 -0
  28. dap_engine/execution/node_executor.py +363 -0
  29. dap_engine/execution/output_parser.py +162 -0
  30. dap_engine/execution/run_orchestrator.py +213 -0
  31. dap_engine/execution/run_registry.py +158 -0
  32. dap_engine/execution/runner.py +422 -0
  33. dap_engine/execution/validator.py +580 -0
  34. dap_engine/persistence/__init__.py +0 -0
  35. dap_engine/persistence/_common.py +24 -0
  36. dap_engine/persistence/agents.py +410 -0
  37. dap_engine/persistence/db.py +179 -0
  38. dap_engine/persistence/migrations.py +739 -0
  39. dap_engine/persistence/models.py +569 -0
  40. dap_engine/persistence/pipelines.py +328 -0
  41. dap_engine/persistence/projects.py +256 -0
  42. dap_engine/persistence/repository.py +101 -0
  43. dap_engine/persistence/runs.py +482 -0
  44. dap_engine/py.typed +0 -0
  45. dap_engine-0.3.0.dist-info/METADATA +49 -0
  46. dap_engine-0.3.0.dist-info/RECORD +48 -0
  47. dap_engine-0.3.0.dist-info/WHEEL +4 -0
  48. dap_engine-0.3.0.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,125 @@
1
+ """Admin-only audit log read endpoint (#301, sub-C3).
2
+
3
+ Append-only events land in ``audit_log`` from the auth subsystem and
4
+ ownership-enforcing repo helpers. This module exposes them to the
5
+ admin panel via a paginated, filterable read endpoint.
6
+
7
+ Filters are deliberately minimal — ``event_type`` (exact) and
8
+ ``user_id`` (exact). They cover the two primary investigation flows
9
+ the audit log was designed for ("what did user X do?", "show me all
10
+ password-reset attempts"); richer filters (date range, JSONB
11
+ queries over ``event_data``) can land in a follow-up without
12
+ breaking the wire shape.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import uuid
18
+ from datetime import datetime
19
+ from typing import Any
20
+
21
+ from fastapi import APIRouter, Depends, HTTPException, Query, status
22
+ from pydantic import BaseModel
23
+ from sqlalchemy import ColumnElement, func, select
24
+ from sqlalchemy.ext.asyncio import AsyncSession
25
+
26
+ from dap_engine.auth.db import get_async_session
27
+ from dap_engine.auth.users import current_active_user
28
+ from dap_engine.persistence.models import AuditLogORM, UserORM
29
+
30
+ router = APIRouter(prefix="/audit", tags=["audit"])
31
+
32
+
33
+ class AuditEventRead(BaseModel):
34
+ """Public representation of an audit row.
35
+
36
+ ``user_id`` and ``event_data`` are both nullable on the column —
37
+ keep the same nullability here so admins can see legitimate
38
+ "no actor" events (migration backfills, pre-auth failures) without
39
+ the API contract lying.
40
+ """
41
+
42
+ id: uuid.UUID
43
+ user_id: uuid.UUID | None
44
+ event_type: str
45
+ event_data: dict[str, Any] | None
46
+ created_at: datetime
47
+
48
+ model_config = {"from_attributes": True}
49
+
50
+
51
+ class AuditEventList(BaseModel):
52
+ """Paginated list — matches the shape ``GET /users`` returns."""
53
+
54
+ items: list[AuditEventRead]
55
+ total: int
56
+ offset: int
57
+ limit: int
58
+
59
+
60
+ @router.get(
61
+ "/events",
62
+ response_model=AuditEventList,
63
+ summary="List audit events (admin-only, paginated)",
64
+ )
65
+ async def list_audit_events(
66
+ user: UserORM = Depends(current_active_user),
67
+ session: AsyncSession = Depends(get_async_session),
68
+ *,
69
+ event_type: str | None = Query(
70
+ default=None,
71
+ description="Filter to events of this exact type (e.g. ``user.logged_in``).",
72
+ ),
73
+ user_id: uuid.UUID | None = Query(
74
+ default=None,
75
+ description="Filter to events triggered by this user.",
76
+ ),
77
+ offset: int = Query(default=0, ge=0),
78
+ limit: int = Query(default=50, ge=1, le=500),
79
+ ) -> AuditEventList:
80
+ """Paginated audit log read.
81
+
82
+ Admin-only. Non-admins get ``404`` to match the anti-enumeration
83
+ rule the rest of the admin surface follows. Anonymous → ``401``
84
+ from ``current_active_user``.
85
+
86
+ Results are sorted ``created_at DESC`` so the freshest events
87
+ land at the top of the table.
88
+ """
89
+ if not user.is_superuser:
90
+ raise HTTPException(
91
+ status_code=status.HTTP_404_NOT_FOUND,
92
+ detail="Not Found",
93
+ )
94
+
95
+ where: list[ColumnElement[bool]] = []
96
+ if event_type is not None:
97
+ where.append(AuditLogORM.event_type == event_type)
98
+ if user_id is not None:
99
+ where.append(AuditLogORM.user_id == user_id)
100
+
101
+ total = (
102
+ await session.scalar(
103
+ select(func.count()).select_from(AuditLogORM).where(*where),
104
+ )
105
+ ) or 0
106
+ rows = (
107
+ (
108
+ await session.execute(
109
+ select(AuditLogORM)
110
+ .where(*where)
111
+ .order_by(AuditLogORM.created_at.desc())
112
+ .offset(offset)
113
+ .limit(limit),
114
+ )
115
+ )
116
+ .scalars()
117
+ .all()
118
+ )
119
+
120
+ return AuditEventList(
121
+ items=[AuditEventRead.model_validate(row) for row in rows],
122
+ total=total,
123
+ offset=offset,
124
+ limit=limit,
125
+ )
dap_engine/auth/db.py ADDED
@@ -0,0 +1,135 @@
1
+ """Async SQLAlchemy engine for fastapi-users.
2
+
3
+ The rest of the persistence layer uses a sync engine
4
+ (``persistence/db.py``); fastapi-users requires async. This module
5
+ maintains a parallel async engine pointing at the same underlying
6
+ database. Schema is created/migrated once via the sync engine on
7
+ startup; this engine only opens new connections through async drivers.
8
+
9
+ Driver selection mirrors the sync side:
10
+ - SQLite → ``sqlite+aiosqlite:///<path>`` (aiosqlite is already a
11
+ langgraph-checkpoint-sqlite transitive dep).
12
+ - PostgreSQL → ``postgresql+psycopg://...`` — psycopg v3 is a runtime
13
+ dep and supports both sync and async over the same URL prefix
14
+ (SQLAlchemy picks the mode based on ``create_async_engine`` vs
15
+ ``create_engine``).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import uuid
21
+ from collections.abc import AsyncGenerator
22
+ from pathlib import Path
23
+
24
+ from fastapi import Depends, Request
25
+ from fastapi_users.db import SQLAlchemyUserDatabase
26
+ from sqlalchemy.ext.asyncio import (
27
+ AsyncEngine,
28
+ AsyncSession,
29
+ async_sessionmaker,
30
+ create_async_engine,
31
+ )
32
+
33
+ from dap_engine.persistence.db import _normalize_pg_prefix, detect_dialect
34
+ from dap_engine.persistence.models import OAuthAccountORM, UserORM
35
+
36
+ __all__ = [
37
+ "AsyncSession",
38
+ "create_async_engine_for_url",
39
+ "get_async_session",
40
+ "get_user_db",
41
+ "make_async_session_factory",
42
+ ]
43
+
44
+
45
+ def _async_url_for(database_url: str | None, db_path: str | None) -> str:
46
+ """Build a SQLAlchemy async URL from the same inputs the sync engine uses.
47
+
48
+ Mirrors ``create_app()``'s sync-engine selection logic exactly: only
49
+ PostgreSQL URLs in ``database_url`` are honoured; SQLite URLs are
50
+ ignored in favour of ``db_path`` so both engines always point at the
51
+ same underlying SQLite file. Otherwise an operator setting
52
+ ``DAP_DATABASE_URL=sqlite:///foo.db`` would silently get a different
53
+ DB for auth than for the rest of the engine.
54
+
55
+ Raises ``ValueError`` if neither input yields a usable URL —
56
+ callers must validate config before reaching this helper.
57
+ """
58
+ if database_url and detect_dialect(database_url) == "postgresql":
59
+ url = _normalize_pg_prefix(database_url)
60
+ url = url.replace("postgresql+asyncpg://", "postgresql+psycopg://", 1)
61
+ if url.startswith("postgresql://"):
62
+ url = "postgresql+psycopg://" + url[len("postgresql://") :]
63
+ return url
64
+ # Sync engine treats anything that isn't a Postgres URL as "use db_path",
65
+ # so do the same here. ``database_url`` carrying a SQLite URL is
66
+ # effectively dead code on the sync side; honouring it asymmetrically
67
+ # would diverge the auth and main databases.
68
+ if db_path:
69
+ absolute = Path(db_path).resolve()
70
+ return f"sqlite+aiosqlite:///{absolute}"
71
+ raise ValueError("Either database_url (postgresql) or db_path must be provided")
72
+
73
+
74
+ def create_async_engine_for_url(
75
+ database_url: str | None,
76
+ db_path: str | None,
77
+ ) -> AsyncEngine:
78
+ """Create the async engine used by fastapi-users.
79
+
80
+ Pool sizes are smaller than the sync engine's — auth traffic is
81
+ sparse compared to the runs/state endpoints. ``pool_pre_ping`` is on
82
+ so a token-validation request after a long idle period doesn't fail
83
+ on a NAT-dropped TCP connection.
84
+ """
85
+ url = _async_url_for(database_url, db_path)
86
+ return create_async_engine(
87
+ url,
88
+ echo=False,
89
+ future=True,
90
+ pool_size=2,
91
+ max_overflow=4,
92
+ pool_pre_ping=True,
93
+ )
94
+
95
+
96
+ def make_async_session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
97
+ return async_sessionmaker(engine, expire_on_commit=False)
98
+
99
+
100
+ # ---------------------------------------------------------------------------
101
+ # FastAPI dependencies
102
+ # ---------------------------------------------------------------------------
103
+ #
104
+ # Reading the factory off ``app.state`` (rather than a module-level
105
+ # global) lets the engine lifespan own its lifecycle and lets tests swap
106
+ # the factory per-test via ``app.state.async_session_factory = ...``.
107
+
108
+
109
+ def _get_session_factory(request: Request) -> async_sessionmaker[AsyncSession]:
110
+ factory: async_sessionmaker[AsyncSession] | None = getattr(
111
+ request.app.state, "async_session_factory", None
112
+ )
113
+ if factory is None:
114
+ raise RuntimeError(
115
+ "auth.db.async_session_factory missing from app.state — "
116
+ "engine lifespan did not initialise auth (check DAP_AUTH_JWT_SECRET)"
117
+ )
118
+ return factory
119
+
120
+
121
+ async def get_async_session(
122
+ factory: async_sessionmaker[AsyncSession] = Depends(_get_session_factory),
123
+ ) -> AsyncGenerator[AsyncSession]:
124
+ async with factory() as session:
125
+ yield session
126
+
127
+
128
+ async def get_user_db(
129
+ session: AsyncSession = Depends(get_async_session),
130
+ ) -> AsyncGenerator[SQLAlchemyUserDatabase[UserORM, uuid.UUID]]:
131
+ # Pass OAuthAccountORM as the third argument so fastapi-users'
132
+ # OAuth router can look up / create linked identities. Without this
133
+ # the router silently 404s on every callback (no linked-account
134
+ # storage available).
135
+ yield SQLAlchemyUserDatabase(session, UserORM, OAuthAccountORM)
@@ -0,0 +1,41 @@
1
+ """OAuth2 client builders for GitHub + Google (#299, sub-A2).
2
+
3
+ Each provider is opt-in: when the corresponding env-var pair is unset
4
+ the engine simply doesn't mount the router for that provider. This is
5
+ intentional — a self-host install can run with email+password only,
6
+ and only set up OAuth credentials once they're ready to wire up the
7
+ GitHub/Google App configurations.
8
+
9
+ Scopes:
10
+ - GitHub: ``read:user`` + ``user:email`` — minimum required to fetch
11
+ the verified primary email. Without ``user:email`` the GitHub API
12
+ returns a username but no email and the OAuth router fails with
13
+ ``OAUTH_NOT_AVAILABLE_EMAIL``.
14
+ - Google: ``openid`` + ``email`` + ``profile`` — defaults baked into
15
+ ``GoogleOAuth2``; we use the upstream defaults rather than passing
16
+ scopes explicitly.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from httpx_oauth.clients.github import GitHubOAuth2
22
+ from httpx_oauth.clients.google import GoogleOAuth2
23
+
24
+ # GitHub requires `user:email` to read the verified primary email.
25
+ GITHUB_DEFAULT_SCOPES = ["read:user", "user:email"]
26
+
27
+
28
+ def make_github_client(client_id: str, client_secret: str) -> GitHubOAuth2:
29
+ """Construct a configured GitHub OAuth2 client."""
30
+ return GitHubOAuth2(client_id, client_secret, scopes=GITHUB_DEFAULT_SCOPES)
31
+
32
+
33
+ def make_google_client(client_id: str, client_secret: str) -> GoogleOAuth2:
34
+ """Construct a configured Google OAuth2 client.
35
+
36
+ Google's default scopes (openid + email + profile) are sufficient
37
+ to populate the user account; passing custom scopes here would
38
+ require also updating the consent-screen configuration in Google
39
+ Cloud Console.
40
+ """
41
+ return GoogleOAuth2(client_id, client_secret)
@@ -0,0 +1,64 @@
1
+ """Ownership / RBAC policies (#299, sub-A4b).
2
+
3
+ Generic helpers used by every resource route that needs to gate access
4
+ on "owner OR admin". Centralised here so the rule has one place to
5
+ evolve (e.g. adding team membership in the future) instead of each
6
+ router rolling its own check.
7
+
8
+ Convention: when a check fails, raise ``HTTPException(404)`` — not
9
+ ``403``. A 403 leaks the existence of an out-of-scope resource ("yes,
10
+ this id exists, but you can't see it"); a 404 is indistinguishable
11
+ from "no such id" so the endpoint can't be used to enumerate other
12
+ users' resources. The same anti-enumeration rule we already apply on
13
+ ``DELETE /auth/api-tokens/{id}`` (sub-A3).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import uuid
19
+
20
+ from fastapi import HTTPException, status
21
+
22
+ from dap_engine.persistence.models import UserORM
23
+
24
+ __all__ = [
25
+ "is_owner_or_admin",
26
+ "verify_owner_or_admin",
27
+ ]
28
+
29
+
30
+ def is_owner_or_admin(user: UserORM, resource_user_id: uuid.UUID | None) -> bool:
31
+ """Pure predicate — admins see everything, owners see their own.
32
+
33
+ A NULL ``resource_user_id`` (legacy pre-v0.3 row that backfill
34
+ didn't claim, or a row created before sub-A4b enforces NOT NULL
35
+ in the application layer) is visible to admins only. Non-admins
36
+ see those rows as "not yours" so they don't get exposed by
37
+ accident during the v0.3 transition.
38
+ """
39
+ if user.is_superuser:
40
+ return True
41
+ if resource_user_id is None:
42
+ return False
43
+ return resource_user_id == user.id
44
+
45
+
46
+ def verify_owner_or_admin(
47
+ user: UserORM,
48
+ resource_user_id: uuid.UUID | None,
49
+ *,
50
+ resource_kind: str = "resource",
51
+ ) -> None:
52
+ """Raise ``HTTPException(404)`` when the caller can't access the row.
53
+
54
+ Use immediately after the ``GET ... WHERE id = ?`` lookup that
55
+ returned the row. ``resource_kind`` is the noun used in the
56
+ detail message (``"agent"``, ``"pipeline"``, …) so the response
57
+ body matches what the user just tried to access.
58
+ """
59
+ if is_owner_or_admin(user, resource_user_id):
60
+ return
61
+ raise HTTPException(
62
+ status_code=status.HTTP_404_NOT_FOUND,
63
+ detail=f"{resource_kind} not found",
64
+ )
@@ -0,0 +1,37 @@
1
+ """Pydantic schemas exposed to fastapi-users.
2
+
3
+ The base classes (``schemas.BaseUser``, ``BaseUserCreate``,
4
+ ``BaseUserUpdate``) bring the auth-mandatory fields (id, email,
5
+ password, is_active, is_superuser, is_verified). ``UserRead`` mixes in
6
+ ``BaseOAuthAccountMixin`` so the OAuth callback response includes the
7
+ linked ``oauth_accounts`` list — fastapi-users serialises the
8
+ relationship into this field automatically when the User model has an
9
+ ``oauth_accounts`` Mapped attribute.
10
+
11
+ We don't add custom fields here — the ``created_at`` / ``last_login_at``
12
+ columns on the ORM aren't user-settable through the API, so they don't
13
+ appear in the schemas.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import uuid
19
+
20
+ from fastapi_users import schemas
21
+
22
+
23
+ class UserRead(schemas.BaseUser[uuid.UUID], schemas.BaseOAuthAccountMixin):
24
+ """Public user representation returned by ``GET /users/me`` etc.
25
+
26
+ The ``BaseOAuthAccountMixin`` mixin adds
27
+ ``oauth_accounts: list[BaseOAuthAccount]`` so OAuth callbacks
28
+ return linked-identity info alongside the standard user fields.
29
+ """
30
+
31
+
32
+ class UserCreate(schemas.BaseUserCreate):
33
+ """Payload for ``POST /auth/register``."""
34
+
35
+
36
+ class UserUpdate(schemas.BaseUserUpdate):
37
+ """Payload for ``PATCH /users/me`` (and admin user updates)."""