naos-api 0.1.0__tar.gz
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-0.1.0/PKG-INFO +71 -0
- naos_api-0.1.0/README.md +54 -0
- naos_api-0.1.0/pyproject.toml +28 -0
- naos_api-0.1.0/setup.cfg +4 -0
- naos_api-0.1.0/src/naos_api/__init__.py +0 -0
- naos_api-0.1.0/src/naos_api/app.py +69 -0
- naos_api-0.1.0/src/naos_api/audit.py +244 -0
- naos_api-0.1.0/src/naos_api/auth.py +72 -0
- naos_api-0.1.0/src/naos_api/clock.py +16 -0
- naos_api-0.1.0/src/naos_api/db.py +28 -0
- naos_api-0.1.0/src/naos_api/errors.py +34 -0
- naos_api-0.1.0/src/naos_api/images/__init__.py +0 -0
- naos_api-0.1.0/src/naos_api/images/service.py +68 -0
- naos_api-0.1.0/src/naos_api/lifecycle.py +58 -0
- naos_api-0.1.0/src/naos_api/mcp.py +98 -0
- naos_api-0.1.0/src/naos_api/merges.py +200 -0
- naos_api-0.1.0/src/naos_api/models.py +113 -0
- naos_api-0.1.0/src/naos_api/mounts.py +92 -0
- naos_api-0.1.0/src/naos_api/network.py +75 -0
- naos_api-0.1.0/src/naos_api/policies.py +86 -0
- naos_api-0.1.0/src/naos_api/py.typed +0 -0
- naos_api-0.1.0/src/naos_api/routes/__init__.py +18 -0
- naos_api-0.1.0/src/naos_api/routes/audit.py +53 -0
- naos_api-0.1.0/src/naos_api/routes/deps.py +57 -0
- naos_api-0.1.0/src/naos_api/routes/images.py +67 -0
- naos_api-0.1.0/src/naos_api/routes/policies.py +82 -0
- naos_api-0.1.0/src/naos_api/routes/runner.py +261 -0
- naos_api-0.1.0/src/naos_api/routes/runs.py +106 -0
- naos_api-0.1.0/src/naos_api/routes/secrets.py +45 -0
- naos_api-0.1.0/src/naos_api/runners.py +431 -0
- naos_api-0.1.0/src/naos_api/runs.py +139 -0
- naos_api-0.1.0/src/naos_api/secrets.py +60 -0
- naos_api-0.1.0/src/naos_api/settings.py +25 -0
- naos_api-0.1.0/src/naos_api/shell.py +33 -0
- naos_api-0.1.0/src/naos_api/spec.py +66 -0
- naos_api-0.1.0/src/naos_api.egg-info/PKG-INFO +71 -0
- naos_api-0.1.0/src/naos_api.egg-info/SOURCES.txt +55 -0
- naos_api-0.1.0/src/naos_api.egg-info/dependency_links.txt +1 -0
- naos_api-0.1.0/src/naos_api.egg-info/requires.txt +9 -0
- naos_api-0.1.0/src/naos_api.egg-info/top_level.txt +1 -0
- naos_api-0.1.0/tests/test_api_auth.py +49 -0
- naos_api-0.1.0/tests/test_api_db.py +35 -0
- naos_api-0.1.0/tests/test_api_health.py +18 -0
- naos_api-0.1.0/tests/test_audit.py +276 -0
- naos_api-0.1.0/tests/test_images.py +90 -0
- naos_api-0.1.0/tests/test_immutability.py +53 -0
- naos_api-0.1.0/tests/test_lifecycle.py +39 -0
- naos_api-0.1.0/tests/test_mcp.py +120 -0
- naos_api-0.1.0/tests/test_merges.py +327 -0
- naos_api-0.1.0/tests/test_mounts.py +115 -0
- naos_api-0.1.0/tests/test_network.py +79 -0
- naos_api-0.1.0/tests/test_routes.py +236 -0
- naos_api-0.1.0/tests/test_runner_auth.py +202 -0
- naos_api-0.1.0/tests/test_runner_lifecycle.py +438 -0
- naos_api-0.1.0/tests/test_runs_service.py +244 -0
- naos_api-0.1.0/tests/test_shell.py +55 -0
- naos_api-0.1.0/tests/test_spec.py +52 -0
naos_api-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: naos-api
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Control plane for naos: owns Runs, their policies and the runners that lease them
|
|
5
|
+
Project-URL: Homepage, https://github.com/oberon-systems/naos
|
|
6
|
+
Project-URL: Repository, https://github.com/oberon-systems/naos
|
|
7
|
+
Requires-Python: >=3.12
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
Requires-Dist: fastapi
|
|
10
|
+
Requires-Dist: httpx
|
|
11
|
+
Requires-Dist: naos-common
|
|
12
|
+
Requires-Dist: pydantic-settings
|
|
13
|
+
Requires-Dist: sqlmodel
|
|
14
|
+
Provides-Extra: server
|
|
15
|
+
Requires-Dist: psycopg[binary]; extra == "server"
|
|
16
|
+
Requires-Dist: uvicorn[standard]; extra == "server"
|
|
17
|
+
|
|
18
|
+
# naos api
|
|
19
|
+
|
|
20
|
+
The control plane of [naos](https://github.com/oberon-systems/naos). It owns
|
|
21
|
+
Runs and the immutable policy each Run is created with, the image catalog, the
|
|
22
|
+
profiles and the audit trail, and it is the only thing runners talk to: they
|
|
23
|
+
register, lease Runs, report transitions and push events through it.
|
|
24
|
+
|
|
25
|
+
The service is [FastAPI](https://fastapi.tiangolo.com/) over
|
|
26
|
+
[SQLModel](https://sqlmodel.tiangolo.com/), with no state of its own besides
|
|
27
|
+
the database. Operator routes live under `/api/v1` behind a bearer token, the
|
|
28
|
+
runner interface under `/api/v1/runners` behind a token each runner is issued
|
|
29
|
+
at registration.
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install "naos-api[server]"
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The `server` extra adds [uvicorn](https://www.uvicorn.org/) and the
|
|
38
|
+
[psycopg](https://www.psycopg.org/) driver, which the library itself does not
|
|
39
|
+
need. The published image carries both:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
docker pull ghcr.io/oberon-systems/naos-api
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Configure
|
|
46
|
+
|
|
47
|
+
Settings are read from `NAOS_*` environment variables once per process. Both
|
|
48
|
+
token settings hold a SHA-256, never the token; while one is unset, the routes
|
|
49
|
+
behind it answer 401.
|
|
50
|
+
|
|
51
|
+
| Variable | Default | Meaning |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| `NAOS_DATABASE_URL` | required | For example `postgresql+psycopg://naos@db.example.com/naos` |
|
|
54
|
+
| `NAOS_ALLOWED_MOUNT_ROOTS` | `[]` | Host directories a mount policy may name |
|
|
55
|
+
| `NAOS_OPERATOR_TOKEN_SHA256` | unset | SHA-256 of the operator token |
|
|
56
|
+
| `NAOS_RUNNER_ENROLLMENT_TOKEN_SHA256` | unset | SHA-256 of the enrollment token |
|
|
57
|
+
| `NAOS_LEASE_TTL_SECONDS` | `60` | Lease extension per heartbeat, 5 to 3600 |
|
|
58
|
+
|
|
59
|
+
The full table, the endpoints and the runner interface are in
|
|
60
|
+
[docs/03-api-design.md](https://github.com/oberon-systems/naos/blob/main/docs/03-api-design.md).
|
|
61
|
+
|
|
62
|
+
## Run
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
export NAOS_DATABASE_URL=postgresql+psycopg://naos@127.0.0.1/naos
|
|
66
|
+
export NAOS_OPERATOR_TOKEN_SHA256=$(printf %s "$NAOS_OPERATOR_TOKEN" | sha256sum | cut -d' ' -f1)
|
|
67
|
+
uvicorn --factory naos_api.app:create_app --host 127.0.0.1
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`create_app()` builds the application and starts the background sweep that
|
|
71
|
+
expires runner leases; the schema is created on startup.
|
naos_api-0.1.0/README.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# naos api
|
|
2
|
+
|
|
3
|
+
The control plane of [naos](https://github.com/oberon-systems/naos). It owns
|
|
4
|
+
Runs and the immutable policy each Run is created with, the image catalog, the
|
|
5
|
+
profiles and the audit trail, and it is the only thing runners talk to: they
|
|
6
|
+
register, lease Runs, report transitions and push events through it.
|
|
7
|
+
|
|
8
|
+
The service is [FastAPI](https://fastapi.tiangolo.com/) over
|
|
9
|
+
[SQLModel](https://sqlmodel.tiangolo.com/), with no state of its own besides
|
|
10
|
+
the database. Operator routes live under `/api/v1` behind a bearer token, the
|
|
11
|
+
runner interface under `/api/v1/runners` behind a token each runner is issued
|
|
12
|
+
at registration.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install "naos-api[server]"
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
The `server` extra adds [uvicorn](https://www.uvicorn.org/) and the
|
|
21
|
+
[psycopg](https://www.psycopg.org/) driver, which the library itself does not
|
|
22
|
+
need. The published image carries both:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
docker pull ghcr.io/oberon-systems/naos-api
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Configure
|
|
29
|
+
|
|
30
|
+
Settings are read from `NAOS_*` environment variables once per process. Both
|
|
31
|
+
token settings hold a SHA-256, never the token; while one is unset, the routes
|
|
32
|
+
behind it answer 401.
|
|
33
|
+
|
|
34
|
+
| Variable | Default | Meaning |
|
|
35
|
+
|---|---|---|
|
|
36
|
+
| `NAOS_DATABASE_URL` | required | For example `postgresql+psycopg://naos@db.example.com/naos` |
|
|
37
|
+
| `NAOS_ALLOWED_MOUNT_ROOTS` | `[]` | Host directories a mount policy may name |
|
|
38
|
+
| `NAOS_OPERATOR_TOKEN_SHA256` | unset | SHA-256 of the operator token |
|
|
39
|
+
| `NAOS_RUNNER_ENROLLMENT_TOKEN_SHA256` | unset | SHA-256 of the enrollment token |
|
|
40
|
+
| `NAOS_LEASE_TTL_SECONDS` | `60` | Lease extension per heartbeat, 5 to 3600 |
|
|
41
|
+
|
|
42
|
+
The full table, the endpoints and the runner interface are in
|
|
43
|
+
[docs/03-api-design.md](https://github.com/oberon-systems/naos/blob/main/docs/03-api-design.md).
|
|
44
|
+
|
|
45
|
+
## Run
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
export NAOS_DATABASE_URL=postgresql+psycopg://naos@127.0.0.1/naos
|
|
49
|
+
export NAOS_OPERATOR_TOKEN_SHA256=$(printf %s "$NAOS_OPERATOR_TOKEN" | sha256sum | cut -d' ' -f1)
|
|
50
|
+
uvicorn --factory naos_api.app:create_app --host 127.0.0.1
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`create_app()` builds the application and starts the background sweep that
|
|
54
|
+
expires runner leases; the schema is created on startup.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=69"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "naos-api"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Control plane for naos: owns Runs, their policies and the runners that lease them"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"fastapi",
|
|
13
|
+
"httpx",
|
|
14
|
+
"naos-common",
|
|
15
|
+
"pydantic-settings",
|
|
16
|
+
"sqlmodel",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Homepage = "https://github.com/oberon-systems/naos"
|
|
21
|
+
Repository = "https://github.com/oberon-systems/naos"
|
|
22
|
+
|
|
23
|
+
[project.optional-dependencies]
|
|
24
|
+
# What serves the app in a container; the library itself needs neither.
|
|
25
|
+
server = ["psycopg[binary]", "uvicorn[standard]"]
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.package-data]
|
|
28
|
+
naos_api = ["py.typed"]
|
naos_api-0.1.0/setup.cfg
ADDED
|
File without changes
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import logging
|
|
3
|
+
from collections.abc import AsyncIterator
|
|
4
|
+
from contextlib import asynccontextmanager, suppress
|
|
5
|
+
|
|
6
|
+
from fastapi import APIRouter, Depends, FastAPI
|
|
7
|
+
from sqlmodel import Session
|
|
8
|
+
|
|
9
|
+
from naos_api.auth import require_principal
|
|
10
|
+
from naos_api.clock import now_ts
|
|
11
|
+
from naos_api.db import Database
|
|
12
|
+
from naos_api.errors import DomainError
|
|
13
|
+
from naos_api.routes import api_router, domain_error_handler, runner_router
|
|
14
|
+
from naos_api.runners import expire_leases
|
|
15
|
+
from naos_api.settings import get_settings
|
|
16
|
+
|
|
17
|
+
log = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def build_v1_router(*routers: APIRouter) -> APIRouter:
|
|
21
|
+
v1 = APIRouter(prefix="/api/v1", dependencies=[Depends(require_principal)])
|
|
22
|
+
for router in routers:
|
|
23
|
+
v1.include_router(router)
|
|
24
|
+
return v1
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def sweep_leases(db: Database) -> list[str]:
|
|
28
|
+
with Session(db.engine) as session:
|
|
29
|
+
return expire_leases(session, now_ts())
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
async def _sweep_forever(db: Database, interval: int) -> None:
|
|
33
|
+
while True:
|
|
34
|
+
try:
|
|
35
|
+
expired = await asyncio.to_thread(sweep_leases, db)
|
|
36
|
+
except Exception:
|
|
37
|
+
log.exception("lease sweep failed")
|
|
38
|
+
else:
|
|
39
|
+
if expired:
|
|
40
|
+
log.warning("expired runner leases: %s", ", ".join(expired))
|
|
41
|
+
await asyncio.sleep(interval)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@asynccontextmanager
|
|
45
|
+
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
46
|
+
interval = get_settings().lease_sweep_interval_seconds
|
|
47
|
+
sweep = asyncio.create_task(_sweep_forever(app.state.db, interval))
|
|
48
|
+
try:
|
|
49
|
+
yield
|
|
50
|
+
finally:
|
|
51
|
+
sweep.cancel()
|
|
52
|
+
with suppress(asyncio.CancelledError):
|
|
53
|
+
await sweep
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def create_app() -> FastAPI:
|
|
57
|
+
settings = get_settings()
|
|
58
|
+
app = FastAPI(title="naos", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
|
|
59
|
+
app.state.db = Database(settings.database_url)
|
|
60
|
+
app.state.db.create_schema()
|
|
61
|
+
app.add_exception_handler(DomainError, domain_error_handler)
|
|
62
|
+
|
|
63
|
+
@app.get("/healthz")
|
|
64
|
+
def healthz() -> dict[str, str]:
|
|
65
|
+
return {"status": "ok"}
|
|
66
|
+
|
|
67
|
+
app.include_router(build_v1_router(api_router))
|
|
68
|
+
app.include_router(runner_router, prefix="/api/v1")
|
|
69
|
+
return app
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
from typing import Annotated, Any, Literal, Self
|
|
3
|
+
from uuid import uuid4
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, ConfigDict, Field, StrictInt, create_model, model_validator
|
|
6
|
+
from sqlmodel import Session, col, select
|
|
7
|
+
|
|
8
|
+
from naos_api.clock import now_ts
|
|
9
|
+
from naos_api.lifecycle import RunStatus
|
|
10
|
+
from naos_api.models import AuditEvent, Lease, Run
|
|
11
|
+
|
|
12
|
+
Actor = Literal["operator", "runner", "system"]
|
|
13
|
+
EventId = Annotated[str, Field(pattern=r"^evt_[0-9a-f]{32}$")]
|
|
14
|
+
Id = Annotated[str, Field(pattern=r"^[A-Za-z0-9_]{1,64}$")]
|
|
15
|
+
Name = Annotated[str, Field(max_length=256)]
|
|
16
|
+
Text = Annotated[str, Field(max_length=500)]
|
|
17
|
+
GuestPath = Annotated[str, Field(max_length=4096)]
|
|
18
|
+
Count = Annotated[StrictInt, Field(ge=0)]
|
|
19
|
+
|
|
20
|
+
API_EVENTS: dict[str, frozenset[str]] = {
|
|
21
|
+
"run_created": frozenset(),
|
|
22
|
+
"run_transition": frozenset({"from", "to", "reason"}),
|
|
23
|
+
"run_stop_requested": frozenset({"status"}),
|
|
24
|
+
"runner_registered": frozenset(),
|
|
25
|
+
"lease_acquired": frozenset({"lease_id"}),
|
|
26
|
+
"lease_expired": frozenset({"lease_id"}),
|
|
27
|
+
"token_rotated": frozenset(),
|
|
28
|
+
"waiting_rebound": frozenset({"lease_id"}),
|
|
29
|
+
"credentials_issued": frozenset({"names"}),
|
|
30
|
+
"diff_reported": frozenset({"entries", "rejected", "sensitive", "policy", "decided"}),
|
|
31
|
+
"merge_decided": frozenset({"paths", "resolutions"}),
|
|
32
|
+
"merge_reported": frozenset(
|
|
33
|
+
{"outcome", "applied", "skipped", "exported", "backed_up", "conflicts"}
|
|
34
|
+
),
|
|
35
|
+
"policy_created": frozenset({"policy_id", "kind"}),
|
|
36
|
+
"image_registered": frozenset({"image_id", "version", "digest"}),
|
|
37
|
+
"secret_created": frozenset({"name"}),
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
_VM = {"vm_id": Id, "run_id": Id}
|
|
41
|
+
_RUN = {"run_id": Id}
|
|
42
|
+
_NETWORK = {"run_id": Id, "protocol": Name, "host": Name, "rule": Name}
|
|
43
|
+
_SHELL = {"run_id": Id, "capability": Name, "path": GuestPath}
|
|
44
|
+
RUNNER_EVENTS: dict[str, dict[str, Any]] = {
|
|
45
|
+
"runner_registered": {"runner_id": Id},
|
|
46
|
+
"runner_credentials_dropped": {"runner_id": Id},
|
|
47
|
+
"run_claimed": _RUN,
|
|
48
|
+
"run_failed": _RUN | {"reason": Text},
|
|
49
|
+
"orphan_destroyed": _VM,
|
|
50
|
+
"lease_fenced": {"vms": Count},
|
|
51
|
+
"image_cached": {"digest": Name},
|
|
52
|
+
"image_rejected": {"digest": Name, "reason": Text},
|
|
53
|
+
"vm_created": _VM,
|
|
54
|
+
"vm_stopped": _VM,
|
|
55
|
+
"workspace_shared": _RUN | {"mode": Literal["ro", "rw"]},
|
|
56
|
+
"workspace_collected": _RUN | {"entries": Count, "rejected": Count},
|
|
57
|
+
"merge_conflict": _RUN | {"conflicts": Count},
|
|
58
|
+
"merge_applied": _RUN | {"applied": Count, "backed_up": Count, "exported": Count},
|
|
59
|
+
"changes_archived": _VM,
|
|
60
|
+
"vm_destroyed": _VM,
|
|
61
|
+
"console_attached": _VM,
|
|
62
|
+
"network_policy_configured": _RUN,
|
|
63
|
+
"network_allowed": _NETWORK,
|
|
64
|
+
"network_denied": _NETWORK | {"reason": Text},
|
|
65
|
+
"shell_policy_configured": _RUN,
|
|
66
|
+
"shell_allowed": _SHELL,
|
|
67
|
+
"shell_denied": _SHELL | {"reason": Text},
|
|
68
|
+
"mcp_attached": _RUN,
|
|
69
|
+
"mcp_rejected": _RUN | {"reason": Text},
|
|
70
|
+
"mcp_policy_configured": _RUN,
|
|
71
|
+
"mcp_credentials_updated": _RUN | {"names": Text},
|
|
72
|
+
"mcp_call": _RUN
|
|
73
|
+
| {
|
|
74
|
+
"server": Name,
|
|
75
|
+
"tool": Name,
|
|
76
|
+
"resource": GuestPath,
|
|
77
|
+
"decision": Literal["allow", "deny"],
|
|
78
|
+
"duration_ms": Count,
|
|
79
|
+
"category": Name,
|
|
80
|
+
},
|
|
81
|
+
"audit_dropped": {"dropped": Count},
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _schema(event: str, fields: dict[str, Any]) -> type[BaseModel]:
|
|
86
|
+
required: dict[str, Any] = {name: (kind, ...) for name, kind in fields.items()}
|
|
87
|
+
return create_model(
|
|
88
|
+
f"{event}_fields", __config__=ConfigDict(extra="forbid", strict=True), **required
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
_FIELDS = {event: _schema(event, fields) for event, fields in RUNNER_EVENTS.items()}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class RunnerEventIn(BaseModel):
|
|
96
|
+
model_config = ConfigDict(extra="allow", frozen=True)
|
|
97
|
+
|
|
98
|
+
id: EventId
|
|
99
|
+
at: Count
|
|
100
|
+
event: str
|
|
101
|
+
|
|
102
|
+
@model_validator(mode="after")
|
|
103
|
+
def _known_fields(self) -> Self:
|
|
104
|
+
fields = _FIELDS.get(self.event)
|
|
105
|
+
if fields is None:
|
|
106
|
+
raise ValueError(f"{self.event} is not a runner audit event")
|
|
107
|
+
fields.model_validate(self.model_extra or {})
|
|
108
|
+
return self
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def fields(self) -> dict[str, Any]:
|
|
112
|
+
return dict(self.model_extra or {})
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def record(
|
|
116
|
+
session: Session,
|
|
117
|
+
event: str,
|
|
118
|
+
*,
|
|
119
|
+
actor: Actor,
|
|
120
|
+
run_id: str | None = None,
|
|
121
|
+
runner_id: str | None = None,
|
|
122
|
+
**data: Any,
|
|
123
|
+
) -> None:
|
|
124
|
+
unknown = sorted(set(data) - API_EVENTS[event])
|
|
125
|
+
if unknown:
|
|
126
|
+
raise ValueError(f"{event} does not carry {', '.join(unknown)}")
|
|
127
|
+
session.add(
|
|
128
|
+
AuditEvent(
|
|
129
|
+
id=f"evt_{uuid4().hex}",
|
|
130
|
+
at=now_ts(),
|
|
131
|
+
source="api",
|
|
132
|
+
event=event,
|
|
133
|
+
actor=actor,
|
|
134
|
+
run_id=run_id,
|
|
135
|
+
runner_id=runner_id,
|
|
136
|
+
data=data,
|
|
137
|
+
)
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def transitioned(
|
|
142
|
+
session: Session,
|
|
143
|
+
run_id: str,
|
|
144
|
+
expected: RunStatus,
|
|
145
|
+
target: RunStatus,
|
|
146
|
+
reason: str | None,
|
|
147
|
+
*,
|
|
148
|
+
actor: Actor,
|
|
149
|
+
runner_id: str | None = None,
|
|
150
|
+
) -> None:
|
|
151
|
+
moved = {"from": str(expected), "to": str(target), "reason": reason}
|
|
152
|
+
record(
|
|
153
|
+
session,
|
|
154
|
+
"run_transition",
|
|
155
|
+
actor=actor,
|
|
156
|
+
run_id=run_id,
|
|
157
|
+
runner_id=runner_id,
|
|
158
|
+
**moved,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _held(session: Session, runner_id: str, run_ids: set[str]) -> set[str]:
|
|
163
|
+
if not run_ids:
|
|
164
|
+
return set()
|
|
165
|
+
statement = (
|
|
166
|
+
select(Run.id)
|
|
167
|
+
.join(Lease, col(Run.lease_id) == col(Lease.id))
|
|
168
|
+
.where(col(Lease.runner_id) == runner_id, col(Run.id).in_(run_ids))
|
|
169
|
+
)
|
|
170
|
+
return set(session.exec(statement).all())
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _stored(session: Session, ids: list[str]) -> set[str]:
|
|
174
|
+
return set(session.exec(select(AuditEvent.id).where(col(AuditEvent.id).in_(ids))).all())
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def ingest(
|
|
178
|
+
session: Session, runner_id: str, events: Sequence[RunnerEventIn]
|
|
179
|
+
) -> tuple[int, list[str]]:
|
|
180
|
+
held = _held(session, runner_id, {e.fields["run_id"] for e in events if "run_id" in e.fields})
|
|
181
|
+
refused = [e.id for e in events if "run_id" in e.fields and e.fields["run_id"] not in held]
|
|
182
|
+
for attempt in range(2):
|
|
183
|
+
seen = _stored(session, [event.id for event in events]) | set(refused)
|
|
184
|
+
accepted = 0
|
|
185
|
+
for event in events:
|
|
186
|
+
if event.id in seen:
|
|
187
|
+
continue
|
|
188
|
+
seen.add(event.id)
|
|
189
|
+
fields = event.fields
|
|
190
|
+
session.add(
|
|
191
|
+
AuditEvent(
|
|
192
|
+
id=event.id,
|
|
193
|
+
at=event.at,
|
|
194
|
+
source="runner",
|
|
195
|
+
event=event.event,
|
|
196
|
+
actor="runner",
|
|
197
|
+
run_id=fields.pop("run_id", None),
|
|
198
|
+
vm_id=fields.pop("vm_id", None),
|
|
199
|
+
runner_id=runner_id,
|
|
200
|
+
data=fields,
|
|
201
|
+
)
|
|
202
|
+
)
|
|
203
|
+
accepted += 1
|
|
204
|
+
try:
|
|
205
|
+
session.commit()
|
|
206
|
+
except Exception:
|
|
207
|
+
# A retried batch raced this one; the second pass skips what it stored.
|
|
208
|
+
session.rollback()
|
|
209
|
+
if attempt == 1:
|
|
210
|
+
raise
|
|
211
|
+
continue
|
|
212
|
+
return accepted, refused
|
|
213
|
+
raise AssertionError("unreachable")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def timeline(session: Session, run_id: str, limit: int) -> Sequence[AuditEvent]:
|
|
217
|
+
statement = (
|
|
218
|
+
select(AuditEvent)
|
|
219
|
+
.where(col(AuditEvent.run_id) == run_id)
|
|
220
|
+
.order_by(col(AuditEvent.at), col(AuditEvent.seq))
|
|
221
|
+
.limit(limit)
|
|
222
|
+
)
|
|
223
|
+
return session.exec(statement).all()
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def search(
|
|
227
|
+
session: Session,
|
|
228
|
+
*,
|
|
229
|
+
runner_id: str | None,
|
|
230
|
+
event: str | None,
|
|
231
|
+
since: int | None,
|
|
232
|
+
after: int | None,
|
|
233
|
+
limit: int,
|
|
234
|
+
) -> Sequence[AuditEvent]:
|
|
235
|
+
statement = select(AuditEvent)
|
|
236
|
+
if runner_id is not None:
|
|
237
|
+
statement = statement.where(col(AuditEvent.runner_id) == runner_id)
|
|
238
|
+
if event is not None:
|
|
239
|
+
statement = statement.where(col(AuditEvent.event) == event)
|
|
240
|
+
if since is not None:
|
|
241
|
+
statement = statement.where(col(AuditEvent.at) >= since)
|
|
242
|
+
if after is not None:
|
|
243
|
+
statement = statement.where(col(AuditEvent.seq) > after)
|
|
244
|
+
return session.exec(statement.order_by(col(AuditEvent.seq)).limit(limit)).all()
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import hmac
|
|
2
|
+
from typing import Annotated
|
|
3
|
+
|
|
4
|
+
from fastapi import Depends, HTTPException, status
|
|
5
|
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
6
|
+
from sqlmodel import Session
|
|
7
|
+
|
|
8
|
+
from naos_api import runners
|
|
9
|
+
from naos_api.clock import NowDep
|
|
10
|
+
from naos_api.db import get_session
|
|
11
|
+
from naos_api.runners import RunnerPrincipal, hash_token
|
|
12
|
+
from naos_api.settings import get_settings
|
|
13
|
+
|
|
14
|
+
_bearer = HTTPBearer(auto_error=False)
|
|
15
|
+
BearerDep = Annotated[HTTPAuthorizationCredentials | None, Depends(_bearer)]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _unauthorized(detail: str) -> HTTPException:
|
|
19
|
+
return HTTPException(
|
|
20
|
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
21
|
+
detail=detail,
|
|
22
|
+
headers={"WWW-Authenticate": "Bearer"},
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _matches(credentials: HTTPAuthorizationCredentials | None, expected: str | None) -> bool:
|
|
27
|
+
return (
|
|
28
|
+
credentials is not None
|
|
29
|
+
and expected is not None
|
|
30
|
+
and hmac.compare_digest(hash_token(credentials.credentials), expected)
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _operator_hash() -> str | None:
|
|
35
|
+
return get_settings().operator_token_sha256
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def require_principal(
|
|
39
|
+
credentials: BearerDep, expected: Annotated[str | None, Depends(_operator_hash)]
|
|
40
|
+
) -> None:
|
|
41
|
+
if not _matches(credentials, expected):
|
|
42
|
+
raise _unauthorized("operator is not authorized")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _enrollment_hash() -> str | None:
|
|
46
|
+
return get_settings().runner_enrollment_token_sha256
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def require_enrollment(
|
|
50
|
+
credentials: BearerDep, expected: Annotated[str | None, Depends(_enrollment_hash)]
|
|
51
|
+
) -> None:
|
|
52
|
+
if not _matches(credentials, expected):
|
|
53
|
+
raise _unauthorized("runner enrollment is not authorized")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def require_runner(
|
|
57
|
+
runner_id: str,
|
|
58
|
+
credentials: BearerDep,
|
|
59
|
+
session: Annotated[Session, Depends(get_session)],
|
|
60
|
+
now: NowDep,
|
|
61
|
+
) -> RunnerPrincipal:
|
|
62
|
+
principal = (
|
|
63
|
+
None if credentials is None else runners.authenticate(session, credentials.credentials, now)
|
|
64
|
+
)
|
|
65
|
+
if principal is None:
|
|
66
|
+
raise _unauthorized("runner credentials are not valid")
|
|
67
|
+
if principal.runner_id != runner_id:
|
|
68
|
+
raise HTTPException(
|
|
69
|
+
status_code=status.HTTP_403_FORBIDDEN,
|
|
70
|
+
detail="runner credentials do not belong to this runner",
|
|
71
|
+
)
|
|
72
|
+
return principal
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from typing import Annotated
|
|
3
|
+
|
|
4
|
+
from fastapi import Depends
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def now_ts() -> int:
|
|
8
|
+
"""Seconds since the Unix epoch, UTC. The only time source in the API."""
|
|
9
|
+
return int(time.time())
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def get_now() -> int:
|
|
13
|
+
return now_ts()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
NowDep = Annotated[int, Depends(get_now)]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from collections.abc import Iterator
|
|
2
|
+
|
|
3
|
+
from fastapi import Request
|
|
4
|
+
from sqlmodel import Session, SQLModel, create_engine
|
|
5
|
+
|
|
6
|
+
import naos_api.models # noqa: F401 registers the tables on SQLModel.metadata
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Database:
|
|
10
|
+
def __init__(self, url: str) -> None:
|
|
11
|
+
self.engine = create_engine(url)
|
|
12
|
+
|
|
13
|
+
def create_schema(self) -> None:
|
|
14
|
+
SQLModel.metadata.create_all(self.engine)
|
|
15
|
+
with self.engine.connect() as connection:
|
|
16
|
+
for table in SQLModel.metadata.sorted_tables:
|
|
17
|
+
try:
|
|
18
|
+
connection.execute(table.select().limit(0))
|
|
19
|
+
except Exception as err:
|
|
20
|
+
raise RuntimeError(
|
|
21
|
+
f"table {table.name} does not match the models;"
|
|
22
|
+
" migrate or recreate the database"
|
|
23
|
+
) from err
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def get_session(request: Request) -> Iterator[Session]:
|
|
27
|
+
with Session(request.app.state.db.engine) as session:
|
|
28
|
+
yield session
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
class DomainError(Exception):
|
|
2
|
+
"""Base for every error the domain raises instead of an HTTP status."""
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class NotFoundError(DomainError):
|
|
6
|
+
"""The addressed entity does not exist."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class InvalidTransitionError(DomainError):
|
|
10
|
+
"""The requested lifecycle move is not allowed from the current status."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class IdempotencyConflictError(DomainError):
|
|
14
|
+
"""The idempotency key was reused with a different request body."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class PolicyError(DomainError):
|
|
18
|
+
"""The submitted policy is invalid or does not resolve to a policy."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class LeaseError(DomainError):
|
|
22
|
+
"""The runner lease is missing, expired, or belongs to another runner."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ImageConflictError(DomainError):
|
|
26
|
+
"""The image id or digest is already registered with other values."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class SecretConflictError(DomainError):
|
|
30
|
+
"""A secret with this name already exists."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class MergeError(DomainError):
|
|
34
|
+
"""The merge selection does not fit the collected diff."""
|
|
File without changes
|