- ApiAdminController: GET /me; GET|POST /namespaces; GET|POST /principals, GET|PATCH /principals/:id, POST /principals/:id/keys, DELETE /keys/:id; GET|POST /grants, DELETE /grants/:id. - Authorization from namespace grants (ADR-011): admin allows granting and creating below; inherit needs inheriting admin; managing another principal's keys/status needs admin over all of its grants, so a key never widens the caller's access. Keys shown once, no-store. - tests/admin-api.sh (91 checks incl. escalation and isolation attempts). - OpenAPI, README, AGENTS.md, acceptance report updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>graph-relationships
| @@ -39,11 +39,12 @@ When unsure about an object, ProgID, method or config key, check `/opt/axonasp/w | |||||
| - Semantic retrieval: `core/lib.Embeddings.asp` (Ollama client, Qdrant client, `embedding_index` bookkeeping, `Ranker_Class` used by recall/search/context; it also applies usefulness feedback on the current revision, see `ApplyFeedback`). Write paths call `Emb_MarkPending`/`Emb_MarkDelete*` inside their transaction and `Emb_AfterWrite` after commit; new write paths that change memory or chunk text must do the same. `scripts\embed.cmd status|run|reindex`. Regression suite: `bash tests/phase3-semantic.sh`. The `embed-worker` container runs `scripts/embed.asp` (`EMBED_ACTION=worker`) every 30 seconds to retry pending/failed items. | - Semantic retrieval: `core/lib.Embeddings.asp` (Ollama client, Qdrant client, `embedding_index` bookkeeping, `Ranker_Class` used by recall/search/context; it also applies usefulness feedback on the current revision, see `ApplyFeedback`). Write paths call `Emb_MarkPending`/`Emb_MarkDelete*` inside their transaction and `Emb_AfterWrite` after commit; new write paths that change memory or chunk text must do the same. `scripts\embed.cmd status|run|reindex`. Regression suite: `bash tests/phase3-semantic.sh`. The `embed-worker` container runs `scripts/embed.asp` (`EMBED_ACTION=worker`) every 30 seconds to retry pending/failed items. | ||||
| - Learning loop: `ApiLearningController` (session events, `POST /learn`, candidates, review, `GET /memories/:id/sources`, `POST /feedback`) with helpers in `core/lib.Learning.asp`: `Evidence_Class` (validate, resolve and pin evidence), `Mem_Create`/`Mem_Revise`/`Mem_Verify` (memory writes shared with review; inside a transaction), `Mem_ForgetLinked` (called by forget), and `Tel_*` (retrieval telemetry: recall/search/context must record the `query_id` they return and the revision of each result, or feedback cannot reference them). Review needs `verify` and is refused to the author without `admin`. New tenant-scoped tables must also be deleted by `provision purge`. Regression suite: `bash tests/phase3-learning.sh`. | - Learning loop: `ApiLearningController` (session events, `POST /learn`, candidates, review, `GET /memories/:id/sources`, `POST /feedback`) with helpers in `core/lib.Learning.asp`: `Evidence_Class` (validate, resolve and pin evidence), `Mem_Create`/`Mem_Revise`/`Mem_Verify` (memory writes shared with review; inside a transaction), `Mem_ForgetLinked` (called by forget), and `Tel_*` (retrieval telemetry: recall/search/context must record the `query_id` they return and the revision of each result, or feedback cannot reference them). Review needs `verify` and is refused to the author without `admin`. New tenant-scoped tables must also be deleted by `provision purge`. Regression suite: `bash tests/phase3-learning.sh`. | ||||
| - Ingestion jobs: `core/lib.Jobs.asp` (`Job_Create`, `Job_Claim`, `Job_RunIngest`, `Job_ProcessDue`), shared by `ApiDocumentsController.Ingest` and the worker (`scripts/embed.asp`, actions `jobs` and `worker`). Claim jobs only with `Job_Claim` (conditional UPDATE) and keep publishing plus the job update in one transaction. Regression suite: `bash tests/phase3-jobs.sh` (uses `tests/fixtures/job_state.asp` to simulate interruptions). | - Ingestion jobs: `core/lib.Jobs.asp` (`Job_Create`, `Job_Claim`, `Job_RunIngest`, `Job_ProcessDue`), shared by `ApiDocumentsController.Ingest` and the worker (`scripts/embed.asp`, actions `jobs` and `worker`). Claim jobs only with `Job_Claim` (conditional UPDATE) and keep publishing plus the job update in one transaction. Regression suite: `bash tests/phase3-jobs.sh` (uses `tests/fixtures/job_state.asp` to simulate interruptions). | ||||
| - Management: `ApiAdminController` (`/me`, `/namespaces`, `/principals`, `/principals/:id/keys`, `/keys/:id`, `/grants`). Authorization is path-based through `Api_PathAllows`: creating below a namespace or granting with inherit needs an inheriting admin grant (checked with the probe path `<path>/*`), and `CanManage` (keys, status) needs admin over every grant of the target, so new endpoints that hand out credentials or access must keep that rule (ADR-011). Do not add Idempotency-Key support to endpoints that return a key: the stored replay would contain the plain key. Regression suite: `bash tests/admin-api.sh`. | |||||
| - Portability: `ApiPortabilityController` (`POST /exports`, `POST /imports`). The export format (`agent-memory-export`, `schema_version` 1) is a contract: a new canonical table or column means a new schema version (and an importer for the old one), and the import must keep ids, revisions, timestamps and principal ids, rebuild derived data (content hashes, FTS, `Emb_MarkPending`) and stay all-or-nothing. Author ids unknown to the target get placeholder principals (`Api_EnsureReferencedPrincipals`, status `imported`, never authenticates) inside the import transaction. Regression suite: `bash tests/phase3-portability.sh`. | - Portability: `ApiPortabilityController` (`POST /exports`, `POST /imports`). The export format (`agent-memory-export`, `schema_version` 1) is a contract: a new canonical table or column means a new schema version (and an importer for the old one), and the import must keep ids, revisions, timestamps and principal ids, rebuild derived data (content hashes, FTS, `Emb_MarkPending`) and stay all-or-nothing. Author ids unknown to the target get placeholder principals (`Api_EnsureReferencedPrincipals`, status `imported`, never authenticates) inside the import transaction. Regression suite: `bash tests/phase3-portability.sh`. | ||||
| - Backup/restore: `scripts\backup.cmd backup|verify|repair` and `scripts\restore.cmd <file>` (`scripts/backup.asp`; see README "Operations"). Backups go to `db/backups/` (git-ignored). `bash tests/backup-restore.sh` restores into an isolated container on port 8802 and never touches the live database. Never run `restore.cmd` against the live database without the user's go-ahead. | - Backup/restore: `scripts\backup.cmd backup|verify|repair` and `scripts\restore.cmd <file>` (`scripts/backup.asp`; see README "Operations"). Backups go to `db/backups/` (git-ignored). `bash tests/backup-restore.sh` restores into an isolated container on port 8802 and never touches the live database. Never run `restore.cmd` against the live database without the user's go-ahead. | ||||
| - Observability: `core/lib.Observability.asp` (included before `lib.Api.asp`). `Api_Send` calls `Obs_Record` once per response (access-log line via `console.log`, counters in `Application`); `MVC_InvokeAction` sets `Obs_Action`, so metric labels are controller actions, never raw paths. A response written without `Api_Send` must call `Obs_Record status` itself (as `ApiHealthController.Metrics` does). Never log bodies, query strings or keys. `GET /api/v1/metrics` needs `AMK_METRICS_TOKEN` (`.env`, git-ignored). Regression suite: `bash tests/observability.sh`. | - Observability: `core/lib.Observability.asp` (included before `lib.Api.asp`). `Api_Send` calls `Obs_Record` once per response (access-log line via `console.log`, counters in `Application`); `MVC_InvokeAction` sets `Obs_Action`, so metric labels are controller actions, never raw paths. A response written without `Api_Send` must call `Obs_Record status` itself (as `ApiHealthController.Metrics` does). Never log bodies, query strings or keys. `GET /api/v1/metrics` needs `AMK_METRICS_TOKEN` (`.env`, git-ignored). Regression suite: `bash tests/observability.sh`. | ||||
| - Retrieval benchmark: `bash tests/retrieval-benchmark.sh` (corpus, labelled queries and thresholds in `tests/benchmark/fixtures.json`, driver `tests/benchmark/run_benchmark.py`). Rerun it after any change to ranking, the embedding model, `EmbeddingMinScore` or the FTS query; never lower a threshold to make it pass (record a decision in `docs/decisions.md` instead). `docs/acceptance.md` is the acceptance report: update its evidence table and criteria mapping when suites or checks change. | - Retrieval benchmark: `bash tests/retrieval-benchmark.sh` (corpus, labelled queries and thresholds in `tests/benchmark/fixtures.json`, driver `tests/benchmark/run_benchmark.py`). Rerun it after any change to ranking, the embedding model, `EmbeddingMinScore` or the FTS query; never lower a threshold to make it pass (record a decision in `docs/decisions.md` instead). `docs/acceptance.md` is the acceptance report: update its evidence table and criteria mapping when suites or checks change. | ||||
| - The AxonASP image is pinned by digest in `docker-compose.yml`. To upgrade, change the digest deliberately, `docker compose up -d`, and rerun all ten suites (`tests/*.sh`). | |||||
| - The AxonASP image is pinned by digest in `docker-compose.yml`. To upgrade, change the digest deliberately, `docker compose up -d`, and rerun all eleven suites (`tests/*.sh`). | |||||
| ### This repo's own knowledge base (dogfooding) | ### This repo's own knowledge base (dogfooding) | ||||
| @@ -61,6 +61,7 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec | |||||
| - Phase 3 (part): learning loop. Agents record experiences in a session (`POST /sessions/:id/events`) and propose knowledge with evidence (`POST /learn`: a new memory, or a new revision of `target_memory_id` at `base_revision`). Another principal with `verify` reviews it (`POST /candidates/:id/review`); the author cannot approve its own candidate without `admin`. Accepting creates the memory (an identical active one is reused), or revises the target if it has not changed meanwhile (else 409 `stale_candidate`), copies the evidence with pinned target revisions and, with `"verify": true`, records a verification. `GET /memories/:id/sources` shows evidence and verifications per revision (evidence the caller cannot read is shown as `available: false`, without its id). Recall, search and context return a `query_id` and record the returned results and revisions (the query text is kept only as a hash); `POST /feedback` rates one result (useful, not_useful, incorrect, harmful). Ratings on a result's current revision adjust its rank in recall, search and context (useful raises it, incorrect/harmful halve its score per rating); results show their `feedback` counts and a warning names demoted results. A corrected memory starts without feedback. Forgetting a memory removes its evidence, verifications, feedback and telemetry rows. | - Phase 3 (part): learning loop. Agents record experiences in a session (`POST /sessions/:id/events`) and propose knowledge with evidence (`POST /learn`: a new memory, or a new revision of `target_memory_id` at `base_revision`). Another principal with `verify` reviews it (`POST /candidates/:id/review`); the author cannot approve its own candidate without `admin`. Accepting creates the memory (an identical active one is reused), or revises the target if it has not changed meanwhile (else 409 `stale_candidate`), copies the evidence with pinned target revisions and, with `"verify": true`, records a verification. `GET /memories/:id/sources` shows evidence and verifications per revision (evidence the caller cannot read is shown as `available: false`, without its id). Recall, search and context return a `query_id` and record the returned results and revisions (the query text is kept only as a hash); `POST /feedback` rates one result (useful, not_useful, incorrect, harmful). Ratings on a result's current revision adjust its rank in recall, search and context (useful raises it, incorrect/harmful halve its score per rating); results show their `feedback` counts and a warning names demoted results. A corrected memory starts without feedback. Forgetting a memory removes its evidence, verifications, feedback and telemetry rows. | ||||
| - Durable ingestion jobs: `POST /ingestion/jobs` stores the job and its input before processing, so nothing acknowledged is lost. By default it is processed inside the request (201, or 200 when unchanged); with `"async": true` the answer is 202 with the job and the embed-worker publishes it. A job interrupted mid-ingest (lease of 5 minutes) or failed with an internal error is retried by the worker, at most 3 attempts; other failures (unreadable input, namespace gone, permission lost, re-checked at processing time) wait for `POST /jobs/:id/retry`. Identical text is a no-op and publishing happens in one transaction with the job update, so retries and duplicate submissions never publish duplicate chunks. `GET /jobs/:id` shows state, attempts, `auto_retry` and the error. | - Durable ingestion jobs: `POST /ingestion/jobs` stores the job and its input before processing, so nothing acknowledged is lost. By default it is processed inside the request (201, or 200 when unchanged); with `"async": true` the answer is 202 with the job and the embed-worker publishes it. A job interrupted mid-ingest (lease of 5 minutes) or failed with an internal error is retried by the worker, at most 3 attempts; other failures (unreadable input, namespace gone, permission lost, re-checked at processing time) wait for `POST /jobs/:id/retry`. Identical text is a no-op and publishing happens in one transaction with the job update, so retries and duplicate submissions never publish duplicate chunks. `GET /jobs/:id` shows state, attempts, `auto_retry` and the error. | ||||
| - Portability: `POST /exports` writes a canonical JSON document (`format` `agent-memory-export`, `schema_version` 1, SHA-256 `integrity.digest` over the exact `data` text) with every namespace the caller can read, or the `namespace_ids` asked for: memories with all revisions and verifications, documents with revisions and chunks, and evidence links (links to targets the caller cannot read are left out and counted). Ids, revision numbers, timestamps and principal ids are kept. `POST /imports` takes that document unchanged (max 8 MiB): it needs `admin` on every target namespace (matched by path; they must exist), rebuilds content hashes and lexical indexes and queues embeddings, and is all-or-nothing (409 `import_conflict` when an id exists, 422 for a wrong format, `unsupported_schema_version` or `integrity_mismatch`). Re-exporting imported data gives the same `data`. Not in version 1: sessions, experiences, candidates, feedback, telemetry, audit events. | - Portability: `POST /exports` writes a canonical JSON document (`format` `agent-memory-export`, `schema_version` 1, SHA-256 `integrity.digest` over the exact `data` text) with every namespace the caller can read, or the `namespace_ids` asked for: memories with all revisions and verifications, documents with revisions and chunks, and evidence links (links to targets the caller cannot read are left out and counted). Ids, revision numbers, timestamps and principal ids are kept. `POST /imports` takes that document unchanged (max 8 MiB): it needs `admin` on every target namespace (matched by path; they must exist), rebuilds content hashes and lexical indexes and queues embeddings, and is all-or-nothing (409 `import_conflict` when an id exists, 422 for a wrong format, `unsupported_schema_version` or `integrity_mismatch`). Re-exporting imported data gives the same `data`. Not in version 1: sessions, experiences, candidates, feedback, telemetry, audit events. | ||||
| - Management API: `GET /me`; `GET|POST /namespaces`; `GET|POST /principals`, `GET|PATCH /principals/:id`, `POST /principals/:id/keys`, `DELETE /keys/:id`; `GET|POST /grants`, `DELETE /grants/:id`. `admin` on a namespace lets a caller create namespaces below it and grant or revoke access there; a principal's keys and status can only be managed by someone who holds admin wherever that principal has access, so a new key never widens the caller's access (see [docs/decisions.md](docs/decisions.md) ADR-011). New keys are returned once. Tenants, top-level namespaces and purges stay with `provision.cmd` / `ops.sh provision`. | |||||
| - Backup and restore: `scripts\backup.cmd` (see Operations below). | - Backup and restore: `scripts\backup.cmd` (see Operations below). | ||||
| - Observability: every API response carries `X-Request-Id` (a caller's own `X-Request-Id` of 8-64 characters `[A-Za-z0-9._:-]` is kept for correlation; it also appears in error bodies and audit events) and writes one JSON access-log line to stdout: request id, method, controller action, status, duration, tenant and principal ids. Bodies, query strings and keys are never logged. `GET /api/v1/metrics` serves Prometheus text: request counters and a latency histogram per action (in process memory, reset by a restart), and installation-wide counts of memories, candidates, jobs, embedding index states, retrieval calls (with empty results and total time) and feedback. It needs the `AMK_METRICS_TOKEN` bearer token and answers 404 while that is unset. | - Observability: every API response carries `X-Request-Id` (a caller's own `X-Request-Id` of 8-64 characters `[A-Za-z0-9._:-]` is kept for correlation; it also appears in error bodies and audit events) and writes one JSON access-log line to stdout: request id, method, controller action, status, duration, tenant and principal ids. Bodies, query strings and keys are never logged. `GET /api/v1/metrics` serves Prometheus text: request counters and a latency histogram per action (in process memory, reset by a restart), and installation-wide counts of memories, candidates, jobs, embedding index states, retrieval calls (with empty results and total time) and feedback. It needs the `AMK_METRICS_TOKEN` bearer token and answers 404 while that is unset. | ||||
| @@ -68,16 +69,15 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec | |||||
| - Characters above U+FFFF (emoji) are rejected with 422 `unsupported_character`: the pinned AxonASP build cannot hold them (see AGENTS.md section 8). | - Characters above U+FFFF (emoji) are rejected with 422 `unsupported_character`: the pinned AxonASP build cannot hold them (see AGENTS.md section 8). | ||||
| **Tooling** | **Tooling** | ||||
| - `scripts\provision.cmd` (tenant, principal, key, namespace, grant, revoke, list, purge); see AGENTS.md section 1. Quote permission lists in PowerShell: `'"read,write"'`. | |||||
| - `scripts\provision.cmd` (tenant, principal, key, namespace, grant, revoke, list, purge); see AGENTS.md section 1. Needed for tenants, the first admin of a tenant and top-level namespaces; the rest can go through the management API. Quote permission lists in PowerShell: `'"read,write"'`. | |||||
| - `scripts\export-memories.ps1` / `scripts/export-memories.sh`: dump every readable memory (set `AMK_KEY`). | - `scripts\export-memories.ps1` / `scripts/export-memories.sh`: dump every readable memory (set `AMK_KEY`). | ||||
| - `scripts/ops.sh`: the same tools for a Linux server (migrate, provision, embed, backup, verify, restore, repair). | - `scripts/ops.sh`: the same tools for a Linux server (migrate, provision, embed, backup, verify, restore, repair). | ||||
| - `scripts\embed.cmd status|run|reindex`: semantic index status, catch up on pending/failed items, or rebuild (after changing the model). | - `scripts\embed.cmd status|run|reindex`: semantic index status, catch up on pending/failed items, or rebuild (after changing the model). | ||||
| - Tests (containers must be running): `bash tests/phase1-api.sh` (79 checks), `bash tests/phase2-api.sh` (45), `bash tests/phase3-context.sh` (60), `bash tests/phase3-semantic.sh` (30; stops and restarts the ollama container once), `bash tests/phase3-learning.sh` (93), `bash tests/phase3-portability.sh` (47), `bash tests/backup-restore.sh` (21; starts a throw-away container on port 8802), `bash tests/phase3-jobs.sh` (41; stops the embed-worker container while it runs), `bash tests/observability.sh` (25; restarts the container; the metrics checks need `AMK_METRICS_TOKEN`), `bash tests/retrieval-benchmark.sh` (5 threshold checks over 56 labelled queries; stops and restarts the ollama container). Each creates and purges its own tenants. | |||||
| - Tests (containers must be running): `bash tests/phase1-api.sh` (79 checks), `bash tests/phase2-api.sh` (45), `bash tests/phase3-context.sh` (60), `bash tests/phase3-semantic.sh` (30; stops and restarts the ollama container once), `bash tests/phase3-learning.sh` (93), `bash tests/phase3-portability.sh` (47), `bash tests/backup-restore.sh` (21; starts a throw-away container on port 8802), `bash tests/phase3-jobs.sh` (41; stops the embed-worker container while it runs), `bash tests/observability.sh` (25; restarts the container; the metrics checks need `AMK_METRICS_TOKEN`), `bash tests/admin-api.sh` (91), `bash tests/retrieval-benchmark.sh` (5 threshold checks over 56 labelled queries; stops and restarts the ollama container). Each creates and purges its own tenants. | |||||
| - Acceptance: [docs/acceptance.md](docs/acceptance.md) maps every MVP acceptance criterion (AC-01 to AC-18) to its automated checks and a manual verification, with the benchmark results and what is not tested. Architecture decisions: [docs/decisions.md](docs/decisions.md). | - Acceptance: [docs/acceptance.md](docs/acceptance.md) maps every MVP acceptance criterion (AC-01 to AC-18) to its automated checks and a manual verification, with the benchmark results and what is not tested. Architecture decisions: [docs/decisions.md](docs/decisions.md). | ||||
| **Next (not started)** | **Next (not started)** | ||||
| 1. Consolidation of related experiences into candidates (today agents propose them by hand with `POST /learn`). | 1. Consolidation of related experiences into candidates (today agents propose them by hand with `POST /learn`). | ||||
| 2. Management endpoints for namespaces, principals and grants (today only via `provision.cmd`). | |||||
| ## Operations: backup and restore | ## Operations: backup and restore | ||||
| @@ -0,0 +1,872 @@ | |||||
| <% | |||||
| ' ApiAdminController: management of namespaces, principals, API keys and grants inside the caller's tenant | |||||
| ' (spec section 9 "Management", FR-017, section 16 least privilege). Replaces scripts\provision.cmd for day-to-day work; | |||||
| ' tenants, top-level namespaces and purges stay with the CLI. | |||||
| ' | |||||
| ' GET /api/v1/me WhoAmI the caller: principal, tenant, grants | |||||
| ' GET /api/v1/namespaces Namespaces namespaces the caller can read, with its permissions on each | |||||
| ' POST /api/v1/namespaces CreateNamespace {"path":"/a/b"} (missing parents are created) | |||||
| ' GET /api/v1/principals Principals principals of the tenant (admins only) | |||||
| ' POST /api/v1/principals CreatePrincipal {"name","type":"human|agent|service"} -> principal + API key (once) | |||||
| ' GET /api/v1/principals/:id Principal principal, its keys (when manageable) and grants | |||||
| ' PATCH /api/v1/principals/:id UpdatePrincipal {"status":"active|disabled"} | |||||
| ' POST /api/v1/principals/:id/keys CreateKey new API key (shown once) | |||||
| ' DELETE /api/v1/keys/:id RevokeKey | |||||
| ' GET /api/v1/grants Grants ?namespace_id=&principal_id= (grants the caller administers) | |||||
| ' POST /api/v1/grants CreateGrant {"principal_id","namespace_id","permissions":[...],"inherit":true, | |||||
| ' "expires_at":"YYYY-MM-DD HH:MM:SS"} | |||||
| ' DELETE /api/v1/grants/:id DeleteGrant | |||||
| ' | |||||
| ' Authorization (docs/decisions.md ADR-011): | |||||
| ' - "admin" on a namespace lets the caller create namespaces below it, and grant or revoke access on it. Granting with | |||||
| ' inherit, or creating a namespace below, needs an inheriting admin grant (one that also covers descendants). | |||||
| ' - Listing principals and creating one needs admin on at least one namespace. | |||||
| ' - Managing another principal (keys, status) needs admin on every namespace that principal holds a grant on, | |||||
| ' inheriting where that grant inherits, so a key can never give the caller more access than it already has. | |||||
| ' Callers may always manage their own keys. Placeholder principals from imports cannot be managed. | |||||
| ' - No permission answers 404, as everywhere in the API. Responses that contain a key are sent with no-store. | |||||
| ' - Idempotency-Key is not supported on these endpoints: a replay would have to store the plain key. | |||||
| Const ADM_PERMS = ",read,write,delete,verify,admin," | |||||
| Class ApiAdminController_Class | |||||
| Private m_errs | |||||
| Public Property Get useLayout() | |||||
| useLayout = False | |||||
| End Property | |||||
| Public Property Let useLayout(v) | |||||
| End Property | |||||
| Public Property Get Title() | |||||
| Title = "Admin API" | |||||
| End Property | |||||
| '--------------------------------------------------------------- | |||||
| ' GET /api/v1/me | |||||
| '--------------------------------------------------------------- | |||||
| Public Sub WhoAmI() | |||||
| Dim rs, name, pType, out | |||||
| If Not Api_Authenticate() Then Exit Sub | |||||
| Set rs = DAL().Query("SELECT name, type FROM principals WHERE id = ?", Api_PrincipalId) | |||||
| name = "" & rs(0) | |||||
| pType = "" & rs(1) | |||||
| rs.Close | |||||
| out = "{""principal_id"":" & JsonLite_Quote(Api_PrincipalId) & ",""tenant_id"":" & JsonLite_Quote(Api_TenantId) & _ | |||||
| ",""name"":" & JsonLite_Quote(name) & ",""type"":" & JsonLite_Quote(pType) & _ | |||||
| ",""grants"":" & GrantsJson("g.principal_id = ?", Api_PrincipalId) & "}" | |||||
| Api_Send 200, out | |||||
| End Sub | |||||
| '--------------------------------------------------------------- | |||||
| ' GET /api/v1/namespaces | |||||
| '--------------------------------------------------------------- | |||||
| Public Sub Namespaces() | |||||
| Dim readable, perms(), names, i, rs, out, id, p | |||||
| If Not Api_Authenticate() Then Exit Sub | |||||
| readable = Api_AllowedNamespaceIds("read") | |||||
| If Len(readable) = 0 Then | |||||
| Api_Send 200, "{""data"":[]}" | |||||
| Exit Sub | |||||
| End If | |||||
| names = Array("read", "write", "delete", "verify", "admin") | |||||
| ReDim perms(4) | |||||
| For i = 0 To 4 | |||||
| perms(i) = "," & Api_AllowedNamespaceIds(names(i)) & "," | |||||
| Next | |||||
| out = "" | |||||
| Set rs = DAL().Query("SELECT id, path, parent_id, created_at FROM namespaces WHERE tenant_id = ? AND id IN (" & readable & ") ORDER BY path", Api_TenantId) | |||||
| Do While Not rs.EOF | |||||
| id = "" & rs(0) | |||||
| p = "" | |||||
| For i = 0 To 4 | |||||
| If InStr(perms(i), ",'" & id & "',") > 0 Then | |||||
| If Len(p) > 0 Then | |||||
| p = p & "," | |||||
| End If | |||||
| p = p & JsonLite_Quote(names(i)) | |||||
| End If | |||||
| Next | |||||
| If Len(out) > 0 Then | |||||
| out = out & "," | |||||
| End If | |||||
| out = out & "{""id"":" & JsonLite_Quote(id) & ",""path"":" & JsonLite_Quote("" & rs(1)) & _ | |||||
| ",""parent_id"":" & JStr(rs(2)) & ",""permissions"":[" & p & "],""created_at"":" & JsonLite_Quote("" & rs(3)) & "}" | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| Api_Send 200, "{""data"":[" & out & "]}" | |||||
| End Sub | |||||
| '--------------------------------------------------------------- | |||||
| ' POST /api/v1/namespaces {"path":"/a/b"} | |||||
| '--------------------------------------------------------------- | |||||
| Public Sub CreateNamespace() | |||||
| Dim body, input, path, rs, parts, i, cur, parentId, id, created, k, existing | |||||
| If Not Api_Authenticate() Then Exit Sub | |||||
| body = Api_ReadBody() | |||||
| If IsEmpty(body) Then Exit Sub | |||||
| Set input = JsonLite_Parse(body) | |||||
| m_errs = "" | |||||
| path = LCase(ReqString(input, "path", 400)) | |||||
| If Len(m_errs) = 0 Then | |||||
| If Not ValidPath(path) Then | |||||
| AddErr "path must look like /team/project: lower-case a-z, 0-9, '-', '_' and '.', separated by '/'." | |||||
| End If | |||||
| End If | |||||
| If Len(m_errs) > 0 Then | |||||
| Api_Invalid Split(m_errs, Chr(30)) | |||||
| Exit Sub | |||||
| End If | |||||
| ' The new namespace must be covered by an inheriting admin grant of the caller. | |||||
| If Not Api_PathAllows(path, "admin") Then | |||||
| Api_Audit "admin.namespace.create", "namespace", "", "denied" | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| Set rs = DAL().Query("SELECT id FROM namespaces WHERE tenant_id = ? AND path = ?", Array(Api_TenantId, path)) | |||||
| existing = "" | |||||
| If Not rs.EOF Then | |||||
| existing = "" & rs(0) | |||||
| End If | |||||
| rs.Close | |||||
| If Len(existing) > 0 Then | |||||
| Api_Error 409, "namespace_exists", "A namespace with this path already exists (" & existing & ")." | |||||
| Exit Sub | |||||
| End If | |||||
| parts = Split(Mid(path, 2), "/") | |||||
| cur = "" | |||||
| parentId = Null | |||||
| created = 0 | |||||
| On Error Resume Next | |||||
| DAL().BeginTransaction | |||||
| For i = 0 To UBound(parts) | |||||
| cur = cur & "/" & parts(i) | |||||
| Set rs = DAL().Query("SELECT id FROM namespaces WHERE tenant_id = ? AND path = ?", Array(Api_TenantId, cur)) | |||||
| id = "" | |||||
| If Err.Number = 0 Then | |||||
| If Not rs.EOF Then | |||||
| id = "" & rs(0) | |||||
| End If | |||||
| rs.Close | |||||
| End If | |||||
| If Err.Number <> 0 Then | |||||
| Exit For | |||||
| End If | |||||
| If Len(id) = 0 Then | |||||
| id = Api_NewId() | |||||
| DAL().Execute "INSERT INTO namespaces (id, tenant_id, parent_id, name, path, owner_principal_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)", _ | |||||
| Array(id, Api_TenantId, parentId, parts(i), cur, Api_PrincipalId, Api_Now()) | |||||
| If Err.Number <> 0 Then | |||||
| Exit For | |||||
| End If | |||||
| created = created + 1 | |||||
| End If | |||||
| parentId = id | |||||
| Next | |||||
| If Err.Number <> 0 Then | |||||
| k = Err.Number : Api_NoteDbError | |||||
| Err.Clear | |||||
| DAL().RollbackTransaction | |||||
| Api_DbFailed k, "" | |||||
| Exit Sub | |||||
| End If | |||||
| DAL().CommitTransaction | |||||
| If Err.Number <> 0 Then | |||||
| k = Err.Number : Api_NoteDbError | |||||
| Api_DbFailed k, "" | |||||
| Exit Sub | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| Api_Audit "admin.namespace.create", "namespace", id, "ok" | |||||
| Response.AddHeader "Location", "/api/v1/namespaces" | |||||
| Api_Send 201, "{""id"":" & JsonLite_Quote(id) & ",""path"":" & JsonLite_Quote(path) & ",""parent_id"":" & JStr(parentAt(path)) & _ | |||||
| ",""namespaces_created"":" & created & "}" | |||||
| End Sub | |||||
| '--------------------------------------------------------------- | |||||
| ' GET /api/v1/principals | |||||
| '--------------------------------------------------------------- | |||||
| Public Sub Principals() | |||||
| Dim rs, out | |||||
| If Not Api_Authenticate() Then Exit Sub | |||||
| If Len(Api_AllowedNamespaceIds("admin")) = 0 Then | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| out = "" | |||||
| Set rs = DAL().Query("SELECT id, name, type, status, created_at FROM principals WHERE tenant_id = ? ORDER BY created_at, id", Api_TenantId) | |||||
| Do While Not rs.EOF | |||||
| If Len(out) > 0 Then | |||||
| out = out & "," | |||||
| End If | |||||
| out = out & PrincipalJson(rs(0), rs(1), rs(2), rs(3), rs(4)) | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| Api_Send 200, "{""data"":[" & out & "]}" | |||||
| End Sub | |||||
| '--------------------------------------------------------------- | |||||
| ' POST /api/v1/principals {"name","type"} | |||||
| '--------------------------------------------------------------- | |||||
| Public Sub CreatePrincipal() | |||||
| Dim body, input, name, pType, id, keyId, plain, ts, k | |||||
| If Not Api_Authenticate() Then Exit Sub | |||||
| If Len(Api_AllowedNamespaceIds("admin")) = 0 Then | |||||
| Api_Audit "admin.principal.create", "principal", "", "denied" | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| body = Api_ReadBody() | |||||
| If IsEmpty(body) Then Exit Sub | |||||
| Set input = JsonLite_Parse(body) | |||||
| m_errs = "" | |||||
| name = ReqString(input, "name", 200) | |||||
| pType = LCase(ReqString(input, "type", 20)) | |||||
| If Len(m_errs) = 0 Then | |||||
| If pType <> "human" And pType <> "agent" And pType <> "service" Then | |||||
| AddErr "type must be human, agent or service." | |||||
| End If | |||||
| End If | |||||
| If Len(m_errs) > 0 Then | |||||
| Api_Invalid Split(m_errs, Chr(30)) | |||||
| Exit Sub | |||||
| End If | |||||
| id = Api_NewId() | |||||
| ts = Api_Now() | |||||
| plain = NewKeyText() | |||||
| keyId = Api_NewId() | |||||
| On Error Resume Next | |||||
| DAL().BeginTransaction | |||||
| DAL().Execute "INSERT INTO principals (id, tenant_id, type, name, status, created_at) VALUES (?, ?, ?, ?, 'active', ?)", _ | |||||
| Array(id, Api_TenantId, pType, name, ts) | |||||
| If Err.Number = 0 Then | |||||
| DAL().Execute "INSERT INTO api_keys (id, principal_id, key_hash, key_prefix, status, created_at) VALUES (?, ?, ?, ?, 'active', ?)", _ | |||||
| Array(keyId, id, Api_Sha256(plain), Left(plain, 8), ts) | |||||
| End If | |||||
| If Err.Number <> 0 Then | |||||
| k = Err.Number : Api_NoteDbError | |||||
| Err.Clear | |||||
| DAL().RollbackTransaction | |||||
| Api_DbFailed k, "" | |||||
| Exit Sub | |||||
| End If | |||||
| DAL().CommitTransaction | |||||
| If Err.Number <> 0 Then | |||||
| k = Err.Number : Api_NoteDbError | |||||
| Api_DbFailed k, "" | |||||
| Exit Sub | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| Api_Audit "admin.principal.create", "principal", id, "ok" | |||||
| Response.AddHeader "Location", "/api/v1/principals/" & id | |||||
| Response.AddHeader "Cache-Control", "no-store" | |||||
| Api_Send 201, "{""principal"":" & PrincipalJson(id, name, pType, "active", ts) & ",""api_key"":" & KeyJson(keyId, plain, ts) & "}" | |||||
| End Sub | |||||
| '--------------------------------------------------------------- | |||||
| ' GET /api/v1/principals/:id | |||||
| '--------------------------------------------------------------- | |||||
| Public Sub Principal(id) | |||||
| Dim rs, pj, isSelf, keys, grants, adminIds | |||||
| If Not Api_Authenticate() Then Exit Sub | |||||
| isSelf = (id = Api_PrincipalId) | |||||
| adminIds = Api_AllowedNamespaceIds("admin") | |||||
| If Not isSelf And Len(adminIds) = 0 Then | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| pj = LoadPrincipalJson(id) | |||||
| If Len(pj) = 0 Then | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| If isSelf Then | |||||
| grants = GrantsJson("g.principal_id = ?", id) | |||||
| Else | |||||
| grants = GrantsJson("g.principal_id = ? AND g.namespace_id IN (" & adminIds & ")", id) | |||||
| End If | |||||
| keys = "null" | |||||
| If CanManage(id) Then | |||||
| keys = "" | |||||
| Set rs = DAL().Query("SELECT id, key_prefix, status, created_at, expires_at, last_used_at FROM api_keys WHERE principal_id = ? ORDER BY created_at, id", id) | |||||
| Do While Not rs.EOF | |||||
| If Len(keys) > 0 Then | |||||
| keys = keys & "," | |||||
| End If | |||||
| keys = keys & "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""prefix"":" & JsonLite_Quote("" & rs(1)) & _ | |||||
| ",""status"":" & JsonLite_Quote("" & rs(2)) & ",""created_at"":" & JsonLite_Quote("" & rs(3)) & _ | |||||
| ",""expires_at"":" & JStr(rs(4)) & ",""last_used_at"":" & JStr(rs(5)) & "}" | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| keys = "[" & keys & "]" | |||||
| End If | |||||
| Api_Send 200, Left(pj, Len(pj) - 1) & ",""keys"":" & keys & ",""grants"":" & grants & "}" | |||||
| End Sub | |||||
| '--------------------------------------------------------------- | |||||
| ' PATCH /api/v1/principals/:id {"status":"active|disabled"} | |||||
| '--------------------------------------------------------------- | |||||
| Public Sub UpdatePrincipal(id) | |||||
| Dim body, input, status, k, pj | |||||
| If Not Api_Authenticate() Then Exit Sub | |||||
| If Not CanManage(id) Then | |||||
| Api_Audit "admin.principal.update", "principal", id, "denied" | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| body = Api_ReadBody() | |||||
| If IsEmpty(body) Then Exit Sub | |||||
| Set input = JsonLite_Parse(body) | |||||
| m_errs = "" | |||||
| status = LCase(ReqString(input, "status", 20)) | |||||
| If Len(m_errs) = 0 Then | |||||
| If status <> "active" And status <> "disabled" Then | |||||
| AddErr "status must be active or disabled." | |||||
| End If | |||||
| End If | |||||
| If Len(m_errs) > 0 Then | |||||
| Api_Invalid Split(m_errs, Chr(30)) | |||||
| Exit Sub | |||||
| End If | |||||
| If id = Api_PrincipalId Then | |||||
| Api_Error 422, "cannot_change_self", "A principal cannot change its own status." | |||||
| Exit Sub | |||||
| End If | |||||
| On Error Resume Next | |||||
| DAL().Execute "UPDATE principals SET status = ? WHERE id = ? AND tenant_id = ?", Array(status, id, Api_TenantId) | |||||
| If Err.Number <> 0 Then | |||||
| k = Err.Number : Api_NoteDbError | |||||
| Api_DbFailed k, "" | |||||
| Exit Sub | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| Api_Audit "admin.principal.update", "principal", id, status | |||||
| pj = LoadPrincipalJson(id) | |||||
| Api_Send 200, pj | |||||
| End Sub | |||||
| '--------------------------------------------------------------- | |||||
| ' POST /api/v1/principals/:id/keys | |||||
| '--------------------------------------------------------------- | |||||
| Public Sub CreateKey(id) | |||||
| Dim rs, status, keyId, plain, ts, k | |||||
| If Not Api_Authenticate() Then Exit Sub | |||||
| If Not CanManage(id) Then | |||||
| Api_Audit "admin.key.create", "principal", id, "denied" | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| Set rs = DAL().Query("SELECT status FROM principals WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) | |||||
| status = "" & rs(0) | |||||
| rs.Close | |||||
| If status <> "active" Then | |||||
| Api_Error 409, "principal_not_active", "Keys can only be created for an active principal; this one is " & status & "." | |||||
| Exit Sub | |||||
| End If | |||||
| plain = NewKeyText() | |||||
| keyId = Api_NewId() | |||||
| ts = Api_Now() | |||||
| On Error Resume Next | |||||
| DAL().Execute "INSERT INTO api_keys (id, principal_id, key_hash, key_prefix, status, created_at) VALUES (?, ?, ?, ?, 'active', ?)", _ | |||||
| Array(keyId, id, Api_Sha256(plain), Left(plain, 8), ts) | |||||
| If Err.Number <> 0 Then | |||||
| k = Err.Number : Api_NoteDbError | |||||
| Api_DbFailed k, "" | |||||
| Exit Sub | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| Api_Audit "admin.key.create", "api_key", keyId, "ok" | |||||
| Response.AddHeader "Cache-Control", "no-store" | |||||
| Api_Send 201, "{""principal_id"":" & JsonLite_Quote(id) & ",""api_key"":" & KeyJson(keyId, plain, ts) & "}" | |||||
| End Sub | |||||
| '--------------------------------------------------------------- | |||||
| ' DELETE /api/v1/keys/:id | |||||
| '--------------------------------------------------------------- | |||||
| Public Sub RevokeKey(id) | |||||
| Dim rs, pid, k | |||||
| If Not Api_Authenticate() Then Exit Sub | |||||
| pid = "" | |||||
| If Api_IsId(id) Then | |||||
| Set rs = DAL().Query("SELECT k.principal_id FROM api_keys k JOIN principals p ON p.id = k.principal_id WHERE k.id = ? AND p.tenant_id = ?", Array(id, Api_TenantId)) | |||||
| If Not rs.EOF Then | |||||
| pid = "" & rs(0) | |||||
| End If | |||||
| rs.Close | |||||
| End If | |||||
| If Len(pid) = 0 Then | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| If Not CanManage(pid) Then | |||||
| Api_Audit "admin.key.revoke", "api_key", id, "denied" | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| On Error Resume Next | |||||
| DAL().Execute "UPDATE api_keys SET status = 'revoked' WHERE id = ?", id | |||||
| If Err.Number <> 0 Then | |||||
| k = Err.Number : Api_NoteDbError | |||||
| Api_DbFailed k, "" | |||||
| Exit Sub | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| Api_Audit "admin.key.revoke", "api_key", id, "ok" | |||||
| Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""principal_id"":" & JsonLite_Quote(pid) & ",""status"":""revoked""}" | |||||
| End Sub | |||||
| '--------------------------------------------------------------- | |||||
| ' GET /api/v1/grants?namespace_id=&principal_id= | |||||
| '--------------------------------------------------------------- | |||||
| Public Sub Grants() | |||||
| Dim adminIds, ns, pid, where, params | |||||
| If Not Api_Authenticate() Then Exit Sub | |||||
| adminIds = Api_AllowedNamespaceIds("admin") | |||||
| If Len(adminIds) = 0 Then | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| ns = Trim("" & Request.QueryString("namespace_id")) | |||||
| pid = Trim("" & Request.QueryString("principal_id")) | |||||
| m_errs = "" | |||||
| If Len(ns) > 0 Then | |||||
| If Not Api_IsId(ns) Then | |||||
| AddErr "namespace_id must be a valid id." | |||||
| End If | |||||
| End If | |||||
| If Len(pid) > 0 Then | |||||
| If Not Api_IsId(pid) Then | |||||
| AddErr "principal_id must be a valid id." | |||||
| End If | |||||
| End If | |||||
| If Len(m_errs) > 0 Then | |||||
| Api_Invalid Split(m_errs, Chr(30)) | |||||
| Exit Sub | |||||
| End If | |||||
| where = "g.namespace_id IN (" & adminIds & ")" | |||||
| If Len(ns) > 0 And Len(pid) > 0 Then | |||||
| where = where & " AND g.namespace_id = ? AND g.principal_id = ?" | |||||
| params = Array(ns, pid) | |||||
| ElseIf Len(ns) > 0 Then | |||||
| where = where & " AND g.namespace_id = ?" | |||||
| params = ns | |||||
| ElseIf Len(pid) > 0 Then | |||||
| where = where & " AND g.principal_id = ?" | |||||
| params = pid | |||||
| Else | |||||
| params = Empty | |||||
| End If | |||||
| Api_Send 200, "{""data"":" & GrantsJson(where, params) & "}" | |||||
| End Sub | |||||
| '--------------------------------------------------------------- | |||||
| ' POST /api/v1/grants | |||||
| '--------------------------------------------------------------- | |||||
| Public Sub CreateGrant() | |||||
| Dim body, input, pid, ns, permsArr, perms, inherit, expires, i, p, path, rs, pStatus, existing, id, ts, k | |||||
| If Not Api_Authenticate() Then Exit Sub | |||||
| body = Api_ReadBody() | |||||
| If IsEmpty(body) Then Exit Sub | |||||
| Set input = JsonLite_Parse(body) | |||||
| m_errs = "" | |||||
| pid = ReqString(input, "principal_id", 64) | |||||
| ns = ReqString(input, "namespace_id", 64) | |||||
| If Len(pid) > 0 Then | |||||
| If Not Api_IsId(pid) Then | |||||
| AddErr "principal_id must be a valid id." | |||||
| End If | |||||
| End If | |||||
| If Len(ns) > 0 Then | |||||
| If Not Api_IsId(ns) Then | |||||
| AddErr "namespace_id must be a valid id." | |||||
| End If | |||||
| End If | |||||
| perms = "" | |||||
| If input.HasRaw("permissions") Then | |||||
| permsArr = JsonLite_ParseStringArray(input.Raw("permissions")) | |||||
| Else | |||||
| permsArr = Null | |||||
| End If | |||||
| If IsNull(permsArr) Then | |||||
| AddErr "permissions must be a non-empty array of read, write, delete, verify, admin." | |||||
| Else | |||||
| For i = 0 To UBound(permsArr) | |||||
| p = LCase(Trim(permsArr(i))) | |||||
| If InStr(ADM_PERMS, "," & p & ",") = 0 Or Len(p) = 0 Then | |||||
| AddErr "unknown permission: " & permsArr(i) & " (allowed: read, write, delete, verify, admin)." | |||||
| Exit For | |||||
| End If | |||||
| If InStr("," & perms & ",", "," & p & ",") = 0 Then | |||||
| If Len(perms) > 0 Then | |||||
| perms = perms & "," | |||||
| End If | |||||
| perms = perms & p | |||||
| End If | |||||
| Next | |||||
| If Len(perms) = 0 And Len(m_errs) = 0 Then | |||||
| AddErr "permissions must not be empty." | |||||
| End If | |||||
| End If | |||||
| inherit = 1 | |||||
| If input.Exists("inherit") Then | |||||
| If VarType(input.Item("inherit")) = vbBoolean Then | |||||
| If Not input.Item("inherit") Then | |||||
| inherit = 0 | |||||
| End If | |||||
| Else | |||||
| AddErr "inherit must be true or false." | |||||
| End If | |||||
| End If | |||||
| expires = OptString(input, "expires_at", 19) | |||||
| If Not IsNull(expires) Then | |||||
| If Not IsTimestamp(expires) Then | |||||
| AddErr "expires_at must be a UTC time like 2027-01-31 18:00:00." | |||||
| ElseIf expires <= Api_Now() Then | |||||
| AddErr "expires_at must be in the future." | |||||
| End If | |||||
| End If | |||||
| If Len(m_errs) > 0 Then | |||||
| Api_Invalid Split(m_errs, Chr(30)) | |||||
| Exit Sub | |||||
| End If | |||||
| ' Admin on the namespace; an inheriting grant also needs inheriting admin (it reaches every descendant). | |||||
| path = Api_NamespacePath(ns) | |||||
| If IsNull(path) Then | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| If Not Api_PathAllows(path, "admin") Then | |||||
| Api_Audit "admin.grant.create", "namespace", ns, "denied" | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| If inherit = 1 Then | |||||
| If Not Api_PathAllows(path & "/*", "admin") Then | |||||
| Api_Error 422, "inherit_not_allowed", "Your admin access on this namespace does not extend to its descendants; grant with inherit false." | |||||
| Exit Sub | |||||
| End If | |||||
| End If | |||||
| Set rs = DAL().Query("SELECT status FROM principals WHERE id = ? AND tenant_id = ?", Array(pid, Api_TenantId)) | |||||
| pStatus = "" | |||||
| If Not rs.EOF Then | |||||
| pStatus = "" & rs(0) | |||||
| End If | |||||
| rs.Close | |||||
| If pStatus <> "active" Then | |||||
| Api_Error 422, "principal_not_found", "principal_id must be an active principal of your tenant." | |||||
| Exit Sub | |||||
| End If | |||||
| Set rs = DAL().Query("SELECT id FROM access_grants WHERE principal_id = ? AND namespace_id = ?", Array(pid, ns)) | |||||
| existing = "" | |||||
| If Not rs.EOF Then | |||||
| existing = "" & rs(0) | |||||
| End If | |||||
| rs.Close | |||||
| If Len(existing) > 0 Then | |||||
| Api_Error 409, "grant_exists", "This principal already has a grant on this namespace (" & existing & "); delete it first to change it." | |||||
| Exit Sub | |||||
| End If | |||||
| id = Api_NewId() | |||||
| ts = Api_Now() | |||||
| On Error Resume Next | |||||
| DAL().Execute "INSERT INTO access_grants (id, principal_id, namespace_id, permissions, inherit, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)", _ | |||||
| Array(id, pid, ns, perms, inherit, ts, expires) | |||||
| If Err.Number <> 0 Then | |||||
| k = Err.Number : Api_NoteDbError | |||||
| Api_DbFailed k, "" | |||||
| Exit Sub | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| Api_Audit "admin.grant.create", "grant", id, perms | |||||
| Response.AddHeader "Location", "/api/v1/grants?principal_id=" & pid | |||||
| Api_Send 201, GrantJson(id, pid, ns, path, perms, inherit, expires, ts) | |||||
| End Sub | |||||
| '--------------------------------------------------------------- | |||||
| ' DELETE /api/v1/grants/:id | |||||
| '--------------------------------------------------------------- | |||||
| Public Sub DeleteGrant(id) | |||||
| Dim rs, pid, path, k | |||||
| If Not Api_Authenticate() Then Exit Sub | |||||
| pid = "" | |||||
| If Api_IsId(id) Then | |||||
| Set rs = DAL().Query("SELECT g.principal_id, n.path FROM access_grants g JOIN namespaces n ON n.id = g.namespace_id WHERE g.id = ? AND n.tenant_id = ?", Array(id, Api_TenantId)) | |||||
| If Not rs.EOF Then | |||||
| pid = "" & rs(0) | |||||
| path = "" & rs(1) | |||||
| End If | |||||
| rs.Close | |||||
| End If | |||||
| If Len(pid) = 0 Then | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| If Not Api_PathAllows(path, "admin") Then | |||||
| Api_Audit "admin.grant.delete", "grant", id, "denied" | |||||
| Api_NotFound | |||||
| Exit Sub | |||||
| End If | |||||
| If pid = Api_PrincipalId Then | |||||
| Api_Error 422, "cannot_change_self", "A principal cannot remove its own grants; ask another admin." | |||||
| Exit Sub | |||||
| End If | |||||
| On Error Resume Next | |||||
| DAL().Execute "DELETE FROM access_grants WHERE id = ?", id | |||||
| If Err.Number <> 0 Then | |||||
| k = Err.Number : Api_NoteDbError | |||||
| Api_DbFailed k, "" | |||||
| Exit Sub | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| Api_Audit "admin.grant.delete", "grant", id, "ok" | |||||
| Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""deleted"":true}" | |||||
| End Sub | |||||
| '--------------------------------------------------------------- | |||||
| ' Helpers | |||||
| '--------------------------------------------------------------- | |||||
| ' True when the caller may manage principal pid (keys, status): itself, or a principal of the tenant whose every | |||||
| ' grant lies where the caller holds admin (inheriting admin where the grant inherits). Never for placeholders. | |||||
| Private Function CanManage(pid) | |||||
| Dim rs, status, paths(), inh(), n, i | |||||
| CanManage = False | |||||
| If Not Api_IsId(pid) Then Exit Function | |||||
| Set rs = DAL().Query("SELECT status FROM principals WHERE id = ? AND tenant_id = ?", Array(pid, Api_TenantId)) | |||||
| status = "" | |||||
| If Not rs.EOF Then | |||||
| status = "" & rs(0) | |||||
| End If | |||||
| rs.Close | |||||
| If Len(status) = 0 Or status = "imported" Then Exit Function | |||||
| If pid = Api_PrincipalId Then | |||||
| CanManage = True | |||||
| Exit Function | |||||
| End If | |||||
| If Len(Api_AllowedNamespaceIds("admin")) = 0 Then Exit Function | |||||
| n = 0 | |||||
| ReDim paths(7) | |||||
| ReDim inh(7) | |||||
| Set rs = DAL().Query("SELECT n.path, g.inherit FROM access_grants g JOIN namespaces n ON n.id = g.namespace_id WHERE g.principal_id = ?", pid) | |||||
| Do While Not rs.EOF | |||||
| If n > UBound(paths) Then | |||||
| ReDim Preserve paths(n * 2) | |||||
| ReDim Preserve inh(n * 2) | |||||
| End If | |||||
| paths(n) = "" & rs(0) | |||||
| inh(n) = CLng(rs(1)) | |||||
| n = n + 1 | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| For i = 0 To n - 1 | |||||
| If Not Api_PathAllows(paths(i), "admin") Then Exit Function | |||||
| If inh(i) = 1 Then | |||||
| If Not Api_PathAllows(paths(i) & "/*", "admin") Then Exit Function | |||||
| End If | |||||
| Next | |||||
| CanManage = True | |||||
| End Function | |||||
| Private Function LoadPrincipalJson(id) | |||||
| Dim rs | |||||
| LoadPrincipalJson = "" | |||||
| If Not Api_IsId(id) Then Exit Function | |||||
| Set rs = DAL().Query("SELECT id, name, type, status, created_at FROM principals WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) | |||||
| If Not rs.EOF Then | |||||
| LoadPrincipalJson = PrincipalJson(rs(0), rs(1), rs(2), rs(3), rs(4)) | |||||
| End If | |||||
| rs.Close | |||||
| End Function | |||||
| Private Function PrincipalJson(id, name, pType, status, createdAt) | |||||
| PrincipalJson = "{""id"":" & JsonLite_Quote("" & id) & ",""name"":" & JsonLite_Quote("" & name) & ",""type"":" & JsonLite_Quote("" & pType) & _ | |||||
| ",""status"":" & JsonLite_Quote("" & status) & ",""created_at"":" & JsonLite_Quote("" & createdAt) & "}" | |||||
| End Function | |||||
| Private Function KeyJson(keyId, plain, createdAt) | |||||
| KeyJson = "{""id"":" & JsonLite_Quote(keyId) & ",""key"":" & JsonLite_Quote(plain) & ",""prefix"":" & JsonLite_Quote(Left(plain, 8)) & _ | |||||
| ",""created_at"":" & JsonLite_Quote(createdAt) & ",""note"":""Shown only in this response; store it now.""}" | |||||
| End Function | |||||
| ' JSON array of grants matching a WHERE clause on access_grants g (namespaces n joined). | |||||
| Private Function GrantsJson(where, params) | |||||
| Dim rs, out | |||||
| out = "" | |||||
| Set rs = DAL().Query("SELECT g.id, g.principal_id, g.namespace_id, n.path, g.permissions, g.inherit, g.expires_at, g.created_at " & _ | |||||
| "FROM access_grants g JOIN namespaces n ON n.id = g.namespace_id WHERE n.tenant_id = '" & Api_TenantId & "' AND " & where & _ | |||||
| " ORDER BY n.path, g.created_at", params) | |||||
| Do While Not rs.EOF | |||||
| If Len(out) > 0 Then | |||||
| out = out & "," | |||||
| End If | |||||
| out = out & GrantJson("" & rs(0), "" & rs(1), "" & rs(2), "" & rs(3), "" & rs(4), CLng(rs(5)), rs(6), "" & rs(7)) | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| GrantsJson = "[" & out & "]" | |||||
| End Function | |||||
| Private Function GrantJson(id, pid, ns, path, perms, inherit, expires, createdAt) | |||||
| Dim a, i, p | |||||
| a = Split(perms, ",") | |||||
| p = "" | |||||
| For i = 0 To UBound(a) | |||||
| If Len(Trim(a(i))) > 0 Then | |||||
| If Len(p) > 0 Then | |||||
| p = p & "," | |||||
| End If | |||||
| p = p & JsonLite_Quote(Trim(a(i))) | |||||
| End If | |||||
| Next | |||||
| GrantJson = "{""id"":" & JsonLite_Quote(id) & ",""principal_id"":" & JsonLite_Quote(pid) & ",""namespace_id"":" & JsonLite_Quote(ns) & _ | |||||
| ",""path"":" & JsonLite_Quote(path) & ",""permissions"":[" & p & "],""inherit"":" & LCase(CStr(inherit = 1)) & _ | |||||
| ",""expires_at"":" & JStr(expires) & ",""created_at"":" & JsonLite_Quote(createdAt) & "}" | |||||
| End Function | |||||
| Private Function NewKeyText() | |||||
| Dim c | |||||
| Set c = Server.CreateObject("G3CRYPTO") | |||||
| NewKeyText = "amk_" & c.RandomHex(32) | |||||
| Set c = Nothing | |||||
| End Function | |||||
| Private Function parentAt(path) | |||||
| Dim rs, pp | |||||
| parentAt = Null | |||||
| pp = Left(path, InStrRev(path, "/") - 1) | |||||
| If Len(pp) = 0 Then Exit Function | |||||
| Set rs = DAL().Query("SELECT id FROM namespaces WHERE tenant_id = ? AND path = ?", Array(Api_TenantId, pp)) | |||||
| If Not rs.EOF Then | |||||
| parentAt = "" & rs(0) | |||||
| End If | |||||
| rs.Close | |||||
| End Function | |||||
| Private Function ValidPath(p) | |||||
| Dim i, c | |||||
| ValidPath = False | |||||
| If Len(p) < 2 Or Len(p) > 400 Then Exit Function | |||||
| If Left(p, 1) <> "/" Or Right(p, 1) = "/" Or InStr(p, "//") > 0 Then Exit Function | |||||
| For i = 1 To Len(p) | |||||
| c = Mid(p, i, 1) | |||||
| If Not ((c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or c = "/" Or c = "-" Or c = "_" Or c = ".") Then Exit Function | |||||
| Next | |||||
| ValidPath = True | |||||
| End Function | |||||
| ' "YYYY-MM-DD HH:MM:SS" | |||||
| Private Function IsTimestamp(s) | |||||
| Dim re | |||||
| Set re = New RegExp | |||||
| re.Pattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$" | |||||
| IsTimestamp = re.Test(s) | |||||
| End Function | |||||
| Private Function JStr(v) | |||||
| If IsNull(v) Then | |||||
| JStr = "null" | |||||
| ElseIf IsEmpty(v) Then | |||||
| JStr = "null" | |||||
| Else | |||||
| JStr = JsonLite_Quote("" & v) | |||||
| End If | |||||
| End Function | |||||
| Private Sub AddErr(msg) | |||||
| If Len(m_errs) > 0 Then | |||||
| m_errs = m_errs & Chr(30) | |||||
| End If | |||||
| m_errs = m_errs & msg | |||||
| End Sub | |||||
| Private Function ReqString(input, name, maxLen) | |||||
| Dim v | |||||
| ReqString = "" | |||||
| If Not input.Exists(name) Then | |||||
| AddErr name & " is required." | |||||
| Exit Function | |||||
| End If | |||||
| v = input.Item(name) | |||||
| If IsNull(v) Then | |||||
| AddErr name & " is required." | |||||
| Exit Function | |||||
| End If | |||||
| If VarType(v) <> vbString Then | |||||
| AddErr name & " must be a string." | |||||
| Exit Function | |||||
| End If | |||||
| v = Trim(v) | |||||
| If Len(v) = 0 Then | |||||
| AddErr name & " must not be empty." | |||||
| Exit Function | |||||
| End If | |||||
| If Len(v) > maxLen Then | |||||
| AddErr name & " must be at most " & maxLen & " characters." | |||||
| Exit Function | |||||
| End If | |||||
| ReqString = v | |||||
| End Function | |||||
| Private Function OptString(input, name, maxLen) | |||||
| Dim v | |||||
| OptString = Null | |||||
| If Not input.Exists(name) Then | |||||
| Exit Function | |||||
| End If | |||||
| v = input.Item(name) | |||||
| If IsNull(v) Then | |||||
| Exit Function | |||||
| End If | |||||
| If VarType(v) <> vbString Then | |||||
| AddErr name & " must be a string." | |||||
| Exit Function | |||||
| End If | |||||
| If Len(v) > maxLen Then | |||||
| AddErr name & " must be at most " & maxLen & " characters." | |||||
| Exit Function | |||||
| End If | |||||
| OptString = v | |||||
| End Function | |||||
| Public Sub Invoke(actionName, args) | |||||
| Select Case LCase(actionName) | |||||
| Case "whoami" : WhoAmI | |||||
| Case "namespaces" : Namespaces | |||||
| Case "createnamespace" : CreateNamespace | |||||
| Case "principals" : Principals | |||||
| Case "createprincipal" : CreatePrincipal | |||||
| Case "principal" : Principal args(0) | |||||
| Case "updateprincipal" : UpdatePrincipal args(0) | |||||
| Case "createkey" : CreateKey args(0) | |||||
| Case "revokekey" : RevokeKey args(0) | |||||
| Case "grants" : Grants | |||||
| Case "creategrant" : CreateGrant | |||||
| Case "deletegrant" : DeleteGrant args(0) | |||||
| Case Else | |||||
| Err.Raise 438, "ApiAdminController_Class", "Action '" & actionName & "' not found" | |||||
| End Select | |||||
| End Sub | |||||
| End Class | |||||
| Dim ApiAdminController_Class__Singleton | |||||
| Function ApiAdminController() | |||||
| If IsEmpty(ApiAdminController_Class__Singleton) Then | |||||
| Set ApiAdminController_Class__Singleton = New ApiAdminController_Class | |||||
| End If | |||||
| Set ApiAdminController = ApiAdminController_Class__Singleton | |||||
| End Function | |||||
| ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) | |||||
| Sub ApiAdminController_Invoke(actionName, args) | |||||
| ApiAdminController().Invoke actionName, args | |||||
| End Sub | |||||
| %> | |||||
| @@ -8,3 +8,4 @@ | |||||
| <!--#include file="ApiContextController.asp" --> | <!--#include file="ApiContextController.asp" --> | ||||
| <!--#include file="ApiLearningController.asp" --> | <!--#include file="ApiLearningController.asp" --> | ||||
| <!--#include file="ApiPortabilityController.asp" --> | <!--#include file="ApiPortabilityController.asp" --> | ||||
| <!--#include file="ApiAdminController.asp" --> | |||||
| @@ -18,6 +18,7 @@ Class ControllerRegistry_Class | |||||
| RegisterController "apicontextcontroller" | RegisterController "apicontextcontroller" | ||||
| RegisterController "apilearningcontroller" | RegisterController "apilearningcontroller" | ||||
| RegisterController "apiportabilitycontroller" | RegisterController "apiportabilitycontroller" | ||||
| RegisterController "apiadmincontroller" | |||||
| RegisterController "apidocumentscontroller" | RegisterController "apidocumentscontroller" | ||||
| RegisterController "apihealthcontroller" | RegisterController "apihealthcontroller" | ||||
| RegisterController "apisessionscontroller" | RegisterController "apisessionscontroller" | ||||
| @@ -6,7 +6,7 @@ condition is "all MVP acceptance criteria pass". | |||||
| - Installation under test: the development container (`docker compose up -d`, AxonASP image pinned by digest in | - Installation under test: the development container (`docker compose up -d`, AxonASP image pinned by digest in | ||||
| `docker-compose.yml`, SQLite, Ollama `nomic-embed-text`, Qdrant). | `docker-compose.yml`, SQLite, Ollama `nomic-embed-text`, Qdrant). | ||||
| - How to reproduce: run the ten suites listed under "Evidence" from Git Bash in the repo root with the containers up. | |||||
| - How to reproduce: run the eleven suites listed under "Evidence" from Git Bash in the repo root with the containers up. | |||||
| Each suite provisions and purges its own tenants and prints `passed: N failed: M`. | Each suite provisions and purges its own tenants and prints `passed: N failed: M`. | ||||
| - Manual checks use `curl` against `http://localhost:8801/api/v1` with a key from `scripts\provision.cmd` | - Manual checks use `curl` against `http://localhost:8801/api/v1` with a key from `scripts\provision.cmd` | ||||
| (`H='Authorization: Bearer <key>'`); the expected result is given for each. | (`H='Authorization: Bearer <key>'`); the expected result is given for each. | ||||
| @@ -71,6 +71,7 @@ Run on 2026-12-05 on the development container, all suites from a restarted cont | |||||
| | `tests/phase3-jobs.sh` | 41 | passed | | | `tests/phase3-jobs.sh` | 41 | passed | | ||||
| | `tests/backup-restore.sh` | 21 | passed | | | `tests/backup-restore.sh` | 21 | passed | | ||||
| | `tests/observability.sh` | 25 | passed | | | `tests/observability.sh` | 25 | passed | | ||||
| | `tests/admin-api.sh` | 91 | passed | | |||||
| | `tests/retrieval-benchmark.sh` | 5 | passed | | | `tests/retrieval-benchmark.sh` | 5 | passed | | ||||
| The production server (agent-memory-void) runs the same code; there `scripts/ops.sh backup` reports `RESULT: ok` | The production server (agent-memory-void) runs the same code; there `scripts/ops.sh backup` reports `RESULT: ok` | ||||
| @@ -93,3 +93,23 @@ building phases 1 to 3. Status is "accepted" unless noted. A change to one of th | |||||
| - Alternatives: OpenTelemetry export, a metrics database, continuous replication (for example Litestream). | - Alternatives: OpenTelemetry export, a metrics database, continuous replication (for example Litestream). | ||||
| - Consequences: nothing extra to run. Counters reset on restart, and backups need a schedule and an off-machine copy | - Consequences: nothing extra to run. Counters reset on restart, and backups need a schedule and an off-machine copy | ||||
| (open item on the production server). | (open item on the production server). | ||||
| ## ADR-011 Management API: delegated administration without escalation | |||||
| - Context: provisioning went through a CLI on the server (`provision.cmd` / `ops.sh`), which needs shell access to the | |||||
| host. The specification lists management endpoints as mandatory "API or secure configuration". | |||||
| - Decision: management endpoints inside a tenant (`/me`, `/namespaces`, `/principals`, `/principals/{id}/keys`, | |||||
| `/keys/{id}`, `/grants`) with authorization derived from the existing namespace grants, no new role: | |||||
| - `admin` on a namespace allows granting and revoking access on it; granting with inherit, and creating namespaces | |||||
| below it, needs an admin grant that itself inherits. | |||||
| - Listing and creating principals needs admin somewhere; a new principal has no access until granted. | |||||
| - Issuing keys for, disabling or enabling another principal needs admin over every namespace where that principal | |||||
| has a grant (inheriting where its grant inherits). A key therefore never lets the caller act with more access than | |||||
| it already holds. Callers may manage their own keys but not their own status or grants. | |||||
| - No permission answers 404; keys are returned once with `Cache-Control: no-store`; no Idempotency-Key replay for | |||||
| responses that contain a key. | |||||
| - Tenants, top-level namespaces and purges stay with the CLI (operator actions). | |||||
| - Alternatives: a tenant-wide administrator role (simpler, but all-or-nothing); exposing tenant creation (needs a | |||||
| service-level operator identity that does not exist yet). | |||||
| - Consequences: teams can run their own namespaces without shell access to the server. The rule has to be kept by any | |||||
| future endpoint that issues credentials or access (AGENTS.md). | |||||
| @@ -57,6 +57,20 @@ | |||||
| router.AddRoute "POST", "/api/v1/exports", "ApiPortabilityController", "Export" | router.AddRoute "POST", "/api/v1/exports", "ApiPortabilityController", "Export" | ||||
| router.AddRoute "POST", "/api/v1/imports", "ApiPortabilityController", "Import" | router.AddRoute "POST", "/api/v1/imports", "ApiPortabilityController", "Import" | ||||
| ' Management: namespaces, principals, API keys, grants (spec section 9) | |||||
| router.AddRoute "GET", "/api/v1/me", "ApiAdminController", "WhoAmI" | |||||
| router.AddRoute "GET", "/api/v1/namespaces", "ApiAdminController", "Namespaces" | |||||
| router.AddRoute "POST", "/api/v1/namespaces", "ApiAdminController", "CreateNamespace" | |||||
| router.AddRoute "GET", "/api/v1/principals", "ApiAdminController", "Principals" | |||||
| router.AddRoute "POST", "/api/v1/principals", "ApiAdminController", "CreatePrincipal" | |||||
| router.AddRoute "GET", "/api/v1/principals/:id", "ApiAdminController", "Principal" | |||||
| router.AddRoute "PATCH", "/api/v1/principals/:id", "ApiAdminController", "UpdatePrincipal" | |||||
| router.AddRoute "POST", "/api/v1/principals/:id/keys", "ApiAdminController", "CreateKey" | |||||
| router.AddRoute "DELETE", "/api/v1/keys/:id", "ApiAdminController", "RevokeKey" | |||||
| router.AddRoute "GET", "/api/v1/grants", "ApiAdminController", "Grants" | |||||
| router.AddRoute "POST", "/api/v1/grants", "ApiAdminController", "CreateGrant" | |||||
| router.AddRoute "DELETE", "/api/v1/grants/:id", "ApiAdminController", "DeleteGrant" | |||||
| ' Dispatch the request (resolves route and executes controller action). | ' Dispatch the request (resolves route and executes controller action). | ||||
| ' MVC() is called with parentheses: AxonASP cannot use "MVC.Method args" on a parameterless function. | ' MVC() is called with parentheses: AxonASP cannot use "MVC.Method args" on a parameterless function. | ||||
| MVC().DispatchRequest Request.ServerVariables("REQUEST_METHOD"), GetRequestPath() | MVC().DispatchRequest Request.ServerVariables("REQUEST_METHOD"), GetRequestPath() | ||||
| @@ -0,0 +1,167 @@ | |||||
| #!/usr/bin/env bash | |||||
| # Management API checks (spec section 9 "Management", section 16 least privilege; docs/decisions.md ADR-011): | |||||
| # namespaces, principals, API keys and grants. Covers the happy paths, validation (422), bad input (400), unknown ids | |||||
| # (404), wrong method (405), privilege escalation attempts (keys for principals with wider access, inheriting grants | |||||
| # from a non-inheriting admin, grants outside the caller's scope), tenant isolation (AC-06), key revocation and | |||||
| # principal disabling, UTF-8 round trip and a cold first request. | |||||
| # | |||||
| # Needs the container from docker-compose.yml running. Provisions two throw-away tenants and purges them at the end. | |||||
| # bash tests/admin-api.sh | |||||
| set -u | |||||
| BASE=${BASE:-http://localhost:8801/api/v1} | |||||
| PASS=0; FAIL=0; FAILED=(); TENANTS=() | |||||
| TMP=$(mktemp -d) | |||||
| prov() { | |||||
| MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site \ | |||||
| -e "PROV_ACTION=$1" -e "PROV_ARG1=${2:-}" -e "PROV_ARG2=${3:-}" -e "PROV_ARG3=${4:-}" -e "PROV_ARG4=${5:-}" \ | |||||
| axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\015' | |||||
| } | |||||
| field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; } | |||||
| cleanup() { for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; rm -rf "$TMP"; } | |||||
| trap cleanup EXIT | |||||
| check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; } | |||||
| code() { local key=$1 m=$2 p=$3; shift 3; curl -s -o /dev/null -w '%{http_code}' -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; } | |||||
| body() { local key=$1 m=$2 p=$3; shift 3; curl -s -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; } | |||||
| jq_() { python -I -c "import sys,json;sys.stdin.reconfigure(encoding='utf-8');d=json.load(sys.stdin);print($1)"; } | |||||
| mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); } | |||||
| grant_body() { python -I -c "import json,sys;d={'principal_id':sys.argv[1],'namespace_id':sys.argv[2],'permissions':sys.argv[3].split(',')}; | |||||
| if sys.argv[4]!='': d['inherit']=(sys.argv[4]=='true') | |||||
| print(json.dumps(d))" "$1" "$2" "$3" "${4:-}"; } | |||||
| # ---- setup ------------------------------------------------------------------------------------------------------ | |||||
| TA=$(prov tenant "adm-A" | field tenant_id); TB=$(prov tenant "adm-B" | field tenant_id); TENANTS=("$TA" "$TB") | |||||
| mk "$TA" owner human; OWN=$P_ID; OK=$P_KEY | |||||
| mk "$TA" subadmin agent; SUB=$P_ID; SK=$P_KEY | |||||
| mk "$TA" narrow agent; NAR=$P_ID; NK=$P_KEY | |||||
| mk "$TA" plain agent; PLA=$P_ID; PK=$P_KEY | |||||
| mk "$TB" adminB human; BAD=$P_ID; BK=$P_KEY | |||||
| prov grant "$OWN" /org admin 1 >/dev/null | |||||
| prov grant "$SUB" /org/team-a admin 1 >/dev/null | |||||
| prov grant "$NAR" /org/team-b admin 0 >/dev/null | |||||
| prov grant "$PLA" /org/team-a read 1 >/dev/null | |||||
| prov grant "$BAD" /org admin 1 >/dev/null | |||||
| NSA=$(prov namespace "$TA" /org/team-a | field namespace_id); NSB=$(prov namespace "$TA" /org/team-b | field namespace_id) | |||||
| NSBB=$(prov namespace "$TB" /org | field namespace_id) | |||||
| [ -n "$NSA" ] && [ -n "$NSB" ] && [ -n "$OK" ] && [ -n "$BK" ] || { echo "setup failed"; exit 2; } | |||||
| # ---- cold start: first request after a restart is a write ------------------------------------------------------- | |||||
| docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done | |||||
| R=$(body "$SK" POST /namespaces -d '{"path":"/org/team-a/x/y"}') | |||||
| check "cold: sub-admin creates nested namespace" "2 /org/team-a/x/y" "$(echo "$R" | jq_ "str(d['namespaces_created'])+' '+d['path']")" | |||||
| NSX=$(echo "$R" | jq_ "d['id']") | |||||
| # ---- me and namespaces ------------------------------------------------------------------------------------------- | |||||
| check "me -> own principal" "$PLA plain agent" "$(body "$PK" GET /me | jq_ "d['principal_id']+' '+d['name']+' '+d['type']")" | |||||
| check "me lists own grants" "/org/team-a read" "$(body "$PK" GET /me | jq_ "' '.join([d['grants'][0]['path']]+d['grants'][0]['permissions'])")" | |||||
| check "me no auth -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/me")" | |||||
| check "namespaces: reader sees team-a subtree only" "/org/team-a /org/team-a/x /org/team-a/x/y" "$(body "$PK" GET /namespaces | jq_ "' '.join(n['path'] for n in d['data'])")" | |||||
| check "namespaces: reader permissions" "['read']" "$(body "$PK" GET /namespaces | jq_ "d['data'][0]['permissions']")" | |||||
| check "namespaces: owner has admin on team-b" "yes" "$(body "$OK" GET /namespaces | jq_ "'yes' if any(n['path']=='/org/team-b' and 'admin' in n['permissions'] for n in d['data']) else 'no'")" | |||||
| check "namespaces: tenant B sees only its own" "/org" "$(body "$BK" GET /namespaces | jq_ "' '.join(n['path'] for n in d['data'])")" | |||||
| # ---- create namespace ---------------------------------------------------------------------------------------------- | |||||
| check "create outside admin scope -> 404" "404" "$(code "$SK" POST /namespaces -d '{"path":"/org/team-b/y"}')" | |||||
| check "non-inheriting admin cannot create below -> 404" "404" "$(code "$NK" POST /namespaces -d '{"path":"/org/team-b/z"}')" | |||||
| check "reader cannot create -> 404" "404" "$(code "$PK" POST /namespaces -d '{"path":"/org/team-a/r"}')" | |||||
| check "top-level namespace -> 404" "404" "$(code "$OK" POST /namespaces -d '{"path":"/elsewhere"}')" | |||||
| check "existing namespace -> 409" "409" "$(code "$SK" POST /namespaces -d '{"path":"/org/team-a/x"}')" | |||||
| check "upper-case path is normalised" "201 " "$(code "$OK" POST /namespaces -d '{"path":"/org/Team-C"}') $(body "$OK" GET /namespaces | jq_ "'' if any(n['path']=='/org/team-c' for n in d['data']) else 'missing'")" | |||||
| check "bad path -> 422" "422" "$(code "$OK" POST /namespaces -d '{"path":"/org/has space"}')" | |||||
| check "path without slash -> 422" "422" "$(code "$OK" POST /namespaces -d '{"path":"org/x"}')" | |||||
| check "trailing slash -> 422" "422" "$(code "$OK" POST /namespaces -d '{"path":"/org/x/"}')" | |||||
| check "missing path -> 422" "422" "$(code "$OK" POST /namespaces -d '{}')" | |||||
| check "path not a string -> 422" "422" "$(code "$OK" POST /namespaces -d '{"path":5}')" | |||||
| check "invalid JSON -> 400" "400" "$(code "$OK" POST /namespaces -d '{"path":')" | |||||
| check "empty body -> 400" "400" "$(code "$OK" POST /namespaces)" | |||||
| check "namespaces wrong method -> 405" "405" "$(code "$OK" PUT /namespaces -d '{}')" | |||||
| check "tenant B cannot create in A's tree (own /org instead)" "/org/team-a" "$(body "$BK" POST /namespaces -d '{"path":"/org/team-a"}' | jq_ "d['path']")" | |||||
| # ---- principals ---------------------------------------------------------------------------------------------------- | |||||
| check "reader lists principals -> 404" "404" "$(code "$PK" GET /principals)" | |||||
| check "sub-admin lists tenant principals" "4" "$(body "$SK" GET /principals | jq_ "len(d['data'])")" | |||||
| check "principals list has no keys" "no" "$(body "$SK" GET /principals | grep -q 'amk_' && echo yes || echo no)" | |||||
| python -I -c "import json,sys;open(sys.argv[1],'w',encoding='utf-8').write(json.dumps({'name':'Bot <b>'+chr(252)+chr(223)+chr(0x65e5)+'</b>','type':'agent'},ensure_ascii=False))" "$TMP/p.json" | |||||
| curl -s -D "$TMP/h.txt" -o "$TMP/r.json" -X POST -H "Authorization: Bearer $SK" --data-binary @"$TMP/p.json" "$BASE/principals" | |||||
| check "create principal -> 201" "201" "$(sed -n '1s/^HTTP[^ ]* \([0-9]*\).*/\1/p' "$TMP/h.txt")" | |||||
| check "create principal: no-store" "yes" "$(grep -qi '^cache-control: no-store' "$TMP/h.txt" && echo yes || echo no)" | |||||
| NEW=$(jq_ "d['principal']['id']" < "$TMP/r.json"); NEWK=$(jq_ "d['api_key']['key']" < "$TMP/r.json"); NEWKID=$(jq_ "d['api_key']['id']" < "$TMP/r.json") | |||||
| check "new key has prefix" "amk_" "${NEWK:0:4}" | |||||
| check "new key authenticates; UTF-8 name round trip" "yes" "$(body "$NEWK" GET /me | jq_ "'yes' if d['name']=='Bot <b>'+chr(252)+chr(223)+chr(0x65e5)+'</b>' and d['principal_id']=='$NEW' else 'no'")" | |||||
| check "new principal has no access yet" "0" "$(body "$NEWK" GET /namespaces | jq_ "len(d['data'])")" | |||||
| check "create principal bad type -> 422" "422" "$(code "$SK" POST /principals -d '{"name":"x","type":"robot"}')" | |||||
| check "create principal missing name -> 422" "422" "$(code "$SK" POST /principals -d '{"type":"agent"}')" | |||||
| check "reader cannot create principals -> 404" "404" "$(code "$PK" POST /principals -d '{"name":"x","type":"agent"}')" | |||||
| check "principals wrong method -> 405" "405" "$(code "$SK" DELETE /principals)" | |||||
| check "sub-admin sees keys of a manageable principal" "1 no" "$(body "$SK" GET /principals/$NEW | jq_ "str(len(d['keys']))+' '+('yes' if 'key' in d['keys'][0] else 'no')")" | |||||
| check "sub-admin cannot see owner's keys or grants" "None []" "$(body "$SK" GET /principals/$OWN | jq_ "str(d['keys'])+' '+str(d['grants'])")" | |||||
| check "reader sees itself" "$PLA" "$(body "$PK" GET /principals/$PLA | jq_ "d['id']")" | |||||
| check "reader cannot see others -> 404" "404" "$(code "$PK" GET /principals/$OWN)" | |||||
| check "tenant B cannot see A's principal -> 404" "404" "$(code "$BK" GET /principals/$NEW)" | |||||
| check "unknown principal -> 404" "404" "$(code "$OK" GET /principals/00000000-0000-4000-8000-000000000000)" | |||||
| check "malformed principal id -> 404" "404" "$(code "$OK" GET /principals/abc)" | |||||
| # ---- grants -------------------------------------------------------------------------------------------------------- | |||||
| R=$(body "$SK" POST /grants -d "$(grant_body "$NEW" "$NSA" "read,write,read")") | |||||
| check "grant -> permissions de-duplicated, inherit default" "['read', 'write'] True" "$(echo "$R" | jq_ "str(d['permissions'])+' '+str(d['inherit'])")" | |||||
| G1=$(echo "$R" | jq_ "d['id']") | |||||
| check "new principal can now read team-a" "yes" "$(body "$NEWK" GET /namespaces | jq_ "'yes' if any(n['path']=='/org/team-a' for n in d['data']) else 'no'")" | |||||
| check "duplicate grant -> 409" "409" "$(code "$SK" POST /grants -d "$(grant_body "$NEW" "$NSA" "read")")" | |||||
| check "grant outside scope -> 404" "404" "$(code "$SK" POST /grants -d "$(grant_body "$NEW" "$NSB" "read")")" | |||||
| check "non-inheriting admin: inherit grant -> 422" "inherit_not_allowed" "$(body "$NK" POST /grants -d "$(grant_body "$NEW" "$NSB" "read" true)" | jq_ "d['error']['code']")" | |||||
| R=$(body "$NK" POST /grants -d "$(grant_body "$NEW" "$NSB" "read" false)") | |||||
| check "non-inheriting admin: inherit false -> 201" "False" "$(echo "$R" | jq_ "d['inherit']")" | |||||
| G2=$(echo "$R" | jq_ "d['id']") | |||||
| check "unknown permission -> 422" "422" "$(code "$SK" POST /grants -d "$(grant_body "$PLA" "$NSX" "superuser")")" | |||||
| check "permissions not an array -> 422" "422" "$(code "$SK" POST /grants -d "{\"principal_id\":\"$PLA\",\"namespace_id\":\"$NSX\",\"permissions\":\"read\"}")" | |||||
| check "empty permissions -> 422" "422" "$(code "$SK" POST /grants -d "{\"principal_id\":\"$PLA\",\"namespace_id\":\"$NSX\",\"permissions\":[]}")" | |||||
| check "inherit not boolean -> 422" "422" "$(code "$SK" POST /grants -d "{\"principal_id\":\"$PLA\",\"namespace_id\":\"$NSX\",\"permissions\":[\"read\"],\"inherit\":\"yes\"}")" | |||||
| check "expires_at in the past -> 422" "422" "$(code "$SK" POST /grants -d "{\"principal_id\":\"$PLA\",\"namespace_id\":\"$NSX\",\"permissions\":[\"read\"],\"expires_at\":\"2020-01-01 00:00:00\"}")" | |||||
| check "expires_at bad format -> 422" "422" "$(code "$SK" POST /grants -d "{\"principal_id\":\"$PLA\",\"namespace_id\":\"$NSX\",\"permissions\":[\"read\"],\"expires_at\":\"tomorrow\"}")" | |||||
| check "malformed ids -> 422" "422" "$(code "$SK" POST /grants -d '{"principal_id":"x","namespace_id":"y","permissions":["read"]}')" | |||||
| check "grant to other tenant's principal -> 422" "principal_not_found" "$(body "$SK" POST /grants -d "$(grant_body "$BAD" "$NSX" "read")" | jq_ "d['error']['code']")" | |||||
| check "grant on other tenant's namespace -> 404" "404" "$(code "$SK" POST /grants -d "$(grant_body "$PLA" "$NSBB" "read")")" | |||||
| check "expiring grant -> 201 with expires_at" "2099-01-01 00:00:00" "$(body "$SK" POST /grants -d "{\"principal_id\":\"$PLA\",\"namespace_id\":\"$NSX\",\"permissions\":[\"write\"],\"expires_at\":\"2099-01-01 00:00:00\"}" | jq_ "d['expires_at']")" | |||||
| check "grants list (sub-admin) has G1, not team-b" "yes no" "$(body "$SK" GET /grants | jq_ "('yes' if any(g['id']=='$G1' for g in d['data']) else 'no')+' '+('yes' if any(g['id']=='$G2' for g in d['data']) else 'no')")" | |||||
| check "grants filter by principal" "$NEW" "$(body "$SK" GET "/grants?principal_id=$NEW" | jq_ "' '.join(sorted(set(g['principal_id'] for g in d['data'])))")" | |||||
| check "grants filter by namespace" "/org/team-a" "$(body "$SK" GET "/grants?namespace_id=$NSA" | jq_ "' '.join(sorted(set(g['path'] for g in d['data'])))")" | |||||
| check "grants bad filter -> 422" "422" "$(code "$SK" GET "/grants?principal_id=abc")" | |||||
| check "grants list by reader -> 404" "404" "$(code "$PK" GET /grants)" | |||||
| check "grants wrong method -> 405" "405" "$(code "$SK" PUT /grants -d '{}')" | |||||
| # ---- keys and principal status: no escalation ---------------------------------------------------------------------- | |||||
| check "sub-admin cannot issue key for principal with access outside its scope -> 404" "404" "$(code "$SK" POST /principals/$NEW/keys)" | |||||
| check "sub-admin cannot issue key for the owner -> 404" "404" "$(code "$SK" POST /principals/$OWN/keys)" | |||||
| check "non-inheriting admin cannot issue key (inheriting grant elsewhere) -> 404" "404" "$(code "$NK" POST /principals/$NEW/keys)" | |||||
| R=$(body "$OK" POST /principals/$NEW/keys) | |||||
| check "owner issues key -> new key works" "$NEW" "$(body "$(echo "$R" | jq_ "d['api_key']['key']")" GET /me | jq_ "d['principal_id']")" | |||||
| K2=$(echo "$R" | jq_ "d['api_key']['key']") | |||||
| check "reader issues own key -> 201" "201" "$(code "$PK" POST /principals/$PLA/keys)" | |||||
| check "tenant B issues key for A principal -> 404" "404" "$(code "$BK" POST /principals/$NEW/keys)" | |||||
| check "revoke by tenant B -> 404" "404" "$(code "$BK" DELETE /keys/$NEWKID)" | |||||
| check "revoke by sub-admin (not manageable) -> 404" "404" "$(code "$SK" DELETE /keys/$NEWKID)" | |||||
| check "owner revokes first key -> 200" "revoked" "$(body "$OK" DELETE /keys/$NEWKID | jq_ "d['status']")" | |||||
| check "revoked key -> 401" "401" "$(code "$NEWK" GET /me)" | |||||
| check "second key still works" "200" "$(code "$K2" GET /me)" | |||||
| check "revoke again -> 200" "200" "$(code "$OK" DELETE /keys/$NEWKID)" | |||||
| check "revoke unknown key -> 404" "404" "$(code "$OK" DELETE /keys/00000000-0000-4000-8000-000000000000)" | |||||
| check "disable principal -> 200" "disabled" "$(body "$OK" PATCH /principals/$NEW -d '{"status":"disabled"}' | jq_ "d['status']")" | |||||
| check "disabled principal's key -> 401" "401" "$(code "$K2" GET /me)" | |||||
| check "key for disabled principal -> 409" "409" "$(code "$OK" POST /principals/$NEW/keys)" | |||||
| check "enable principal -> key works again" "200" "$(code "$OK" PATCH /principals/$NEW -d '{"status":"active"}' >/dev/null; code "$K2" GET /me)" | |||||
| check "change own status -> 422" "422" "$(code "$OK" PATCH /principals/$OWN -d '{"status":"disabled"}')" | |||||
| check "bad status -> 422" "422" "$(code "$OK" PATCH /principals/$NEW -d '{"status":"gone"}')" | |||||
| check "sub-admin disables owner -> 404" "404" "$(code "$SK" PATCH /principals/$OWN -d '{"status":"disabled"}')" | |||||
| # ---- delete grants ------------------------------------------------------------------------------------------------- | |||||
| check "delete own grant -> 422" "422" "$(code "$SK" DELETE /grants/$(body "$SK" GET /me | jq_ "d['grants'][0]['id']"))" | |||||
| check "delete grant outside scope -> 404" "404" "$(code "$SK" DELETE /grants/$G2)" | |||||
| check "tenant B deletes A grant -> 404" "404" "$(code "$BK" DELETE /grants/$G1)" | |||||
| check "owner deletes team-b grant -> 200" "True" "$(body "$OK" DELETE /grants/$G2 | jq_ "d['deleted']")" | |||||
| check "now sub-admin may issue a key -> 201" "201" "$(code "$SK" POST /principals/$NEW/keys)" | |||||
| check "delete grant again -> 404" "404" "$(code "$OK" DELETE /grants/$G2)" | |||||
| check "sub-admin deletes G1 -> access gone" "0" "$(code "$SK" DELETE /grants/$G1 >/dev/null; body "$K2" GET /namespaces | jq_ "len(d['data'])")" | |||||
| echo "passed: $PASS failed: $FAIL" | |||||
| for f in "${FAILED[@]}"; do echo " FAIL: $f"; done | |||||
| [ "$FAIL" -eq 0 ] | |||||
Powered by TurnKey Linux.