diff --git a/CHANGELOG.md b/CHANGELOG.md index 8941863a..c99fb58d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -64,6 +64,11 @@ Everything on `main` before the first tagged release. AgentOS.NET has not shippe and theme, Api, Web and optional Ollama, with the key ring certificate-wrapped and row-level security on by default. CI lints and templates the chart and runs a cold install plus an upgrade on kind. +- **API tokens v2 + `/v1` (E1.3).** Personal API tokens for every member and service accounts for admins, scoped + `read` / `run` / `admin`, salted-HMAC storage, a platform max-lifetime setting + (`Tenants:ApiTokens:MaxLifetimeDays`), use + refusal auditing. The Api serves every route under `/v1` with a + published OpenAPI document ([docs/api/openapi-v1.json](docs/api/openapi-v1.json)) and a + [deprecation policy](docs/API.md#deprecation-policy). The VS Code extension can store a token and start a run. - **Approval policies** (E1.5). Per tenant and per project (Settings › Autopilot › Approvals): a person with the new **Approver** role (or an admin) approves the plan, opening the pull request, the change and/or the merge on **Board › Tasks › Approvals** — Approve, or Reject with a reason; who and when are recorded and audited @@ -90,6 +95,12 @@ Everything on `main` before the first tagged release. AgentOS.NET has not shippe - Sign-in cookies are isolated per instance and a failed OIDC callback restarts sign-in instead of erroring. - Code-scanning (CodeQL) alerts are cleared as they land, with compiler-enforced twins for their classes. +### Deprecated + +- The unversioned Api routes (`/pipeline`, `/runs`, `/tenants/…`, …) — use the same path under `/v1`. They keep + working until at least **2027-05-03** and answer with `Deprecation`, `Sunset` and `Link: rel="successor-version"` + headers ([docs/API.md](docs/API.md#deprecation-policy)). + ### Security - Postgres row-level security on every tenant table ([ADR-0012](docs/adr/0012-postgres-row-level-security.md)). @@ -128,5 +139,7 @@ Everything on `main` before the first tagged release. AgentOS.NET has not shippe [docs/CONFIG.md](docs/CONFIG.md#set-at-deploy-bootstrap). - The `approver` realm role (E1.5) is created by the azd post-deploy hook and the Helm realm job; a local realm imported before it needs the role added through the Keycloak admin API, or its volume dropped. +- Existing API tokens keep working — the `AddApiTokenScopesAndSalt` migration gives them scopes from their old + role and they stay service accounts; scripts calling the unversioned Api routes should move to `/v1`. [Unreleased]: https://github.com/hoangsnowy/AgentOS.NET/commits/main diff --git a/CLAUDE.md b/CLAUDE.md index 4e880f5f..5e0b65be 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -65,7 +65,7 @@ CI: `.github/workflows/ci.yml` runs `restore → build Release → test` on Ubun ## Architecture -Modular monolith. Solution file is **`AgentOs.slnx`** (the .NET 10 XML format). Each module is an `AgentOs.Modules.*` class library that **references `AgentOs.Domain` + `AgentOs.SharedKernel` only**; cross-module references are explicit and minimal (e.g. `Llm → AppConfig`, `Integration → Tools`). Hosts (`Api`, `Web`) reference every module and wire them with one `services.AddModulesFromAssemblies(cfg, …)` call + `await app.Services.InitializeModulesAsync()` + `app.MapModuleEndpoints()` — no per-module wiring in `Program.cs`. +Modular monolith. Solution file is **`AgentOs.slnx`** (the .NET 10 XML format). Each module is an `AgentOs.Modules.*` class library that **references `AgentOs.Domain` + `AgentOs.SharedKernel` only**; cross-module references are explicit and minimal (e.g. `Llm → AppConfig`, `Integration → Tools`). Hosts (`Api`, `Web`) reference every module and wire them with one `services.AddModulesFromAssemblies(cfg, …)` call + `await app.Services.InitializeModulesAsync()` + `app.MapVersionedModuleEndpoints()` (the Api: every module REST route under `/v1` plus its deprecated unversioned twin; SignalR hubs implement `IProtocolEndpointModule` and stay at their own path — see [docs/API.md](docs/API.md)) — no per-module wiring in `Program.cs`. | Project | Role | |---|---| diff --git a/README.md b/README.md index 65322064..b1fd55ff 100644 --- a/README.md +++ b/README.md @@ -459,19 +459,24 @@ tenant. Settings and keys are stored per `(tenant, key)` and always read for an ## API -Every route requires an authenticated principal unless it is explicitly public (fallback policy): on the -Api that is `/`, `/version`, `/health`, `/alive`, `POST /tenants/register`, `GET /tenants/invitations/preview`, -the runner hub (it authenticates the runner itself) and, outside Production, `/openapi` + `/scalar`. The Api -validates a Keycloak bearer token (RS256 only); the Web uses a cookie session (`/account/login` → OIDC). Both hosts -rate-limit per tenant, per user and per anonymous client (Settings → Platform → Request limits). The complete, always-current list is the **Scalar UI** at `/scalar/v1`. -The most used routes: +Versioned REST under **`/v1`** — the unversioned paths still work but are deprecated (`Deprecation` / `Sunset` +headers, sunset 2027-05-03). Every route requires an authenticated principal unless it is explicitly public +(fallback policy): on the Api that is `/`, `/version`, `/health`, `/alive`, `POST /tenants/register`, +`GET /tenants/invitations/preview` (and their `/v1` twins), the runner hub (it authenticates the runner itself) and, +outside Production, `/openapi` + `/scalar`. The Api takes `Authorization: Bearer` with a Keycloak access token +(people, RS256 only) **or** an AgentOS.NET API token `aos_…` (personal tokens and service accounts, scoped read / run / +admin — Settings → API tokens); the Web uses a cookie session (`/account/login` → OIDC). Both hosts rate-limit per +tenant, per user and per anonymous client (Settings → Platform → Request limits) — a token counts as its tenant and +principal exactly like a JWT. Contract, auth, CI example and deprecation policy: **[docs/API.md](docs/API.md)**; +OpenAPI: [docs/api/openapi-v1.json](docs/api/openapi-v1.json) (live in the **Scalar UI** at `/scalar/v1` outside +Production). The most used routes (all under `/v1`): | Method | Path | Auth | Description | |---|---|---|---| | `POST` | `/pipeline` · `/pipeline/stream` | signed in | Run the full flow (SSE progress on `/stream`) | | `POST` | `/requirement` · `/code` · `/test` · `/qa` | signed in | Run one agent on its own | | `GET` | `/runs`, `/runs/{id}` | signed in | Persisted runs | -| `GET` | `/tenants/me` | signed in | Resolved tenant, user, roles | +| `GET` | `/tenants/me` | signed in | Resolved tenant, user, roles (and an API token's scopes) | | `GET` `POST` | `/tenants`, `/tenants/{id}/members` | Admin | Tenants and members | | `GET` `POST` `DELETE` | `/settings*` | Admin | Legacy runtime-config endpoint (see CONFIG.md) | | `POST` | `/llm/test` | signed in | Probe the configured provider with a minimal call | diff --git a/SECURITY.md b/SECURITY.md index 243a69f5..cd2c9f3b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -25,6 +25,10 @@ When reporting, include: affected component, reproduction steps, and impact. [docs/SETUP.md](docs/SETUP.md). - **API auth** is Keycloak OIDC JWT bearer (RS256); tokens are signed by the Keycloak realm key and validated against its JWKS — rotate the signing key in Keycloak, not in AgentOS.NET. +- **API tokens** (`aos_…`, personal tokens and service accounts) are the machine credential for CI, scripts and the + VS Code extension. Treat one like a password: store it in a CI secret store or VS Code secret storage, never in a + repository; give it the lowest scope that works (`read` < `run` < `admin`) and the shortest expiry; revoke it in + **Settings → API tokens** the moment it may have leaked (effective on the next request). See [docs/API.md](docs/API.md#api-tokens). - The **remote dev-agent runtime** executes work on a developer machine — treat the pairing credential as a secret. Remote execution is gated by the `RemoteAgent:AutoApprove` platform setting, which Production locks off (a gate, not yet a per-run human approval — see the @@ -55,6 +59,12 @@ When reporting, include: affected component, reproduction steps, and impact. - **QA gate before every PR** — a pipeline result becomes a pull request only when QA passed on real model output (`PrGate`, enforced inside the PR service itself): failed runs, the iteration cap with QA still failing, and offline canned text are blocked with the reason on the session. +- **API tokens** — shown once, stored only as a salted HMAC-SHA256 (per-token random salt) and compared in constant + time; scoped (`read` = safe methods, `run` = writes, `admin` = the workspace-admin role, never `platform-admin`), + always expiring (capped by the `Tenants:ApiTokens:MaxLifetimeDays` platform setting), revocable, with last use + shown. Create, revoke, use and refusal are audited (use / refusal at most once per token per 5 minutes, with IP and + user agent). Service accounts need a workspace admin; a removed member's personal tokens are revoked before their + account is deleted. - **Approval policies + repo safety** — per tenant / project, an approver (or admin) approves the plan, the pull request, the change and/or the merge on Board › Tasks (audited); a gate fails closed — rejected or nobody who can approve stops the task. AgentOS.NET never opens a pull request from, or merges, the default branch, and refuses a diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 00000000..ced3bbe1 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,146 @@ +# AgentOS.NET REST API + +The Api host (`src/AgentOs.Api`) serves a versioned REST API, an MCP endpoint at `/mcp`, and the paired-runner +SignalR hub. This page is the contract: how versions work, how to authenticate (people and machines), and what +happens when something is deprecated. + +- **Current version:** `v1` — every route is under `/v1/…`. +- **OpenAPI:** [`docs/api/openapi-v1.json`](api/openapi-v1.json) (committed, reviewed with each change) and live at + `/openapi/v1.json` + the Scalar UI at `/scalar/v1` outside Production. + +## Versions + +| Path | Status | Notes | +|---|---|---| +| `/v1/` | **current** | The contract. Named operations, documented in `openapi-v1.json`. | +| `/` (no version) | **deprecated** since 2026-11-03, sunset **2027-05-03** | The same handlers. Still work; answer with deprecation headers (below). Not in the OpenAPI document. | +| `/`, `/version`, `/health`, `/alive`, `/health/llm` | unversioned | Operational probes — never versioned, never deprecated. | +| `/mcp` | unversioned | MCP (Streamable HTTP) — versioned by the MCP protocol itself. | +| `/hubs/remote-agent` | unversioned | Paired-runner SignalR hub — versioned by its own wire contract. | + +Every module's REST routes are mapped through `ModuleLoader.MapVersionedModuleEndpoints` +(`src/AgentOs.SharedKernel/Modularity/ModuleLoader.cs`): once under `/v1` and once at the old path with +`ApiDeprecationMetadata`. A module whose endpoints are a protocol (a SignalR hub) implements +`IProtocolEndpointModule` and is mapped once, at its own path. + +### Deprecation headers + +A response from a deprecated route carries: + +```http +Deprecation: @1793664000 +Sunset: Mon, 03 May 2027 00:00:00 GMT +Link: ; rel="successor-version", ; rel="deprecation"; type="text/html" +``` + +- `Deprecation` ([RFC 9745](https://www.rfc-editor.org/rfc/rfc9745)) — when the route was deprecated (an RFC 9651 + date: `@` + Unix seconds). +- `Sunset` ([RFC 8594](https://www.rfc-editor.org/rfc/rfc8594)) — the earliest date it may stop working. +- `Link rel="successor-version"` — the route to call instead; `rel="deprecation"` — this policy. + +The headers are added before authentication, so a `401`, `403` or `429` from a deprecated route says so too. +Clients should log or alert on any response that carries `Deprecation`. + +## Deprecation policy + +1. **Within a version, changes are additive only.** New routes, new optional request fields and new response fields + may appear in `v1` at any time; clients must ignore unknown response fields. Removing or renaming a route, a + required field or a response field, or changing a field's type or meaning, is a breaking change. +2. **A breaking change ships as a new version** (`/v2/…`) next to the old one. The old version's routes are then + marked deprecated and keep working. +3. **Minimum notice: six months** from the first release that announces the deprecation to the `Sunset` date, and + never removed in a patch release. The `Deprecation` and `Sunset` headers, this page and the + [CHANGELOG](../CHANGELOG.md) (**Deprecated** section, with a migration note) announce it together. +4. **After the sunset date** the route may be removed in the next minor or major release; removals are listed under + **Removed** in the CHANGELOG with the successor route. +5. **Security exception.** A route that cannot be made safe may be withdrawn sooner; the CHANGELOG **Security** + section says why and what to use instead. +6. **The committed OpenAPI document is the review gate.** `docs/api/openapi-v1.json` is regenerated by a test + (`ApiV1IntegrationTests`, `AGENTOS_UPDATE_OPENAPI=1`) and the test fails when the running Api no longer matches + it — so every contract change shows up as a diff in the pull request and is reviewed against rule 1. + +The unversioned routes that existed before `v1` are the first deprecation under this policy: deprecated +2026-11-03, sunset 2027-05-03. + +## Authentication + +Every route except the operational probes and the public sign-up / invitation-preview routes needs +`Authorization: Bearer `. The Api accepts two kinds of bearer token on the same header: + +| Token | Who | How it is checked | +|---|---|---| +| Keycloak access token (JWT, RS256) | people (the desktop, Scalar) | signature against the realm JWKS, issuer, audience, lifetime | +| AgentOS.NET API token `aos__` | scripts, CI, the VS Code extension, MCP clients | prefix lookup → salted-HMAC compare in constant time → not revoked, not expired | + +`Bearer aos_…` is forwarded from the JWT scheme to the API-token scheme +(`ApiTokenAuthentication.AddApiTokenAuthentication`), so nothing else changes for callers: the principal carries the +same `tenant`, `sub`, name and role claims a JWT would. + +### API tokens + +Created in the desktop, **Settings → People & data → API tokens**: + +- **Personal token** — any member. Acts as that member (`sub` = their user id; runs are attributed to them). Revoked + automatically when the member is removed from the workspace. +- **Service account** — workspace admins only. A workspace identity for CI (`sub` = `apitoken:`, name + `service:`), not tied to a person. + +Each token has a **scope** (closed upwards — admin includes run includes read): + +| Scope | Allows | +|---|---| +| `read` | `GET` / `HEAD` / `OPTIONS` — runs, results, settings views, `/v1/tenants/me` | +| `run` | also `POST` / `PUT` / `PATCH` / `DELETE` — start pipeline runs, upload ticket files, call `/mcp` | +| `admin` | also the workspace-admin routes (the principal gets the `admin` role). Admins only. Never `platform-admin`. | + +A request whose method needs a scope the token lacks gets `403` (`application/problem+json`, *Insufficient token +scope*). An invalid, revoked or expired token gets `401` with `WWW-Authenticate: Bearer error="invalid_token"`. + +The plaintext is shown **once** at creation; only a salted HMAC-SHA256 is stored. Every token expires — at most +`Tenants:ApiTokens:MaxLifetimeDays` (platform setting, default 366 days; see [CONFIG.md](CONFIG.md)). Creation, +revocation and use are audited (**Settings → Audit log**: `apitoken.created`, `apitoken.revoked`, `apitoken.used`, +`apitoken.refused`; use and refusal rows are written at most once per token per 5 minutes, with the caller's IP and +user agent). The token list shows when each token was last used. + +Check what a token resolves to: + +```bash +curl -s -H "Authorization: Bearer $AGENTOS_TOKEN" https://agentos.example.com/v1/tenants/me +# {"tenantId":"acme","userId":"apitoken:…","userName":"service:ci-deploy","roles":["member"], +# "isAuthenticated":true,"isAdmin":false,"authMethod":"api_token","scopes":["read","run"]} +``` + +### CI: start a run with a service account + +Create a service account with the `run` scope, store it as a CI secret, and call the Api: + +```yaml +# .github/workflows/agentos.yml +jobs: + agentos: + runs-on: ubuntu-latest + steps: + - name: Run the AgentOS.NET pipeline + env: + AGENTOS_URL: https://agentos.example.com + AGENTOS_TOKEN: ${{ secrets.AGENTOS_TOKEN }} + run: | + curl --fail-with-body -sS -X POST "$AGENTOS_URL/v1/pipeline" \ + -H "Authorization: Bearer $AGENTOS_TOKEN" -H "Content-Type: application/json" \ + -d '{"description":"As a user I can reset my password by email"}' +``` + +`/v1/pipeline/stream` returns the same run as Server-Sent Events (`progress`, `result`, `error`). + +### VS Code extension + +The **AgentOS.NET Runner** extension (`tools/agentos-vscode`) uses a personal token for API calls: +**AgentOS.NET: Set API token** stores it in VS Code secret storage (checked against `/v1/tenants/me`), +**Run the pipeline on a user story** calls `POST /v1/pipeline`, **Check API token** / **Clear API token** manage it. +Set `agentos.apiUrl` to the Api's base URL. + +## Errors + +Errors are RFC 7807 `application/problem+json` (`status`, `title`, `detail`, `traceId`); validation failures are +`400` with an `errors` map. `402` means the workspace's monthly budget cap is reached; `429` is the per-tenant rate +limit (120 requests/minute on the Api). diff --git a/docs/CONFIG.md b/docs/CONFIG.md index de09be5c..ca1e3e79 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -415,6 +415,7 @@ as one fixed dev user, so production-sized per-user buckets would throttle a UI | Key | Default | Notes | |---|---|---| | `RemoteAgent:AutoApprove` | `false` (Production locked) | Unattended remote execution. | +| `Tenants:ApiTokens:MaxLifetimeDays` | `366` (platform, 1–1825) | Longest expiry a new personal token or service-account token may get (Settings → Platform → Safety). Existing tokens keep their expiry. See [API.md](API.md#api-tokens). | | `Tenants:OpenSignup` | `true` in Development, else `false` | Lets anyone create a new workspace (and become its admin) from `/signup` / `POST /tenants/register`. Invitations always work. Pin it with `Settings:Locks:Tenants:OpenSignup`. | | `Tools:EnforceByDefault` | `true` in Production, else `false` | Fail-closed tool policy. | | `Workspaces:AllowedHosts` | empty | Self-hosted GitHub Enterprise / Azure DevOps Server hosts, comma-separated (atop `SsrfGuard`; public provider hosts always allowed). | diff --git a/docs/api/openapi-v1.json b/docs/api/openapi-v1.json new file mode 100644 index 00000000..98ffbb45 --- /dev/null +++ b/docs/api/openapi-v1.json @@ -0,0 +1,2895 @@ +{ + "openapi": "3.1.1", + "info": { + "title": "AgentOS.NET API", + "description": "Versioned REST API of AgentOS.NET. Authenticate with \u0060Authorization: Bearer \u003Ctoken\u003E\u0060 \u2014 a Keycloak access token (people) or an AgentOS.NET API token \u0060aos_\u2026\u0060 (personal tokens and service accounts, created in Settings \u203A API tokens; scopes: read = GET, run = also POST/PUT/PATCH/DELETE, admin = also tenant-admin routes). The unversioned routes (the same paths without \u0060/v1\u0060) are deprecated and answer with \u0060Deprecation\u0060, \u0060Sunset\u0060 and \u0060Link: rel=\u0022successor-version\u0022\u0060 headers; see https://github.com/hoangsnowy/AgentOS.NET/blob/main/docs/API.md#deprecation-policy.", + "license": { + "name": "MIT" + }, + "version": "v1" + }, + "paths": { + "/": { + "get": { + "tags": [ + "Meta" + ], + "summary": "Service identity", + "operationId": "Root", + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/version": { + "get": { + "tags": [ + "Meta" + ], + "summary": "Running release version (monitoring/upgrade verification)", + "operationId": "Version", + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/health/llm": { + "get": { + "tags": [ + "Meta" + ], + "summary": "LLM provider configuration readiness (not a pod-recycle signal)", + "operationId": "HealthLlm", + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/settings/{prefix}": { + "get": { + "tags": [ + "Settings" + ], + "summary": "Read every key beneath a prefix (Llm, Github); secret values are masked", + "operationId": "SettingsList", + "parameters": [ + { + "name": "prefix", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/settings/Github/test": { + "post": { + "tags": [ + "Settings" + ], + "summary": "Probe GitHub with the saved (or a just-typed) Pipeline auto-PR token; never returns the token", + "operationId": "SettingsGithubTest", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/GitHubTestRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/settings": { + "post": { + "tags": [ + "Settings" + ], + "summary": "Set a single key (overwrite if present)", + "operationId": "SettingsSet", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/SetEntryRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/settings/{key}": { + "delete": { + "tags": [ + "Settings" + ], + "summary": "Delete a key", + "operationId": "SettingsDelete", + "parameters": [ + { + "name": "key", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/tenants/me": { + "get": { + "tags": [ + "Tenants" + ], + "summary": "Resolved tenant \u002B user \u002B roles (and, for an API token, its scopes) for the current request", + "operationId": "TenantMe", + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/tenants": { + "get": { + "tags": [ + "Tenants" + ], + "summary": "List every tenant (platform admin only)", + "operationId": "TenantsList", + "responses": { + "200": { + "description": "OK" + } + } + }, + "post": { + "tags": [ + "Tenants" + ], + "summary": "Provision a tenant \u002B admin user (platform admin only)", + "operationId": "TenantsCreate", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateTenantRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/tenants/register": { + "post": { + "tags": [ + "Tenants" + ], + "summary": "Self-service sign-up: invite / slug / auto-create (public)", + "operationId": "TenantsRegister", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RegisterTenantRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/tenants/{tenantId}/invitations": { + "post": { + "tags": [ + "Tenants" + ], + "summary": "Mint a signup invitation URL for the tenant (admin only)", + "operationId": "TenantsCreateInvitation", + "parameters": [ + { + "name": "tenantId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateInvitationRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/tenants/invitations/preview": { + "get": { + "tags": [ + "Tenants" + ], + "summary": "Decode an invitation token without consuming it (public)", + "operationId": "TenantsPreviewInvitation", + "parameters": [ + { + "name": "token", + "in": "query", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/tenants/{tenantId}/members": { + "get": { + "tags": [ + "Tenants" + ], + "summary": "List the members of the current tenant (tenant Admin only)", + "operationId": "TenantsListMembers", + "parameters": [ + { + "name": "tenantId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + }, + "post": { + "tags": [ + "Tenants" + ], + "summary": "Invite a member into a tenant (admin only)", + "operationId": "TenantsInviteMember", + "parameters": [ + { + "name": "tenantId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InviteMemberRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/tenants/{tenantId}/members/{userId}": { + "patch": { + "tags": [ + "Tenants" + ], + "summary": "Change a member\u0027s roles (tenant Admin only)", + "operationId": "TenantsUpdateMemberRoles", + "parameters": [ + { + "name": "tenantId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateMemberRolesRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + } + }, + "delete": { + "tags": [ + "Tenants" + ], + "summary": "Remove a member from the tenant (tenant Admin only)", + "operationId": "TenantsRemoveMember", + "parameters": [ + { + "name": "tenantId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/tenants/{tenantId}/members/{userId}/reset-password": { + "post": { + "tags": [ + "Tenants" + ], + "summary": "Send a member a password-reset email (tenant Admin only)", + "operationId": "TenantsResetMemberPassword", + "parameters": [ + { + "name": "tenantId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "userId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/tenants/{tenantId}/audit": { + "get": { + "tags": [ + "Tenants" + ], + "summary": "Audit trail for the current tenant (tenant Admin only)", + "operationId": "TenantsAudit", + "parameters": [ + { + "name": "tenantId", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "max", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/requirement": { + "post": { + "tags": [ + "Agents" + ], + "summary": "KC1 \u2014 Analyze user story \u2192 structured requirement spec", + "operationId": "Requirement", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UserStory" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RequirementSpec" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/HttpValidationProblemDetails" + } + } + } + }, + "402": { + "description": "Payment Required", + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + } + } + }, + "/v1/code": { + "post": { + "tags": [ + "Agents" + ], + "summary": "KC2 \u2014 Generate C# Clean Architecture source code from the spec", + "operationId": "Code", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/CodeRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CodeArtifact" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/HttpValidationProblemDetails" + } + } + } + }, + "402": { + "description": "Payment Required", + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + } + } + }, + "/v1/test": { + "post": { + "tags": [ + "Agents" + ], + "summary": "KC3 \u2014 Generate xUnit tests (happy/edge/error)", + "operationId": "Test", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/TestRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TestArtifact" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/HttpValidationProblemDetails" + } + } + } + }, + "402": { + "description": "Payment Required", + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + } + } + }, + "/v1/qa": { + "post": { + "tags": [ + "Agents" + ], + "summary": "KC5 \u2014 Assess requirement-code-test consistency", + "operationId": "Qa", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/QaRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/QaReport" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/HttpValidationProblemDetails" + } + } + } + }, + "402": { + "description": "Payment Required", + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + } + } + }, + "/v1/pipeline": { + "post": { + "tags": [ + "Agents" + ], + "summary": "KC4 \u2014 End-to-end pipeline with QA loop (\u2264 NMax iterations)", + "operationId": "Pipeline", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UserStory" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PipelineResult" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PipelineResult" + } + } + } + }, + "400": { + "description": "Bad Request", + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/HttpValidationProblemDetails" + } + } + } + } + } + } + }, + "/v1/pipeline/stream": { + "post": { + "tags": [ + "Agents" + ], + "summary": "KC4 \u2014 Streamed pipeline run. SSE events: progress | result | error", + "operationId": "PipelineStream", + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UserStory" + } + ] + } + } + } + }, + "responses": { + "400": { + "description": "Bad Request", + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/HttpValidationProblemDetails" + } + } + } + } + } + } + }, + "/v1/runs": { + "get": { + "tags": [ + "History" + ], + "summary": "Pipeline run history (summaries, newest first). ?limit (\u2264500) and ?offset page through it.", + "operationId": "Runs", + "parameters": [ + { + "name": "limit", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + }, + { + "name": "offset", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PipelineRunSummary" + } + } + } + } + } + } + } + }, + "/v1/runs/{id}": { + "get": { + "tags": [ + "History" + ], + "summary": "Details of a single pipeline run (full artifact \u002B metrics)", + "operationId": "RunById", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PipelineRunRecord" + } + } + } + }, + "404": { + "description": "Not Found" + } + } + } + }, + "/v1/mcp/servers": { + "get": { + "tags": [ + "Mcp" + ], + "summary": "Configured upstream MCP servers \u002B startup connection status", + "operationId": "McpServers", + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/llm/test": { + "post": { + "tags": [ + "Settings" + ], + "summary": "Probe the configured LLM provider with a minimal call", + "operationId": "LlmTest", + "parameters": [ + { + "name": "provider", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/workspaces": { + "get": { + "tags": [ + "WorkspaceEndpoints" + ], + "parameters": [ + { + "name": "limit", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + }, + { + "name": "offset", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + }, + "post": { + "tags": [ + "WorkspaceEndpoints" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ConnectWorkspaceRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/workspaces/{id}": { + "get": { + "tags": [ + "WorkspaceEndpoints" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + }, + "delete": { + "tags": [ + "WorkspaceEndpoints" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/workspaces/repos": { + "post": { + "tags": [ + "WorkspaceEndpoints" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ListReposRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/workspaces/boards": { + "post": { + "tags": [ + "WorkspaceEndpoints" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ListReposRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/workspaces/{id}/repos": { + "get": { + "tags": [ + "WorkspaceEndpoints" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + }, + "post": { + "tags": [ + "WorkspaceEndpoints" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/AddRepoRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/workspaces/{id}/repos/{repoId}": { + "delete": { + "tags": [ + "WorkspaceEndpoints" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "repoId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/workspaces/{id}/context": { + "get": { + "tags": [ + "WorkspaceEndpoints" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/sessions": { + "get": { + "tags": [ + "SessionEndpoints" + ], + "parameters": [ + { + "name": "limit", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + }, + { + "name": "offset", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + }, + "post": { + "tags": [ + "SessionEndpoints" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/CreateSessionRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/sessions/{id}": { + "get": { + "tags": [ + "SessionEndpoints" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/sessions/{id}/close": { + "post": { + "tags": [ + "SessionEndpoints" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/runners": { + "get": { + "tags": [ + "SessionEndpoints" + ], + "parameters": [ + { + "name": "limit", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + }, + { + "name": "offset", + "in": "query", + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + }, + "post": { + "tags": [ + "SessionEndpoints" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RegisterRunnerRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/runners/{id}/revoke": { + "post": { + "tags": [ + "SessionEndpoints" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/workspaces/{boardId}/tickets/{issue}/files": { + "get": { + "tags": [ + "TicketFileEndpoints" + ], + "parameters": [ + { + "name": "boardId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "issue", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/workspaces/{boardId}/tickets/{issue}/files/{path}": { + "get": { + "tags": [ + "TicketFileEndpoints" + ], + "parameters": [ + { + "name": "boardId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "issue", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + }, + "put": { + "tags": [ + "TicketFileEndpoints" + ], + "parameters": [ + { + "name": "boardId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "issue", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + }, + "delete": { + "tags": [ + "TicketFileEndpoints" + ], + "parameters": [ + { + "name": "boardId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "issue", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/tasks/{sessionId}/design": { + "get": { + "tags": [ + "DesignReviewEndpoints" + ], + "parameters": [ + { + "name": "sessionId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + }, + "/v1/tasks/{sessionId}/design/{run}/shots/{path}": { + "get": { + "tags": [ + "DesignReviewEndpoints" + ], + "parameters": [ + { + "name": "sessionId", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "run", + "in": "path", + "required": true, + "schema": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": "integer", + "format": "int32" + } + }, + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + } + } + } + }, + "components": { + "schemas": { + "AddRepoRequest": { + "required": [ + "owner", + "repo", + "defaultBranch" + ], + "type": "object", + "properties": { + "owner": { + "type": "string" + }, + "repo": { + "type": "string" + }, + "defaultBranch": { + "type": [ + "null", + "string" + ] + } + } + }, + "AgentMetrics": { + "required": [ + "provider", + "model", + "inputTokens", + "outputTokens", + "costUsd", + "latency" + ], + "type": "object", + "properties": { + "provider": { + "type": "string" + }, + "model": { + "type": "string" + }, + "inputTokens": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "outputTokens": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "costUsd": { + "pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d\u002B)?$", + "type": [ + "number", + "string" + ], + "format": "double" + }, + "latency": { + "pattern": "^-?(\\d\u002B\\.)?\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,7})?$", + "type": "string" + }, + "cacheReadTokens": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "cacheWriteTokens": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "reasoningTokens": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + } + }, + "CodeArtifact": { + "required": [ + "projectName", + "architecture", + "files", + "notes", + "metrics" + ], + "type": "object", + "properties": { + "projectName": { + "type": "string" + }, + "architecture": { + "type": "string" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CodeFile" + } + }, + "notes": { + "type": [ + "null", + "string" + ] + }, + "metrics": { + "$ref": "#/components/schemas/AgentMetrics" + } + } + }, + "CodeFile": { + "required": [ + "path", + "content" + ], + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "content": { + "type": "string" + }, + "language": { + "type": "string", + "default": "csharp" + } + } + }, + "CodeRequest": { + "required": [ + "spec" + ], + "type": "object", + "properties": { + "spec": { + "$ref": "#/components/schemas/RequirementSpec" + }, + "previousFeedback": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/QaReport" + } + ] + } + } + }, + "ConnectWorkspaceRequest": { + "required": [ + "name", + "kind", + "projectOwner", + "projectScope", + "projectNumber", + "project", + "host", + "accessToken" + ], + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "kind": { + "$ref": "#/components/schemas/SourceProviderKind" + }, + "projectOwner": { + "type": "string" + }, + "projectScope": { + "type": "string" + }, + "projectNumber": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "null", + "integer", + "string" + ], + "format": "int32" + }, + "project": { + "type": [ + "null", + "string" + ] + }, + "host": { + "type": [ + "null", + "string" + ] + }, + "accessToken": { + "type": "string" + }, + "tracker": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/TrackerBinding" + } + ] + }, + "trackerAccessToken": { + "type": [ + "null", + "string" + ] + } + } + }, + "CreateInvitationRequest": { + "required": [ + "email", + "role", + "ttlHours" + ], + "type": "object", + "properties": { + "email": { + "type": [ + "null", + "string" + ] + }, + "role": { + "type": [ + "null", + "string" + ] + }, + "ttlHours": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "null", + "integer", + "string" + ], + "format": "int32" + } + } + }, + "CreateSessionRequest": { + "required": [ + "workspaceId", + "title" + ], + "type": "object", + "properties": { + "workspaceId": { + "type": "string", + "format": "uuid" + }, + "title": { + "type": "string" + } + } + }, + "CreateTenantRequest": { + "required": [ + "id", + "name", + "adminUsername", + "adminEmail" + ], + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": [ + "null", + "string" + ] + }, + "adminUsername": { + "type": "string" + }, + "adminEmail": { + "type": [ + "null", + "string" + ] + } + } + }, + "EndpointDescriptor": { + "required": [ + "method", + "path", + "purpose" + ], + "type": "object", + "properties": { + "method": { + "type": "string" + }, + "path": { + "type": "string" + }, + "purpose": { + "type": "string" + }, + "authRequired": { + "type": "boolean", + "default": false + } + } + }, + "EntityDescriptor": { + "required": [ + "name", + "fields" + ], + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "fields": { + "type": "array", + "items": { + "type": "string" + } + }, + "notes": { + "type": [ + "null", + "string" + ] + } + } + }, + "GitHubTestRequest": { + "type": "object", + "properties": { + "token": { + "type": [ + "null", + "string" + ] + }, + "owner": { + "type": [ + "null", + "string" + ] + }, + "repo": { + "type": [ + "null", + "string" + ] + }, + "branch": { + "type": [ + "null", + "string" + ] + } + } + }, + "HttpValidationProblemDetails": { + "type": "object", + "properties": { + "type": { + "type": [ + "null", + "string" + ] + }, + "title": { + "type": [ + "null", + "string" + ] + }, + "status": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "null", + "integer", + "string" + ], + "format": "int32" + }, + "detail": { + "type": [ + "null", + "string" + ] + }, + "instance": { + "type": [ + "null", + "string" + ] + }, + "errors": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + }, + "InviteMemberRequest": { + "required": [ + "username", + "email", + "roles" + ], + "type": "object", + "properties": { + "username": { + "type": "string" + }, + "email": { + "type": [ + "null", + "string" + ] + }, + "roles": { + "type": [ + "null", + "array" + ], + "items": { + "type": "string" + } + } + } + }, + "ListReposRequest": { + "required": [ + "kind", + "accessToken", + "owner", + "host" + ], + "type": "object", + "properties": { + "kind": { + "$ref": "#/components/schemas/SourceProviderKind" + }, + "accessToken": { + "type": "string" + }, + "owner": { + "type": [ + "null", + "string" + ] + }, + "host": { + "type": [ + "null", + "string" + ] + } + } + }, + "PipelineResult": { + "required": [ + "userStory", + "spec", + "code", + "tests", + "qaHistory", + "status", + "totalMetrics" + ], + "type": "object", + "properties": { + "userStory": { + "$ref": "#/components/schemas/UserStory" + }, + "spec": { + "$ref": "#/components/schemas/RequirementSpec" + }, + "code": { + "$ref": "#/components/schemas/CodeArtifact" + }, + "tests": { + "$ref": "#/components/schemas/TestArtifact" + }, + "qaHistory": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QaReport" + } + }, + "status": { + "$ref": "#/components/schemas/PipelineStatus" + }, + "totalMetrics": { + "$ref": "#/components/schemas/AgentMetrics" + }, + "iterationCount": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "isOffline": { + "type": "boolean" + } + } + }, + "PipelineRunRecord": { + "required": [ + "id", + "result", + "metrics", + "createdAtUtc", + "completedAtUtc" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "result": { + "$ref": "#/components/schemas/PipelineResult" + }, + "metrics": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RunMetric" + } + }, + "createdAtUtc": { + "type": "string", + "format": "date-time" + }, + "completedAtUtc": { + "type": "string", + "format": "date-time" + } + } + }, + "PipelineRunSummary": { + "required": [ + "id", + "status", + "totalCostUsd", + "iterationCount", + "createdAtUtc", + "completedAtUtc", + "userStoryPreview" + ], + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "status": { + "type": "string" + }, + "totalCostUsd": { + "pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d\u002B)?$", + "type": [ + "number", + "string" + ], + "format": "double" + }, + "iterationCount": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "createdAtUtc": { + "type": "string", + "format": "date-time" + }, + "completedAtUtc": { + "type": [ + "null", + "string" + ], + "format": "date-time" + }, + "userStoryPreview": { + "type": "string" + } + } + }, + "PipelineStatus": { + "type": "integer" + }, + "ProblemDetails": { + "type": "object", + "properties": { + "type": { + "type": [ + "null", + "string" + ] + }, + "title": { + "type": [ + "null", + "string" + ] + }, + "status": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "null", + "integer", + "string" + ], + "format": "int32" + }, + "detail": { + "type": [ + "null", + "string" + ] + }, + "instance": { + "type": [ + "null", + "string" + ] + } + } + }, + "QaIssue": { + "required": [ + "severity", + "category", + "description" + ], + "type": "object", + "properties": { + "severity": { + "type": "string" + }, + "category": { + "type": "string" + }, + "description": { + "type": "string" + }, + "location": { + "type": [ + "null", + "string" + ] + } + } + }, + "QaReport": { + "required": [ + "score", + "isConsistent", + "iterationNeeded", + "issues", + "recommendations", + "metrics" + ], + "type": "object", + "properties": { + "score": { + "pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d\u002B)?(?:[eE][\u002B-]?\\d\u002B)?$", + "type": [ + "number", + "string" + ], + "format": "double" + }, + "isConsistent": { + "type": "boolean" + }, + "iterationNeeded": { + "type": "boolean" + }, + "issues": { + "type": "array", + "items": { + "$ref": "#/components/schemas/QaIssue" + } + }, + "recommendations": { + "type": "array", + "items": { + "type": "string" + } + }, + "metrics": { + "$ref": "#/components/schemas/AgentMetrics" + } + } + }, + "QaRequest": { + "required": [ + "spec", + "code", + "tests" + ], + "type": "object", + "properties": { + "spec": { + "$ref": "#/components/schemas/RequirementSpec" + }, + "code": { + "$ref": "#/components/schemas/CodeArtifact" + }, + "tests": { + "$ref": "#/components/schemas/TestArtifact" + } + } + }, + "RegisterRunnerRequest": { + "required": [ + "label" + ], + "type": "object", + "properties": { + "label": { + "type": "string" + } + } + }, + "RegisterTenantRequest": { + "required": [ + "tenantId", + "tenantName", + "username", + "email", + "password", + "inviteToken" + ], + "type": "object", + "properties": { + "tenantId": { + "type": [ + "null", + "string" + ] + }, + "tenantName": { + "type": [ + "null", + "string" + ] + }, + "username": { + "type": "string" + }, + "email": { + "type": [ + "null", + "string" + ] + }, + "password": { + "type": "string" + }, + "inviteToken": { + "type": [ + "null", + "string" + ] + } + } + }, + "RequirementSpec": { + "required": [ + "title", + "summary", + "stakeholders", + "functionalRequirements", + "nonFunctionalRequirements", + "entities", + "endpoints", + "acceptanceCriteria", + "metrics" + ], + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "stakeholders": { + "type": "array", + "items": { + "type": "string" + } + }, + "functionalRequirements": { + "type": "array", + "items": { + "type": "string" + } + }, + "nonFunctionalRequirements": { + "type": "array", + "items": { + "type": "string" + } + }, + "entities": { + "type": "array", + "items": { + "$ref": "#/components/schemas/EntityDescriptor" + } + }, + "endpoints": { + "type": "array", + "items": { + "$ref": "#/components/schemas/EndpointDescriptor" + } + }, + "acceptanceCriteria": { + "type": "array", + "items": { + "type": "string" + } + }, + "metrics": { + "$ref": "#/components/schemas/AgentMetrics" + } + } + }, + "RunMetric": { + "required": [ + "runId", + "kcId", + "iteration", + "agentName", + "model", + "provider", + "tokensIn", + "tokensOut", + "latencyMs", + "costUsd", + "success", + "errorMessage", + "timestamp" + ], + "type": "object", + "properties": { + "runId": { + "type": "string" + }, + "kcId": { + "type": "string" + }, + "iteration": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "agentName": { + "type": "string" + }, + "model": { + "type": "string" + }, + "provider": { + "type": "string" + }, + "tokensIn": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "tokensOut": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "latencyMs": { + "pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d\u002B)?(?:[eE][\u002B-]?\\d\u002B)?$", + "type": [ + "number", + "string" + ], + "format": "double" + }, + "costUsd": { + "pattern": "^-?(?:0|[1-9]\\d*)(?:\\.\\d\u002B)?$", + "type": [ + "number", + "string" + ], + "format": "double" + }, + "success": { + "type": "boolean" + }, + "errorMessage": { + "type": [ + "null", + "string" + ] + }, + "timestamp": { + "type": "string", + "format": "date-time" + }, + "cacheReadTokens": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32", + "default": 0 + }, + "cacheWriteTokens": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32", + "default": 0 + }, + "reasoningTokens": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32", + "default": 0 + } + } + }, + "SetEntryRequest": { + "required": [ + "key", + "value" + ], + "type": "object", + "properties": { + "key": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "SourceProviderKind": { + "type": "integer" + }, + "TestArtifact": { + "required": [ + "framework", + "files", + "happyPathCount", + "edgeCaseCount", + "errorCaseCount", + "estimatedCoveragePercent", + "metrics" + ], + "type": "object", + "properties": { + "framework": { + "type": "string" + }, + "files": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CodeFile" + } + }, + "happyPathCount": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "edgeCaseCount": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "errorCaseCount": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "estimatedCoveragePercent": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + }, + "metrics": { + "$ref": "#/components/schemas/AgentMetrics" + }, + "totalCount": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32" + } + } + }, + "TestRequest": { + "required": [ + "spec", + "code" + ], + "type": "object", + "properties": { + "spec": { + "$ref": "#/components/schemas/RequirementSpec" + }, + "code": { + "$ref": "#/components/schemas/CodeArtifact" + }, + "previousFeedback": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/QaReport" + } + ] + } + } + }, + "TrackerBinding": { + "required": [ + "kind", + "site", + "project", + "account", + "filter", + "startState", + "doneState" + ], + "type": "object", + "properties": { + "kind": { + "$ref": "#/components/schemas/SourceProviderKind" + }, + "site": { + "type": "string" + }, + "project": { + "type": "string" + }, + "account": { + "type": [ + "null", + "string" + ] + }, + "filter": { + "$ref": "#/components/schemas/TrackerFilter" + }, + "startState": { + "type": [ + "null", + "string" + ] + }, + "doneState": { + "type": [ + "null", + "string" + ] + }, + "host": { + "type": [ + "null", + "string" + ] + } + } + }, + "TrackerFilter": { + "type": "object", + "properties": { + "areaPath": { + "type": [ + "null", + "string" + ] + }, + "iterationPath": { + "type": [ + "null", + "string" + ] + }, + "states": { + "type": [ + "null", + "array" + ], + "items": { + "type": "string" + } + }, + "tags": { + "type": [ + "null", + "array" + ], + "items": { + "type": "string" + } + }, + "jql": { + "type": [ + "null", + "string" + ] + } + } + }, + "UpdateMemberRolesRequest": { + "required": [ + "roles" + ], + "type": "object", + "properties": { + "roles": { + "type": [ + "null", + "array" + ], + "items": { + "type": "string" + } + } + } + }, + "UserStory": { + "required": [ + "description" + ], + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "nMax": { + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ], + "format": "int32", + "default": 3 + }, + "locale": { + "type": "string", + "default": "vi-VN" + } + } + } + }, + "securitySchemes": { + "Bearer": { + "type": "http", + "description": "A Keycloak access token (JWT) or an AgentOS.NET API token (aos_\u2026).", + "scheme": "bearer" + } + } + }, + "security": [ + { + "Bearer": [] + } + ], + "tags": [ + { + "name": "Meta" + }, + { + "name": "Settings" + }, + { + "name": "Tenants" + }, + { + "name": "Agents" + }, + { + "name": "History" + }, + { + "name": "Mcp" + }, + { + "name": "WorkspaceEndpoints" + }, + { + "name": "SessionEndpoints" + }, + { + "name": "TicketFileEndpoints" + }, + { + "name": "DesignReviewEndpoints" + } + ] +} diff --git a/docs/plans/enterprise-readiness.md b/docs/plans/enterprise-readiness.md index 97594bce..098afdcb 100644 --- a/docs/plans/enterprise-readiness.md +++ b/docs/plans/enterprise-readiness.md @@ -47,8 +47,9 @@ real services: | E0.6 per-tenant run admission | #200 | Concurrency + burst tests; Settings → Platform → Run limits | | E0.7 repo instruction files | #197 | Real GitHub: the sandbox's `AGENTS.md` read back on the lab | | E0.8 OpenAI-compatible provider | #198, #202 | Wire test against a real OpenAI-protocol server | +| E1.3 API tokens + service accounts + `/v1` 🟡 | #332, [API.md](../API.md) | Integration tests on the real Api host (token auth next to JWT, scope per method, admin scope → Admin policy, revoked/expired → 401, `/v1` + deprecated twins with headers, OpenAPI = committed copy); lifecycle unit tests. Acceptance still to do on the lab: a CI pipeline triggers a run with a service-account token | | E1.4 tenant export + purge | #208 | Real-auth: export (no secrets) → UI purge → zero rows, users gone, audited | -| E1.5 approval policies + repo safety 🟡 | this PR | Shipped, not yet verified on the lab: policy evaluation, fail-closed paths, Autopilot waiting + resuming, draft PRs and branch-protection / CODEOWNERS refusals unit-tested (mocked GitHub); acceptance — a "merge needs approval" policy holds a lab run until an approver clicks Approve, the audit shows who; a real protected repo refuses an unreviewed merge | +| E1.5 approval policies + repo safety 🟡 | #328 | Shipped, not yet verified on the lab: policy evaluation, fail-closed paths, Autopilot waiting + resuming, draft PRs and branch-protection / CODEOWNERS refusals unit-tested (mocked GitHub); acceptance — a "merge needs approval" policy holds a lab run until an approver clicks Approve, the audit shows who; a real protected repo refuses an unreviewed merge | | E1.6 workspace rules + versioned prompts | #206 | Agent prompt carries the rules; versions + restore | | E1.10 dashboards, alerts, SLOs | #302, [OPERATIONS.md](../OPERATIONS.md) | Real code → OTLP → Prometheus 3.7: every dashboard series present, 3 Grafana dashboards render (light + dark), `AgentOsBudgetBlockingRuns` fired + `AgentOsBudgetOverCap` pending on an over-cap tenant; `promtool test rules` green. Lab over-cap run + Azure deploy still to do | | E1.9 on-prem install (compose + Helm + offline bundle) | #298, [ONPREM.md](../ONPREM.md) | Compose cold install → themed login → desktop; pg_dump restore drill; air-gapped bundle (`docker save`→`load`, no repo) boots; key ring certificate-wrapped, RLS on; chart lint/template + strict schema check; kind cold install + upgrade in CI (`deploy-lint`) | @@ -61,7 +62,7 @@ Live agent runs without an API key: `lab.ps1 pair` routes the lab to this machin 5-agent pipeline completed live. **Next:** -- E1.1 SSO brokering, E1.2 RBAC v2, E1.3 API tokens + `/v1`; E1.5 lab acceptance; +- E1.1 SSO brokering, E1.2 RBAC v2; E1.3 lab acceptance (CI run with a service-account token); E1.5 lab acceptance; - E1.7 skills, E1.8 ADO boards + Jira; - E1.10 ops; tag the first release (E1.11/E1.13 acceptance: `cosign verify` on it); - the open gaps ranked in [threat-model.md § 15](../security/threat-model.md#15-top-gaps-prioritised). @@ -75,8 +76,8 @@ Status: ✅ shipped + verified · 🟡 partial · ❌ absent. "Where" cites the | 1 | SSO | Entra ID / Okta / ADFS / Google via OIDC or SAML, MFA policy, JIT provisioning | ❌ Keycloak local users only | realm has no `identityProviders` | **E1.1** | | 2 | Provisioning | SCIM 2.0 create/update/**deprovision** → sessions revoked | ❌ | — | **E2.1** | | 3 | RBAC | viewer · developer · approver · admin · auditor; per-workspace scope; custom roles later | 🟡 4 roles (admin · approver · member · platform-admin) | `IdentityModule.cs`; `TenantRoles.cs` | **E1.2** | -| 4 | Machine access | API tokens / service accounts, scoped + expiring, for CI and the CLI | ❌ JWT only | — | **E1.3** | -| 5 | API contract | versioned REST (`/v1`), published OpenAPI, deprecation policy | 🟡 unversioned | Scalar UI on Api | **E1.3** | +| 4 | Machine access | API tokens / service accounts, scoped + expiring, for CI and the CLI | 🟡 shipped, lab CI run pending | personal tokens + service accounts, salted HMAC, scopes read/run/admin, max-lifetime setting, audited (`ApiTokens/*`, `ApiTokenTests`, `ApiV1IntegrationTests`); VS Code extension uses them | **E1.3** | +| 5 | API contract | versioned REST (`/v1`), published OpenAPI, deprecation policy | ✅ | `/v1` + deprecated unversioned twins with `Deprecation`/`Sunset` (`ApiVersioning.cs`); [`openapi-v1.json`](../api/openapi-v1.json) gated by a test; [API.md § Deprecation policy](../API.md#deprecation-policy) | **E1.3** | | 6 | Tenant isolation | DB-enforced, proven by test | 🟡 EF filters + E2E (#192), no RLS | plan 0.9 | **E0.1** | | 7 | Key management | DataProtection ring wrapped by KMS (Key Vault / HSM / cert), rotation | 🟡 ring in Postgres, unwrapped | `DataProtectionExtensions.cs` | **E0.2** | | 8 | Data lifecycle | retention per data class, tenant export, purge (GDPR), legal hold | ❌ | — | **E1.4** | diff --git a/docs/security/hardening.md b/docs/security/hardening.md index 18e3ab2a..a66a2901 100644 --- a/docs/security/hardening.md +++ b/docs/security/hardening.md @@ -188,5 +188,11 @@ Tick every box before exposing a deployment to people outside the team that oper - [ ] `ASPNETCORE_ENVIRONMENT=Production` on both hosts (Aspire `launchProfileName: null` drops it — set it explicitly; see CLAUDE.md *Lessons learned*). - [ ] No `Settings__Locks__*` env override unless it is a recorded decision. -- [ ] Scalar / OpenAPI is not exposed (mapped only outside Production, `src/AgentOs.Api/Program.cs:174-183`) — also - keep Staging environments off the internet. +- [ ] Scalar / OpenAPI is not exposed (mapped only outside Production, `src/AgentOs.Api/Program.cs`) — also + keep Staging environments off the internet. The contract is published as [`docs/api/openapi-v1.json`](../api/openapi-v1.json) + instead. +- [ ] API tokens: lower `Tenants:ApiTokens:MaxLifetimeDays` (Settings → Platform → Safety, default 366) to your + credential-rotation policy; review **Settings → API tokens** for stale service accounts (*Last used*), and alert + on `apitoken.refused` rows in the audit log ([API.md](../API.md#api-tokens)). +- [ ] Clients have moved off the deprecated unversioned routes before their sunset (2027-05-03): watch for responses + carrying a `Deprecation` header ([API.md](../API.md#deprecation-policy)). diff --git a/src/AgentOs.Api/ApiDocument.cs b/src/AgentOs.Api/ApiDocument.cs new file mode 100644 index 00000000..42fc3d96 --- /dev/null +++ b/src/AgentOs.Api/ApiDocument.cs @@ -0,0 +1,48 @@ +// E1.3 — the published OpenAPI "v1" document: title, version, how to authenticate (Keycloak JWT or an AgentOS.NET API +// token, both as a Bearer token) and the deprecation policy. The servers list is left out so the committed copy +// (docs/api/openapi-v1.json) is the same on every machine; clients pass their own base URL. + +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using AgentOs.SharedKernel.Http; +using Microsoft.AspNetCore.OpenApi; +using Microsoft.OpenApi; + +namespace AgentOs.Api; + +/// Describes the v1 OpenAPI document. +public sealed class ApiDocumentV1 : IOpenApiDocumentTransformer +{ + /// The bearer security scheme name. + public const string BearerScheme = "Bearer"; + + /// + public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken) + { + System.ArgumentNullException.ThrowIfNull(document); + document.Info = new OpenApiInfo + { + Title = "AgentOS.NET API", + Version = ApiVersions.V1, + Description = + "Versioned REST API of AgentOS.NET. Authenticate with `Authorization: Bearer ` — a Keycloak access token " + + "(people) or an AgentOS.NET API token `aos_…` (personal tokens and service accounts, created in Settings › API tokens; " + + "scopes: read = GET, run = also POST/PUT/PATCH/DELETE, admin = also tenant-admin routes). " + + "The unversioned routes (the same paths without `/v1`) are deprecated and answer with `Deprecation`, `Sunset` and " + + "`Link: rel=\"successor-version\"` headers; see " + ApiVersions.PolicyUrl + ".", + License = new OpenApiLicense { Name = "MIT" }, + }; + document.Servers = []; + document.Components ??= new OpenApiComponents(); + document.Components.SecuritySchemes ??= new Dictionary(); + document.Components.SecuritySchemes[BearerScheme] = new OpenApiSecurityScheme + { + Type = SecuritySchemeType.Http, + Scheme = "bearer", + Description = "A Keycloak access token (JWT) or an AgentOS.NET API token (aos_…).", + }; + document.Security = [new OpenApiSecurityRequirement { [new OpenApiSecuritySchemeReference(BearerScheme, document)] = [] }]; + return Task.CompletedTask; + } +} diff --git a/src/AgentOs.Api/Program.cs b/src/AgentOs.Api/Program.cs index 5aedfa69..eac4ab40 100644 --- a/src/AgentOs.Api/Program.cs +++ b/src/AgentOs.Api/Program.cs @@ -14,9 +14,11 @@ using AgentOs.Modules.RemoteAgent; using AgentOs.Modules.Sessions; using AgentOs.Modules.Tenants; +using AgentOs.Modules.Tenants.ApiTokens; using AgentOs.Modules.Tools; using AgentOs.Modules.Workspaces; using AgentOs.ServiceDefaults; +using AgentOs.SharedKernel.Http; using AgentOs.SharedKernel.Identity; using AgentOs.SharedKernel.Modularity; using AgentOs.SharedKernel.Plugins; @@ -35,7 +37,9 @@ // Console format + per-request tenant/traceId scopes come from ServiceDefaults (AddAgentOsLogging): // JSON console in Production, human-readable elsewhere. -builder.Services.AddOpenApi(); +// E1.3: one OpenAPI document per REST version — "v1" documents the /v1 routes (the deprecated unversioned twins are +// excluded), served at /openapi/v1.json outside Production and committed as docs/api/openapi-v1.json. +builder.Services.AddOpenApi(AgentOs.SharedKernel.Http.ApiVersions.V1, o => o.AddDocumentTransformer()); // RFC 7807 error contract: unhandled endpoint exceptions become application/problem+json (status, // title, traceId) instead of a bare 500 — no stack traces leave the process outside Development. builder.Services.AddProblemDetails(); @@ -69,13 +73,10 @@ // Auth scheme is host-specific: API hosts Keycloak JWT bearer (Web does cookie + OIDC). builder.Services.AddJwtAuth(builder.Configuration); -// E1.3: API tokens (service accounts) next to Keycloak JWTs — "Bearer aos_…" is forwarded to the token scheme. -builder.Services.AddAuthentication() - .AddScheme( - AgentOs.Modules.Tenants.ApiTokens.ApiTokenAuthentication.Scheme, null); -builder.Services.PostConfigure( - Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme, - o => o.ForwardDefaultSelector = AgentOs.Modules.Tenants.ApiTokens.ApiTokenAuthentication.ForwardSelector); +// E1.3: personal API tokens + service accounts next to Keycloak JWTs — "Bearer aos_…" is forwarded to the token scheme. +// Self-contained: adds a scheme + chains the JWT forward selector; no default scheme or authorization policy changes. +builder.Services.AddApiTokenAuthentication( + Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme); // Module discovery: each .Assembly contributes one IModule. builder.Services.AddModulesFromAssemblies(builder.Configuration, @@ -147,7 +148,13 @@ app.UseResponseCompression(); +// E1.3: unversioned module routes still work but announce Deprecation / Sunset / successor Link headers — before auth, +// so a 401 / 403 / 429 on a deprecated route says so too. +app.UseApiDeprecationHeaders(); + app.UseAuthentication(); +// E1.3: an API token's scope (read | run | admin) gates the HTTP method; JWT callers pass through. +app.UseApiTokenScopes(); app.UseAuthorization(); // After auth so the per-tenant partition can read the tenant claim (S2). @@ -224,7 +231,12 @@ .WithTags("Meta") .RequireAuthorization(); -app.MapModuleEndpoints(); +// E1.3: every module REST route under /v1 (+ its deprecated unversioned twin); SignalR hubs stay at their own path. +app.MapVersionedModuleEndpoints(routes => routes.MapPost("/llm/test", LlmTestAsync) + .WithName("LlmTest") + .WithSummary("Probe the configured LLM provider with a minimal call") + .WithTags("Settings") + .RequireAuthorization()); // Epic E4 — MCP HTTP endpoint at /mcp. Streamable HTTP per spec. RequireAuthorization so an // anonymous caller can't drive the full 5-agent LLM pipeline (uncapped spend) or read another @@ -233,9 +245,11 @@ // Settings "Test" — probe one provider (?provider=, from the Model keys cards; allow-listed by LlmProbe) or, with // none named, the Orchestrator's configured provider, with a minimal call. -app.MapPost("/llm/test", async ([Microsoft.AspNetCore.Mvc.FromQuery(Name = "provider")] string? requested, +app.Run(); + +static async Task LlmTestAsync([Microsoft.AspNetCore.Mvc.FromQuery(Name = "provider")] string? requested, ILlmClientFactory factory, IConfiguration cfg, ITenantContext tenant, - Microsoft.Extensions.Options.IOptions llmOptions, IServiceProvider services, CancellationToken ct) => + Microsoft.Extensions.Options.IOptions llmOptions, IServiceProvider services, CancellationToken ct) { if (requested is not null && !LlmProbe.CanProbe(requested)) { @@ -300,10 +314,4 @@ return Results.Ok(new { ok = false, provider, model, error = ex.Message }); } #pragma warning restore CA1031 -}) - .WithName("LlmTest") - .WithSummary("Probe the configured LLM provider with a minimal call") - .WithTags("Settings") - .RequireAuthorization(); - -app.Run(); +} diff --git a/src/AgentOs.Modules.RemoteAgent/RemoteAgentModule.cs b/src/AgentOs.Modules.RemoteAgent/RemoteAgentModule.cs index 1e34758e..f9b2be29 100644 --- a/src/AgentOs.Modules.RemoteAgent/RemoteAgentModule.cs +++ b/src/AgentOs.Modules.RemoteAgent/RemoteAgentModule.cs @@ -12,7 +12,7 @@ namespace AgentOs.Modules.RemoteAgent; -public sealed class RemoteAgentModule : IModule, IEndpointModule +public sealed class RemoteAgentModule : IModule, IProtocolEndpointModule { public void AddServices(IServiceCollection services, IConfiguration configuration) { diff --git a/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenAuthenticationHandler.cs b/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenAuthenticationHandler.cs index d38724a0..f15f7bd2 100644 --- a/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenAuthenticationHandler.cs +++ b/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenAuthenticationHandler.cs @@ -1,13 +1,20 @@ -// Authenticates `Authorization: Bearer aos_…` (E1.3). The Api's JWT bearer scheme forwards here for tokens with the -// aos_ scheme (ApiTokenAuthentication.ForwardSelector), so one Authorization header serves both humans (Keycloak -// JWT) and machines (API token). The principal carries the same claims a JWT would: tenant, sub, name, role. +// Authenticates `Authorization: Bearer aos_…` (E1.3). The host's primary bearer scheme (Keycloak JWT on the Api) +// forwards here for tokens with the aos_ prefix (ApiTokenAuthentication.ForwardSelector), so one Authorization header +// serves both humans (Keycloak JWT) and machines (API token). The principal carries the same claims a JWT would — +// tenant, sub, name, role — plus the token's scopes, which ApiTokenScopeMiddleware enforces per HTTP method. +// +// Registration is self-contained (AddApiTokenAuthentication + UseApiTokenScopes): it adds a scheme and chains the +// primary scheme's forward selector without replacing the default scheme, authorization policies or a fallback policy. using System; +using System.Collections.Generic; +using System.Globalization; using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; using AgentOs.SharedKernel.Identity; using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -15,18 +22,84 @@ namespace AgentOs.Modules.Tenants.ApiTokens; -/// Scheme name + the JWT forward selector. +/// Scheme name, claim names, the forward selector and the host wiring. public static class ApiTokenAuthentication { /// Authentication scheme name. public const string Scheme = "ApiToken"; - /// For JwtBearerOptions.ForwardDefaultSelector: route aos_ bearer tokens to this scheme. + /// Claim marking a principal authenticated by an API token. + public const string AuthMethodClaim = "auth_method"; + + /// Value of for API tokens. + public const string AuthMethod = "api_token"; + + /// Claim carrying the token id. + public const string TokenIdClaim = "token_id"; + + /// Claim carrying the token kind (personal | service). + public const string TokenKindClaim = "token_kind"; + + private const string BearerPrefix = "Bearer " + ApiTokenFormat.Scheme; + + /// For the primary scheme's ForwardDefaultSelector: route aos_ bearer tokens to this scheme. public static string? ForwardSelector(HttpContext context) { ArgumentNullException.ThrowIfNull(context); - var header = context.Request.Headers.Authorization.ToString(); - return header.StartsWith("Bearer " + ApiTokenFormat.Scheme, StringComparison.Ordinal) ? Scheme : null; + return context.Request.Headers.Authorization.ToString().StartsWith(BearerPrefix, StringComparison.Ordinal) ? Scheme : null; + } + + /// True when was authenticated by an API token. + public static bool IsApiToken(this ClaimsPrincipal? user) + => string.Equals(user?.FindFirst(AuthMethodClaim)?.Value, AuthMethod, StringComparison.Ordinal); + + /// + /// Register the API-token scheme and forward Bearer aos_… to it from (the + /// host's primary bearer scheme, e.g. JwtBearer). Any forward selector already on that scheme still runs for other + /// headers. Adds no default scheme and no authorization policy. + /// + public static IServiceCollection AddApiTokenAuthentication(this IServiceCollection services, string forwardFromScheme) + where TPrimaryOptions : AuthenticationSchemeOptions + { + ArgumentNullException.ThrowIfNull(services); + ArgumentException.ThrowIfNullOrWhiteSpace(forwardFromScheme); + services.AddAuthentication().AddScheme(Scheme, null); + services.PostConfigure(forwardFromScheme, o => + { + var previous = o.ForwardDefaultSelector; + o.ForwardDefaultSelector = ctx => ForwardSelector(ctx) ?? previous?.Invoke(ctx); + }); + return services; + } + + /// Enforce API-token scopes (place after UseAuthentication, before UseAuthorization). + public static IApplicationBuilder UseApiTokenScopes(this IApplicationBuilder app) + { + ArgumentNullException.ThrowIfNull(app); + return app.UseMiddleware(); + } + + /// The claims for a validated token. + public static IReadOnlyList ClaimsFor(ApiTokenIdentity identity) + { + ArgumentNullException.ThrowIfNull(identity); + var personal = identity.Kind == ApiTokenKind.Personal && !string.IsNullOrWhiteSpace(identity.OwnerUserId); + // A personal token acts as its owner (their user id, so runs and runners are attributed to them); a service + // account is its own principal. + var subject = personal ? identity.OwnerUserId! : $"apitoken:{identity.Id}"; + var name = personal ? identity.CreatedBy : $"service:{identity.Name}"; + return + [ + new Claim(ClaimNames.Tenant, identity.TenantId), + new Claim(ClaimNames.Subject, subject), + new Claim("preferred_username", name), + new Claim(ClaimTypes.Name, name), + new Claim(ClaimTypes.Role, identity.Role), + new Claim(ApiTokenScopes.ClaimType, ApiTokenScopes.Format(identity.Scopes)), + new Claim(AuthMethodClaim, AuthMethod), + new Claim(TokenIdClaim, identity.Id.ToString("D", CultureInfo.InvariantCulture)), + new Claim(TokenKindClaim, identity.Kind), + ]; } } @@ -35,29 +108,59 @@ public sealed class ApiTokenAuthenticationHandler( IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder) : AuthenticationHandler(options, logger, encoder) { + /// protected override async Task HandleAuthenticateAsync() { - var header = Request.Headers.Authorization.ToString(); - if (!header.StartsWith("Bearer " + ApiTokenFormat.Scheme, StringComparison.Ordinal)) + if (ApiTokenAuthentication.ForwardSelector(Context) is null) { return AuthenticateResult.NoResult(); } + var header = Request.Headers.Authorization.ToString(); var service = Context.RequestServices.GetRequiredService(); - var identity = await service.ValidateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted).ConfigureAwait(false); + var use = new ApiTokenUse(Context.Connection.RemoteIpAddress?.ToString(), Request.Headers.UserAgent.ToString()); + var identity = await service.ValidateAsync(header["Bearer ".Length..].Trim(), use, Context.RequestAborted).ConfigureAwait(false); if (identity is null) { return AuthenticateResult.Fail("Invalid, revoked or expired API token."); } - var claims = new[] - { - new Claim(ClaimNames.Tenant, identity.TenantId), - new Claim(ClaimNames.Subject, $"apitoken:{identity.Id}"), - new Claim("preferred_username", $"token:{identity.Name}"), - new Claim(ClaimTypes.Name, $"token:{identity.Name}"), - new Claim(ClaimTypes.Role, identity.Role), - new Claim("auth_method", "api_token"), - }; - var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ApiTokenAuthentication.Scheme, ClaimTypes.Name, ClaimTypes.Role)); + var principal = new ClaimsPrincipal(new ClaimsIdentity(ApiTokenAuthentication.ClaimsFor(identity), + ApiTokenAuthentication.Scheme, ClaimTypes.Name, ClaimTypes.Role)); return AuthenticateResult.Success(new AuthenticationTicket(principal, ApiTokenAuthentication.Scheme)); } + + /// + protected override Task HandleChallengeAsync(AuthenticationProperties properties) + { + Response.StatusCode = StatusCodes.Status401Unauthorized; + Response.Headers.WWWAuthenticate = "Bearer error=\"invalid_token\""; + return Task.CompletedTask; + } +} + +/// +/// Maps the HTTP method to the scope an API-token caller needs — safe methods (GET/HEAD/OPTIONS/TRACE) need +/// read, everything else run — and answers 403 (problem+json) when the token lacks it. Admin-only routes +/// are additionally gated by the role claim (admin scope ⇒ admin role). Keycloak (JWT) callers pass through. +/// +public sealed class ApiTokenScopeMiddleware(RequestDelegate next) +{ + /// Run the check. + public Task InvokeAsync(HttpContext context) + { + ArgumentNullException.ThrowIfNull(context); + if (!context.User.IsApiToken()) { return next(context); } + var required = RequiredScope(context.Request.Method); + if (ApiTokenScopes.Allows(context.User.FindFirst(ApiTokenScopes.ClaimType)?.Value, required)) { return next(context); } + return Results.Problem( + statusCode: StatusCodes.Status403Forbidden, + title: "Insufficient token scope", + detail: $"This API token lacks the '{required}' scope needed for {context.Request.Method} requests.") + .ExecuteAsync(context); + } + + /// The scope a request with needs. + public static string RequiredScope(string method) + => HttpMethods.IsGet(method) || HttpMethods.IsHead(method) || HttpMethods.IsOptions(method) || HttpMethods.IsTrace(method) + ? ApiTokenScopes.Read + : ApiTokenScopes.Run; } diff --git a/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenEntity.cs b/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenEntity.cs index ea8e9445..ae78e849 100644 --- a/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenEntity.cs +++ b/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenEntity.cs @@ -1,4 +1,4 @@ -// A tenant API token row (E1.3). Only the SHA-256 of the token is stored; Prefix is the lookup key. +// A tenant API token row (E1.3). Only a salted HMAC of the token is stored; Prefix is the lookup key. using System; @@ -11,7 +11,23 @@ public sealed class ApiTokenEntity public string TenantId { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; public string Prefix { get; set; } = string.Empty; + + /// HMAC-SHA256(key = , token) as lower hex; plain SHA-256 for rows created before the salt. public string TokenHash { get; set; } = string.Empty; + + /// Per-token random salt (hex). Empty only on legacy rows (unsalted SHA-256). + public string Salt { get; set; } = string.Empty; + + /// (acts as its owner) or (a service account). + public string Kind { get; set; } = ApiTokenKind.Service; + + /// Space-separated scopes (), closed upwards: admin ⇒ run ⇒ read. + public string Scopes { get; set; } = ApiTokenScopes.Read; + + /// The Keycloak user id a personal token acts as; null for service accounts. + public string? OwnerUserId { get; set; } + + /// Derived from (admin scope ⇒ admin, else member) — kept for older readers. public string Role { get; set; } = "member"; public string CreatedBy { get; set; } = string.Empty; public DateTimeOffset CreatedAtUtc { get; set; } diff --git a/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenScopes.cs b/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenScopes.cs new file mode 100644 index 00000000..aeaccd6c --- /dev/null +++ b/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenScopes.cs @@ -0,0 +1,96 @@ +// E1.3 — what an API token may do, and whom it acts as. +// Scopes read — safe HTTP methods (GET/HEAD/OPTIONS): runs, results, settings views +// run — also unsafe methods (POST/PUT/PATCH/DELETE): start runs, write data; MCP (JSON-RPC over POST) +// admin — also the tenant-admin policy (the token's principal gets the admin role) +// Scopes are closed upwards (admin ⇒ run ⇒ read), so a token holds one of three levels. The level is enforced by +// ApiTokenScopeMiddleware (method → scope) and by the role claim (admin endpoints need role admin). +// Kinds personal — acts as the member who created it (sub = their user id); revoked when they are removed +// service — a tenant service account (sub = apitoken:); admins only + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace AgentOs.Modules.Tenants.ApiTokens; + +/// API token scopes (E1.3). +public static class ApiTokenScopes +{ + /// Read-only: safe HTTP methods. + public const string Read = "read"; + + /// Read + start runs / write (unsafe HTTP methods). + public const string Run = "run"; + + /// Run + the tenant-admin role. + public const string Admin = "admin"; + + /// The claim carrying the space-separated scopes (OAuth 2.0 convention). + public const string ClaimType = "scope"; + + /// Every scope, lowest first. + public static IReadOnlyList All { get; } = [Read, Run, Admin]; + + /// The closed set for a requested level or list: admin ⇒ run ⇒ read. Throws on an unknown scope or none. + public static IReadOnlyList Normalize(IEnumerable? requested) + { + var highest = -1; + var scopes = (requested ?? []).Select(raw => raw?.Trim().ToLowerInvariant() ?? string.Empty).Where(s => s.Length > 0); + foreach (var scope in scopes) + { + var rank = Rank(scope); + if (rank < 0) + { + throw new InvalidOperationException($"Unknown scope '{scope}'. Scopes: {string.Join(", ", All)}."); + } + highest = Math.Max(highest, rank); + } + if (highest < 0) + { + throw new InvalidOperationException($"Choose at least one scope: {string.Join(", ", All)}."); + } + return All.Take(highest + 1).ToArray(); + } + + /// Space-separated storage / claim form. + public static string Format(IEnumerable scopes) => string.Join(' ', scopes); + + /// Parse the storage / claim form (unknown entries dropped). + public static IReadOnlyList Parse(string? value) + => string.IsNullOrWhiteSpace(value) + ? [] + : value.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Where(s => Rank(s) >= 0).ToArray(); + + /// True when (space-separated) includes . + public static bool Allows(string? granted, string scope) => Parse(granted).Contains(scope, StringComparer.Ordinal); + + /// The role a token with carries. + public static string RoleFor(IEnumerable scopes) => scopes.Contains(Admin, StringComparer.Ordinal) ? "admin" : "member"; + + /// Scopes for a legacy row that only had a role. + public static string FromLegacyRole(string? role) => Format(string.Equals(role, "admin", StringComparison.Ordinal) ? All : [Read, Run]); + + /// The highest scope of the set (for display). + public static string Highest(IEnumerable scopes) => scopes.OrderBy(Rank).LastOrDefault() ?? Read; + + private static int Rank(string scope) => scope switch + { + Read => 0, + Run => 1, + Admin => 2, + _ => -1, + }; +} + +/// API token kinds (E1.3). +public static class ApiTokenKind +{ + /// Acts as the member who created it. + public const string Personal = "personal"; + + /// A tenant service account (admins only). + public const string Service = "service"; + + /// True for a known kind. + public static bool IsKnown(string? kind) => kind is Personal or Service; +} diff --git a/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenService.cs b/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenService.cs index e7498751..ccd581e8 100644 --- a/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenService.cs +++ b/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenService.cs @@ -1,48 +1,84 @@ -// Enterprise review E1.3 — machine access: tenant-scoped API tokens (service accounts) so CI pipelines, scripts and -// MCP clients call the Api without a browser login. +// Enterprise review E1.3 — machine access: personal API tokens and tenant service accounts, so CI pipelines, scripts, +// the VS Code extension and MCP clients call the Api without a browser login. // Format aos__ prefix = 10 base32 chars (lookup key, shown in the UI), secret = 32 random bytes -// Stored SHA-256 of the WHOLE token (hex) — the plaintext is shown once at creation and never again +// Stored HMAC-SHA256(key = a per-token 16-byte random salt, token) as hex — the plaintext is shown once at creation +// and never again. Rows from before the salt keep their plain SHA-256 and still validate. // Checked prefix lookup (indexed) → constant-time hash compare → not revoked, not expired → a principal with the -// tenant claim and the token's role (member | admin). Last use is recorded at most every 5 minutes. -// Create / revoke land in the audit trail. Tokens never carry platform-admin. +// tenant claim, the token's scopes (read | run | admin, closed upwards) and the derived role. +// Limits expiry 1..Tenants:ApiTokens:MaxLifetimeDays (a platform setting); service accounts and the admin scope +// need a tenant admin; tokens never carry platform-admin. +// Audit create, revoke, and use: a use row (with the caller's IP + user agent) whenever last-used advances — at +// most once per token per 5 minutes — and a refusal row (revoked / expired / wrong secret on a real prefix), +// also at most once per token per 5 minutes so a stale CI secret can't flood the trail. Every use is +// additionally logged (token id + prefix only). using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; +using AgentOs.Domain.Configuration; using AgentOs.Modules.Tenants.Persistence; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; namespace AgentOs.Modules.Tenants.ApiTokens; /// One API token as listed (never the secret). -public sealed record ApiTokenInfo(Guid Id, string Name, string Prefix, string Role, string CreatedBy, DateTimeOffset CreatedAtUtc, - DateTimeOffset ExpiresAtUtc, DateTimeOffset? LastUsedAtUtc, DateTimeOffset? RevokedAtUtc) +public sealed record ApiTokenInfo(Guid Id, string Name, string Prefix, string Kind, IReadOnlyList Scopes, string? OwnerUserId, + string CreatedBy, DateTimeOffset CreatedAtUtc, DateTimeOffset ExpiresAtUtc, DateTimeOffset? LastUsedAtUtc, DateTimeOffset? RevokedAtUtc) { /// Usable right now. public bool IsActive(DateTimeOffset now) => RevokedAtUtc is null && ExpiresAtUtc > now; + + /// The role the token's principal carries. + public string Role => ApiTokenScopes.RoleFor(Scopes); } /// A token that passed validation. -public sealed record ApiTokenIdentity(Guid Id, string TenantId, string Name, string Role); +public sealed record ApiTokenIdentity(Guid Id, string TenantId, string Name, string Kind, IReadOnlyList Scopes, + string? OwnerUserId, string CreatedBy, DateTimeOffset ExpiresAtUtc) +{ + /// The role the token's principal carries. + public string Role => ApiTokenScopes.RoleFor(Scopes); +} + +/// Who creates / lists / revokes tokens. +/// Display name for the audit trail and "created by". +/// Keycloak user id (the owner of personal tokens). +/// Tenant admin: may create service accounts + admin-scoped tokens and see / revoke every token. +public sealed record ApiTokenActor(string Name, string? UserId, bool IsAdmin); -/// Create, list, revoke and validate tenant API tokens. +/// What to create. +public sealed record ApiTokenRequest(string TenantId, string Name, string Kind, IReadOnlyCollection Scopes, int ExpiresInDays, ApiTokenActor Actor); + +/// Where a token was presented (for the audit row). +public sealed record ApiTokenUse(string? IpAddress, string? UserAgent); + +/// Create, list, revoke and validate API tokens. public interface IApiTokenService { /// Create a token; returns its info and the plaintext — shown ONCE. - Task<(ApiTokenInfo Info, string Token)> CreateAsync(string tenantId, string name, string role, int expiresInDays, string actor, CancellationToken ct = default); + Task<(ApiTokenInfo Info, string Token)> CreateAsync(ApiTokenRequest request, CancellationToken ct = default); + + /// The tokens may see in the tenant (admin: all; member: their personal tokens), newest first. + Task> ListAsync(string tenantId, ApiTokenActor viewer, CancellationToken ct = default); + + /// Revoke a token (admin: any of the tenant's; member: their own). False when not found / not allowed / already revoked. + Task RevokeAsync(string tenantId, Guid id, ApiTokenActor actor, CancellationToken ct = default); - /// The tenant's tokens, newest first. - Task> ListAsync(string tenantId, CancellationToken ct = default); + /// Revoke every active personal token holds in the tenant (member removal). Returns the count. + Task RevokeForOwnerAsync(string tenantId, string ownerUserId, string actor, CancellationToken ct = default); - /// Revoke a token of the tenant (no-op when already revoked or not the tenant's). - Task RevokeAsync(string tenantId, Guid id, string actor, CancellationToken ct = default); + /// The longest expiry, in days, a new token may have. + Task MaxLifetimeDaysAsync(string tenantId, CancellationToken ct = default); /// The identity behind , or null when unknown, revoked, expired or malformed. - Task ValidateAsync(string token, CancellationToken ct = default); + Task ValidateAsync(string token, ApiTokenUse? use = null, CancellationToken ct = default); } /// Token format helpers (pure). @@ -51,8 +87,14 @@ public static class ApiTokenFormat /// Every token starts with this. public const string Scheme = "aos_"; - /// Roles a token may hold. - public static IReadOnlyList Roles { get; } = ["member", "admin"]; + /// The platform setting that caps a token's lifetime. + public const string MaxLifetimeKey = "Tenants:ApiTokens:MaxLifetimeDays"; + + /// Lifetime cap when the setting is unset. + public const int DefaultMaxLifetimeDays = 366; + + /// Longest name. + public const int MaxNameLength = 128; private const string Base32 = "abcdefghijklmnopqrstuvwxyz234567"; @@ -61,14 +103,16 @@ public static (string Token, string Prefix) New() { Span idBytes = stackalloc byte[10]; RandomNumberGenerator.Fill(idBytes); - var prefix = string.Create(10, idBytes.ToArray(), static (span, bytes) => - { - for (var i = 0; i < span.Length; i++) { span[i] = Base32[bytes[i] & 31]; } - }); + Span prefix = stackalloc char[10]; + for (var i = 0; i < prefix.Length; i++) { prefix[i] = Base32[idBytes[i] & 31]; } var secret = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)).TrimEnd('=').Replace('+', '-').Replace('/', '_'); - return ($"{Scheme}{prefix}_{secret}", prefix); + var p = new string(prefix); + return ($"{Scheme}{p}_{secret}", p); } + /// A fresh per-token salt (16 random bytes, hex). + public static string NewSalt() => Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16)); + /// The prefix of a well-formed token, else null. public static string? PrefixOf(string? token) { @@ -78,98 +122,237 @@ public static (string Token, string Prefix) New() return underscore == 10 ? rest[..10].ToString() : null; } - /// SHA-256 (hex) of the whole token. - public static string Hash(string token) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token))); + /// The stored hash of : HMAC-SHA256 keyed by (hex), or the + /// legacy unsalted SHA-256 when is empty. Lower hex, 64 chars. + public static string Hash(string token, string salt) + { + ArgumentNullException.ThrowIfNull(token); + var bytes = Encoding.UTF8.GetBytes(token); + return string.IsNullOrEmpty(salt) + ? Convert.ToHexStringLower(SHA256.HashData(bytes)) + : Convert.ToHexStringLower(HMACSHA256.HashData(Convert.FromHexString(salt), bytes)); + } + + /// Constant-time compare of two hex hashes. + public static bool HashEquals(string presented, string stored) + => CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(presented), Encoding.ASCII.GetBytes(stored)); } -internal sealed class ApiTokenService(TenantsDbContext db, IAuditLog audit, TimeProvider clock) : IApiTokenService +internal sealed partial class ApiTokenService( + TenantsDbContext db, IAuditLog audit, TimeProvider clock, ISettings? settings = null, + ILogger? logger = null, ApiTokenAuditThrottle? throttle = null) : IApiTokenService { - private static readonly TimeSpan LastUsedGranularity = TimeSpan.FromMinutes(5); + private static readonly TimeSpan UseGranularity = TimeSpan.FromMinutes(5); + + // Hashed when a prefix is unknown, so an unknown token costs the same as a wrong secret. + private static readonly string DummySalt = ApiTokenFormat.NewSalt(); - public async Task<(ApiTokenInfo Info, string Token)> CreateAsync(string tenantId, string name, string role, int expiresInDays, string actor, CancellationToken ct = default) + private readonly ILogger _log = logger ?? (ILogger)NullLogger.Instance; + private readonly ApiTokenAuditThrottle _throttle = throttle ?? ApiTokenAuditThrottle.Shared; + + public async Task<(ApiTokenInfo Info, string Token)> CreateAsync(ApiTokenRequest request, CancellationToken ct = default) { - ArgumentException.ThrowIfNullOrWhiteSpace(tenantId); - ArgumentException.ThrowIfNullOrWhiteSpace(name); - if (!ApiTokenFormat.Roles.Contains(role, StringComparer.Ordinal)) + ArgumentNullException.ThrowIfNull(request); + ArgumentException.ThrowIfNullOrWhiteSpace(request.TenantId); + ArgumentNullException.ThrowIfNull(request.Actor); + var name = request.Name?.Trim() ?? string.Empty; + if (name.Length is 0 or > ApiTokenFormat.MaxNameLength) + { + throw new InvalidOperationException($"Give the token a name (1–{ApiTokenFormat.MaxNameLength} characters)."); + } + if (!ApiTokenKind.IsKnown(request.Kind)) + { + throw new InvalidOperationException($"Kind must be {ApiTokenKind.Personal} or {ApiTokenKind.Service}."); + } + var scopes = ApiTokenScopes.Normalize(request.Scopes); + var actor = request.Actor; + if (request.Kind == ApiTokenKind.Service && !actor.IsAdmin) + { + throw new InvalidOperationException("Only a workspace admin can create a service account."); + } + if (scopes.Contains(ApiTokenScopes.Admin) && !actor.IsAdmin) { - throw new InvalidOperationException($"Role must be one of: {string.Join(", ", ApiTokenFormat.Roles)}."); + throw new InvalidOperationException("Only a workspace admin can create a token with the admin scope."); } - if (expiresInDays is < 1 or > 366) + if (request.Kind == ApiTokenKind.Personal && string.IsNullOrWhiteSpace(actor.UserId)) { - throw new InvalidOperationException("Expiry must be between 1 and 366 days."); + throw new InvalidOperationException("A personal token needs a signed-in user to act as."); } + var maxDays = await MaxLifetimeDaysAsync(request.TenantId, ct).ConfigureAwait(false); + if (request.ExpiresInDays < 1 || request.ExpiresInDays > maxDays) + { + throw new InvalidOperationException($"Expiry must be between 1 and {maxDays} days."); + } + var (token, prefix) = ApiTokenFormat.New(); + var salt = ApiTokenFormat.NewSalt(); var now = clock.GetUtcNow(); var entity = new ApiTokenEntity { Id = Guid.NewGuid(), - TenantId = tenantId, - Name = name.Trim(), + TenantId = request.TenantId, + Name = name, Prefix = prefix, - TokenHash = ApiTokenFormat.Hash(token), - Role = role, - CreatedBy = actor, + Salt = salt, + TokenHash = ApiTokenFormat.Hash(token, salt), + Kind = request.Kind, + Scopes = ApiTokenScopes.Format(scopes), + OwnerUserId = request.Kind == ApiTokenKind.Personal ? actor.UserId : null, + Role = ApiTokenScopes.RoleFor(scopes), + CreatedBy = actor.Name, CreatedAtUtc = now, - ExpiresAtUtc = now.AddDays(expiresInDays), + ExpiresAtUtc = now.AddDays(request.ExpiresInDays), }; db.ApiTokens.Add(entity); await db.SaveChangesAsync(ct).ConfigureAwait(false); - await audit.WriteAsync(new AuditEntry(Guid.NewGuid(), tenantId, actor, AuditActions.ApiTokenCreated, - $"{entity.Name} ({prefix}, {role}, {expiresInDays} d)", null, null, now), ct).ConfigureAwait(false); + await audit.WriteAsync(new AuditEntry(Guid.NewGuid(), request.TenantId, actor.Name, AuditActions.ApiTokenCreated, + $"{entity.Name} ({prefix}, {entity.Kind}, {entity.Scopes}, {request.ExpiresInDays} d)", null, null, now), ct).ConfigureAwait(false); return (ToInfo(entity), token); } - public async Task> ListAsync(string tenantId, CancellationToken ct = default) - => await db.ApiTokens.AsNoTracking() - .Where(t => t.TenantId == tenantId) - .OrderByDescending(t => t.CreatedAtUtc) - .Select(t => new ApiTokenInfo(t.Id, t.Name, t.Prefix, t.Role, t.CreatedBy, t.CreatedAtUtc, t.ExpiresAtUtc, t.LastUsedAtUtc, t.RevokedAtUtc)) - .ToListAsync(ct).ConfigureAwait(false); + public async Task> ListAsync(string tenantId, ApiTokenActor viewer, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(viewer); + var query = db.ApiTokens.AsNoTracking().Where(t => t.TenantId == tenantId); + if (!viewer.IsAdmin) + { + if (string.IsNullOrWhiteSpace(viewer.UserId)) { return []; } + query = query.Where(t => t.Kind == ApiTokenKind.Personal && t.OwnerUserId == viewer.UserId); + } + var rows = await query.OrderByDescending(t => t.CreatedAtUtc).ToListAsync(ct).ConfigureAwait(false); + return rows.Select(ToInfo).ToArray(); + } - public async Task RevokeAsync(string tenantId, Guid id, string actor, CancellationToken ct = default) + public async Task RevokeAsync(string tenantId, Guid id, ApiTokenActor actor, CancellationToken ct = default) { + ArgumentNullException.ThrowIfNull(actor); var entity = await db.ApiTokens.FirstOrDefaultAsync(t => t.Id == id && t.TenantId == tenantId, ct).ConfigureAwait(false); if (entity is null || entity.RevokedAtUtc is not null) { return false; } + var own = entity.Kind == ApiTokenKind.Personal && actor.UserId is { Length: > 0 } && entity.OwnerUserId == actor.UserId; + if (!actor.IsAdmin && !own) { return false; } entity.RevokedAtUtc = clock.GetUtcNow(); await db.SaveChangesAsync(ct).ConfigureAwait(false); - await audit.WriteAsync(new AuditEntry(Guid.NewGuid(), tenantId, actor, AuditActions.ApiTokenRevoked, - $"{entity.Name} ({entity.Prefix})", null, null, entity.RevokedAtUtc.Value), ct).ConfigureAwait(false); + await audit.WriteAsync(new AuditEntry(Guid.NewGuid(), tenantId, actor.Name, AuditActions.ApiTokenRevoked, + $"{entity.Name} ({entity.Prefix}, {entity.Kind})", null, null, entity.RevokedAtUtc.Value), ct).ConfigureAwait(false); return true; } - public async Task ValidateAsync(string token, CancellationToken ct = default) + public async Task RevokeForOwnerAsync(string tenantId, string ownerUserId, string actor, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(ownerUserId); + var rows = await db.ApiTokens + .Where(t => t.TenantId == tenantId && t.Kind == ApiTokenKind.Personal && t.OwnerUserId == ownerUserId && t.RevokedAtUtc == null) + .ToListAsync(ct).ConfigureAwait(false); + if (rows.Count == 0) { return 0; } + var now = clock.GetUtcNow(); + foreach (var row in rows) { row.RevokedAtUtc = now; } + await db.SaveChangesAsync(ct).ConfigureAwait(false); + foreach (var row in rows) + { + await audit.WriteAsync(new AuditEntry(Guid.NewGuid(), tenantId, actor, AuditActions.ApiTokenRevoked, + $"{row.Name} ({row.Prefix}, {row.Kind}, owner removed)", null, null, now), ct).ConfigureAwait(false); + } + return rows.Count; + } + + public async Task MaxLifetimeDaysAsync(string tenantId, CancellationToken ct = default) + { + if (settings is null) { return ApiTokenFormat.DefaultMaxLifetimeDays; } + var days = await settings.GetIntAsync(ApiTokenFormat.MaxLifetimeKey, tenantId, ApiTokenFormat.DefaultMaxLifetimeDays, ct).ConfigureAwait(false); + return days < 1 ? ApiTokenFormat.DefaultMaxLifetimeDays : days; + } + + public async Task ValidateAsync(string token, ApiTokenUse? use = null, CancellationToken ct = default) { if (ApiTokenFormat.PrefixOf(token) is not { } prefix) { return null; } // The token is the credential: this lookup runs before any tenant is known (auth), across tenants by design. var entity = await db.ApiTokens.IgnoreQueryFilters().FirstOrDefaultAsync(t => t.Prefix == prefix, ct).ConfigureAwait(false); - if (entity is null) { return null; } - var presented = Encoding.ASCII.GetBytes(ApiTokenFormat.Hash(token)); - var stored = Encoding.ASCII.GetBytes(entity.TokenHash); - if (!CryptographicOperations.FixedTimeEquals(presented, stored)) { return null; } + if (entity is null) + { + _ = ApiTokenFormat.HashEquals(ApiTokenFormat.Hash(token, DummySalt), ApiTokenFormat.Hash(token, DummySalt)); + return null; + } var now = clock.GetUtcNow(); - if (entity.RevokedAtUtc is not null || entity.ExpiresAtUtc <= now) { return null; } - if (entity.LastUsedAtUtc is null || now - entity.LastUsedAtUtc.Value > LastUsedGranularity) + var refusal = !ApiTokenFormat.HashEquals(ApiTokenFormat.Hash(token, entity.Salt), entity.TokenHash) ? "wrong secret" + : entity.RevokedAtUtc is not null ? "revoked" + : entity.ExpiresAtUtc <= now ? "expired" + : null; + if (refusal is not null) + { + LogRefused(_log, entity.Id, entity.Prefix, refusal); + if (_throttle.ShouldRecord(entity.Id, now, UseGranularity)) + { + await audit.WriteAsync(new AuditEntry(Guid.NewGuid(), entity.TenantId, $"token:{entity.Name}", AuditActions.ApiTokenRefused, + $"{entity.Name} ({entity.Prefix}, {refusal})", use?.IpAddress, use?.UserAgent, now), ct).ConfigureAwait(false); + } + return null; + } + + LogUsed(_log, entity.Id, entity.Prefix); + if (entity.LastUsedAtUtc is null || now - entity.LastUsedAtUtc.Value > UseGranularity) { entity.LastUsedAtUtc = now; await db.SaveChangesAsync(ct).ConfigureAwait(false); + await audit.WriteAsync(new AuditEntry(Guid.NewGuid(), entity.TenantId, $"token:{entity.Name}", AuditActions.ApiTokenUsed, + $"{entity.Name} ({entity.Prefix}, {entity.Kind}, {entity.Scopes})", use?.IpAddress, use?.UserAgent, now), ct).ConfigureAwait(false); } - return new ApiTokenIdentity(entity.Id, entity.TenantId, entity.Name, entity.Role); + return new ApiTokenIdentity(entity.Id, entity.TenantId, entity.Name, entity.Kind, ScopesOf(entity), entity.OwnerUserId, + entity.CreatedBy, entity.ExpiresAtUtc); } + private static IReadOnlyList ScopesOf(ApiTokenEntity t) + => ApiTokenScopes.Parse(string.IsNullOrWhiteSpace(t.Scopes) ? ApiTokenScopes.FromLegacyRole(t.Role) : t.Scopes); + private static ApiTokenInfo ToInfo(ApiTokenEntity t) - => new(t.Id, t.Name, t.Prefix, t.Role, t.CreatedBy, t.CreatedAtUtc, t.ExpiresAtUtc, t.LastUsedAtUtc, t.RevokedAtUtc); + => new(t.Id, t.Name, t.Prefix, t.Kind, ScopesOf(t), t.OwnerUserId, t.CreatedBy, t.CreatedAtUtc, t.ExpiresAtUtc, t.LastUsedAtUtc, t.RevokedAtUtc); + + [LoggerMessage(Level = LogLevel.Debug, Message = "API token {TokenId} ({Prefix}) authenticated.")] + private static partial void LogUsed(ILogger logger, Guid tokenId, string prefix); + + [LoggerMessage(Level = LogLevel.Warning, Message = "API token {TokenId} ({Prefix}) refused: {Reason}.")] + private static partial void LogRefused(ILogger logger, Guid tokenId, string prefix, string reason); +} + +/// At most one refusal audit row per token per window, process-wide. +internal sealed class ApiTokenAuditThrottle +{ + /// The process-wide instance. + public static ApiTokenAuditThrottle Shared { get; } = new(); + + private readonly ConcurrentDictionary _last = new(); + + /// True (and the window restarts) when nothing was recorded for within . + public bool ShouldRecord(Guid id, DateTimeOffset now, TimeSpan window) + { + var ticks = now.UtcTicks; + while (true) + { + if (!_last.TryGetValue(id, out var previous)) + { + if (_last.TryAdd(id, ticks)) { return true; } + continue; + } + if (ticks - previous < window.Ticks) { return false; } + if (_last.TryUpdate(id, ticks, previous)) { return true; } + } + } } /// No database: tokens are unavailable (creation fails loudly; validation always refuses). internal sealed class NullApiTokenService : IApiTokenService { - public Task<(ApiTokenInfo Info, string Token)> CreateAsync(string tenantId, string name, string role, int expiresInDays, string actor, CancellationToken ct = default) + public Task<(ApiTokenInfo Info, string Token)> CreateAsync(ApiTokenRequest request, CancellationToken ct = default) => throw new InvalidOperationException("API tokens need a database — this run has none."); - public Task> ListAsync(string tenantId, CancellationToken ct = default) + public Task> ListAsync(string tenantId, ApiTokenActor viewer, CancellationToken ct = default) => Task.FromResult>([]); - public Task RevokeAsync(string tenantId, Guid id, string actor, CancellationToken ct = default) => Task.FromResult(false); + public Task RevokeAsync(string tenantId, Guid id, ApiTokenActor actor, CancellationToken ct = default) => Task.FromResult(false); + + public Task RevokeForOwnerAsync(string tenantId, string ownerUserId, string actor, CancellationToken ct = default) => Task.FromResult(0); + + public Task MaxLifetimeDaysAsync(string tenantId, CancellationToken ct = default) => Task.FromResult(ApiTokenFormat.DefaultMaxLifetimeDays); - public Task ValidateAsync(string token, CancellationToken ct = default) => Task.FromResult(null); + public Task ValidateAsync(string token, ApiTokenUse? use = null, CancellationToken ct = default) + => Task.FromResult(null); } diff --git a/src/AgentOs.Modules.Tenants/Endpoints/TenantEndpoints.cs b/src/AgentOs.Modules.Tenants/Endpoints/TenantEndpoints.cs index fc98366f..203a15dd 100644 --- a/src/AgentOs.Modules.Tenants/Endpoints/TenantEndpoints.cs +++ b/src/AgentOs.Modules.Tenants/Endpoints/TenantEndpoints.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using AgentOs.Modules.Tenants.ApiTokens; using AgentOs.Modules.Tenants.Email; using AgentOs.Modules.Tenants.Keycloak; using AgentOs.SharedKernel.Hosting; @@ -23,15 +24,17 @@ public static IEndpointRouteBuilder MapTenantEndpoints(this IEndpointRouteBuilde { ArgumentNullException.ThrowIfNull(app); - app.MapGet("/tenants/me", (ITenantContext tenant) => Results.Ok(new TenantMeResponse( + app.MapGet("/tenants/me", (ITenantContext tenant, HttpContext http) => Results.Ok(new TenantMeResponse( tenant.TenantId, tenant.UserId, tenant.UserName, tenant.Roles, tenant.IsAuthenticated, - tenant.IsAdmin))) + tenant.IsAdmin, + http.User.IsApiToken() ? ApiTokenAuthentication.AuthMethod : "jwt", + ApiTokenScopes.Parse(http.User.FindFirst(ApiTokenScopes.ClaimType)?.Value)))) .WithName("TenantMe") - .WithSummary("Resolved tenant + user + roles for the current request") + .WithSummary("Resolved tenant + user + roles (and, for an API token, its scopes) for the current request") .WithTags("Tenants") .RequireAuthorization(); @@ -425,7 +428,8 @@ internal static async Task RemoveMemberAsync( CancellationToken ct, [Microsoft.AspNetCore.Mvc.FromServices] AgentOs.Domain.Sessions.IRunnerDirectory? runners = null, [Microsoft.AspNetCore.Mvc.FromServices] AgentOs.Domain.Sessions.IRunnerDisconnector? disconnector = null, - [Microsoft.AspNetCore.Mvc.FromServices] Microsoft.Extensions.Logging.ILoggerFactory? loggers = null) + [Microsoft.AspNetCore.Mvc.FromServices] Microsoft.Extensions.Logging.ILoggerFactory? loggers = null, + [Microsoft.AspNetCore.Mvc.FromServices] IApiTokenService? apiTokens = null) { ArgumentNullException.ThrowIfNull(kc); ArgumentNullException.ThrowIfNull(ctx); @@ -452,9 +456,11 @@ internal static async Task RemoveMemberAsync( var result = await MemberRemoval.RemoveAsync(tenantId, userId, new MemberRemovalActor(ctx.UserId, http.Connection.RemoteIpAddress?.ToString(), http.Request.Headers.UserAgent.ToString()), - kc, audit, runners, disconnector, loggers?.CreateLogger(typeof(MemberRemoval).FullName!), ct).ConfigureAwait(false); + kc, audit, runners, disconnector, apiTokens, loggers?.CreateLogger(typeof(MemberRemoval).FullName!), ct).ConfigureAwait(false); return result.Outcome switch { + MemberRemovalOutcome.TokensNotRevoked => Results.Problem( + title: "Couldn't revoke the member's API tokens", detail: result.Error, statusCode: StatusCodes.Status503ServiceUnavailable), MemberRemovalOutcome.ComputersNotRevoked => Results.Problem( title: "Couldn't disconnect the member's computers", detail: result.Error, statusCode: StatusCodes.Status503ServiceUnavailable), MemberRemovalOutcome.AccountNotDeleted => Results.Problem( @@ -476,14 +482,17 @@ private static async Task UserInTenantAsync( } } -/// Response shape for GET /tenants/me. +/// Response shape for GET /tenants/me. AuthMethod is jwt or api_token; Scopes is +/// empty for a Keycloak (JWT) caller. public sealed record TenantMeResponse( string TenantId, string? UserId, string? UserName, IReadOnlyList Roles, bool IsAuthenticated, - bool IsAdmin); + bool IsAdmin, + string AuthMethod, + IReadOnlyList Scopes); /// Body for POST /tenants. public sealed record CreateTenantRequest(string Id, string? Name, string AdminUsername, string? AdminEmail); diff --git a/src/AgentOs.Modules.Tenants/IAuditLog.cs b/src/AgentOs.Modules.Tenants/IAuditLog.cs index 47fc150a..0b8f00de 100644 --- a/src/AgentOs.Modules.Tenants/IAuditLog.cs +++ b/src/AgentOs.Modules.Tenants/IAuditLog.cs @@ -46,6 +46,12 @@ public static class AuditActions public const string TenantExported = "tenant.exported"; public const string ApiTokenCreated = "apitoken.created"; public const string ApiTokenRevoked = "apitoken.revoked"; + + /// An API token authenticated a request (at most one row per token per 5 minutes; every use is logged). + public const string ApiTokenUsed = "apitoken.used"; + + /// A revoked / expired / wrong-secret token was presented (at most one row per token per 5 minutes). + public const string ApiTokenRefused = "apitoken.refused"; public const string TicketFlowChanged = "ticketflow.changed"; /// The owner approved a design, or asked for design changes (Board › Tasks, ADR-0016). diff --git a/src/AgentOs.Modules.Tenants/MemberRemoval.cs b/src/AgentOs.Modules.Tenants/MemberRemoval.cs index dedf463e..90b33d6a 100644 --- a/src/AgentOs.Modules.Tenants/MemberRemoval.cs +++ b/src/AgentOs.Modules.Tenants/MemberRemoval.cs @@ -1,6 +1,6 @@ // GAP-04 — removing a member from a tenant, in the one order that can't leave their computers paired: -// 1. revoke (and disconnect) every runner they own in the tenant — idempotent, so a failure here removes nothing and a -// retry starts over; +// 1. revoke (and disconnect) every runner they own in the tenant, and every personal API token they hold (E1.3) — +// idempotent, so a failure here removes nothing and a retry starts over; // 2. delete their Keycloak account; // 3. once the delete is committed, finish with CancellationToken.None: a second revoke sweep (a computer paired between // 1 and 2) and the member.removed audit row. A failure there is logged and recorded in the audit row, never thrown — @@ -25,6 +25,9 @@ public enum MemberRemovalOutcome /// The account was deleted (and the audit row written). Check . Removed, + /// Their personal API tokens could not be revoked, so nothing was removed. Safe to retry. + TokensNotRevoked, + /// Their computers could not be revoked, so nothing was removed. Safe to retry. ComputersNotRevoked, @@ -58,7 +61,7 @@ public static partial class MemberRemoval public static async Task RemoveAsync( string tenantId, string userId, MemberRemovalActor actor, IKeycloakAdminClient keycloak, IAuditLog audit, IRunnerDirectory? runners, IRunnerDisconnector? disconnector, - ILogger? logger = null, CancellationToken ct = default) + ApiTokens.IApiTokenService? apiTokens = null, ILogger? logger = null, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(tenantId); ArgumentException.ThrowIfNullOrWhiteSpace(userId); @@ -79,6 +82,19 @@ public static async Task RemoveAsync( $"Couldn't disconnect their paired computers, so nothing was removed: {ex.Message}"); } + // 1b. Their personal API tokens act as them — revoke them before the account goes, for the same reason. + int tokensRevoked; + try + { + tokensRevoked = apiTokens is null ? 0 : await apiTokens.RevokeForOwnerAsync(tenantId, userId, actor.UserId ?? "admin", ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + if (logger is not null) { LogTokensFailed(logger, ex, LogSafe.Scrub(tenantId), LogSafe.Scrub(userId)); } + return new MemberRemovalResult(MemberRemovalOutcome.TokensNotRevoked, revoked.Count, + $"Couldn't revoke their API tokens, so nothing was removed: {ex.Message}"); + } + // 2. The account. try { @@ -107,6 +123,7 @@ public static async Task RemoveAsync( } var target = count == 0 ? $"user={userId}" : $"user={userId},runnersRevoked={count}"; if (warning is not null) { target += ",runnerRevokeFailed=true"; } + if (tokensRevoked > 0) { target += $",apiTokensRevoked={tokensRevoked}"; } await audit.WriteAsync(new AuditEntry( Guid.NewGuid(), tenantId, actor.UserId, AuditActions.MemberRemoved, target, actor.IpAddress, actor.UserAgent, DateTimeOffset.UtcNow), CancellationToken.None).ConfigureAwait(false); @@ -116,6 +133,9 @@ await audit.WriteAsync(new AuditEntry( [LoggerMessage(Level = LogLevel.Warning, Message = "Revoking the computers of member {UserId} in tenant {TenantId} failed.")] private static partial void LogRevokeFailed(ILogger logger, Exception ex, string tenantId, string userId); + [LoggerMessage(Level = LogLevel.Warning, Message = "Revoking the API tokens of member {UserId} in tenant {TenantId} failed.")] + private static partial void LogTokensFailed(ILogger logger, Exception ex, string tenantId, string userId); + [LoggerMessage(Level = LogLevel.Warning, Message = "Deleting member {UserId} of tenant {TenantId} failed; their computers are already revoked.")] private static partial void LogDeleteFailed(ILogger logger, Exception ex, string tenantId, string userId); } diff --git a/src/AgentOs.Modules.Tenants/Persistence/Migrations/20261103133906_AddApiTokenScopesAndSalt.Designer.cs b/src/AgentOs.Modules.Tenants/Persistence/Migrations/20261103133906_AddApiTokenScopesAndSalt.Designer.cs new file mode 100644 index 00000000..88779b5f --- /dev/null +++ b/src/AgentOs.Modules.Tenants/Persistence/Migrations/20261103133906_AddApiTokenScopesAndSalt.Designer.cs @@ -0,0 +1,177 @@ +// +using System; +using AgentOs.Modules.Tenants.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace AgentOs.Modules.Tenants.Persistence.Migrations +{ + [DbContext(typeof(TenantsDbContext))] + [Migration("20261103133906_AddApiTokenScopesAndSalt")] + partial class AddApiTokenScopesAndSalt + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("tenants") + .HasAnnotation("ProductVersion", "10.0.14") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("AgentOs.Modules.Tenants.ApiTokens.ApiTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("ExpiresAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(16) + .HasColumnType("character varying(16)") + .HasDefaultValue("service"); + + b.Property("LastUsedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OwnerUserId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Prefix") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("RevokedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Salt") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasDefaultValue(""); + + b.Property("Scopes") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasDefaultValue(""); + + b.Property("TenantId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("Prefix") + .IsUnique(); + + b.HasIndex("TenantId"); + + b.HasIndex("TenantId", "OwnerUserId"); + + b.ToTable("api_tokens", "tenants"); + }); + + modelBuilder.Entity("AgentOs.Modules.Tenants.Persistence.Entities.AuditEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("IpAddress") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Target") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("TenantId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserAgent") + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("UserId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.HasKey("Id"); + + b.HasIndex("TenantId", "TimestampUtc"); + + b.ToTable("audit_events", "tenants"); + }); + + modelBuilder.Entity("AgentOs.Modules.Tenants.Persistence.Entities.TenantEntity", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.ToTable("tenants", "tenants"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/AgentOs.Modules.Tenants/Persistence/Migrations/20261103133906_AddApiTokenScopesAndSalt.cs b/src/AgentOs.Modules.Tenants/Persistence/Migrations/20261103133906_AddApiTokenScopesAndSalt.cs new file mode 100644 index 00000000..a839348f --- /dev/null +++ b/src/AgentOs.Modules.Tenants/Persistence/Migrations/20261103133906_AddApiTokenScopesAndSalt.cs @@ -0,0 +1,87 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace AgentOs.Modules.Tenants.Persistence.Migrations +{ + /// + public partial class AddApiTokenScopesAndSalt : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Kind", + schema: "tenants", + table: "api_tokens", + type: "character varying(16)", + maxLength: 16, + nullable: false, + defaultValue: "service"); + + migrationBuilder.AddColumn( + name: "OwnerUserId", + schema: "tenants", + table: "api_tokens", + type: "character varying(128)", + maxLength: 128, + nullable: true); + + migrationBuilder.AddColumn( + name: "Salt", + schema: "tenants", + table: "api_tokens", + type: "character varying(64)", + maxLength: 64, + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "Scopes", + schema: "tenants", + table: "api_tokens", + type: "character varying(64)", + maxLength: 64, + nullable: false, + defaultValue: ""); + + migrationBuilder.CreateIndex( + name: "IX_api_tokens_TenantId_OwnerUserId", + schema: "tenants", + table: "api_tokens", + columns: new[] { "TenantId", "OwnerUserId" }); + + // Tokens created before scopes held only a role: member could run, admin could also administer. + migrationBuilder.Sql("""UPDATE tenants.api_tokens SET "Scopes" = CASE WHEN "Role" = 'admin' THEN 'read run admin' ELSE 'read run' END WHERE "Scopes" = '';"""); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_api_tokens_TenantId_OwnerUserId", + schema: "tenants", + table: "api_tokens"); + + migrationBuilder.DropColumn( + name: "Kind", + schema: "tenants", + table: "api_tokens"); + + migrationBuilder.DropColumn( + name: "OwnerUserId", + schema: "tenants", + table: "api_tokens"); + + migrationBuilder.DropColumn( + name: "Salt", + schema: "tenants", + table: "api_tokens"); + + migrationBuilder.DropColumn( + name: "Scopes", + schema: "tenants", + table: "api_tokens"); + } + } +} diff --git a/src/AgentOs.Modules.Tenants/Persistence/Migrations/TenantsDbContextModelSnapshot.cs b/src/AgentOs.Modules.Tenants/Persistence/Migrations/TenantsDbContextModelSnapshot.cs index 5a5fe6a3..28a1287c 100644 --- a/src/AgentOs.Modules.Tenants/Persistence/Migrations/TenantsDbContextModelSnapshot.cs +++ b/src/AgentOs.Modules.Tenants/Persistence/Migrations/TenantsDbContextModelSnapshot.cs @@ -18,7 +18,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) #pragma warning disable 612, 618 modelBuilder .HasDefaultSchema("tenants") - .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("ProductVersion", "10.0.14") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); @@ -40,6 +40,13 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("ExpiresAtUtc") .HasColumnType("timestamp with time zone"); + b.Property("Kind") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(16) + .HasColumnType("character varying(16)") + .HasDefaultValue("service"); + b.Property("LastUsedAtUtc") .HasColumnType("timestamp with time zone"); @@ -48,6 +55,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasMaxLength(128) .HasColumnType("character varying(128)"); + b.Property("OwnerUserId") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + b.Property("Prefix") .IsRequired() .HasMaxLength(16) @@ -61,6 +72,20 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasMaxLength(16) .HasColumnType("character varying(16)"); + b.Property("Salt") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasDefaultValue(""); + + b.Property("Scopes") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasDefaultValue(""); + b.Property("TenantId") .IsRequired() .HasMaxLength(64) @@ -78,6 +103,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("TenantId"); + b.HasIndex("TenantId", "OwnerUserId"); + b.ToTable("api_tokens", "tenants"); }); diff --git a/src/AgentOs.Modules.Tenants/Persistence/TenantsDbContext.cs b/src/AgentOs.Modules.Tenants/Persistence/TenantsDbContext.cs index 448264e6..0952424f 100644 --- a/src/AgentOs.Modules.Tenants/Persistence/TenantsDbContext.cs +++ b/src/AgentOs.Modules.Tenants/Persistence/TenantsDbContext.cs @@ -44,7 +44,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) e.HasIndex(x => new { x.TenantId, x.TimestampUtc }); }); - // E1.3: API tokens — only the SHA-256 is stored; Prefix is the (unique) lookup key at authentication. + // E1.3: API tokens — only a salted HMAC is stored; Prefix is the (unique) lookup key at authentication. modelBuilder.Entity(e => { e.ToTable("api_tokens"); @@ -54,9 +54,14 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) e.Property(x => x.Prefix).HasMaxLength(16).IsRequired(); e.Property(x => x.TokenHash).HasMaxLength(64).IsRequired(); e.Property(x => x.Role).HasMaxLength(16).IsRequired(); + e.Property(x => x.Salt).HasMaxLength(64).IsRequired().HasDefaultValue(string.Empty); + e.Property(x => x.Kind).HasMaxLength(16).IsRequired().HasDefaultValue(AgentOs.Modules.Tenants.ApiTokens.ApiTokenKind.Service); + e.Property(x => x.Scopes).HasMaxLength(64).IsRequired().HasDefaultValue(string.Empty); + e.Property(x => x.OwnerUserId).HasMaxLength(128); e.Property(x => x.CreatedBy).HasMaxLength(128).IsRequired(); e.HasIndex(x => x.Prefix).IsUnique(); e.HasIndex(x => x.TenantId); + e.HasIndex(x => new { x.TenantId, x.OwnerUserId }); }); } } diff --git a/src/AgentOs.Modules.Tenants/Settings/TenantsSettings.cs b/src/AgentOs.Modules.Tenants/Settings/TenantsSettings.cs index fcc92f1b..7f370ca9 100644 --- a/src/AgentOs.Modules.Tenants/Settings/TenantsSettings.cs +++ b/src/AgentOs.Modules.Tenants/Settings/TenantsSettings.cs @@ -23,5 +23,15 @@ public IEnumerable Describe() Scope = SettingScope.Platform, Help = "Let anyone create a new workspace (and become its admin) from the sign-up page. Off outside Development; invitations always work.", }; + + // E1.3: the longest expiry a new API token may get. Platform-only so a workspace can't extend it. + yield return new(ApiTokens.ApiTokenFormat.MaxLifetimeKey, SettingKind.WholeNumber, "Safety", "API token max lifetime (days)") + { + DefaultValue = ApiTokens.ApiTokenFormat.DefaultMaxLifetimeDays.ToString(System.Globalization.CultureInfo.InvariantCulture), + Scope = SettingScope.Platform, + Min = 1, + Max = 1825, + Help = "The longest expiry a new personal token or service-account token may have. Existing tokens keep their expiry.", + }; } } diff --git a/src/AgentOs.Modules.Tenants/TenantsModule.cs b/src/AgentOs.Modules.Tenants/TenantsModule.cs index 5b6c5f1e..5464135c 100644 --- a/src/AgentOs.Modules.Tenants/TenantsModule.cs +++ b/src/AgentOs.Modules.Tenants/TenantsModule.cs @@ -103,7 +103,9 @@ public void AddServices(IServiceCollection services, IConfiguration configuratio services.AddScoped(); services.AddScoped(); services.AddScoped(sp => new ApiTokens.ApiTokenService( - sp.GetRequiredService(), sp.GetRequiredService(), sp.GetService() ?? TimeProvider.System)); + sp.GetRequiredService(), sp.GetRequiredService(), sp.GetService() ?? TimeProvider.System, + sp.GetService(), + sp.GetService>())); } else { diff --git a/src/AgentOs.SharedKernel/Http/ApiVersioning.cs b/src/AgentOs.SharedKernel/Http/ApiVersioning.cs new file mode 100644 index 00000000..71f99ab7 --- /dev/null +++ b/src/AgentOs.SharedKernel/Http/ApiVersioning.cs @@ -0,0 +1,116 @@ +// E1.3 — the versioned REST contract. Every module route is served twice by the Api: +// /v1/ the contract: named endpoints, in the published OpenAPI document "v1" +// / the original unversioned path — still works, but is deprecated: it answers with +// Deprecation (RFC 9745), Sunset (RFC 8594) and Link rel="successor-version" / rel="deprecation" +// headers, carries no endpoint names (so names stay unique) and is left out of the OpenAPI document. +// Protocol endpoints (SignalR hubs, MCP) and operational routes (/health, /alive, /version, /) are not versioned — +// they have their own wire versioning or are probed by infrastructure. Policy: docs/API.md#deprecation-policy. + +using System; +using System.Globalization; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; + +namespace AgentOs.SharedKernel.Http; + +/// API version names, prefixes and the deprecation dates of the unversioned routes. +public static class ApiVersions +{ + /// The current major version (also the OpenAPI document name). + public const string V1 = "v1"; + + /// Route prefix of . + public const string V1Prefix = "/" + V1; + + /// Endpoint group name of the deprecated unversioned routes (never documented). + public const string Unversioned = "unversioned"; + + /// Where the deprecation policy is published (the Link rel="deprecation" target). + public const string PolicyUrl = "https://github.com/hoangsnowy/AgentOS.NET/blob/main/docs/API.md#deprecation-policy"; + + /// When the unversioned routes were deprecated (the day /v1 shipped). + public static DateTimeOffset UnversionedDeprecatedAt { get; } = new(2026, 11, 3, 0, 0, 0, TimeSpan.Zero); + + /// When the unversioned routes may be removed (the policy's minimum six months after deprecation). + public static DateTimeOffset UnversionedSunsetAt { get; } = new(2027, 5, 3, 0, 0, 0, TimeSpan.Zero); +} + +/// Endpoint metadata: this route is deprecated; announces it. +/// When it was deprecated (RFC 9745 Deprecation). +/// When it may stop working (RFC 8594 Sunset), if decided. +/// Prefix that turns this path into its successor (e.g. /v1), if any. +/// The deprecation policy (Link rel="deprecation"). +public sealed record ApiDeprecationMetadata(DateTimeOffset DeprecatedAt, DateTimeOffset? SunsetAt, string? SuccessorPrefix, string? PolicyUrl) +{ + /// The metadata every unversioned module route carries. + public static ApiDeprecationMetadata Unversioned { get; } = + new(ApiVersions.UnversionedDeprecatedAt, ApiVersions.UnversionedSunsetAt, ApiVersions.V1Prefix, ApiVersions.PolicyUrl); + + /// The Deprecation header value: an RFC 9651 date (@ + Unix seconds). + public string DeprecationHeader => "@" + DeprecatedAt.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture); + + /// The Sunset header value (IMF-fixdate), or null. + public string? SunsetHeader => SunsetAt?.UtcDateTime.ToString("r", CultureInfo.InvariantCulture); + + /// Write the headers for a request to (escaped form). + public void Apply(IHeaderDictionary headers, string path) + { + ArgumentNullException.ThrowIfNull(headers); + headers["Deprecation"] = DeprecationHeader; + if (SunsetHeader is { } sunset) { headers["Sunset"] = sunset; } + var links = new System.Collections.Generic.List(2); + if (SuccessorPrefix is { Length: > 0 }) { links.Add($"<{SuccessorPrefix}{path}>; rel=\"successor-version\""); } + if (PolicyUrl is { Length: > 0 }) { links.Add($"<{PolicyUrl}>; rel=\"deprecation\"; type=\"text/html\""); } + if (links.Count > 0) { headers.Append("Link", string.Join(", ", links)); } + } +} + +/// Map routes under a version prefix (plus the deprecated unversioned path) and announce deprecations. +public static class ApiVersioning +{ + /// + /// Map 's routes twice: under /v1 (group name v1, documented) and at the original + /// path (group unversioned, deprecated, undocumented, endpoint names stripped so they stay unique). + /// + public static IEndpointRouteBuilder MapVersioned(this IEndpointRouteBuilder endpoints, Action map) + { + ArgumentNullException.ThrowIfNull(endpoints); + ArgumentNullException.ThrowIfNull(map); + + var v1 = endpoints.MapGroup(ApiVersions.V1Prefix); + v1.WithGroupName(ApiVersions.V1); + map(v1); + + var legacy = endpoints.MapGroup(string.Empty); + legacy.WithGroupName(ApiVersions.Unversioned) + .WithMetadata(ApiDeprecationMetadata.Unversioned) + .ExcludeFromDescription(); + // After the endpoints' own conventions: the /v1 twin owns the endpoint and route names. (Finally is a default + // interface member, so it is reached through the interface.) + IEndpointConventionBuilder legacyConventions = legacy; + legacyConventions.Finally(static builder => + { + for (var i = builder.Metadata.Count - 1; i >= 0; i--) + { + if (builder.Metadata[i] is IEndpointNameMetadata or IRouteNameMetadata) { builder.Metadata.RemoveAt(i); } + } + }); + map(legacy); + return endpoints; + } + + /// Add Deprecation / Sunset / Link headers to responses of deprecated endpoints. + public static IApplicationBuilder UseApiDeprecationHeaders(this IApplicationBuilder app) + { + ArgumentNullException.ThrowIfNull(app); + return app.Use(static (context, next) => + { + if (context.GetEndpoint()?.Metadata.GetMetadata() is { } deprecation) + { + deprecation.Apply(context.Response.Headers, context.Request.Path.ToUriComponent()); + } + return next(context); + }); + } +} diff --git a/src/AgentOs.SharedKernel/Modularity/IProtocolEndpointModule.cs b/src/AgentOs.SharedKernel/Modularity/IProtocolEndpointModule.cs new file mode 100644 index 00000000..2bd74cbb --- /dev/null +++ b/src/AgentOs.SharedKernel/Modularity/IProtocolEndpointModule.cs @@ -0,0 +1,8 @@ +// A module whose endpoints are a wire protocol with its own versioning (a SignalR hub), not REST. The host's versioned +// mapping (ModuleLoader.MapVersionedModuleEndpoints) maps these once, at their own path — never under /v1 and never +// marked deprecated, so a paired runner's hub URL keeps working unchanged. + +namespace AgentOs.SharedKernel.Modularity; + +/// An endpoint module serving a protocol endpoint (e.g. a SignalR hub) that is not REST-versioned. +public interface IProtocolEndpointModule : IEndpointModule; diff --git a/src/AgentOs.SharedKernel/Modularity/ModuleLoader.cs b/src/AgentOs.SharedKernel/Modularity/ModuleLoader.cs index 5ef769ec..204ed92b 100644 --- a/src/AgentOs.SharedKernel/Modularity/ModuleLoader.cs +++ b/src/AgentOs.SharedKernel/Modularity/ModuleLoader.cs @@ -56,6 +56,31 @@ public static IEndpointRouteBuilder MapModuleEndpoints(this WebApplication app) return app; } + /// + /// Map every module's endpoints behind the versioned REST contract (E1.3): REST modules under /v1 plus their + /// deprecated unversioned twins (); s + /// once at their own path. adds the host's own REST routes to the same contract. + /// + public static IEndpointRouteBuilder MapVersionedModuleEndpoints(this WebApplication app, Action? hostRoutes = null) + { + ArgumentNullException.ThrowIfNull(app); + + var modules = app.Services.GetServices().OfType().ToArray(); + foreach (var protocol in modules.OfType()) + { + protocol.MapEndpoints(app); + } + Http.ApiVersioning.MapVersioned(app, group => + { + foreach (var module in modules.Where(m => m is not IProtocolEndpointModule)) + { + module.MapEndpoints(group); + } + hostRoutes?.Invoke(group); + }); + return app; + } + /// Resolve every registered and await InitializeAsync /// sequentially. public static async Task InitializeModulesAsync(this IServiceProvider services, CancellationToken ct = default) diff --git a/src/AgentOs.Web/Components/Pages/ApiTokensApp.razor b/src/AgentOs.Web/Components/Pages/ApiTokensApp.razor index 746458de..96635299 100644 --- a/src/AgentOs.Web/Components/Pages/ApiTokensApp.razor +++ b/src/AgentOs.Web/Components/Pages/ApiTokensApp.razor @@ -1,7 +1,9 @@ -@* ApiTokensApp — Settings → API tokens (enterprise review E1.3). Tenant admins create service-account tokens for - CI pipelines, scripts and MCP clients calling the Api (Authorization: Bearer aos_…). A token has a name, a role - (member | admin — never platform-admin) and an expiry; its secret is shown ONCE at creation (only a SHA-256 is - stored). Revoke takes effect on the next request. Create / revoke are audited. *@ +@* ApiTokensApp — Settings → API tokens (enterprise review E1.3). Every member creates PERSONAL tokens (they act as the + member, e.g. for the VS Code extension or a script); tenant admins also create SERVICE ACCOUNTS (a workspace identity + for CI). A token has a name, a scope (read · run · admin — admin only for admins, never platform-admin) and an expiry + capped by the platform setting Tenants:ApiTokens:MaxLifetimeDays. Its secret is shown ONCE at creation (only a salted + HMAC is stored). Revoke takes effect on the next request. Create / use / revoke are audited. Admins see and revoke + every token in the workspace; members see their own. *@ @using Microsoft.AspNetCore.Components.Authorization @using AgentOs.Modules.Tenants.ApiTokens @@ -13,10 +15,6 @@ { } -else if (!_isAdmin) -{ - -} else if (_tenantId is null) { @@ -26,7 +24,7 @@ else

API tokens · @_tenantId

-

Service-account tokens for CI, scripts and MCP clients: Authorization: Bearer aos_… on the Api.

+

For scripts, CI, the VS Code extension and MCP clients: Authorization: Bearer aos_… on the Api's /v1 routes.

@@ -35,18 +33,31 @@ else - - + + @if (_isAdmin) + { + + } - + + + + @@ -66,32 +77,32 @@ else } - + @if (_rows is null) { } else if (_rows.Count == 0) { - + } else { - + @foreach (var t in _rows) { var active = t.IsActive(DateTimeOffset.UtcNow); - + + - - + @@ -103,6 +114,8 @@ else } @code { + private static readonly int[] StandardDays = [7, 30, 90, 180, 365]; + [CascadingParameter] private Task? AuthState { get; set; } private bool _resolved; @@ -110,10 +123,12 @@ else private bool _busy; // Null = the sign-in carries no tenant claim: fail closed (GAP-17), never the shared "default" tenant. private string? _tenantId; - private string _actor = "admin"; + private ApiTokenActor _actor = new("member", null, false); private string _name = string.Empty; - private string _role = "member"; + private string _kind = ApiTokenKind.Personal; + private string _scope = ApiTokenScopes.Read; private int _days = 90; + private int _maxDays = ApiTokenFormat.DefaultMaxLifetimeDays; private string? _newToken; private IReadOnlyList? _rows; @@ -124,22 +139,44 @@ else var state = await AuthState; _isAdmin = state.User.IsAdmin(); _tenantId = state.User.GetTenantId(); - _actor = state.User.Identity?.Name ?? "admin"; + _actor = new ApiTokenActor(state.User.Identity?.Name ?? "member", state.User.GetUserId(), _isAdmin); + } + // Admins mostly create CI identities; members can only create personal tokens. + _kind = _isAdmin ? ApiTokenKind.Service : ApiTokenKind.Personal; + _scope = _isAdmin ? ApiTokenScopes.Run : ApiTokenScopes.Read; + if (_tenantId is { } tenant) + { + _maxDays = await Tokens.MaxLifetimeDaysAsync(tenant); + _days = Math.Min(_days, _maxDays); + _rows = await Tokens.ListAsync(tenant, _actor); } _resolved = true; - if (_isAdmin && _tenantId is not null) { _rows = await Tokens.ListAsync(_tenantId); } } + private IEnumerable ExpiryChoices() + { + var choices = StandardDays.Where(d => d < _maxDays).ToList(); + choices.Add(_maxDays); + return choices; + } + + private static string ExpiryLabel(int days) => days switch + { + 1 => "1 day", + 365 => "1 year", + _ => $"{days} days", + }; + private async Task CreateAsync() { if (_tenantId is not { } tenant) { return; } _busy = true; try { - var (_, token) = await Tokens.CreateAsync(tenant, _name, _role, _days, _actor); + var (_, token) = await Tokens.CreateAsync(new ApiTokenRequest(tenant, _name, _kind, [_scope], _days, _actor)); _newToken = token; _name = string.Empty; - _rows = await Tokens.ListAsync(tenant); + _rows = await Tokens.ListAsync(tenant, _actor); } catch (InvalidOperationException ex) { @@ -158,7 +195,7 @@ else try { if (await Tokens.RevokeAsync(tenant, token.Id, _actor)) { Toasts.Show("API tokens", $"{token.Name} revoked.", ToastKind.Ok); } - _rows = await Tokens.ListAsync(tenant); + _rows = await Tokens.ListAsync(tenant, _actor); } finally { diff --git a/src/AgentOs.Web/Components/Pages/SettingsHub.razor b/src/AgentOs.Web/Components/Pages/SettingsHub.razor index f06e35bc..d7de6e64 100644 --- a/src/AgentOs.Web/Components/Pages/SettingsHub.razor +++ b/src/AgentOs.Web/Components/Pages/SettingsHub.razor @@ -89,7 +89,7 @@ new("audit", "Governance", "Activity log", "clock-counter", Access.Admin), new("evidence", "Governance", "Tool calls", "scroll", Access.Admin, Hidden: true), // a view of Activity log new("users", "People & data", "Users", "user", Access.Admin), - new("tokens", "People & data", "API tokens", "tag", Access.Admin), + new("tokens", "People & data", "API tokens", "tag", Access.Everyone), // personal tokens for all; service accounts admin-only new("data", "People & data", "Data", "floppy-disk", Access.Admin), new("general", "Personal", "General", "gear", Access.Everyone, Host: true), new("appearance", "Personal", "Appearance", "palette", Access.Everyone, Host: true), diff --git a/src/AgentOs.Web/Components/Pages/UsersApp.razor b/src/AgentOs.Web/Components/Pages/UsersApp.razor index f05bf5ba..ce9d28ca 100644 --- a/src/AgentOs.Web/Components/Pages/UsersApp.razor +++ b/src/AgentOs.Web/Components/Pages/UsersApp.razor @@ -265,7 +265,8 @@ else var services = scope.ServiceProvider; var result = await MemberRemoval.RemoveAsync(_tenantId, m.Id, new MemberRemovalActor(_myUserId), Kc, services.GetRequiredService(), services.GetService(), - RunnerDisconnector, Loggers.CreateLogger(typeof(MemberRemoval).FullName!)); + RunnerDisconnector, services.GetService(), + Loggers.CreateLogger(typeof(MemberRemoval).FullName!)); ShowRemoval(m, result); await LoadMembersAsync(); }, diff --git a/src/AgentOs.Web/Services/AppCatalog.cs b/src/AgentOs.Web/Services/AppCatalog.cs index d0e1b22e..22ed9b65 100644 --- a/src/AgentOs.Web/Services/AppCatalog.cs +++ b/src/AgentOs.Web/Services/AppCatalog.cs @@ -34,7 +34,7 @@ public static class AppCatalog // (Workspaces + Sessions were standalone admin windows fully subsumed by Board → deleted.) new("users", "Users", "user", "Manage tenant members + roles", "Admin", 880, 600, Pinned: false, AdminOnly: true, ComponentType: typeof(UsersApp), Color: "#e5a50a"), new("evidence", "Evidence", "scroll", "Tool-invocation audit trail", "Admin", 960, 620, Pinned: false, AdminOnly: true, ComponentType: typeof(EvidenceApp), Color: "#c01c28"), - new("tokens", "API tokens", "tag", "Service-account tokens for CI, scripts and MCP clients", "Admin", 980, 620, Pinned: false, AdminOnly: true, ComponentType: typeof(ApiTokensApp), Color: "#1c71d8"), + new("tokens", "API tokens", "tag", "Personal tokens and service accounts for CI, scripts and the VS Code extension", "System", 980, 620, Pinned: false, AdminOnly: false, ComponentType: typeof(ApiTokensApp), Color: "#1c71d8"), new("data", "Data", "floppy-disk", "Export this workspace; platform admins purge tenants", "Admin", 900, 600, Pinned: false, AdminOnly: true, ComponentType: typeof(DataApp), Color: "#26a269"), new("audit", "Audit log", "clock-counter", "Who changed what — settings, members, sign-in", "Admin", 980, 640, Pinned: false, AdminOnly: true, ComponentType: typeof(AuditLogApp), Color: "#865e3c"), new("policy", "Policy", "shield", "Per-tenant tool allowlist", "Admin", 900, 620, Pinned: false, AdminOnly: true, ComponentType: typeof(PolicyApp), Color: "#613583"), diff --git a/src/AgentOs.Web/Services/SettingsSearch.cs b/src/AgentOs.Web/Services/SettingsSearch.cs index c3f4fc7b..70e04ba4 100644 --- a/src/AgentOs.Web/Services/SettingsSearch.cs +++ b/src/AgentOs.Web/Services/SettingsSearch.cs @@ -48,7 +48,7 @@ private sealed record Page(string Target, string Title, string Path, string Icon new("evidence", "Tool calls", Gov + " › Activity log", "scroll", "evidence tool calls invocations trail governance", Access.Admin), new("audit", "Activity log", Gov, "clock-counter", "audit log activity who changed history sign-in login members csv", Access.Admin), new("users", "Users", People, "user", "users members invite invitation roles people team", Access.Admin), - new("tokens", "API tokens", People, "tag", "api token service account ci pipeline script machine bearer mcp client", Access.Admin), + new("tokens", "API tokens", People, "tag", "api token personal access token pat service account ci pipeline script machine bearer mcp client vs code extension", Access.Everyone), new("data", "Data", People, "floppy-disk", "export purge delete tenant workspace data download gdpr", Access.Admin), new("general", "General", Personal, "gear", "general preferences", Access.Everyone), new("appearance", "Appearance", Personal, "palette", "appearance theme dark light mode wallpaper accent glass motion animation", Access.Everyone), diff --git a/src/AgentOs.Web/Services/ShellActions.cs b/src/AgentOs.Web/Services/ShellActions.cs index 325bc74f..b2fff6a0 100644 --- a/src/AgentOs.Web/Services/ShellActions.cs +++ b/src/AgentOs.Web/Services/ShellActions.cs @@ -46,7 +46,7 @@ public static class ShellActions new(Idea, "Start from an idea", "Board · turn an idea into a plan and tasks", "git-pull-request") { Keywords = "new idea ticket story issue plan board decompose" }, new(AddKey, "Connect an AI account", "Settings › AI › Model keys", "key") { Keywords = "add model key api connect account llm provider anthropic openai gemini xai azure", AdminOnly = true }, new(Invite, "Invite a member", "Settings › People & data › Users", "user") { Keywords = "invite add user member people team", AdminOnly = true }, - new(Token, "Create an API token", "Settings › People & data › API tokens", "tag") { Keywords = "create new api token service account ci machine", AdminOnly = true }, + new(Token, "Create an API token", "Settings › People & data › API tokens", "tag") { Keywords = "create new api token personal access token service account ci machine" }, new(Export, "Export workspace data", "Settings › People & data › Data", "floppy-disk") { Keywords = "export download backup data workspace", AdminOnly = true }, new(Theme, "Switch light / dark theme", "Appearance", "moon") { Keywords = "theme dark light mode toggle switch appearance night" }, new(SignOut, "Sign out", "End this session", "power") { Keywords = "sign out log out logout exit leave" }, diff --git a/tests/AgentOs.E2E.Tests/AgentOsUi/ApiTokensRealAuthTests.cs b/tests/AgentOs.E2E.Tests/AgentOsUi/ApiTokensRealAuthTests.cs index c6cf1d61..abef434a 100644 --- a/tests/AgentOs.E2E.Tests/AgentOsUi/ApiTokensRealAuthTests.cs +++ b/tests/AgentOs.E2E.Tests/AgentOsUi/ApiTokensRealAuthTests.cs @@ -1,6 +1,7 @@ -// REAL-AUTH E2E — E1.3 on the full stack: a tenant admin creates an API token in Settings → API tokens, a machine -// calls the real Api with `Authorization: Bearer aos_…` and is authenticated as that tenant with the token's role; -// after Revoke in the UI the same call is refused. Cleanup removes the token row and its audit rows. +// REAL-AUTH E2E — E1.3 on the full stack: a tenant admin creates a service-account token (scope "run") in Settings → +// API tokens, a machine calls the real Api's /v1 routes with `Authorization: Bearer aos_…` and is authenticated as that +// tenant with the token's scopes; the unversioned route still answers, with a Deprecation header; after Revoke in the UI +// the same call is refused. Cleanup removes the token row and its audit rows. // - Gates: RUN_AGENTOS_E2E_REAL=true; Api at AGENTOS_API_URL (default https://localhost:5080); AGENTOS_PG_CONN for cleanup. using System; @@ -47,19 +48,26 @@ public async Task Token_AuthenticatesAgainstTheApi_UntilRevoked() using var http = new HttpClient(handler); http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); - using (var me = await http.GetAsync($"{ApiUrl}/tenants/me")) + using (var me = await http.GetAsync($"{ApiUrl}/v1/tenants/me")) { Assert.Equal(HttpStatusCode.OK, me.StatusCode); var body = await me.Content.ReadAsStringAsync(); Assert.Contains("\"default\"", body, StringComparison.Ordinal); // the operator's tenant - Assert.Contains($"token:{name}", body, StringComparison.Ordinal); + Assert.Contains($"service:{name}", body, StringComparison.Ordinal); + Assert.Contains("\"api_token\"", body, StringComparison.Ordinal); + Assert.False(me.Headers.Contains("Deprecation")); + } + using (var legacy = await http.GetAsync($"{ApiUrl}/tenants/me")) + { + Assert.Equal(HttpStatusCode.OK, legacy.StatusCode); + Assert.True(legacy.Headers.Contains("Deprecation")); } var row = win.Locator("tr", new() { HasTextString = name }); await row.GetByRole(AriaRole.Button, new() { Name = "Revoke" }).ClickAsync(); await Assertions.Expect(row.Locator(".badge")).ToHaveTextAsync("revoked", new() { Timeout = 15_000 }); - using var after = await http.GetAsync($"{ApiUrl}/tenants/me"); + using var after = await http.GetAsync($"{ApiUrl}/v1/tenants/me"); Assert.Equal(HttpStatusCode.Unauthorized, after.StatusCode); } finally diff --git a/tests/AgentOs.Tests/AgentOs.Tests.csproj b/tests/AgentOs.Tests/AgentOs.Tests.csproj index 7a1674e4..271d966c 100644 --- a/tests/AgentOs.Tests/AgentOs.Tests.csproj +++ b/tests/AgentOs.Tests/AgentOs.Tests.csproj @@ -48,9 +48,9 @@ + - diff --git a/tests/AgentOs.Tests/Api/ApiV1IntegrationTests.cs b/tests/AgentOs.Tests/Api/ApiV1IntegrationTests.cs new file mode 100644 index 00000000..6cb390d0 --- /dev/null +++ b/tests/AgentOs.Tests/Api/ApiV1IntegrationTests.cs @@ -0,0 +1,356 @@ +extern alias ApiHost; + +// E1.3 integration — the REAL Api host booted in-process (WebApplicationFactory, Development, no database) with the +// token store swapped for the real ApiTokenService on EF InMemory. Proves, through the actual middleware pipeline: +// • Bearer aos_… authenticates next to the Keycloak JWT scheme and maps to the token's tenant + scopes; +// • the scope gates the HTTP method (read ⇒ GET only, run ⇒ writes) and the admin scope the Admin policy; +// • revoked / expired / forged tokens get 401; +// • every module route answers under /v1, and the unversioned twin still works with Deprecation / Sunset / Link; +// • the SignalR hub is not versioned; /v1 endpoint names are unique, legacy twins carry none; +// • /openapi/v1.json documents the /v1 routes (not the legacy ones) and matches the committed docs/api/openapi-v1.json +// (regenerate with AGENTOS_UPDATE_OPENAPI=1). + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using AgentOs.Modules.Tenants; +using AgentOs.Modules.Tenants.ApiTokens; +using AgentOs.Modules.Tenants.Persistence; +using AgentOs.SharedKernel.Http; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using NSubstitute; +using Shouldly; +using Xunit; + +namespace AgentOs.Tests.Api; + +/// The Api with an in-memory token store. +public sealed class ApiHostFixture : WebApplicationFactory +{ + private readonly string _db = "api-tokens-" + Guid.NewGuid().ToString("N"); + + /// The clock the token service reads (tests move it to expire tokens). + public MutableClock Clock { get; } = new(new DateTimeOffset(2026, 11, 3, 12, 0, 0, TimeSpan.Zero)); + + /// Audit rows the token service wrote. + public IAuditLog Audit { get; } = Substitute.For(); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + ArgumentNullException.ThrowIfNull(builder); + builder.UseEnvironment("Development"); + // Hosts read the environment from configuration too (AddJwtAuth's dev-Keycloak fallback, ModuleEnvironment). + builder.UseSetting("ASPNETCORE_ENVIRONMENT", "Development"); + builder.UseSetting("Persistence:RequireDatabase", "false"); + builder.UseSetting("Persistence:RowLevelSecurity", "false"); + builder.UseSetting("APPLICATIONINSIGHTS_CONNECTION_STRING", string.Empty); + builder.ConfigureTestServices(services => + { + var options = new DbContextOptionsBuilder().UseInMemoryDatabase(_db).Options; + services.RemoveAll(); + services.AddScoped(_ => new ApiTokenService(new TenantsDbContext(options), Audit, Clock, throttle: new ApiTokenAuditThrottle())); + }); + } + + /// Create a token straight through the service (as the desktop would). + public async Task CreateTokenAsync(string scope, string kind = ApiTokenKind.Service, string tenant = "acme", int days = 30) + { + await using var scope_ = Services.CreateAsyncScope(); + var svc = scope_.ServiceProvider.GetRequiredService(); + var (_, token) = await svc.CreateAsync(new ApiTokenRequest(tenant, $"t-{Guid.NewGuid():N}"[..12], kind, [scope], days, + new ApiTokenActor("alice", "user-alice", IsAdmin: true))); + return token; + } + + /// Revoke the token whose plaintext is . + public async Task RevokeAsync(string token, string tenant = "acme") + { + await using var scope = Services.CreateAsyncScope(); + var svc = scope.ServiceProvider.GetRequiredService(); + var identity = await svc.ValidateAsync(token) ?? throw new InvalidOperationException("token not valid"); + (await svc.RevokeAsync(tenant, identity.Id, new ApiTokenActor("alice", "user-alice", true))).ShouldBeTrue(); + } + + /// A client sending Authorization: Bearer . + public HttpClient ClientWith(string? token) + { + var client = CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + if (token is not null) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); } + return client; + } +} + +/// A settable clock. +public sealed class MutableClock(DateTimeOffset now) : TimeProvider +{ + /// Now. + public DateTimeOffset Now { get; set; } = now; + + /// + public override DateTimeOffset GetUtcNow() => Now; +} + +public sealed class ApiV1IntegrationTests(ApiHostFixture api) : IClassFixture +{ + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static StringContent Json(string body) => new(body, Encoding.UTF8, "application/json"); + + // ── token auth ────────────────────────────────────────────────────────────────────────────────────────────────── + + [Fact] + public async Task Token_AuthenticatesAsItsTenant_WithItsScopes() + { + using var client = api.ClientWith(await api.CreateTokenAsync(ApiTokenScopes.Run)); + + using var response = await client.GetAsync("/v1/tenants/me", Ct); + + response.StatusCode.ShouldBe(HttpStatusCode.OK); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Ct)); + body.RootElement.GetProperty("tenantId").GetString().ShouldBe("acme"); + body.RootElement.GetProperty("isAuthenticated").GetBoolean().ShouldBeTrue(); + body.RootElement.GetProperty("authMethod").GetString().ShouldBe("api_token"); + body.RootElement.GetProperty("scopes").EnumerateArray().Select(e => e.GetString()).ShouldBe(["read", "run"]); + body.RootElement.GetProperty("userName").GetString()!.ShouldStartWith("service:"); + } + + [Fact] + public async Task PersonalToken_ActsAsItsOwner() + { + using var client = api.ClientWith(await api.CreateTokenAsync(ApiTokenScopes.Read, ApiTokenKind.Personal)); + + using var response = await client.GetAsync("/v1/tenants/me", Ct); + + response.StatusCode.ShouldBe(HttpStatusCode.OK); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Ct)); + body.RootElement.GetProperty("userId").GetString().ShouldBe("user-alice"); + body.RootElement.GetProperty("userName").GetString().ShouldBe("alice"); + } + + [Fact] + public async Task ReadScope_AllowsGet_RefusesWrites() + { + using var client = api.ClientWith(await api.CreateTokenAsync(ApiTokenScopes.Read)); + + using var get = await client.GetAsync("/v1/tenants/me", Ct); + using var post = await client.PostAsync("/v1/requirement", Json("{}"), Ct); + + get.StatusCode.ShouldBe(HttpStatusCode.OK); + post.StatusCode.ShouldBe(HttpStatusCode.Forbidden); + (await post.Content.ReadAsStringAsync(Ct)).ShouldContain("'run' scope"); + } + + [Fact] + public async Task RunScope_ReachesTheEndpoint() + { + using var client = api.ClientWith(await api.CreateTokenAsync(ApiTokenScopes.Run)); + + // An empty story is a 400 validation problem from the endpoint itself — i.e. auth + scope let it through. + using var post = await client.PostAsync("/v1/requirement", Json("{}"), Ct); + + post.StatusCode.ShouldBe(HttpStatusCode.BadRequest); + } + + [Fact] + public async Task AdminScope_IsNeededForAdminRoutes() + { + using var run = api.ClientWith(await api.CreateTokenAsync(ApiTokenScopes.Run)); + using var admin = api.ClientWith(await api.CreateTokenAsync(ApiTokenScopes.Admin)); + + using var asRun = await run.GetAsync("/v1/mcp/servers", Ct); + using var asAdmin = await admin.GetAsync("/v1/mcp/servers", Ct); + + asRun.StatusCode.ShouldBe(HttpStatusCode.Forbidden); + asAdmin.StatusCode.ShouldBe(HttpStatusCode.OK); + } + + [Fact] + public async Task RevokedToken_Gets401() + { + var token = await api.CreateTokenAsync(ApiTokenScopes.Read); + using var client = api.ClientWith(token); + (await client.GetAsync("/v1/tenants/me", Ct)).StatusCode.ShouldBe(HttpStatusCode.OK); + + await api.RevokeAsync(token); + + using var after = await client.GetAsync("/v1/tenants/me", Ct); + after.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + after.Headers.WwwAuthenticate.ToString().ShouldContain("invalid_token"); + } + + [Fact] + public async Task ExpiredToken_Gets401() + { + var token = await api.CreateTokenAsync(ApiTokenScopes.Read, tenant: "expiry", days: 1); + var start = api.Clock.Now; + try + { + api.Clock.Now = start.AddDays(2); + using var client = api.ClientWith(token); + (await client.GetAsync("/v1/tenants/me", Ct)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + } + finally + { + api.Clock.Now = start; + } + } + + [Theory] + [InlineData("aos_abcdefghij_unknown-unknown-unknown-unknown-unknown")] + [InlineData("aos_garbage")] + public async Task UnknownOrMalformedToken_Gets401(string token) + { + using var client = api.ClientWith(token); + (await client.GetAsync("/v1/tenants/me", Ct)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task NoCredentials_Gets401_AndAnonymousRoutesStayOpen() + { + using var client = api.ClientWith(null); + (await client.GetAsync("/v1/tenants/me", Ct)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + (await client.GetAsync("/version", Ct)).StatusCode.ShouldBe(HttpStatusCode.OK); + } + + // GAP-13 fallback policy (deny by default): a route's explicit AllowAnonymous travels with it to both twins, and a + // token principal satisfies "authenticated" exactly like a JWT. + [Theory] + [InlineData("/v1/tenants/invitations/preview")] + [InlineData("/tenants/invitations/preview")] + public async Task FallbackPolicy_PublicRoutesStayPublicOnBothTwins(string path) + { + using var client = api.ClientWith(null); + using var response = await client.GetAsync(path, Ct); + response.StatusCode.ShouldNotBe(HttpStatusCode.Unauthorized); + response.StatusCode.ShouldNotBe(HttpStatusCode.Forbidden); + } + + [Fact] + public async Task FallbackPolicy_TokenPrincipalCountsAsAuthenticated() + { + using var anonymous = api.ClientWith(null); + using var token = api.ClientWith(await api.CreateTokenAsync(ApiTokenScopes.Read)); + + (await anonymous.GetAsync("/health/llm", Ct)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + (await token.GetAsync("/health/llm", Ct)).StatusCode.ShouldBe(HttpStatusCode.OK); + } + + // ── versioning + deprecation ──────────────────────────────────────────────────────────────────────────────────── + + [Fact] + public async Task LegacyRoute_StillWorks_WithDeprecationHeaders() + { + using var client = api.ClientWith(await api.CreateTokenAsync(ApiTokenScopes.Read)); + + using var legacy = await client.GetAsync("/tenants/me", Ct); + using var v1 = await client.GetAsync("/v1/tenants/me", Ct); + + legacy.StatusCode.ShouldBe(HttpStatusCode.OK); + legacy.Headers.GetValues("Deprecation").Single().ShouldBe("@" + ApiVersions.UnversionedDeprecatedAt.ToUnixTimeSeconds()); + legacy.Headers.GetValues("Sunset").Single().ShouldBe("Mon, 03 May 2027 00:00:00 GMT"); + var link = string.Join(", ", legacy.Headers.GetValues("Link")); + link.ShouldContain("; rel=\"successor-version\""); + link.ShouldContain("rel=\"deprecation\""); + + v1.StatusCode.ShouldBe(HttpStatusCode.OK); + v1.Headers.Contains("Deprecation").ShouldBeFalse(); + v1.Headers.Contains("Sunset").ShouldBeFalse(); + } + + [Fact] + public async Task LegacyRoute_AnnouncesDeprecation_EvenWhenUnauthorized() + { + using var client = api.ClientWith(null); + using var legacy = await client.GetAsync("/runs", Ct); + legacy.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + legacy.Headers.Contains("Deprecation").ShouldBeTrue(); + } + + [Fact] + public async Task OperationalRoutes_AreNotDeprecated() + { + using var client = api.ClientWith(null); + using var version = await client.GetAsync("/version", Ct); + version.Headers.Contains("Deprecation").ShouldBeFalse(); + } + + [Fact] + public void Endpoints_V1NamesAreUnique_LegacyTwinsUnnamed_HubUnversioned() + { + var endpoints = api.Services.GetRequiredService().Endpoints.OfType().ToArray(); + var v1 = endpoints.Where(e => e.RoutePattern.RawText?.StartsWith("/v1/", StringComparison.Ordinal) == true).ToArray(); + var legacy = endpoints.Where(e => e.Metadata.GetMetadata() is not null).ToArray(); + + v1.Length.ShouldBeGreaterThan(30); + legacy.Length.ShouldBe(v1.Length); // one deprecated twin per /v1 route + v1.ShouldAllBe(e => e.Metadata.GetMetadata() == null); + legacy.ShouldAllBe(e => e.Metadata.GetMetadata() == null); + var names = endpoints.Select(e => e.Metadata.GetMetadata()?.EndpointName).OfType().ToArray(); + names.Length.ShouldBe(names.Distinct(StringComparer.Ordinal).Count()); + + var hub = endpoints.Where(e => e.RoutePattern.RawText?.Contains("hubs/remote-agent", StringComparison.Ordinal) == true).ToArray(); + hub.ShouldNotBeEmpty(); + hub.ShouldAllBe(e => !e.RoutePattern.RawText!.StartsWith("/v1", StringComparison.Ordinal)); + hub.ShouldAllBe(e => e.Metadata.GetMetadata() == null); + } + + // ── OpenAPI ───────────────────────────────────────────────────────────────────────────────────────────────────── + + [Fact] + public async Task OpenApi_V1DocumentsTheVersionedRoutes_AndMatchesTheCommittedCopy() + { + using var client = api.ClientWith(null); + var json = await client.GetStringAsync("/openapi/v1.json", Ct); + var doc = JsonNode.Parse(json)!.AsObject(); + + doc["info"]!["version"]!.GetValue().ShouldBe("v1"); + doc["info"]!["title"]!.GetValue().ShouldBe("AgentOS.NET API"); + doc["components"]!["securitySchemes"]!["Bearer"]!["scheme"]!.GetValue().ShouldBe("bearer"); + var paths = doc["paths"]!.AsObject().Select(p => p.Key).ToArray(); + paths.ShouldContain("/v1/pipeline"); + paths.ShouldContain("/v1/tenants/me"); + paths.ShouldContain("/v1/runs"); + paths.ShouldNotContain("/pipeline"); // legacy twins are not documented + paths.ShouldNotContain("/tenants/me"); + paths.Where(p => !p.StartsWith("/v1/", StringComparison.Ordinal)).ShouldAllBe(p => OperationalPaths.Contains(p)); + + var committed = Path.Join(RepoRoot(), "docs", "api", "openapi-v1.json"); + var pretty = doc.ToJsonString(new JsonSerializerOptions { WriteIndented = true }).ReplaceLineEndings("\n") + "\n"; + if (Environment.GetEnvironmentVariable("AGENTOS_UPDATE_OPENAPI") == "1") + { + Directory.CreateDirectory(Path.GetDirectoryName(committed)!); + await File.WriteAllTextAsync(committed, pretty, Ct); + } + File.Exists(committed).ShouldBeTrue("docs/api/openapi-v1.json is missing — run the tests with AGENTOS_UPDATE_OPENAPI=1 and commit it."); + (await File.ReadAllTextAsync(committed, Ct)).ReplaceLineEndings("\n").ShouldBe(pretty, + "The /v1 contract changed — regenerate docs/api/openapi-v1.json (AGENTOS_UPDATE_OPENAPI=1) and review the diff: " + + "removing or changing a /v1 operation is a breaking change (docs/API.md#deprecation-policy)."); + } + + private static readonly HashSet OperationalPaths = new(StringComparer.Ordinal) { "/", "/version", "/health/llm" }; + + private static string RepoRoot() + { + for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent) + { + if (File.Exists(Path.Join(dir.FullName, "AgentOs.slnx"))) { return dir.FullName; } + } + throw new DirectoryNotFoundException("AgentOs.slnx not found above the test output directory."); + } +} diff --git a/tests/AgentOs.Tests/Security/HostSecurityTests.cs b/tests/AgentOs.Tests/Security/HostSecurityTests.cs index b35c5b84..feef6287 100644 --- a/tests/AgentOs.Tests/Security/HostSecurityTests.cs +++ b/tests/AgentOs.Tests/Security/HostSecurityTests.cs @@ -376,6 +376,10 @@ public async Task Api_AnonymousEndpointInventory_IsTheReviewedList() "/scalar/{documentName?}", // the docs page + its embedded assets "/tenants/invitations/preview", "/tenants/register", + // E1.3: the same two public handlers under the versioned contract (the unversioned paths are their + // deprecated twins) — nothing else becomes public through /v1. + "/v1/tenants/invitations/preview", + "/v1/tenants/register", "/version", ]); } diff --git a/tests/AgentOs.Tests/Tenants/ApiTokenTests.cs b/tests/AgentOs.Tests/Tenants/ApiTokenTests.cs index dafd1817..4cd1954b 100644 --- a/tests/AgentOs.Tests/Tenants/ApiTokenTests.cs +++ b/tests/AgentOs.Tests/Tenants/ApiTokenTests.cs @@ -1,13 +1,18 @@ -// E1.3 — tenant API tokens: format + hashing, and the full lifecycle (create → validate → revoke / expire) on EF. -// Only the SHA-256 is stored; a token with the right prefix but a wrong secret is refused; tokens never carry -// platform-admin; "Bearer aos_…" is forwarded to the token scheme, a Keycloak JWT is not. +// E1.3 — API tokens: format + salted hashing, scopes, kinds (personal / service account), the full lifecycle +// (create → validate → revoke / expire) on EF, the max-lifetime setting, who may see and revoke what, the audit trail +// (create / use / refuse / revoke), the claims a token maps to, and the method → scope rule. using System; using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading; using System.Threading.Tasks; +using AgentOs.Domain.Configuration; using AgentOs.Modules.Tenants; using AgentOs.Modules.Tenants.ApiTokens; using AgentOs.Modules.Tenants.Persistence; +using AgentOs.SharedKernel.Identity; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using NSubstitute; @@ -18,19 +23,47 @@ namespace AgentOs.Tests.Tenants; public sealed class ApiTokenTests { + private static readonly ApiTokenActor Admin = new("alice", "user-alice", IsAdmin: true); + private static readonly ApiTokenActor Member = new("bob", "user-bob", IsAdmin: false); + private sealed class Clock(DateTimeOffset now) : TimeProvider { public DateTimeOffset Now { get; set; } = now; public override DateTimeOffset GetUtcNow() => Now; } - private static (ApiTokenService Svc, TenantsDbContext Db, Clock Clock) Build() + private sealed class OneSetting(string key, string value) : ISettings + { + public long Version => 0; + + public ValueTask GetAsync(string k, string? tenantId, CancellationToken cancellationToken = default) + => ValueTask.FromResult(k == key ? new SettingValue(value, SettingSource.Platform) : default); + + public ValueTask> ListAsync(string? tenantId, string? category = null, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public ValueTask SetAsync(string k, string? v, SettingScope scope, string? tenantId, string actor, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + } + + private sealed record Harness(ApiTokenService Svc, TenantsDbContext Db, Clock Clock, IAuditLog Audit); + + private static Harness Build(ISettings? settings = null) { var db = new TenantsDbContext(new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options); var clock = new Clock(new DateTimeOffset(2026, 10, 18, 0, 0, 0, TimeSpan.Zero)); - return (new ApiTokenService(db, Substitute.For(), clock), db, clock); + var audit = Substitute.For(); + return new Harness(new ApiTokenService(db, audit, clock, settings, throttle: new ApiTokenAuditThrottle()), db, clock, audit); } + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static ApiTokenRequest Request(string name = "ci-deploy", string kind = ApiTokenKind.Service, string scope = ApiTokenScopes.Run, + int days = 30, ApiTokenActor? actor = null, string tenant = "acme") + => new(tenant, name, kind, [scope], days, actor ?? Admin); + + // ── format + hashing ──────────────────────────────────────────────────────────────────────────────────────────── + [Fact] public void Format_NewToken_HasSchemePrefixAndSecret() { @@ -38,7 +71,6 @@ public void Format_NewToken_HasSchemePrefixAndSecret() token.ShouldStartWith("aos_" + prefix + "_"); prefix.Length.ShouldBe(10); ApiTokenFormat.PrefixOf(token).ShouldBe(prefix); - ApiTokenFormat.Hash(token).Length.ShouldBe(64); ApiTokenFormat.New().Token.ShouldNotBe(token); } @@ -50,58 +82,336 @@ public void Format_NewToken_HasSchemePrefixAndSecret() [InlineData("aos_abcdefghij-secret")] public void Format_Malformed_HasNoPrefix(string? token) => ApiTokenFormat.PrefixOf(token).ShouldBeNull(); + [Fact] + public void Hash_IsSaltedHmac_AndLegacyIsPlainSha256() + { + var (token, _) = ApiTokenFormat.New(); + var saltA = ApiTokenFormat.NewSalt(); + var saltB = ApiTokenFormat.NewSalt(); + + saltA.ShouldNotBe(saltB); + ApiTokenFormat.Hash(token, saltA).Length.ShouldBe(64); + ApiTokenFormat.Hash(token, saltA).ShouldNotBe(ApiTokenFormat.Hash(token, saltB)); // same token, different rows + ApiTokenFormat.Hash(token, saltA).ShouldBe(Convert.ToHexStringLower( + HMACSHA256.HashData(Convert.FromHexString(saltA), Encoding.UTF8.GetBytes(token)))); + ApiTokenFormat.Hash(token, string.Empty).ShouldBe(Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)))); + ApiTokenFormat.HashEquals(ApiTokenFormat.Hash(token, saltA), ApiTokenFormat.Hash(token, saltA)).ShouldBeTrue(); + ApiTokenFormat.HashEquals(ApiTokenFormat.Hash(token, saltA), ApiTokenFormat.Hash(token, saltB)).ShouldBeFalse(); + } + + // ── scopes ────────────────────────────────────────────────────────────────────────────────────────────────────── + + [Theory] + [InlineData("read", "read")] + [InlineData("run", "read run")] + [InlineData("admin", "read run admin")] + [InlineData(" RUN ", "read run")] + public void Scopes_AreClosedUpwards(string requested, string expected) + => ApiTokenScopes.Format(ApiTokenScopes.Normalize([requested])).ShouldBe(expected); + + [Fact] + public void Scopes_RejectUnknownAndEmpty() + { + Should.Throw(() => ApiTokenScopes.Normalize(["write"])); + Should.Throw(() => ApiTokenScopes.Normalize([])); + Should.Throw(() => ApiTokenScopes.Normalize(["platform-admin"])); + } + + [Fact] + public void Scopes_MapToRole_AndLegacyRoles() + { + ApiTokenScopes.RoleFor(ApiTokenScopes.Normalize(["run"])).ShouldBe("member"); + ApiTokenScopes.RoleFor(ApiTokenScopes.Normalize(["admin"])).ShouldBe("admin"); + ApiTokenScopes.FromLegacyRole("member").ShouldBe("read run"); + ApiTokenScopes.FromLegacyRole("admin").ShouldBe("read run admin"); + ApiTokenScopes.Allows("read run", "run").ShouldBeTrue(); + ApiTokenScopes.Allows("read", "run").ShouldBeFalse(); + ApiTokenScopes.Allows(null, "read").ShouldBeFalse(); + } + + [Theory] + [InlineData("GET", "read")] + [InlineData("HEAD", "read")] + [InlineData("OPTIONS", "read")] + [InlineData("POST", "run")] + [InlineData("PUT", "run")] + [InlineData("PATCH", "run")] + [InlineData("DELETE", "run")] + public void ScopeMiddleware_MapsMethodToScope(string method, string scope) + => ApiTokenScopeMiddleware.RequiredScope(method).ShouldBe(scope); + + // ── lifecycle ─────────────────────────────────────────────────────────────────────────────────────────────────── + [Fact] public async Task Lifecycle_Create_Validate_Revoke() { - var (svc, db, _) = Build(); - var (info, token) = await svc.CreateAsync("acme", "ci-deploy", "member", 30, "alice", TestContext.Current.CancellationToken); + var h = Build(); + var (info, token) = await h.Svc.CreateAsync(Request(), Ct); - (await db.ApiTokens.SingleAsync(TestContext.Current.CancellationToken)).TokenHash.ShouldBe(ApiTokenFormat.Hash(token)); - (await db.ApiTokens.SingleAsync(TestContext.Current.CancellationToken)).TokenHash.ShouldNotContain(token); // never stored in clear + var row = await h.Db.ApiTokens.SingleAsync(Ct); + row.Salt.Length.ShouldBe(32); + row.TokenHash.ShouldBe(ApiTokenFormat.Hash(token, row.Salt)); + row.TokenHash.ShouldNotContain(token); // never stored in clear + row.Scopes.ShouldBe("read run"); + row.Role.ShouldBe("member"); - var identity = await svc.ValidateAsync(token, TestContext.Current.CancellationToken); - identity.ShouldBe(new ApiTokenIdentity(info.Id, "acme", "ci-deploy", "member")); + var identity = await h.Svc.ValidateAsync(token, null, Ct); + identity.ShouldNotBeNull(); + identity.Id.ShouldBe(info.Id); + identity.TenantId.ShouldBe("acme"); + identity.Kind.ShouldBe(ApiTokenKind.Service); + identity.Scopes.ShouldBe(["read", "run"]); + identity.Role.ShouldBe("member"); - (await svc.RevokeAsync("other", info.Id, "mallory", TestContext.Current.CancellationToken)).ShouldBeFalse(); // another tenant can't - (await svc.RevokeAsync("acme", info.Id, "alice", TestContext.Current.CancellationToken)).ShouldBeTrue(); - (await svc.ValidateAsync(token, TestContext.Current.CancellationToken)).ShouldBeNull(); + (await h.Svc.RevokeAsync("other", info.Id, Admin with { Name = "mallory" }, Ct)).ShouldBeFalse(); // another tenant can't + (await h.Svc.RevokeAsync("acme", info.Id, Admin, Ct)).ShouldBeTrue(); + (await h.Svc.RevokeAsync("acme", info.Id, Admin, Ct)).ShouldBeFalse(); // already revoked + (await h.Svc.ValidateAsync(token, null, Ct)).ShouldBeNull(); } [Fact] public async Task Validate_RefusesWrongSecret_AndExpired_AndRecordsLastUse() { - var (svc, db, clock) = Build(); - var (_, token) = await svc.CreateAsync("acme", "script", "admin", 1, "alice", TestContext.Current.CancellationToken); + var h = Build(); + var (_, token) = await h.Svc.CreateAsync(Request(scope: ApiTokenScopes.Admin, days: 1), Ct); var forged = token[..(token.LastIndexOf('_') + 1)] + "forged-secret-forged-secret-forged-secret"; - (await svc.ValidateAsync(forged, TestContext.Current.CancellationToken)).ShouldBeNull(); - (await svc.ValidateAsync(token, TestContext.Current.CancellationToken)).ShouldNotBeNull(); - (await db.ApiTokens.SingleAsync(TestContext.Current.CancellationToken)).LastUsedAtUtc.ShouldBe(clock.Now); + (await h.Svc.ValidateAsync(forged, null, Ct)).ShouldBeNull(); + (await h.Svc.ValidateAsync(token, null, Ct)).ShouldNotBeNull(); + (await h.Db.ApiTokens.SingleAsync(Ct)).LastUsedAtUtc.ShouldBe(h.Clock.Now); + + h.Clock.Now = h.Clock.Now.AddDays(2); + (await h.Svc.ValidateAsync(token, null, Ct)).ShouldBeNull(); + } + + [Fact] + public async Task Validate_LegacyUnsaltedRow_StillWorks_WithScopesFromRole() + { + var h = Build(); + var (token, prefix) = ApiTokenFormat.New(); + h.Db.ApiTokens.Add(new ApiTokenEntity + { + Id = Guid.NewGuid(), TenantId = "acme", Name = "old", Prefix = prefix, Salt = string.Empty, + TokenHash = ApiTokenFormat.Hash(token, string.Empty), Role = "admin", Scopes = string.Empty, Kind = ApiTokenKind.Service, + CreatedBy = "alice", CreatedAtUtc = h.Clock.Now, ExpiresAtUtc = h.Clock.Now.AddDays(10), + }); + await h.Db.SaveChangesAsync(Ct); + + var identity = await h.Svc.ValidateAsync(token, null, Ct); + identity.ShouldNotBeNull(); + identity.Scopes.ShouldBe(["read", "run", "admin"]); + identity.Role.ShouldBe("admin"); + } + + [Theory] + [InlineData(0)] + [InlineData(367)] + public async Task Create_RefusesExpiryOutsideTheDefaultCap(int days) + { + var h = Build(); + await Should.ThrowAsync(() => h.Svc.CreateAsync(Request(days: days), Ct)); + } - clock.Now = clock.Now.AddDays(2); - (await svc.ValidateAsync(token, TestContext.Current.CancellationToken)).ShouldBeNull(); + [Fact] + public async Task Create_HonoursTheMaxLifetimeSetting() + { + var h = Build(new OneSetting(ApiTokenFormat.MaxLifetimeKey, "30")); + + (await h.Svc.MaxLifetimeDaysAsync("acme", Ct)).ShouldBe(30); + var ex = await Should.ThrowAsync(() => h.Svc.CreateAsync(Request(days: 31), Ct)); + ex.Message.ShouldContain("30"); + (await h.Svc.CreateAsync(Request(days: 30), Ct)).Info.ExpiresAtUtc.ShouldBe(h.Clock.Now.AddDays(30)); + } + + [Fact] + public void MaxLifetime_IsAPlatformSetting() + { + var descriptor = new AgentOs.Modules.Tenants.Settings.TenantsSettings(openSignupDefault: false).Describe() + .Single(d => d.Key == ApiTokenFormat.MaxLifetimeKey); + descriptor.Scope.ShouldBe(SettingScope.Platform); + descriptor.Kind.ShouldBe(SettingKind.WholeNumber); + descriptor.DefaultValue.ShouldBe("366"); + descriptor.Min.ShouldBe(1); } [Theory] - [InlineData("platform-admin", 30)] - [InlineData("member", 0)] - [InlineData("member", 400)] - public async Task Create_RefusesPlatformRoles_AndBadExpiry(string role, int days) + [InlineData("")] + [InlineData(" ")] + public async Task Create_RefusesBlankName(string name) { - var (svc, _, _) = Build(); - await Should.ThrowAsync(() => svc.CreateAsync("acme", "x", role, days, "alice", TestContext.Current.CancellationToken)); + var h = Build(); + await Should.ThrowAsync(() => h.Svc.CreateAsync(Request(name: name), Ct)); + } + + [Fact] + public async Task Create_MemberCannotCreateServiceAccountsOrAdminScope() + { + var h = Build(); + await Should.ThrowAsync(() => h.Svc.CreateAsync(Request(actor: Member), Ct)); + await Should.ThrowAsync(() => + h.Svc.CreateAsync(Request(kind: ApiTokenKind.Personal, scope: ApiTokenScopes.Admin, actor: Member), Ct)); + await Should.ThrowAsync(() => h.Svc.CreateAsync(Request(kind: "robot"), Ct)); + + var (info, _) = await h.Svc.CreateAsync(Request(kind: ApiTokenKind.Personal, scope: ApiTokenScopes.Run, actor: Member), Ct); + info.Kind.ShouldBe(ApiTokenKind.Personal); + info.OwnerUserId.ShouldBe("user-bob"); + } + + [Fact] + public async Task Create_PersonalTokenNeedsAUser() + { + var h = Build(); + await Should.ThrowAsync(() => + h.Svc.CreateAsync(Request(kind: ApiTokenKind.Personal, actor: new ApiTokenActor("ghost", null, true)), Ct)); + } + + [Fact] + public async Task List_AdminSeesTheTenant_MemberSeesOwnPersonalTokens_NewestFirst() + { + var h = Build(); + await h.Svc.CreateAsync(Request(name: "ci"), Ct); + h.Clock.Now = h.Clock.Now.AddMinutes(1); + await h.Svc.CreateAsync(Request(name: "bob-script", kind: ApiTokenKind.Personal, scope: ApiTokenScopes.Read, actor: Member), Ct); + h.Clock.Now = h.Clock.Now.AddMinutes(1); + await h.Svc.CreateAsync(Request(name: "alice-pat", kind: ApiTokenKind.Personal), Ct); + await h.Svc.CreateAsync(Request(name: "theirs", tenant: "other"), Ct); + + (await h.Svc.ListAsync("acme", Admin, Ct)).Select(t => t.Name).ShouldBe(["alice-pat", "bob-script", "ci"]); + (await h.Svc.ListAsync("acme", Member, Ct)).Select(t => t.Name).ShouldBe(["bob-script"]); + (await h.Svc.ListAsync("acme", new ApiTokenActor("anon", null, false), Ct)).ShouldBeEmpty(); + } + + [Fact] + public async Task Revoke_MemberMayRevokeOnlyOwnTokens() + { + var h = Build(); + var (service, _) = await h.Svc.CreateAsync(Request(name: "ci"), Ct); + var (alices, _) = await h.Svc.CreateAsync(Request(name: "alice-pat", kind: ApiTokenKind.Personal), Ct); + var (bobs, _) = await h.Svc.CreateAsync(Request(name: "bob-pat", kind: ApiTokenKind.Personal, actor: Member), Ct); + + (await h.Svc.RevokeAsync("acme", service.Id, Member, Ct)).ShouldBeFalse(); + (await h.Svc.RevokeAsync("acme", alices.Id, Member, Ct)).ShouldBeFalse(); + (await h.Svc.RevokeAsync("acme", bobs.Id, Member, Ct)).ShouldBeTrue(); + (await h.Svc.RevokeAsync("acme", alices.Id, Admin, Ct)).ShouldBeTrue(); // an admin may revoke anyone's + } + + [Fact] + public async Task RevokeForOwner_RevokesOnlyThatMembersPersonalTokens() + { + var h = Build(); + var (_, bobToken) = await h.Svc.CreateAsync(Request(name: "bob-1", kind: ApiTokenKind.Personal, actor: Member), Ct); + await h.Svc.CreateAsync(Request(name: "bob-2", kind: ApiTokenKind.Personal, actor: Member), Ct); + var (_, ciToken) = await h.Svc.CreateAsync(Request(name: "ci"), Ct); + var (_, aliceToken) = await h.Svc.CreateAsync(Request(name: "alice-pat", kind: ApiTokenKind.Personal), Ct); + + (await h.Svc.RevokeForOwnerAsync("acme", "user-bob", "alice", Ct)).ShouldBe(2); + (await h.Svc.RevokeForOwnerAsync("acme", "user-bob", "alice", Ct)).ShouldBe(0); + + (await h.Svc.ValidateAsync(bobToken, null, Ct)).ShouldBeNull(); + (await h.Svc.ValidateAsync(ciToken, null, Ct)).ShouldNotBeNull(); + (await h.Svc.ValidateAsync(aliceToken, null, Ct)).ShouldNotBeNull(); + } + + // ── audit ─────────────────────────────────────────────────────────────────────────────────────────────────────── + + [Fact] + public async Task Audit_RecordsCreate_Use_Refusal_Revoke() + { + var h = Build(); + var (info, token) = await h.Svc.CreateAsync(Request(), Ct); + await h.Audit.Received(1).WriteAsync(Arg.Is(e => e.Action == AuditActions.ApiTokenCreated && e.TenantId == "acme" + && e.UserId == "alice" && e.Target!.Contains("service") && e.Target.Contains("read run")), Arg.Any()); + + await h.Svc.ValidateAsync(token, new ApiTokenUse("10.0.0.7", "curl/8"), Ct); + await h.Audit.Received(1).WriteAsync(Arg.Is(e => e.Action == AuditActions.ApiTokenUsed + && e.IpAddress == "10.0.0.7" && e.UserAgent == "curl/8"), Arg.Any()); + + // Within 5 minutes: no second use row; after: one more. + await h.Svc.ValidateAsync(token, null, Ct); + h.Clock.Now = h.Clock.Now.AddMinutes(6); + await h.Svc.ValidateAsync(token, null, Ct); + await h.Audit.Received(2).WriteAsync(Arg.Is(e => e.Action == AuditActions.ApiTokenUsed), Arg.Any()); + + await h.Svc.RevokeAsync("acme", info.Id, Admin, Ct); + await h.Audit.Received(1).WriteAsync(Arg.Is(e => e.Action == AuditActions.ApiTokenRevoked), Arg.Any()); + + // A revoked token presented in a loop leaves one refusal row per window, not one per request. + for (var i = 0; i < 5; i++) { (await h.Svc.ValidateAsync(token, null, Ct)).ShouldBeNull(); } + await h.Audit.Received(1).WriteAsync(Arg.Is(e => e.Action == AuditActions.ApiTokenRefused + && e.Target!.Contains("revoked")), Arg.Any()); + } + + [Fact] + public async Task Audit_UnknownPrefixWritesNothing() + { + var h = Build(); + (await h.Svc.ValidateAsync("aos_abcdefghij_" + new string('x', 43), null, Ct)).ShouldBeNull(); + await h.Audit.DidNotReceiveWithAnyArgs().WriteAsync(default!, default); + } + + [Fact] + public void Throttle_RecordsOncePerWindow() + { + var throttle = new ApiTokenAuditThrottle(); + var id = Guid.NewGuid(); + var t0 = DateTimeOffset.UnixEpoch; + throttle.ShouldRecord(id, t0, TimeSpan.FromMinutes(5)).ShouldBeTrue(); + throttle.ShouldRecord(id, t0.AddMinutes(4), TimeSpan.FromMinutes(5)).ShouldBeFalse(); + throttle.ShouldRecord(Guid.NewGuid(), t0, TimeSpan.FromMinutes(5)).ShouldBeTrue(); + throttle.ShouldRecord(id, t0.AddMinutes(5), TimeSpan.FromMinutes(5)).ShouldBeTrue(); + } + + // ── principal ─────────────────────────────────────────────────────────────────────────────────────────────────── + + [Fact] + public void Claims_PersonalTokenActsAsItsOwner() + { + var id = Guid.NewGuid(); + var claims = ApiTokenAuthentication.ClaimsFor(new ApiTokenIdentity(id, "acme", "laptop", ApiTokenKind.Personal, + ["read", "run"], "user-bob", "bob", DateTimeOffset.MaxValue)); + + claims.Single(c => c.Type == ClaimNames.Subject).Value.ShouldBe("user-bob"); + claims.Single(c => c.Type == ClaimNames.Tenant).Value.ShouldBe("acme"); + claims.Single(c => c.Type == "preferred_username").Value.ShouldBe("bob"); + claims.Single(c => c.Type == System.Security.Claims.ClaimTypes.Role).Value.ShouldBe("member"); + claims.Single(c => c.Type == ApiTokenScopes.ClaimType).Value.ShouldBe("read run"); + claims.Single(c => c.Type == ApiTokenAuthentication.TokenIdClaim).Value.ShouldBe(id.ToString()); + } + + [Fact] + public void Claims_ServiceAccountIsItsOwnPrincipal_AndNeverPlatformAdmin() + { + var id = Guid.NewGuid(); + var claims = ApiTokenAuthentication.ClaimsFor(new ApiTokenIdentity(id, "acme", "ci", ApiTokenKind.Service, + ["read", "run", "admin"], null, "alice", DateTimeOffset.MaxValue)); + + claims.Single(c => c.Type == ClaimNames.Subject).Value.ShouldBe($"apitoken:{id}"); + claims.Single(c => c.Type == "preferred_username").Value.ShouldBe("service:ci"); + claims.Where(c => c.Type == System.Security.Claims.ClaimTypes.Role).Select(c => c.Value).ShouldBe(["admin"]); } + // GAP-02 limiter: a token principal lands in the same buckets a Keycloak JWT for the same caller would — its tenant, + // and (personal token) its owner's user bucket, so a token can't buy a second allowance; a service account is its + // own user. [Fact] - public async Task List_IsPerTenant_NewestFirst_WithoutSecrets() + public void RateLimitKeys_TokenPrincipals_PartitionLikeJwtCallers() { - var (svc, _, clock) = Build(); - await svc.CreateAsync("acme", "first", "member", 30, "alice", TestContext.Current.CancellationToken); - clock.Now = clock.Now.AddMinutes(1); - await svc.CreateAsync("acme", "second", "member", 30, "alice", TestContext.Current.CancellationToken); - await svc.CreateAsync("other", "theirs", "member", 30, "bob", TestContext.Current.CancellationToken); + var limits = new AgentOs.ServiceDefaults.RequestRateLimits(Tenant: 600, User: 240, Anonymous: 120); + static DefaultHttpContext As(System.Collections.Generic.IEnumerable claims, string scheme) + => new() { User = new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity(claims, scheme)) }; + var jwt = As([new(ClaimNames.Tenant, "acme"), new(ClaimNames.Subject, "user-bob")], "Bearer"); + var id = Guid.NewGuid(); + var personal = As(ApiTokenAuthentication.ClaimsFor(new ApiTokenIdentity(id, "acme", "laptop", ApiTokenKind.Personal, + ["read"], "user-bob", "bob", DateTimeOffset.MaxValue)), ApiTokenAuthentication.Scheme); + var service = As(ApiTokenAuthentication.ClaimsFor(new ApiTokenIdentity(id, "acme", "ci", ApiTokenKind.Service, + ["read", "run"], null, "alice", DateTimeOffset.MaxValue)), ApiTokenAuthentication.Scheme); - (await svc.ListAsync("acme", TestContext.Current.CancellationToken)).Select(t => t.Name).ShouldBe(["second", "first"]); + AgentOs.ServiceDefaults.RequestRateLimitPolicy.TenantKey(personal, limits) + .ShouldBe(AgentOs.ServiceDefaults.RequestRateLimitPolicy.TenantKey(jwt, limits)); + AgentOs.ServiceDefaults.RequestRateLimitPolicy.UserKey(personal, limits) + .ShouldBe(AgentOs.ServiceDefaults.RequestRateLimitPolicy.UserKey(jwt, limits)); + AgentOs.ServiceDefaults.RequestRateLimitPolicy.TenantKey(service, limits).ShouldBe("t|600|acme"); + AgentOs.ServiceDefaults.RequestRateLimitPolicy.UserKey(service, limits).ShouldBe($"u|240|acme|apitoken:{id}"); } [Fact] @@ -114,5 +424,6 @@ public void ForwardSelector_RoutesOnlyApiTokens() var withJwt = new DefaultHttpContext(); withJwt.Request.Headers.Authorization = "Bearer eyJhbGciOiJSUzI1NiJ9.a.b"; ApiTokenAuthentication.ForwardSelector(withJwt).ShouldBeNull(); + ApiTokenAuthentication.ForwardSelector(new DefaultHttpContext()).ShouldBeNull(); } } diff --git a/tests/AgentOs.Tests/Tenants/MemberRemovalTests.cs b/tests/AgentOs.Tests/Tenants/MemberRemovalTests.cs index 044e82ed..47237146 100644 --- a/tests/AgentOs.Tests/Tenants/MemberRemovalTests.cs +++ b/tests/AgentOs.Tests/Tenants/MemberRemovalTests.cs @@ -209,6 +209,41 @@ private static ITenantContext Admin(string tenant) return ctx; } + // E1.3: a personal API token acts as its owner, so it is revoked with the computers — before the account is deleted. + [Fact] + public async Task RemoveAsync_RevokesPersonalApiTokens_BeforeTheDelete_AndAuditsTheCount() + { + var tokens = Substitute.For(); + tokens.RevokeForOwnerAsync("t1", "leaver", "admin", Arg.Any()).Returns(_ => + { + _steps.Add("tokens"); + return Task.FromResult(2); + }); + + var result = await MemberRemoval.RemoveAsync("t1", "leaver", new MemberRemovalActor("admin"), + _kc, _log, new OrderedDirectory(_steps), new Disconnector(), tokens, ct: TestContext.Current.CancellationToken); + + result.Removed.ShouldBeTrue(); + _steps.ShouldBe(["revoke", "tokens", "delete", "revoke"]); + _audit.ShouldHaveSingleItem().Target.ShouldBe("user=leaver,apiTokensRevoked=2"); + } + + [Fact] + public async Task RemoveAsync_TokenRevokeFails_RemovesNothing() + { + var tokens = Substitute.For(); + tokens.RevokeForOwnerAsync("t1", "leaver", Arg.Any(), Arg.Any()) + .ThrowsAsync(new InvalidOperationException("database unavailable")); + + var result = await MemberRemoval.RemoveAsync("t1", "leaver", new MemberRemovalActor("admin"), + _kc, _log, new OrderedDirectory(_steps), new Disconnector(), tokens, ct: TestContext.Current.CancellationToken); + + result.Outcome.ShouldBe(MemberRemovalOutcome.TokensNotRevoked); + result.Error.ShouldNotBeNull().ShouldContain("API tokens"); + await _kc.DidNotReceiveWithAnyArgs().DeleteUserAsync(default!, default); + _audit.ShouldBeEmpty(); + } + // Revokes the member's runners, recording each sweep in the shared step list; can fail on a given sweep (1-based). private sealed class OrderedDirectory(List steps) : IRunnerDirectory { diff --git a/tests/AgentOs.Tests/Tenants/OpenSignupAndAzureEndpointTests.cs b/tests/AgentOs.Tests/Tenants/OpenSignupAndAzureEndpointTests.cs index 03bfebe0..30665bf2 100644 --- a/tests/AgentOs.Tests/Tenants/OpenSignupAndAzureEndpointTests.cs +++ b/tests/AgentOs.Tests/Tenants/OpenSignupAndAzureEndpointTests.cs @@ -48,7 +48,7 @@ public sealed class OpenSignupAndAzureEndpointTests [InlineData(false, "false")] public void TenantsSettings_DefaultIsOnInDevelopmentOnly(bool development, string expected) { - var d = new TenantsSettings(development).Describe().ShouldHaveSingleItem(); + var d = new TenantsSettings(development).Describe().Single(s => s.Key == TenantsSettings.OpenSignupKey); d.Key.ShouldBe(TenantsSettings.OpenSignupKey); d.DefaultValue.ShouldBe(expected); d.Scope.ShouldBe(SettingScope.Platform); // a tenant admin can't open signup for the platform diff --git a/tools/agentos-vscode/README.md b/tools/agentos-vscode/README.md index 019a08ea..17a36d0d 100644 --- a/tools/agentos-vscode/README.md +++ b/tools/agentos-vscode/README.md @@ -10,9 +10,22 @@ Pair this machine to an AgentOS.NET server and run AI coding sessions locally The extension downloads the AgentOS.NET runner binary from your server and runs it for you — nothing to install by hand, no env vars, no token copy-paste. +## API token + +Call the AgentOS.NET Api with a personal API token (create one in the desktop: **Settings → API tokens**; the `run` +scope lets you start runs): + +1. **AgentOS.NET: Set API token** — paste the `aos_…` token. It is checked against `/v1/tenants/me` and kept + in VS Code secret storage (never in `settings.json`). +2. **AgentOS.NET: Run the pipeline on a user story** — sends the selection (or what you type) to `POST /v1/pipeline`; + the result lands in the output panel. +3. **AgentOS.NET: Check API token** shows the workspace and scopes; **Clear API token** removes it from this machine + (revoke it in the desktop too). + ## Settings - `agentos.serverUrl` — AgentOS.NET server base URL (default `https://localhost:5180`). +- `agentos.apiUrl` — AgentOS.NET Api base URL for API-token calls (default `https://localhost:5080`). - `agentos.cliAgent` — the CLI agent the runner invokes: `claude` (default) or `codex`. Uses your own subscription, not metered API; the server can override it per session. - `agentos.runOnMyMachine` — run sessions autonomously with that CLI (appends `claude --dangerously-skip-permissions` / `codex --full-auto`; the CLI must be installed and logged in). Off by default. diff --git a/tools/agentos-vscode/package.json b/tools/agentos-vscode/package.json index e903c039..d4862ede 100644 --- a/tools/agentos-vscode/package.json +++ b/tools/agentos-vscode/package.json @@ -14,7 +14,11 @@ "commands": [ { "command": "agentos.connect", "title": "AgentOS.NET: Connect this machine" }, { "command": "agentos.disconnect", "title": "AgentOS.NET: Disconnect" }, - { "command": "agentos.showLogs", "title": "AgentOS.NET: Show runner logs" } + { "command": "agentos.showLogs", "title": "AgentOS.NET: Show runner logs" }, + { "command": "agentos.setApiToken", "title": "AgentOS.NET: Set API token" }, + { "command": "agentos.checkApiToken", "title": "AgentOS.NET: Check API token" }, + { "command": "agentos.clearApiToken", "title": "AgentOS.NET: Clear API token" }, + { "command": "agentos.runPipeline", "title": "AgentOS.NET: Run the pipeline on a user story" } ], "configuration": { "title": "AgentOS.NET", @@ -24,6 +28,11 @@ "default": "https://localhost:5180", "description": "AgentOS.NET server base URL (the Web host)." }, + "agentos.apiUrl": { + "type": "string", + "default": "https://localhost:5080", + "description": "AgentOS.NET Api base URL, called with your API token (Set API token) on its /v1 routes." + }, "agentos.runOnMyMachine": { "type": "boolean", "default": false, diff --git a/tools/agentos-vscode/src/extension.ts b/tools/agentos-vscode/src/extension.ts index eec8d0d0..c21d71c7 100644 --- a/tools/agentos-vscode/src/extension.ts +++ b/tools/agentos-vscode/src/extension.ts @@ -6,6 +6,10 @@ // Pairing: Connect -> open /pair/vscode in the browser -> the member approves -> the server // redirects to vscode://agentos.runner/paired?code=... -> we exchange the one-time code (token never // rides the URL) for {runnerId, token, hubUrl} -> store in SecretStorage -> download + spawn the runner. +// +// API token (E1.3): "Set API token" stores a personal API token (aos_..., created in Settings > API tokens) in +// SecretStorage — never in settings.json — and checks it against /v1/tenants/me. "Run the pipeline" then calls +// POST /v1/pipeline with it (the token needs the "run" scope). import * as vscode from 'vscode'; import * as https from 'node:https'; @@ -17,6 +21,8 @@ import { randomUUID } from 'node:crypto'; import { URL, URLSearchParams } from 'node:url'; const SECRET_KEY = 'agentos.runner.credentials'; +const API_TOKEN_KEY = 'agentos.apiToken'; +const API_TOKEN_PREFIX = 'aos_'; const CALLBACK = 'vscode://agentos.runner/paired'; interface Creds { @@ -41,6 +47,10 @@ export function activate(context: vscode.ExtensionContext): void { vscode.commands.registerCommand('agentos.connect', () => connect()), vscode.commands.registerCommand('agentos.disconnect', () => disconnect(context)), vscode.commands.registerCommand('agentos.showLogs', () => output.show()), + vscode.commands.registerCommand('agentos.setApiToken', () => setApiToken(context)), + vscode.commands.registerCommand('agentos.checkApiToken', () => checkApiToken(context)), + vscode.commands.registerCommand('agentos.clearApiToken', () => clearApiToken(context)), + vscode.commands.registerCommand('agentos.runPipeline', () => runPipeline(context)), vscode.window.registerUriHandler({ handleUri: (uri) => onUri(context, uri) }), ); @@ -61,6 +71,98 @@ function serverUrl(): string { return (cfg || 'https://localhost:5180').replace(/\/+$/, ''); } +function apiUrl(): string { + const cfg = vscode.workspace.getConfiguration('agentos').get('apiUrl'); + return (cfg || 'https://localhost:5080').replace(/\/+$/, ''); +} + +interface TenantMe { + tenantId: string; + userName?: string; + authMethod?: string; + scopes?: string[]; +} + +async function setApiToken(context: vscode.ExtensionContext): Promise { + const token = await vscode.window.showInputBox({ + title: 'AgentOS.NET API token', + prompt: 'Paste a personal API token (Settings > API tokens). It is kept in VS Code secret storage.', + password: true, + ignoreFocusOut: true, + validateInput: (v) => (v.trim().startsWith(API_TOKEN_PREFIX) ? undefined : `An API token starts with ${API_TOKEN_PREFIX}`), + }); + if (!token) { + return; + } + try { + const me = (await requestJson('GET', `${apiUrl()}/v1/tenants/me`, undefined, token.trim())) as TenantMe; + await context.secrets.store(API_TOKEN_KEY, token.trim()); + void vscode.window.showInformationMessage(`AgentOS.NET: token saved — ${describe(me)}.`); + } catch (e) { + void vscode.window.showErrorMessage(`AgentOS.NET: the Api refused this token — ${errMsg(e)}`); + } +} + +async function checkApiToken(context: vscode.ExtensionContext): Promise { + const token = await context.secrets.get(API_TOKEN_KEY); + if (!token) { + void vscode.window.showWarningMessage('AgentOS.NET: no API token — run "AgentOS.NET: Set API token".'); + return; + } + try { + const me = (await requestJson('GET', `${apiUrl()}/v1/tenants/me`, undefined, token)) as TenantMe; + void vscode.window.showInformationMessage(`AgentOS.NET: ${describe(me)}.`); + } catch (e) { + void vscode.window.showErrorMessage(`AgentOS.NET: token check failed (revoked or expired?) — ${errMsg(e)}`); + } +} + +async function clearApiToken(context: vscode.ExtensionContext): Promise { + await context.secrets.delete(API_TOKEN_KEY); + void vscode.window.showInformationMessage('AgentOS.NET: API token removed from this machine (revoke it in Settings > API tokens).'); +} + +async function runPipeline(context: vscode.ExtensionContext): Promise { + const token = await context.secrets.get(API_TOKEN_KEY); + if (!token) { + void vscode.window.showWarningMessage('AgentOS.NET: no API token — run "AgentOS.NET: Set API token".'); + return; + } + const editor = vscode.window.activeTextEditor; + const selected = editor && !editor.selection.isEmpty ? editor.document.getText(editor.selection) : ''; + const description = await vscode.window.showInputBox({ + title: 'AgentOS.NET: run the pipeline', + prompt: 'The user story to turn into requirements, code and tests', + value: selected, + ignoreFocusOut: true, + validateInput: (v) => (v.trim() ? undefined : 'Describe the user story'), + }); + if (!description) { + return; + } + await vscode.window.withProgress( + { location: vscode.ProgressLocation.Notification, title: 'AgentOS.NET: running the pipeline…' }, + async () => { + try { + const result = (await requestJson('POST', `${apiUrl()}/v1/pipeline`, { description: description.trim() }, token)) as { + status?: string; + iterations?: number; + }; + output.appendLine(JSON.stringify(result, null, 2)); + output.show(true); + void vscode.window.showInformationMessage(`AgentOS.NET: pipeline ${result.status ?? 'finished'} — details in the output panel.`); + } catch (e) { + void vscode.window.showErrorMessage(`AgentOS.NET: pipeline failed — ${errMsg(e)}`); + } + }, + ); +} + +function describe(me: TenantMe): string { + const scopes = me.scopes && me.scopes.length ? me.scopes.join(' ') : 'n/a'; + return `${me.userName ?? 'unknown'} in workspace ${me.tenantId} (scopes: ${scopes})`; +} + async function connect(): Promise { pendingState = randomUUID(); const url = `${serverUrl()}/pair/vscode?callback=${encodeURIComponent(CALLBACK)}&state=${pendingState}`; @@ -236,7 +338,7 @@ function isLocal(urlStr: string): boolean { } } -function requestJson(method: string, urlStr: string, body?: unknown): Promise { +function requestJson(method: string, urlStr: string, body?: unknown, bearer?: string): Promise { return new Promise((resolve, reject) => { const u = new URL(urlStr); const lib = u.protocol === 'https:' ? https : http; @@ -249,6 +351,7 @@ function requestJson(method: string, urlStr: string, body?: unknown): Promise {
NameTokenRoleCreatedExpiresLast usedStatus
NameTypeTokenScopeExpiresLast usedStatus
@t.Name
by @t.CreatedBy
@t.Name
by @t.CreatedBy · @t.CreatedAtUtc.ToLocalTime().ToString("yyyy-MM-dd")
@(t.Kind == ApiTokenKind.Service ? "Service account" : "Personal") aos_@(t.Prefix)_…@t.Role@t.CreatedAtUtc.ToLocalTime().ToString("yyyy-MM-dd")@ApiTokenScopes.Highest(t.Scopes) @t.ExpiresAtUtc.ToLocalTime().ToString("yyyy-MM-dd") @(t.LastUsedAtUtc?.ToLocalTime().ToString("yyyy-MM-dd HH:mm") ?? "never") @(active ? "active" : t.RevokedAtUtc is not null ? "revoked" : "expired") @if (t.RevokedAtUtc is null) { - Revoke + Revoke }