naos-api 0.1.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.
naos_api/merges.py ADDED
@@ -0,0 +1,200 @@
1
+ from bisect import bisect_left
2
+ from collections.abc import Mapping, Sequence
3
+ from typing import Any
4
+
5
+ from sqlmodel import Session, col, update
6
+
7
+ from naos_api import audit, runners, runs
8
+ from naos_api.errors import InvalidTransitionError, MergeError, NotFoundError
9
+ from naos_api.lifecycle import RunStatus
10
+ from naos_api.models import Merge, Run
11
+ from naos_api.spec import RunSpec
12
+
13
+ S = RunStatus
14
+ REJECTED = "rejected"
15
+
16
+
17
+ def _live(entries: Sequence[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
18
+ return [entry for entry in entries if entry["change"] != REJECTED]
19
+
20
+
21
+ def _policy_decision(policy: str, entries: Sequence[Mapping[str, Any]]) -> dict[str, Any] | None:
22
+ live = _live(entries)
23
+ if policy == "never":
24
+ return {"paths": [], "resolutions": {}}
25
+ if policy == "always" and not any(entry.get("sensitive") for entry in live):
26
+ return {"paths": sorted({entry["path"] for entry in live}), "resolutions": {}}
27
+ return None
28
+
29
+
30
+ def get_merge(session: Session, run_id: str) -> Merge:
31
+ merge = session.get(Merge, run_id)
32
+ if merge is None:
33
+ raise NotFoundError(f"run {run_id} has no collected diff")
34
+ return merge
35
+
36
+
37
+ def report_diff(
38
+ session: Session,
39
+ runner_id: str,
40
+ run_id: str,
41
+ lease_id: str,
42
+ entries: list[dict[str, Any]],
43
+ now: int,
44
+ ) -> Run:
45
+ run = runners.owned_run(session, runner_id, run_id, lease_id, now)
46
+ if session.get(Merge, run_id) is None:
47
+ policy = RunSpec.model_validate(run.spec).merge.policy
48
+ decision = _policy_decision(policy, entries)
49
+ session.add(
50
+ Merge(
51
+ run_id=run_id,
52
+ entries=entries,
53
+ decision=decision,
54
+ created_at=now,
55
+ updated_at=now,
56
+ )
57
+ )
58
+ audit.record(
59
+ session,
60
+ "diff_reported",
61
+ actor="runner",
62
+ run_id=run_id,
63
+ runner_id=runner_id,
64
+ entries=len(entries),
65
+ rejected=len(entries) - len(_live(entries)),
66
+ sensitive=sum(1 for entry in entries if entry.get("sensitive")),
67
+ policy=policy,
68
+ decided=decision is not None,
69
+ )
70
+ try:
71
+ session.commit()
72
+ except Exception:
73
+ # A repeated report raced this one; the diff of the same disk is the same.
74
+ session.rollback()
75
+ get_merge(session, run_id)
76
+ return runs.transition_run(
77
+ session,
78
+ run_id,
79
+ S.COLLECTING,
80
+ S.WAITING_MERGE,
81
+ lease_id=lease_id,
82
+ actor="runner",
83
+ runner_id=runner_id,
84
+ )
85
+
86
+
87
+ def report_merge(
88
+ session: Session,
89
+ runner_id: str,
90
+ run_id: str,
91
+ lease_id: str,
92
+ report: dict[str, Any] | None,
93
+ conflicts: list[dict[str, Any]] | None,
94
+ now: int,
95
+ ) -> Run:
96
+ run = runners.owned_run(session, runner_id, run_id, lease_id, now)
97
+ if run.status is S.COMPLETED and report is not None:
98
+ return run
99
+ if run.status is not S.WAITING_MERGE:
100
+ raise InvalidTransitionError(f"run {run_id} is {run.status}, expected WAITING_MERGE")
101
+ merge = get_merge(session, run_id)
102
+ counts = {name: len(paths) for name, paths in (report or {}).items()}
103
+ audit.record(
104
+ session,
105
+ "merge_reported",
106
+ actor="runner",
107
+ run_id=run_id,
108
+ runner_id=runner_id,
109
+ outcome="applied" if report is not None else "conflict",
110
+ conflicts=len(conflicts or []),
111
+ **counts,
112
+ )
113
+ if report is not None:
114
+ merge.report, merge.conflicts, merge.updated_at = report, None, now
115
+ session.add(merge)
116
+ session.commit()
117
+ return runs.transition_run(
118
+ session,
119
+ run_id,
120
+ S.WAITING_MERGE,
121
+ S.COMPLETED,
122
+ lease_id=lease_id,
123
+ actor="runner",
124
+ runner_id=runner_id,
125
+ )
126
+ merge.conflicts, merge.decision, merge.updated_at = conflicts or [], None, now
127
+ session.add(merge)
128
+ session.commit()
129
+ return run
130
+
131
+
132
+ def _check_selection(
133
+ entries: Sequence[Mapping[str, Any]], paths: set[str], resolutions: Mapping[str, str]
134
+ ) -> None:
135
+ live = _live(entries)
136
+ unknown = sorted((paths | set(resolutions)) - {entry["path"] for entry in live})
137
+ if unknown:
138
+ raise MergeError(f"{unknown[0]} is not a mergeable path of the diff")
139
+ unselected = sorted(set(resolutions) - paths)
140
+ if unselected:
141
+ raise MergeError(f"{unselected[0]} has a resolution but is not selected")
142
+ created_dirs = {
143
+ entry["path"] for entry in live if entry["change"] == "created" and entry["kind"] == "dir"
144
+ }
145
+ # Each host path a selection removes, with the entry that has to be selected for it.
146
+ removed = sorted(
147
+ (entry["from"] if entry["change"] == "renamed" else entry["path"], entry["path"])
148
+ for entry in live
149
+ if entry["change"] in ("deleted", "renamed")
150
+ )
151
+ for entry in live:
152
+ path = entry["path"]
153
+ if path not in paths:
154
+ continue
155
+ parent = path.rpartition("/")[0]
156
+ if parent in created_dirs and parent not in paths:
157
+ raise MergeError(f"{path} needs {parent} too")
158
+ if entry["change"] != "deleted" or entry["kind"] != "dir":
159
+ continue
160
+ prefix = f"{path}/"
161
+ at = bisect_left(removed, (prefix, ""))
162
+ while at < len(removed) and removed[at][0].startswith(prefix):
163
+ owner = removed[at][1]
164
+ if owner not in paths:
165
+ raise MergeError(f"{path} needs {owner} too")
166
+ at += 1
167
+
168
+
169
+ def decide(
170
+ session: Session,
171
+ run_id: str,
172
+ paths: Sequence[str],
173
+ resolutions: Mapping[str, str],
174
+ now: int,
175
+ ) -> Merge:
176
+ run = runs.get_run(session, run_id)
177
+ if run.status is not S.WAITING_MERGE:
178
+ raise InvalidTransitionError(f"run {run_id} is {run.status}, expected WAITING_MERGE")
179
+ merge = get_merge(session, run_id)
180
+ _check_selection(merge.entries, set(paths), resolutions)
181
+ decision = {"paths": sorted(set(paths)), "resolutions": dict(resolutions)}
182
+ decided = session.exec(
183
+ update(Merge)
184
+ .where(col(Merge.run_id) == run_id, col(Merge.decision).is_(None))
185
+ .values(decision=decision, updated_at=now)
186
+ )
187
+ if decided.rowcount == 1:
188
+ audit.record(
189
+ session,
190
+ "merge_decided",
191
+ actor="operator",
192
+ run_id=run_id,
193
+ paths=len(decision["paths"]),
194
+ resolutions=len(decision["resolutions"]),
195
+ )
196
+ session.commit()
197
+ if decided.rowcount != 1:
198
+ raise InvalidTransitionError(f"run {run_id} already has a merge decision pending")
199
+ session.refresh(merge)
200
+ return merge
naos_api/models.py ADDED
@@ -0,0 +1,113 @@
1
+ from typing import Any
2
+
3
+ from sqlmodel import JSON, Column, Field, SQLModel, UniqueConstraint
4
+
5
+ from naos_api.clock import now_ts
6
+ from naos_api.lifecycle import RunStatus
7
+ from naos_api.spec import PolicyKind
8
+
9
+
10
+ class Policy(SQLModel, table=True):
11
+ __tablename__ = "policies"
12
+ __table_args__ = (UniqueConstraint("kind", "digest"),)
13
+
14
+ id: str = Field(primary_key=True)
15
+ kind: PolicyKind
16
+ digest: str
17
+ document: dict[str, Any] = Field(sa_column=Column(JSON, nullable=False))
18
+ created_at: int = Field(default_factory=now_ts)
19
+
20
+
21
+ class Runner(SQLModel, table=True):
22
+ __tablename__ = "agents"
23
+
24
+ id: str = Field(primary_key=True)
25
+ name: str
26
+ token_hash: str = Field(unique=True)
27
+ token_expires_at: int
28
+ prev_token_hash: str | None = Field(default=None, unique=True)
29
+ prev_token_expires_at: int | None = None
30
+ created_at: int = Field(default_factory=now_ts)
31
+ last_heartbeat_at: int | None = None
32
+ revoked_at: int | None = None
33
+
34
+
35
+ class Lease(SQLModel, table=True):
36
+ __tablename__ = "leases"
37
+
38
+ id: str = Field(primary_key=True)
39
+ runner_id: str = Field(index=True)
40
+ # Carries runner_id while the lease is live and NULL once it expires. A plain UNIQUE
41
+ # over it is the portable form of "one live lease per runner": NULLs never collide.
42
+ live_runner_id: str | None = Field(default=None, unique=True)
43
+ acquired_at: int
44
+ expires_at: int
45
+ expired_at: int | None = None
46
+
47
+
48
+ class Run(SQLModel, table=True):
49
+ __tablename__ = "runs"
50
+
51
+ id: str = Field(primary_key=True)
52
+ seq: int = Field(unique=True)
53
+ status: RunStatus = Field(default=RunStatus.PENDING, index=True)
54
+ status_reason: str | None = None
55
+ spec: dict[str, Any] = Field(sa_column=Column(JSON, nullable=False))
56
+ mount_policy_id: str | None = None
57
+ network_policy_id: str | None = None
58
+ shell_policy_id: str | None = None
59
+ mcp_policy_id: str | None = None
60
+ lease_id: str | None = Field(default=None, index=True)
61
+ idempotency_key: str = Field(unique=True)
62
+ request_digest: str
63
+ created_at: int = Field(default_factory=now_ts)
64
+ updated_at: int = Field(default_factory=now_ts)
65
+
66
+
67
+ class Merge(SQLModel, table=True):
68
+ __tablename__ = "merges"
69
+
70
+ run_id: str = Field(primary_key=True)
71
+ entries: list[dict[str, Any]] = Field(sa_column=Column(JSON, nullable=False))
72
+ decision: dict[str, Any] | None = Field(default=None, sa_column=Column(JSON(none_as_null=True)))
73
+ conflicts: list[dict[str, Any]] | None = Field(
74
+ default=None, sa_column=Column(JSON(none_as_null=True))
75
+ )
76
+ report: dict[str, Any] | None = Field(default=None, sa_column=Column(JSON(none_as_null=True)))
77
+ created_at: int = Field(default_factory=now_ts)
78
+ updated_at: int = Field(default_factory=now_ts)
79
+
80
+
81
+ class Secret(SQLModel, table=True):
82
+ __tablename__ = "secrets"
83
+
84
+ id: str = Field(primary_key=True)
85
+ name: str = Field(unique=True)
86
+ value: str
87
+ expires_at: int | None = None
88
+ created_at: int = Field(default_factory=now_ts)
89
+
90
+
91
+ class AuditEvent(SQLModel, table=True):
92
+ __tablename__ = "audit_events"
93
+
94
+ seq: int | None = Field(default=None, primary_key=True)
95
+ id: str = Field(unique=True)
96
+ at: int
97
+ source: str
98
+ event: str = Field(index=True)
99
+ actor: str
100
+ run_id: str | None = Field(default=None, index=True)
101
+ vm_id: str | None = None
102
+ runner_id: str | None = Field(default=None, index=True)
103
+ data: dict[str, Any] = Field(sa_column=Column(JSON, nullable=False))
104
+
105
+
106
+ class Image(SQLModel, table=True):
107
+ __tablename__ = "images"
108
+
109
+ id: str = Field(primary_key=True)
110
+ version: str
111
+ digest: str = Field(unique=True)
112
+ url: str
113
+ created_at: int = Field(default_factory=now_ts)
naos_api/mounts.py ADDED
@@ -0,0 +1,92 @@
1
+ import re
2
+ from collections.abc import Sequence
3
+ from pathlib import PurePosixPath
4
+ from typing import Annotated, Literal
5
+
6
+ from pydantic import Field
7
+
8
+ from naos_api.errors import PolicyError
9
+ from naos_api.spec import StrictModel
10
+
11
+ GUEST_HOME = PurePosixPath("/home/naos")
12
+ WORKSPACE_ROOT = PurePosixPath("/naos")
13
+
14
+ _PROJECT_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
15
+ _SEGMENT = re.compile(r"[A-Za-z0-9._-]{1,255}")
16
+ _CONTROL = re.compile(r"[\x00-\x1f\x7f]")
17
+
18
+ Mode = Literal["ro", "rw"]
19
+ RawPath = Annotated[str, Field(min_length=1, max_length=4096)]
20
+
21
+
22
+ class WorkspaceMountIn(StrictModel):
23
+ host_path: RawPath
24
+ mode: Mode = "rw"
25
+
26
+
27
+ class HomeMountIn(StrictModel):
28
+ host_path: RawPath
29
+ guest_path: RawPath
30
+ mode: Mode = "ro"
31
+
32
+
33
+ class MountPolicyIn(StrictModel):
34
+ workspace: WorkspaceMountIn
35
+ home: Annotated[list[HomeMountIn], Field(max_length=32)] = []
36
+
37
+
38
+ class Mount(StrictModel):
39
+ host_path: str
40
+ guest_path: str
41
+ mode: Mode
42
+
43
+
44
+ class MountPolicy(StrictModel):
45
+ workdir: str
46
+ mounts: list[Mount]
47
+
48
+
49
+ def _host_path(raw: str) -> PurePosixPath:
50
+ parts = raw.split("/")
51
+ if _CONTROL.search(raw) or parts[0] != "" or any(p in ("", ".", "..") for p in parts[1:]):
52
+ raise PolicyError(f"host path {raw!r} must be absolute and normalized")
53
+ return PurePosixPath(raw)
54
+
55
+
56
+ def _guest_home_path(raw: str) -> PurePosixPath:
57
+ parts = raw.split("/")
58
+ if any(p in (".", "..") or not _SEGMENT.fullmatch(p) for p in parts):
59
+ raise PolicyError(f"guest path {raw!r} must be relative to {GUEST_HOME}")
60
+ return GUEST_HOME.joinpath(*parts)
61
+
62
+
63
+ def _authorized(raw: str, roots: Sequence[PurePosixPath]) -> PurePosixPath:
64
+ path = _host_path(raw)
65
+ if not any(path.is_relative_to(root) for root in roots):
66
+ raise PolicyError(f"host path {raw!r} is outside the allowed mount roots")
67
+ return path
68
+
69
+
70
+ def resolve_mount_policy(policy: MountPolicyIn, allowed_roots: Sequence[str]) -> MountPolicy:
71
+ roots = [_host_path(root) for root in allowed_roots]
72
+ workspace_host = _authorized(policy.workspace.host_path, roots)
73
+ if not _PROJECT_NAME.fullmatch(workspace_host.name):
74
+ raise PolicyError(f"workspace name {workspace_host.name!r} is not a valid project name")
75
+
76
+ workdir = WORKSPACE_ROOT / workspace_host.name
77
+ mounts = [
78
+ Mount(host_path=str(workspace_host), guest_path=str(workdir), mode=policy.workspace.mode)
79
+ ]
80
+ for item in policy.home:
81
+ mounts.append(
82
+ Mount(
83
+ host_path=str(_authorized(item.host_path, roots)),
84
+ guest_path=str(_guest_home_path(item.guest_path)),
85
+ mode=item.mode,
86
+ )
87
+ )
88
+
89
+ guest_paths = [mount.guest_path for mount in mounts]
90
+ if len(set(guest_paths)) != len(guest_paths):
91
+ raise PolicyError("guest paths must be unique")
92
+ return MountPolicy(workdir=str(workdir), mounts=mounts)
naos_api/network.py ADDED
@@ -0,0 +1,75 @@
1
+ import re
2
+ from ipaddress import ip_address
3
+ from typing import Annotated, Literal
4
+
5
+ from pydantic import Field, IPvAnyAddress
6
+
7
+ from naos_api.errors import PolicyError
8
+ from naos_api.spec import StrictModel
9
+
10
+ MAX_RULES = 64
11
+ MAX_HOST = 253
12
+ MAX_LABEL = 63
13
+
14
+ Protocol = Literal["http", "https"]
15
+ RawHost = Annotated[str, Field(min_length=1, max_length=MAX_HOST + 1)]
16
+
17
+ _LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?")
18
+
19
+
20
+ class NetworkRuleIn(StrictModel):
21
+ protocol: Protocol | None = None
22
+ host: RawHost | None = None
23
+ ip: IPvAnyAddress | None = None
24
+
25
+
26
+ class NetworkPolicyIn(StrictModel):
27
+ allow: Annotated[list[NetworkRuleIn], Field(max_length=MAX_RULES)] = []
28
+ deny: Annotated[list[NetworkRuleIn], Field(max_length=MAX_RULES)] = []
29
+
30
+
31
+ class NetworkRule(StrictModel):
32
+ protocol: Protocol | None = None
33
+ host: str | None = None
34
+ ip: str | None = None
35
+
36
+
37
+ class NetworkPolicy(StrictModel):
38
+ allow: list[NetworkRule]
39
+ deny: list[NetworkRule]
40
+
41
+
42
+ def resolve_host(raw: str) -> str:
43
+ host = raw.removesuffix(".").lower()
44
+ try:
45
+ ip_address(host)
46
+ except ValueError:
47
+ pass
48
+ else:
49
+ raise PolicyError(f"host {raw!r} is an address literal; use the ip field")
50
+ labels = host.split(".")
51
+ if not host or len(host) > MAX_HOST or host == "localhost":
52
+ raise PolicyError(f"host {raw!r} is not a usable hostname")
53
+ if any(len(label) > MAX_LABEL or not _LABEL.fullmatch(label) for label in labels):
54
+ raise PolicyError(f"host {raw!r} is not a valid hostname")
55
+ return host
56
+
57
+
58
+ def _rule(rule: NetworkRuleIn) -> NetworkRule:
59
+ # A rule with no field set matches every destination, which turns an allow list into allow-all.
60
+ if rule.protocol is None and rule.host is None and rule.ip is None:
61
+ raise PolicyError("a rule must constrain at least one of protocol, host or ip")
62
+ return NetworkRule(
63
+ protocol=rule.protocol,
64
+ host=resolve_host(rule.host) if rule.host is not None else None,
65
+ ip=str(rule.ip) if rule.ip is not None else None,
66
+ )
67
+
68
+
69
+ def resolve_network_policy(policy: NetworkPolicyIn) -> NetworkPolicy:
70
+ if not policy.allow and not policy.deny:
71
+ raise PolicyError("a network policy must carry at least one allow or deny rule")
72
+ return NetworkPolicy(
73
+ allow=[_rule(rule) for rule in policy.allow],
74
+ deny=[_rule(rule) for rule in policy.deny],
75
+ )
naos_api/policies.py ADDED
@@ -0,0 +1,86 @@
1
+ from collections.abc import Sequence
2
+ from typing import Any
3
+ from uuid import uuid4
4
+
5
+ from sqlmodel import Session, select
6
+
7
+ from naos_api import audit
8
+ from naos_api.errors import NotFoundError, PolicyError
9
+ from naos_api.mcp import McpPolicyIn, resolve_mcp_policy
10
+ from naos_api.models import Policy
11
+ from naos_api.mounts import MountPolicyIn, resolve_mount_policy
12
+ from naos_api.network import NetworkPolicyIn, resolve_network_policy
13
+ from naos_api.shell import ShellPolicyIn, resolve_shell_policy
14
+ from naos_api.spec import PolicyKind, RunSpec, digest_of
15
+
16
+ ID_PREFIX = {
17
+ PolicyKind.MOUNT: "mntpol",
18
+ PolicyKind.NETWORK: "netpol",
19
+ PolicyKind.SHELL: "shellpol",
20
+ PolicyKind.MCP: "mcppol",
21
+ }
22
+
23
+
24
+ def _find(session: Session, kind: PolicyKind, digest: str) -> Policy | None:
25
+ statement = select(Policy).where(Policy.kind == kind, Policy.digest == digest)
26
+ return session.exec(statement).first()
27
+
28
+
29
+ def _store(session: Session, kind: PolicyKind, document: dict[str, Any]) -> tuple[Policy, bool]:
30
+ digest = digest_of(document)
31
+ existing = _find(session, kind, digest)
32
+ if existing is not None:
33
+ return existing, False
34
+
35
+ policy = Policy(
36
+ id=f"{ID_PREFIX[kind]}_{uuid4().hex}", kind=kind, digest=digest, document=document
37
+ )
38
+ session.add(policy)
39
+ audit.record(session, "policy_created", actor="operator", policy_id=policy.id, kind=str(kind))
40
+ try:
41
+ session.commit()
42
+ except Exception:
43
+ session.rollback()
44
+ existing = _find(session, kind, digest)
45
+ if existing is None:
46
+ raise
47
+ return existing, False
48
+ return policy, True
49
+
50
+
51
+ def create_mount_policy(
52
+ session: Session, policy: MountPolicyIn, allowed_roots: Sequence[str]
53
+ ) -> tuple[Policy, bool]:
54
+ resolved = resolve_mount_policy(policy, allowed_roots)
55
+ return _store(session, PolicyKind.MOUNT, resolved.model_dump(mode="json"))
56
+
57
+
58
+ def create_network_policy(session: Session, policy: NetworkPolicyIn) -> tuple[Policy, bool]:
59
+ resolved = resolve_network_policy(policy)
60
+ return _store(session, PolicyKind.NETWORK, resolved.model_dump(mode="json"))
61
+
62
+
63
+ def create_shell_policy(session: Session, policy: ShellPolicyIn) -> tuple[Policy, bool]:
64
+ resolved = resolve_shell_policy(policy)
65
+ return _store(session, PolicyKind.SHELL, resolved.model_dump(mode="json"))
66
+
67
+
68
+ def create_mcp_policy(session: Session, policy: McpPolicyIn) -> tuple[Policy, bool]:
69
+ resolved = resolve_mcp_policy(policy)
70
+ return _store(session, PolicyKind.MCP, resolved.model_dump(mode="json"))
71
+
72
+
73
+ def get_policy(session: Session, policy_id: str) -> Policy:
74
+ policy = session.get(Policy, policy_id)
75
+ if policy is None:
76
+ raise NotFoundError(f"policy {policy_id} does not exist")
77
+ return policy
78
+
79
+
80
+ def check_refs(session: Session, spec: RunSpec) -> None:
81
+ for kind, policy_id in spec.policy_refs().items():
82
+ if policy_id is None:
83
+ continue
84
+ policy = session.get(Policy, policy_id)
85
+ if policy is None or policy.kind != kind:
86
+ raise PolicyError(f"{kind} policy {policy_id} does not exist")
naos_api/py.typed ADDED
File without changes
@@ -0,0 +1,18 @@
1
+ from fastapi import APIRouter
2
+
3
+ from naos_api.routes.audit import router as _audit_router
4
+ from naos_api.routes.deps import domain_error_handler
5
+ from naos_api.routes.images import router as _images_router
6
+ from naos_api.routes.policies import router as _policies_router
7
+ from naos_api.routes.runner import router as runner_router
8
+ from naos_api.routes.runs import router as _runs_router
9
+ from naos_api.routes.secrets import router as _secrets_router
10
+
11
+ api_router = APIRouter()
12
+ api_router.include_router(_runs_router)
13
+ api_router.include_router(_policies_router)
14
+ api_router.include_router(_images_router)
15
+ api_router.include_router(_secrets_router)
16
+ api_router.include_router(_audit_router)
17
+
18
+ __all__ = ["api_router", "domain_error_handler", "runner_router"]
@@ -0,0 +1,53 @@
1
+ from typing import Annotated, Any, Self
2
+
3
+ from fastapi import APIRouter, Query
4
+ from pydantic import BaseModel
5
+
6
+ from naos_api import audit, runs
7
+ from naos_api.models import AuditEvent
8
+ from naos_api.routes.deps import SessionDep
9
+
10
+
11
+ class AuditEventRead(BaseModel):
12
+ seq: int
13
+ id: str
14
+ at: int
15
+ source: str
16
+ event: str
17
+ actor: str
18
+ run_id: str | None
19
+ vm_id: str | None
20
+ runner_id: str | None
21
+ data: dict[str, Any]
22
+
23
+ @classmethod
24
+ def of(cls, event: AuditEvent) -> Self:
25
+ return cls.model_validate(event, from_attributes=True)
26
+
27
+
28
+ router = APIRouter()
29
+
30
+
31
+ @router.get("/runs/{run_id}/events")
32
+ def run_events(
33
+ run_id: str,
34
+ session: SessionDep,
35
+ limit: Annotated[int, Query(ge=1, le=10_000)] = 1000,
36
+ ) -> list[AuditEventRead]:
37
+ runs.get_run(session, run_id)
38
+ return [AuditEventRead.of(event) for event in audit.timeline(session, run_id, limit)]
39
+
40
+
41
+ @router.get("/audit")
42
+ def search_events(
43
+ session: SessionDep,
44
+ runner_id: str | None = None,
45
+ event: str | None = None,
46
+ since: Annotated[int | None, Query(ge=0)] = None,
47
+ after: Annotated[int | None, Query(ge=0)] = None,
48
+ limit: Annotated[int, Query(ge=1, le=1000)] = 100,
49
+ ) -> list[AuditEventRead]:
50
+ found = audit.search(
51
+ session, runner_id=runner_id, event=event, since=since, after=after, limit=limit
52
+ )
53
+ return [AuditEventRead.of(row) for row in found]
@@ -0,0 +1,57 @@
1
+ from typing import Annotated
2
+
3
+ from fastapi import Depends, Header, Request
4
+ from fastapi.responses import JSONResponse
5
+ from sqlmodel import Session
6
+
7
+ from naos_api.db import get_session
8
+ from naos_api.errors import (
9
+ IdempotencyConflictError,
10
+ ImageConflictError,
11
+ InvalidTransitionError,
12
+ LeaseError,
13
+ MergeError,
14
+ NotFoundError,
15
+ PolicyError,
16
+ SecretConflictError,
17
+ )
18
+ from naos_api.settings import get_settings
19
+
20
+
21
+ def _lease_ttl() -> int:
22
+ return get_settings().lease_ttl_seconds
23
+
24
+
25
+ def _token_ttl() -> int:
26
+ return get_settings().runner_token_ttl_seconds
27
+
28
+
29
+ def _credential_ttl() -> int:
30
+ return get_settings().run_credential_ttl_seconds
31
+
32
+
33
+ def _mount_roots() -> list[str]:
34
+ return get_settings().allowed_mount_roots
35
+
36
+
37
+ SessionDep = Annotated[Session, Depends(get_session)]
38
+ LeaseTtlDep = Annotated[int, Depends(_lease_ttl)]
39
+ TokenTtlDep = Annotated[int, Depends(_token_ttl)]
40
+ CredentialTtlDep = Annotated[int, Depends(_credential_ttl)]
41
+ MountRootsDep = Annotated[list[str], Depends(_mount_roots)]
42
+ IdempotencyKey = Annotated[str, Header(pattern=r"^[A-Za-z0-9._:-]{1,128}$")]
43
+
44
+ _ERROR_STATUS: dict[type[Exception], int] = {
45
+ NotFoundError: 404,
46
+ InvalidTransitionError: 409,
47
+ IdempotencyConflictError: 409,
48
+ LeaseError: 409,
49
+ ImageConflictError: 409,
50
+ SecretConflictError: 409,
51
+ PolicyError: 422,
52
+ MergeError: 422,
53
+ }
54
+
55
+
56
+ def domain_error_handler(_: Request, exc: Exception) -> JSONResponse:
57
+ return JSONResponse({"detail": str(exc)}, status_code=_ERROR_STATUS.get(type(exc), 400))