naos-api 0.2.0__tar.gz → 0.3.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.2.0 → naos_api-0.3.0}/PKG-INFO +14 -9
- {naos_api-0.2.0 → naos_api-0.3.0}/README.md +4 -1
- {naos_api-0.2.0 → naos_api-0.3.0}/pyproject.toml +9 -7
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/app.py +52 -2
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/audit.py +50 -12
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/auth.py +54 -15
- naos_api-0.3.0/src/naos_api/body_limit.py +34 -0
- naos_api-0.3.0/src/naos_api/cli.py +127 -0
- naos_api-0.3.0/src/naos_api/clock.py +23 -0
- naos_api-0.3.0/src/naos_api/console_hub.py +125 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/consoles.py +13 -9
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/content_hub.py +26 -8
- naos_api-0.3.0/src/naos_api/credentials.py +132 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/db.py +2 -1
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/gates.py +30 -24
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/mcp.py +6 -5
- naos_api-0.3.0/src/naos_api/migrations/versions/0002_image_size_bigint.py +27 -0
- naos_api-0.3.0/src/naos_api/migrations/versions/0003_operator_credentials.py +27 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/models.py +14 -2
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/network.py +9 -3
- naos_api-0.3.0/src/naos_api/no_nul.py +60 -0
- naos_api-0.3.0/src/naos_api/no_store.py +24 -0
- naos_api-0.3.0/src/naos_api/nonces.py +19 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/policies.py +12 -4
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/__init__.py +7 -1
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/audit.py +3 -3
- naos_api-0.3.0/src/naos_api/routes/auth.py +61 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/console.py +94 -20
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/content.py +28 -9
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/deps.py +21 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/images.py +9 -3
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/mcp_servers.py +10 -4
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/policies.py +4 -2
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/profiles.py +3 -3
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/runner.py +8 -6
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/runners.py +2 -2
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/runs.py +5 -3
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/routes/secrets.py +2 -2
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/runners.py +7 -12
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/runs.py +19 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/settings.py +6 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api.egg-info/PKG-INFO +14 -9
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api.egg-info/SOURCES.txt +8 -0
- naos_api-0.3.0/src/naos_api.egg-info/requires.txt +11 -0
- naos_api-0.3.0/tests/test_api_auth.py +362 -0
- naos_api-0.3.0/tests/test_api_db.py +157 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_audit.py +44 -10
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_consoles.py +182 -3
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_gates.py +21 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_images.py +5 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_mcp.py +16 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_merges.py +53 -2
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_migrations.py +7 -6
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_network.py +8 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_policy_names.py +53 -1
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_run_policies.py +19 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_secrets.py +36 -0
- naos_api-0.2.0/src/naos_api/cli.py +0 -30
- naos_api-0.2.0/src/naos_api/clock.py +0 -16
- naos_api-0.2.0/src/naos_api/console_hub.py +0 -60
- naos_api-0.2.0/src/naos_api.egg-info/requires.txt +0 -9
- naos_api-0.2.0/tests/test_api_auth.py +0 -49
- naos_api-0.2.0/tests/test_api_db.py +0 -19
- {naos_api-0.2.0 → naos_api-0.3.0}/setup.cfg +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/__init__.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/errors.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/images/__init__.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/images/service.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/lifecycle.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/mcp_servers.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/merges.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/migrations/__init__.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/migrations/env.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/migrations/versions/0001_initial.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/migrations/versions/__init__.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/model.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/mounts.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/profiles.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/py.typed +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/schema.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/secrets.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/shell.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api/spec.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api.egg-info/dependency_links.txt +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api.egg-info/entry_points.txt +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/src/naos_api.egg-info/top_level.txt +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_api_health.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_immutability.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_lifecycle.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_mcp_servers.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_model.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_mounts.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_profiles.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_routes.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_runner_auth.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_runner_lifecycle.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_runner_placement.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_runners_admin.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_runners_list.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_runs_service.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_runs_view.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_shell.py +0 -0
- {naos_api-0.2.0 → naos_api-0.3.0}/tests/test_spec.py +0 -0
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: naos-api
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Control plane for naos: owns Runs, their policies and the runners that lease them
|
|
5
5
|
Project-URL: Homepage, https://github.com/oberon-systems/naos
|
|
6
6
|
Project-URL: Repository, https://github.com/oberon-systems/naos
|
|
7
7
|
Requires-Python: >=3.12
|
|
8
8
|
Description-Content-Type: text/markdown
|
|
9
|
-
Requires-Dist: alembic
|
|
10
|
-
Requires-Dist:
|
|
11
|
-
Requires-Dist:
|
|
12
|
-
Requires-Dist:
|
|
13
|
-
Requires-Dist:
|
|
9
|
+
Requires-Dist: alembic>=1.20.1
|
|
10
|
+
Requires-Dist: fakeredis>=2.40.0
|
|
11
|
+
Requires-Dist: fastapi>=0.162.0
|
|
12
|
+
Requires-Dist: pydantic-settings>=2.16.2
|
|
13
|
+
Requires-Dist: redis>=8.1.0
|
|
14
|
+
Requires-Dist: sqlmodel>=0.0.48
|
|
15
|
+
Requires-Dist: transitions>=0.9.3
|
|
14
16
|
Provides-Extra: server
|
|
15
|
-
Requires-Dist: psycopg[binary]; extra == "server"
|
|
16
|
-
Requires-Dist: uvicorn[standard]; extra == "server"
|
|
17
|
+
Requires-Dist: psycopg[binary]>=3.3.8; extra == "server"
|
|
18
|
+
Requires-Dist: uvicorn[standard]>=0.54.0; extra == "server"
|
|
17
19
|
|
|
18
20
|
# naos api
|
|
19
21
|
|
|
@@ -53,7 +55,10 @@ behind it answer 401.
|
|
|
53
55
|
| `NAOS_DATABASE_URL` | required | For example `postgresql+psycopg://naos@db.example.com/naos` |
|
|
54
56
|
| `NAOS_DATABASE_AUTO_MIGRATE` | `false` | Bring an empty database to the schema on start |
|
|
55
57
|
| `NAOS_ALLOWED_MOUNT_ROOTS` | `[]` | Host directories a mount policy may name |
|
|
56
|
-
| `NAOS_OPERATOR_TOKEN_SHA256` | unset | SHA-256 of the operator token |
|
|
58
|
+
| `NAOS_OPERATOR_TOKEN_SHA256` | unset | SHA-256 of the operator token, which only logs in |
|
|
59
|
+
| `NAOS_MASTER_KEYS` | `{}` | Keys operator credentials derive from, by id, as JSON |
|
|
60
|
+
| `NAOS_MASTER_KID` | unset | The key that issues new credentials |
|
|
61
|
+
| `NAOS_CACHE_URL` | unset | Redis URL for used nonces; unset keeps them in the process |
|
|
57
62
|
| `NAOS_RUNNER_ENROLLMENT_TOKEN_SHA256` | unset | SHA-256 of the enrollment token |
|
|
58
63
|
| `NAOS_LEASE_TTL_SECONDS` | `60` | Lease extension per heartbeat, 5 to 3600 |
|
|
59
64
|
|
|
@@ -36,7 +36,10 @@ behind it answer 401.
|
|
|
36
36
|
| `NAOS_DATABASE_URL` | required | For example `postgresql+psycopg://naos@db.example.com/naos` |
|
|
37
37
|
| `NAOS_DATABASE_AUTO_MIGRATE` | `false` | Bring an empty database to the schema on start |
|
|
38
38
|
| `NAOS_ALLOWED_MOUNT_ROOTS` | `[]` | Host directories a mount policy may name |
|
|
39
|
-
| `NAOS_OPERATOR_TOKEN_SHA256` | unset | SHA-256 of the operator token |
|
|
39
|
+
| `NAOS_OPERATOR_TOKEN_SHA256` | unset | SHA-256 of the operator token, which only logs in |
|
|
40
|
+
| `NAOS_MASTER_KEYS` | `{}` | Keys operator credentials derive from, by id, as JSON |
|
|
41
|
+
| `NAOS_MASTER_KID` | unset | The key that issues new credentials |
|
|
42
|
+
| `NAOS_CACHE_URL` | unset | Redis URL for used nonces; unset keeps them in the process |
|
|
40
43
|
| `NAOS_RUNNER_ENROLLMENT_TOKEN_SHA256` | unset | SHA-256 of the enrollment token |
|
|
41
44
|
| `NAOS_LEASE_TTL_SECONDS` | `60` | Lease extension per heartbeat, 5 to 3600 |
|
|
42
45
|
|
|
@@ -4,16 +4,18 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "naos-api"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.3.0"
|
|
8
8
|
description = "Control plane for naos: owns Runs, their policies and the runners that lease them"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.12"
|
|
11
11
|
dependencies = [
|
|
12
|
-
"alembic",
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
"
|
|
12
|
+
"alembic>=1.20.1",
|
|
13
|
+
"fakeredis>=2.40.0",
|
|
14
|
+
"fastapi>=0.162.0",
|
|
15
|
+
"pydantic-settings>=2.16.2",
|
|
16
|
+
"redis>=8.1.0",
|
|
17
|
+
"sqlmodel>=0.0.48",
|
|
18
|
+
"transitions>=0.9.3",
|
|
17
19
|
]
|
|
18
20
|
|
|
19
21
|
[project.scripts]
|
|
@@ -25,7 +27,7 @@ Repository = "https://github.com/oberon-systems/naos"
|
|
|
25
27
|
|
|
26
28
|
[project.optional-dependencies]
|
|
27
29
|
# What serves the app in a container; the library itself needs neither.
|
|
28
|
-
server = ["psycopg[binary]", "uvicorn[standard]"]
|
|
30
|
+
server = ["psycopg[binary]>=3.3.8", "uvicorn[standard]>=0.54.0"]
|
|
29
31
|
|
|
30
32
|
[tool.setuptools.package-data]
|
|
31
33
|
naos_api = ["py.typed"]
|
|
@@ -2,34 +2,68 @@ import asyncio
|
|
|
2
2
|
import logging
|
|
3
3
|
from collections.abc import AsyncIterator
|
|
4
4
|
from contextlib import asynccontextmanager, suppress
|
|
5
|
+
from typing import Any
|
|
5
6
|
|
|
6
7
|
from fastapi import APIRouter, Depends, FastAPI
|
|
8
|
+
from fastapi.exceptions import RequestValidationError
|
|
7
9
|
from sqlmodel import Session
|
|
8
10
|
|
|
9
11
|
from naos_api import schema
|
|
10
12
|
from naos_api.auth import require_principal
|
|
13
|
+
from naos_api.body_limit import BodyLimit
|
|
11
14
|
from naos_api.clock import now_ts
|
|
12
15
|
from naos_api.console_hub import ConsoleHub
|
|
13
16
|
from naos_api.content_hub import ContentHub
|
|
14
17
|
from naos_api.db import Database
|
|
15
18
|
from naos_api.errors import DomainError
|
|
19
|
+
from naos_api.no_nul import NoNul
|
|
20
|
+
from naos_api.no_store import NoStore
|
|
21
|
+
from naos_api.nonces import Nonces
|
|
16
22
|
from naos_api.routes import (
|
|
17
23
|
api_router,
|
|
18
24
|
console_router,
|
|
19
25
|
content_router,
|
|
20
26
|
domain_error_handler,
|
|
27
|
+
internal_error_handler,
|
|
21
28
|
runner_console_router,
|
|
22
29
|
runner_content_router,
|
|
23
30
|
runner_router,
|
|
31
|
+
validation_error_handler,
|
|
24
32
|
)
|
|
33
|
+
from naos_api.routes.auth import router as auth_router
|
|
25
34
|
from naos_api.runners import expire_leases
|
|
26
35
|
from naos_api.settings import get_settings
|
|
27
36
|
|
|
28
37
|
log = logging.getLogger(__name__)
|
|
29
38
|
|
|
30
39
|
|
|
40
|
+
# A domain refusal answers 422 with a sentence, a request that fails validation with a list.
|
|
41
|
+
UNPROCESSABLE: dict[int | str, dict[str, Any]] = {
|
|
42
|
+
422: {
|
|
43
|
+
"description": "The request failed validation, or the API refused it",
|
|
44
|
+
"content": {
|
|
45
|
+
"application/json": {
|
|
46
|
+
"schema": {
|
|
47
|
+
"type": "object",
|
|
48
|
+
"properties": {
|
|
49
|
+
"detail": {
|
|
50
|
+
"anyOf": [
|
|
51
|
+
{"type": "string"},
|
|
52
|
+
{"type": "array", "items": {"type": "object"}},
|
|
53
|
+
]
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
31
63
|
def build_v1_router(*routers: APIRouter) -> APIRouter:
|
|
32
|
-
v1 = APIRouter(
|
|
64
|
+
v1 = APIRouter(
|
|
65
|
+
prefix="/api/v1", dependencies=[Depends(require_principal)], responses=UNPROCESSABLE
|
|
66
|
+
)
|
|
33
67
|
for router in routers:
|
|
34
68
|
v1.include_router(router)
|
|
35
69
|
return v1
|
|
@@ -66,18 +100,34 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
|
66
100
|
|
|
67
101
|
def create_app() -> FastAPI:
|
|
68
102
|
settings = get_settings()
|
|
69
|
-
|
|
103
|
+
# No slash redirect: its absolute Location would echo the request's Host back.
|
|
104
|
+
app = FastAPI(
|
|
105
|
+
title="naos",
|
|
106
|
+
docs_url=None,
|
|
107
|
+
redoc_url=None,
|
|
108
|
+
openapi_url=None,
|
|
109
|
+
lifespan=lifespan,
|
|
110
|
+
redirect_slashes=False,
|
|
111
|
+
)
|
|
70
112
|
app.state.db = Database(settings.database_url)
|
|
71
113
|
app.state.console_hub = ConsoleHub()
|
|
72
114
|
app.state.content_hub = ContentHub()
|
|
115
|
+
app.state.nonces = Nonces(settings.cache_url)
|
|
73
116
|
schema.ensure(app.state.db.engine, settings.database_auto_migrate)
|
|
74
117
|
app.add_exception_handler(DomainError, domain_error_handler)
|
|
118
|
+
app.add_exception_handler(RequestValidationError, validation_error_handler)
|
|
119
|
+
app.add_exception_handler(Exception, internal_error_handler)
|
|
120
|
+
# BodyLimit wraps NoNul, so the body NoNul buffers is already bounded.
|
|
121
|
+
app.add_middleware(NoNul)
|
|
122
|
+
app.add_middleware(BodyLimit)
|
|
123
|
+
app.add_middleware(NoStore)
|
|
75
124
|
|
|
76
125
|
@app.get("/healthz")
|
|
77
126
|
def healthz() -> dict[str, str]:
|
|
78
127
|
return {"status": "ok"}
|
|
79
128
|
|
|
80
129
|
app.include_router(build_v1_router(api_router))
|
|
130
|
+
app.include_router(auth_router, prefix="/api/v1")
|
|
81
131
|
app.include_router(runner_router, prefix="/api/v1")
|
|
82
132
|
# A websocket cannot pass the HTTP bearer check of the v1 router, so it carries its own.
|
|
83
133
|
app.include_router(console_router, prefix="/api/v1")
|
|
@@ -1,22 +1,33 @@
|
|
|
1
|
+
import re
|
|
1
2
|
from collections.abc import Sequence
|
|
2
3
|
from typing import Annotated, Any, Literal, Self
|
|
3
4
|
from uuid import uuid4
|
|
4
5
|
|
|
5
|
-
from pydantic import
|
|
6
|
+
from pydantic import (
|
|
7
|
+
BaseModel,
|
|
8
|
+
ConfigDict,
|
|
9
|
+
Field,
|
|
10
|
+
StrictInt,
|
|
11
|
+
ValidationError,
|
|
12
|
+
create_model,
|
|
13
|
+
model_validator,
|
|
14
|
+
)
|
|
6
15
|
from sqlmodel import Session, and_, col, func, or_, select
|
|
7
16
|
|
|
8
17
|
from naos_api.clock import now_ts
|
|
9
18
|
from naos_api.errors import NotFoundError
|
|
10
19
|
from naos_api.lifecycle import RunStatus
|
|
11
|
-
from naos_api.models import AuditEvent, Lease, Run
|
|
20
|
+
from naos_api.models import MAX_INT, AuditEvent, Lease, Run
|
|
12
21
|
|
|
13
22
|
Actor = Literal["operator", "runner", "system"]
|
|
23
|
+
_EVENT_ID = re.compile(r"evt_[0-9a-f]{32}")
|
|
14
24
|
EventId = Annotated[str, Field(pattern=r"^evt_[0-9a-f]{32}$")]
|
|
15
25
|
Id = Annotated[str, Field(pattern=r"^[A-Za-z0-9_]{1,64}$")]
|
|
16
26
|
Name = Annotated[str, Field(max_length=256)]
|
|
17
27
|
Text = Annotated[str, Field(max_length=500)]
|
|
18
28
|
GuestPath = Annotated[str, Field(max_length=4096)]
|
|
19
|
-
Count = Annotated[StrictInt, Field(ge=0)]
|
|
29
|
+
Count = Annotated[StrictInt, Field(ge=0, le=MAX_INT)]
|
|
30
|
+
McpRule = Annotated[str, Field(pattern=r"^(none|[0-9]{1,6})$")]
|
|
20
31
|
|
|
21
32
|
API_EVENTS: dict[str, frozenset[str]] = {
|
|
22
33
|
"run_created": frozenset({"workspace", "profile"}),
|
|
@@ -59,6 +70,8 @@ API_EVENTS: dict[str, frozenset[str]] = {
|
|
|
59
70
|
"profile_deleted": frozenset({"profile_id", "name"}),
|
|
60
71
|
"console_attached": frozenset(),
|
|
61
72
|
"console_typing": frozenset({"view"}),
|
|
73
|
+
"operator_credential_issued": frozenset({"expires_at"}),
|
|
74
|
+
"operator_logged_out": frozenset(),
|
|
62
75
|
"runner_events_refused": frozenset({"count"}),
|
|
63
76
|
}
|
|
64
77
|
|
|
@@ -103,7 +116,7 @@ RUNNER_EVENTS: dict[str, dict[str, Any]] = {
|
|
|
103
116
|
"decision": Literal["allow", "deny"],
|
|
104
117
|
"duration_ms": Count,
|
|
105
118
|
"category": Name,
|
|
106
|
-
"rule":
|
|
119
|
+
"rule": McpRule,
|
|
107
120
|
},
|
|
108
121
|
"model_policy_configured": _RUN,
|
|
109
122
|
"model_attached": _RUN,
|
|
@@ -201,13 +214,18 @@ def transitioned(
|
|
|
201
214
|
)
|
|
202
215
|
|
|
203
216
|
|
|
204
|
-
def _held(session: Session, runner_id: str, run_ids: set[str]) -> set[str]:
|
|
217
|
+
def _held(session: Session, runner_id: str, run_ids: set[str], now: int) -> set[str]:
|
|
205
218
|
if not run_ids:
|
|
206
219
|
return set()
|
|
207
220
|
statement = (
|
|
208
221
|
select(Run.id)
|
|
209
222
|
.join(Lease, col(Run.lease_id) == col(Lease.id))
|
|
210
|
-
.where(
|
|
223
|
+
.where(
|
|
224
|
+
col(Lease.runner_id) == runner_id,
|
|
225
|
+
col(Lease.expired_at).is_(None),
|
|
226
|
+
col(Lease.expires_at) > now,
|
|
227
|
+
col(Run.id).in_(run_ids),
|
|
228
|
+
)
|
|
211
229
|
)
|
|
212
230
|
return set(session.exec(statement).all())
|
|
213
231
|
|
|
@@ -216,13 +234,33 @@ def _stored(session: Session, ids: list[str]) -> set[str]:
|
|
|
216
234
|
return set(session.exec(select(AuditEvent.id).where(col(AuditEvent.id).in_(ids))).all())
|
|
217
235
|
|
|
218
236
|
|
|
237
|
+
def parse_events(raw: Sequence[dict[str, Any]]) -> tuple[list[RunnerEventIn], list[str | None]]:
|
|
238
|
+
"""An invalid event is refused alone, so one guest-fed field cannot sink the batch."""
|
|
239
|
+
events: list[RunnerEventIn] = []
|
|
240
|
+
invalid: list[str | None] = []
|
|
241
|
+
for item in raw:
|
|
242
|
+
try:
|
|
243
|
+
events.append(RunnerEventIn.model_validate(item))
|
|
244
|
+
except ValidationError:
|
|
245
|
+
event_id = item.get("id")
|
|
246
|
+
valid_id = isinstance(event_id, str) and _EVENT_ID.fullmatch(event_id)
|
|
247
|
+
invalid.append(event_id if valid_id else None)
|
|
248
|
+
return events, invalid
|
|
249
|
+
|
|
250
|
+
|
|
219
251
|
def ingest(
|
|
220
|
-
session: Session,
|
|
252
|
+
session: Session,
|
|
253
|
+
runner_id: str,
|
|
254
|
+
events: Sequence[RunnerEventIn],
|
|
255
|
+
now: int,
|
|
256
|
+
invalid: Sequence[str | None] = (),
|
|
221
257
|
) -> tuple[int, list[str]]:
|
|
222
|
-
|
|
223
|
-
|
|
258
|
+
run_ids = {e.fields["run_id"] for e in events if "run_id" in e.fields}
|
|
259
|
+
held = _held(session, runner_id, run_ids, now)
|
|
260
|
+
foreign = [e.id for e in events if "run_id" in e.fields and e.fields["run_id"] not in held]
|
|
261
|
+
refused = foreign + [event_id for event_id in invalid if event_id]
|
|
224
262
|
for attempt in range(2):
|
|
225
|
-
seen = _stored(session, [event.id for event in events]) | set(
|
|
263
|
+
seen = _stored(session, [event.id for event in events]) | set(foreign)
|
|
226
264
|
received = now_ts()
|
|
227
265
|
accepted = 0
|
|
228
266
|
for event in events:
|
|
@@ -245,13 +283,13 @@ def ingest(
|
|
|
245
283
|
)
|
|
246
284
|
)
|
|
247
285
|
accepted += 1
|
|
248
|
-
if
|
|
286
|
+
if foreign or invalid:
|
|
249
287
|
record(
|
|
250
288
|
session,
|
|
251
289
|
"runner_events_refused",
|
|
252
290
|
actor="runner",
|
|
253
291
|
runner_id=runner_id,
|
|
254
|
-
count=len(
|
|
292
|
+
count=len(foreign) + len(invalid),
|
|
255
293
|
)
|
|
256
294
|
try:
|
|
257
295
|
session.commit()
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import hmac
|
|
2
|
-
from typing import Annotated
|
|
2
|
+
from typing import Annotated, Any
|
|
3
3
|
|
|
4
|
-
from fastapi import Depends, HTTPException, WebSocket, WebSocketException, status
|
|
4
|
+
from fastapi import Depends, HTTPException, Request, WebSocket, WebSocketException, status
|
|
5
5
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
6
6
|
from fastapi.security.utils import get_authorization_scheme_param
|
|
7
7
|
from sqlmodel import Session
|
|
8
|
+
from starlette.datastructures import Headers
|
|
9
|
+
from starlette.types import Scope
|
|
8
10
|
|
|
9
|
-
from naos_api import runners
|
|
11
|
+
from naos_api import credentials, runners
|
|
10
12
|
from naos_api.clock import NowDep
|
|
11
13
|
from naos_api.db import get_session, get_socket_session
|
|
12
14
|
from naos_api.runners import RunnerPrincipal, hash_token
|
|
@@ -36,23 +38,60 @@ def _operator_hash() -> str | None:
|
|
|
36
38
|
return get_settings().operator_token_sha256
|
|
37
39
|
|
|
38
40
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
+
# The operator token only logs in; it is refused on every other route.
|
|
42
|
+
def operator_login(token: str) -> bool:
|
|
43
|
+
expected = _operator_hash()
|
|
44
|
+
return expected is not None and hmac.compare_digest(hash_token(token), expected)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# Signed as sent: the raw path and query, the form every client has at hand.
|
|
48
|
+
def _target(scope: Scope) -> str:
|
|
49
|
+
path: bytes = scope.get("raw_path") or scope["path"].encode()
|
|
50
|
+
query: bytes = scope.get("query_string", b"")
|
|
51
|
+
target = path + b"?" + query if query else path
|
|
52
|
+
return target.decode("latin-1")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _signed(headers: Headers) -> credentials.Signed | None:
|
|
56
|
+
names = ("x-credential", "x-timestamp", "x-nonce", "x-signature")
|
|
57
|
+
values = [headers.get(name) for name in names]
|
|
58
|
+
if any(value is None for value in values):
|
|
59
|
+
return None
|
|
60
|
+
return credentials.Signed(*(str(value) for value in values))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _verified(
|
|
64
|
+
session: Session,
|
|
65
|
+
app_state: Any,
|
|
66
|
+
headers: Headers,
|
|
67
|
+
method: str,
|
|
68
|
+
target: str,
|
|
69
|
+
body: bytes,
|
|
70
|
+
now: int,
|
|
71
|
+
) -> bool:
|
|
72
|
+
signed = _signed(headers)
|
|
73
|
+
settings = get_settings()
|
|
74
|
+
return signed is not None and credentials.verify(
|
|
75
|
+
session, settings.master_keys, app_state.nonces, signed, method, target, body, now
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
async def require_principal(
|
|
80
|
+
request: Request, session: Annotated[Session, Depends(get_session)], now: NowDep
|
|
41
81
|
) -> None:
|
|
42
|
-
|
|
43
|
-
|
|
82
|
+
body = await request.body()
|
|
83
|
+
method, target = request.method, _target(request.scope)
|
|
84
|
+
if not _verified(session, request.app.state, request.headers, method, target, body, now):
|
|
85
|
+
raise _unauthorized("operator request is not signed")
|
|
44
86
|
|
|
45
87
|
|
|
46
88
|
def require_operator_connection(
|
|
47
|
-
websocket: WebSocket,
|
|
89
|
+
websocket: WebSocket,
|
|
90
|
+
session: Annotated[Session, Depends(get_socket_session)],
|
|
91
|
+
now: NowDep,
|
|
48
92
|
) -> None:
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
HTTPAuthorizationCredentials(scheme=scheme, credentials=token)
|
|
52
|
-
if scheme.lower() == "bearer" and token
|
|
53
|
-
else None
|
|
54
|
-
)
|
|
55
|
-
if not _matches(credentials, expected):
|
|
93
|
+
target = _target(websocket.scope)
|
|
94
|
+
if not _verified(session, websocket.app.state, websocket.headers, "GET", target, b"", now):
|
|
56
95
|
raise WebSocketException(status.WS_1008_POLICY_VIOLATION, "operator is not authorized")
|
|
57
96
|
|
|
58
97
|
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from fastapi import HTTPException
|
|
2
|
+
from starlette.datastructures import Headers
|
|
3
|
+
from starlette.responses import PlainTextResponse
|
|
4
|
+
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
|
5
|
+
|
|
6
|
+
MAX_BODY_BYTES = 32 * 1024 * 1024
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class BodyLimit:
|
|
10
|
+
"""Refuses a request body past the limit, declared or streamed, before a route parses it."""
|
|
11
|
+
|
|
12
|
+
def __init__(self, app: ASGIApp, limit: int = MAX_BODY_BYTES) -> None:
|
|
13
|
+
self.app = app
|
|
14
|
+
self.limit = limit
|
|
15
|
+
|
|
16
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
17
|
+
if scope["type"] != "http":
|
|
18
|
+
await self.app(scope, receive, send)
|
|
19
|
+
return
|
|
20
|
+
declared = Headers(scope=scope).get("content-length", "")
|
|
21
|
+
if declared and (not declared.isdigit() or int(declared) > self.limit):
|
|
22
|
+
await PlainTextResponse("request body too large", status_code=413)(scope, receive, send)
|
|
23
|
+
return
|
|
24
|
+
seen = 0
|
|
25
|
+
|
|
26
|
+
async def limited() -> Message:
|
|
27
|
+
nonlocal seen
|
|
28
|
+
message = await receive()
|
|
29
|
+
seen += len(message.get("body", b""))
|
|
30
|
+
if seen > self.limit:
|
|
31
|
+
raise HTTPException(413, "request body too large")
|
|
32
|
+
return message
|
|
33
|
+
|
|
34
|
+
await self.app(scope, limited, send)
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import ipaddress
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
import time
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
from typing import IO
|
|
11
|
+
|
|
12
|
+
from alembic.util import CommandError
|
|
13
|
+
|
|
14
|
+
from naos_api import credentials, schema
|
|
15
|
+
from naos_api.db import Database
|
|
16
|
+
from naos_api.settings import get_settings
|
|
17
|
+
|
|
18
|
+
STDIN = "-"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
22
|
+
# urllib carries the Authorization header to wherever a redirect points.
|
|
23
|
+
def redirect_request(self, *_: object) -> None:
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def main(argv: list[str] | None = None) -> int:
|
|
31
|
+
parser = argparse.ArgumentParser(prog="naos-api")
|
|
32
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
33
|
+
commands.add_parser("migrate", help="bring the database to the head revision")
|
|
34
|
+
commands.add_parser("downgrade", help="take the database one revision back")
|
|
35
|
+
sign = commands.add_parser("sign", help="print the headers that sign one operator request")
|
|
36
|
+
sign.add_argument("method")
|
|
37
|
+
sign.add_argument("target", help="the path with its query, as the request sends it")
|
|
38
|
+
sign.add_argument("--body", help="a file holding the request body, - for stdin")
|
|
39
|
+
sign.add_argument("--data", help="the request body itself")
|
|
40
|
+
sign.add_argument("--api", default=os.environ.get("NAOS_API_URL", "http://127.0.0.1:8080"))
|
|
41
|
+
sign.add_argument("--token-file", default=os.environ.get("NAOS_OPERATOR_TOKEN_FILE"))
|
|
42
|
+
args = parser.parse_args(argv)
|
|
43
|
+
if args.command == "sign":
|
|
44
|
+
return _sign(args)
|
|
45
|
+
|
|
46
|
+
db = Database(get_settings().database_url)
|
|
47
|
+
try:
|
|
48
|
+
if args.command == "migrate":
|
|
49
|
+
revision: str | None = schema.migrate(db.engine)
|
|
50
|
+
else:
|
|
51
|
+
revision = schema.downgrade(db.engine)
|
|
52
|
+
except (schema.SchemaError, CommandError) as err:
|
|
53
|
+
print(f"naos-api: {err}", file=sys.stderr)
|
|
54
|
+
return 1
|
|
55
|
+
finally:
|
|
56
|
+
db.engine.dispose()
|
|
57
|
+
print(f"database at {revision or 'base'}")
|
|
58
|
+
return 0
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _api_url(raw: str) -> str | None:
|
|
62
|
+
"""The api the token may go to: https, or plain http to this host only."""
|
|
63
|
+
try:
|
|
64
|
+
url = urllib.parse.urlsplit(raw)
|
|
65
|
+
host = url.hostname or ""
|
|
66
|
+
url.port # noqa: B018 raises on a port that is not a number
|
|
67
|
+
except ValueError:
|
|
68
|
+
return None
|
|
69
|
+
if not host or url.username is not None or url.query or url.fragment:
|
|
70
|
+
return None
|
|
71
|
+
if url.scheme == "https":
|
|
72
|
+
return raw.rstrip("/")
|
|
73
|
+
try:
|
|
74
|
+
loopback = host == "localhost" or ipaddress.ip_address(host).is_loopback
|
|
75
|
+
except ValueError:
|
|
76
|
+
loopback = False
|
|
77
|
+
return raw.rstrip("/") if url.scheme == "http" and loopback else None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _open(request: urllib.request.Request, timeout: float) -> IO[bytes]:
|
|
81
|
+
answer: IO[bytes] = _OPENER.open(request, timeout=timeout)
|
|
82
|
+
return answer
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# Logs in with the operator token and prints the headers, one per line, ready for curl -H.
|
|
86
|
+
def _sign(args: argparse.Namespace) -> int:
|
|
87
|
+
api = _api_url(args.api)
|
|
88
|
+
if api is None:
|
|
89
|
+
print("naos-api: --api is an https url, or http to localhost", file=sys.stderr)
|
|
90
|
+
return 1
|
|
91
|
+
if not args.token_file:
|
|
92
|
+
print(
|
|
93
|
+
"naos-api: --token-file or NAOS_OPERATOR_TOKEN_FILE names the operator token",
|
|
94
|
+
file=sys.stderr,
|
|
95
|
+
)
|
|
96
|
+
return 1
|
|
97
|
+
from_stdin = args.token_file == STDIN
|
|
98
|
+
if from_stdin and args.body == STDIN:
|
|
99
|
+
print("naos-api: only one of the token and the body can come on stdin", file=sys.stderr)
|
|
100
|
+
return 1
|
|
101
|
+
if from_stdin:
|
|
102
|
+
token = sys.stdin.read().strip()
|
|
103
|
+
else:
|
|
104
|
+
with open(args.token_file) as file:
|
|
105
|
+
token = file.read().strip()
|
|
106
|
+
body = (args.data or "").encode()
|
|
107
|
+
if args.body == STDIN:
|
|
108
|
+
body = sys.stdin.buffer.read()
|
|
109
|
+
elif args.body:
|
|
110
|
+
with open(args.body, "rb") as file:
|
|
111
|
+
body = file.read()
|
|
112
|
+
login = urllib.request.Request( # noqa: S310 _api_url allowed only https or loopback http
|
|
113
|
+
f"{api}/api/v1/auth/credential",
|
|
114
|
+
method="POST",
|
|
115
|
+
headers={"Authorization": f"Bearer {token}"},
|
|
116
|
+
)
|
|
117
|
+
try:
|
|
118
|
+
with _open(login, timeout=10) as answer:
|
|
119
|
+
issued = credentials.Issued(**json.load(answer))
|
|
120
|
+
except (urllib.error.URLError, ValueError, TypeError) as err:
|
|
121
|
+
print(f"naos-api: the api refused the login: {err}", file=sys.stderr)
|
|
122
|
+
return 1
|
|
123
|
+
for name, value in credentials.headers(
|
|
124
|
+
issued, args.method, args.target, body, int(time.time())
|
|
125
|
+
).items():
|
|
126
|
+
print(f"{name}: {value}")
|
|
127
|
+
return 0
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from collections.abc import Callable
|
|
3
|
+
from typing import Annotated
|
|
4
|
+
|
|
5
|
+
from fastapi import Depends, FastAPI
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def now_ts() -> int:
|
|
9
|
+
"""Seconds since the Unix epoch, UTC. The only time source in the API."""
|
|
10
|
+
return int(time.time())
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def get_now() -> int:
|
|
14
|
+
return now_ts()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
NowDep = Annotated[int, Depends(get_now)]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# A socket outlives the request that opened it, so it reads the time the way a route would.
|
|
21
|
+
def clock_of(app: FastAPI) -> Callable[[], int]:
|
|
22
|
+
clock: Callable[[], int] = app.dependency_overrides.get(get_now, get_now)
|
|
23
|
+
return clock
|