diff --git a/README.md b/README.md index ffca3dd..14cbec7 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ share one memory, and no one can read a scope they weren't granted. ## Tools -The server exposes eleven tools: `list_scopes`, `store`, `store_batch`, `search`, `recall`, `find_related`, +The server exposes 11 tools, plus 12 `admin_` tools that only admins see (see [Admins](#admins)): `list_scopes`, `store`, `store_batch`, `search`, `recall`, `find_related`, `list_recent`, `update`, `delete`, `stats` and `prune`. They match the original server, plus a `scope` argument on the write tools. Search is hybrid (BM25 full-text plus `gte-small` vector similarity, fused with RRF) with temporal decay. Delete and prune are soft; rows are purged after 30 days. @@ -27,7 +27,7 @@ deno run -A scripts/setup.ts --configure-claude (your OS user), grants it write access and issues a token. It saves `AGENT_MEMORY_URL`, `AGENT_MEMORY_TOKEN` and `AGENT_MEMORY_DB_URL` into `.env` (mode 0600; it refuses to write unless git ignores the file) and prints the token once. `--configure-claude` then runs `claude mcp add` for you. Re-running is safe: nothing is duplicated, and a live token in -`.env` is reused. +`.env` is reused. The member it creates becomes the first admin (see [Admins](#admins)). Flags: `--env-file ` (default `.env`), `--scope ` (default `default`), `--member `, `--email
` (optional; only links the member to a Supabase login), `--bot` (a bot member instead of a @@ -65,6 +65,10 @@ you pass `--remote` (the linked project, or `--remote=`). `function The schema `agent_memory` must **not** be listed under Settings, API, Exposed schemas. Access goes only through the Edge Function; `anon` and `authenticated` have no privileges on it. +Installing by hand, nothing makes you an admin. After creating your own member (see the +[Admin quick-start](#admin-quick-start)), make it the first admin: +`deno run -A scripts/admin.ts set-admin on`. + ### Temporal decay Search scores decay with age, as in the original. The half-life in days is the function secret @@ -100,6 +104,38 @@ deno run -A scripts/admin.ts issue-token alice laptop --expires 90d # shown on Other commands: `list-scopes`, `list-grants`, `list-tokens `, `revoke ` and `revoke-token `. Tokens look like `amm_…` and only their SHA-256 hash is stored. +### Admins + +Some members are admins. An admin can manage the team from Claude, not only from the shell. + +- **The first admin** comes from `scripts/setup.ts`: a human member it creates or reuses is made an admin (a `--bot` + member never is). For an existing install, run `deno run -A scripts/admin.ts set-admin on`. +- **Shell-only commands** (they are not available through Claude): `set-admin on|off`, + `reactivate ` and `admin-log [--since ] [--actor ] [--limit N]`. + `delete-scope`, `deactivate` and `list-members` are also shell commands, and admins can do them from Claude too. + Deactivating a member also drops their admin flag, so a reactivated member is not an admin until `set-admin` is run. + A scope can only be deleted once it holds no memories, live or soft-deleted. +- **From Claude**, admins can do the rest with the `admin_` tools: `admin_list_scopes`, `admin_create_scope`, + `admin_delete_scope`, `admin_list_members`, `admin_create_member`, `admin_deactivate_member`, `admin_list_grants`, + `admin_grant`, `admin_revoke`, `admin_issue_token`, `admin_list_tokens` and `admin_revoke_token`. +- **Connecting an onboarded member.** The admin issues a token with `admin_issue_token` (or `issue-token`) and gives it + to the member, who registers it with Claude Code: + + ```sh + claude mcp add --transport http shared-memory https://.supabase.co/functions/v1/agent-memory \ + --header "Authorization: Bearer " -s user + ``` + + or, with the URL and token in an env file (`AGENT_MEMORY_URL`, `AGENT_MEMORY_TOKEN`), + `deno run -A scripts/configure-claude.ts [--name shared-memory] [--scope user]`, as in the Quick start. +- **Handle issued tokens with care.** A token issued through `admin_issue_token` passes through the admin's Claude + transcript, so give it to the member privately (not in a shared channel), and revoke it if it leaks. Do not + auto-allow the `mcp____admin_*` tools in Claude Code permissions: admin tools run in sessions that also read + memories written by other members, so keep the per-call confirmation on. +- **Admin tools never act on another admin.** Changing an admin, or their grants or tokens, is done from the shell. + +Every admin action, from the shell or from Claude, is recorded in the admin log. The log never holds a token. + ### Undo, and erasing for good `delete` and `prune` are soft: a deleted memory stays restorable for 30 days, then the daily job purges it. A purge @@ -134,7 +170,8 @@ deno run -A scripts/backup.ts restore-backup backup-.json `backup` exports the whole install by default; `--scope` limits it to one scope (and the members it references). The file holds memory content: treat it as private. `restore-backup` loads only into an **empty** install (fresh migrations, no scopes, members or memories) and keeps ids. Access tokens are never exported, so after a restore, -issue new tokens with `issue-token`. +issue new tokens with `issue-token`. Admin flags and deactivation are kept, and backup files written before admin +support still restore (as non-admin, active members). The admin log is **not** exported, so it starts empty after a restore. ### Import from a local agent-memory-mcp store @@ -211,7 +248,8 @@ AGENT_MEMORY_TOKEN=amm_… \ ``` It runs every tool once through the real endpoint, then three concurrent searches, prints `PASS` or `FAIL` per tool and -exits non-zero on any failure. It deletes what it stored. +exits non-zero on any failure. It deletes what it stored. An admin token sees the 12 `admin_` tools as well; the smoke +test only checks that they are present, and does not exercise them. ## Development diff --git a/docs/superpowers/plans/2026-11-07-mcp-admin.md b/docs/superpowers/plans/2026-11-07-mcp-admin.md new file mode 100644 index 0000000..88f7868 --- /dev/null +++ b/docs/superpowers/plans/2026-11-07-mcp-admin.md @@ -0,0 +1,282 @@ +# Admin through the MCP — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or +> superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Admin members manage scopes, members, grants and tokens through the MCP. Shell-only steps remain only for +admins themselves. + +**Architecture:** The rules live once, in Postgres. One group of `postgres`-only functions (`adm_*`) does each admin +action and writes `admin_log`; the shell admin script calls these directly. A second group of member-executable +SECURITY DEFINER wrappers (`admin_*`) checks that the caller is an active admin, applies the "never another admin" and +self-protection rules, then calls the matching `adm_*`. The Edge Function resolves a token to `{ memberId, isAdmin }` +and registers the 12 `admin_` tools only for admins. + +**Tech Stack:** as the existing project: Postgres 17 migrations + pgTAP, Deno, `npm:postgres@3.4.5`, +`npm:@modelcontextprotocol/server@2.4.0`, `npm:zod@4.6.7`. + +**Spec:** [docs/superpowers/specs/2026-11-07-mcp-admin-design.md](../specs/2026-11-07-mcp-admin-design.md) + +## Global Constraints + +- **All schema changes are a NEW migration:** `supabase/migrations/20261107150000_admin.sql`. Existing migrations are + applied to the hosted project and must not change. `supabase db reset` from empty must build everything. +- Every function: `security definer`, `set search_path = ''`, fully qualified names. `revoke execute … from public`, + then grant exactly as each task says. +- `adm_*` functions are executable by `postgres` only. `admin_*` functions are executable by `agent_memory_member`. +- **A bot can never be an admin.** Enforce with a CHECK constraint `kind = 'human' or not is_admin`. +- **Admin tools never act on another admin.** Every `admin_*` that names a member other than the caller, or acts on a + token or grant belonging to one, raises `Member '' is an admin; manage admins from the shell`. +- **`admin_log` never stores a token value or hash**, and `agent_memory_member` has no privilege on it. +- No token expiry is offered through the MCP. +- Error messages raised by `adm_*` and `admin_*` are user-safe, and the TS layer returns them verbatim. Exact texts are + in Task 1's Interfaces. A non-admin calling an `admin_*` function gets `42501 Admin only`. +- Tool results use the existing shape `{ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }`; + failures add `isError: true`. + +## Review Focus + +1. **Names are matched exactly.** `Rik` vs `rik`, or a trailing space, must give `Member 'Rik' not found`, never act on a + different member. Test: Task 2, `member names match exactly`. +2. **Revoking another admin's token by its id.** Token ids are visible to admins only for themselves and non-admins. + Even a guessed id belonging to another admin must be refused. Test: Task 2, + `revoke_token refuses another admin's token`. +3. **A deactivated member's existing token stops working at once.** Expected: 401 on the next request. Tests: Task 1 + `deactivated tokens stop resolving` and Task 5 e2e. +4. **A scope holding only soft-deleted memories.** Expected: delete refused, with the count. Test: Task 1, + `delete_scope counts soft-deleted memories`. +5. **Issuing a token for a deactivated or unknown member.** Expected: an error, and no token row created. Test: + Task 2, `issue_token refuses deactivated and unknown members`. + +--- + +### Task 1: Schema, token resolution, and the `adm_*` core functions + +**Files:** +- Create: `supabase/migrations/20261107150000_admin.sql`, `supabase/tests/database/06_admin_core.test.sql` + +**Interfaces:** +- Produces (schema): + - `members.is_admin boolean not null default false`; + - `members.deactivated_at timestamptz`; + - constraint `members_bot_not_admin check (kind = 'human' or not is_admin)`; + - `agent_memory.admin_log (id bigint generated always as identity primary key, at timestamptz not null default now(), actor_member_id uuid null, actor_label text not null, action text not null, target text not null, details jsonb not null default '{}')`. +- Produces (postgres-only functions; every one appends one `admin_log` row on success): + - `resolve_token(p_hash text) returns uuid`, redefined with `create or replace`: as before, but also requires the member's `deactivated_at is null`. + - `resolve_member(p_hash text) returns table (member_id uuid, is_admin boolean)`: the same rules plus the flag. Empty when unresolved. + - `adm_create_scope(p_name text, p_description text, p_actor uuid, p_label text) returns uuid` + - `adm_delete_scope(p_name text, p_actor uuid, p_label text) returns void` + - `adm_create_member(p_name text, p_kind text, p_email text, p_actor uuid, p_label text) returns uuid`: links `auth_user_id` by case-insensitive email, as `createMember` does today. + - `adm_deactivate_member(p_name text, p_actor uuid, p_label text) returns void`: revokes all live tokens, deletes all grants, sets `deactivated_at`. + - `adm_reactivate_member(p_name text, p_actor uuid, p_label text) returns void`: clears `deactivated_at`; no grants or tokens restored. + - `adm_set_admin(p_name text, p_on boolean, p_actor uuid, p_label text) returns void` + - `adm_grant(p_member text, p_scope text, p_access text, p_actor uuid, p_label text) returns void`: upsert. + - `adm_revoke(p_member text, p_scope text, p_actor uuid, p_label text) returns boolean`: false if there was no grant. + - `adm_issue_token(p_member text, p_name text, p_hash text, p_expires timestamptz, p_actor uuid, p_label text) returns uuid`: the caller hashes the token; only the hash is stored, and the log gets the token id and name. + - `adm_revoke_token(p_id uuid, p_actor uuid, p_label text) returns void` +- Exact error texts (`raise exception '…'`, default SQLSTATE P0001): + - `Scope '%' not found`, `Member '%' not found`, `Token % not found` + - `Scope '%' already exists`, `Member '%' already exists` + - `Scope names are lowercase letters, digits and hyphens, starting with a letter or digit (max 63)` + - `Scope '%' still holds % memories; move, delete or erase them first`: counts live AND soft-deleted memories. + - `Member '%' is deactivated`: for grant and issue_token. + - `A bot can't be an admin` + - `Can't remove the last active admin` + - `Access must be read or write` + +- [ ] **Step 1: Write the failing pgTAP test** `06_admin_core.test.sql`, run as postgres: + - schema: the columns exist; inserting a bot with `is_admin = true` → `throws_ok` 23514. + - `deactivated tokens stop resolving`: create a member, issue a token (insert its hash via `adm_issue_token`), then: + - `resolve_token(hash)` = member; + - `adm_deactivate_member` → `resolve_token(hash)` is null, `resolve_member(hash)` returns 0 rows; + - the member's grants count is 0, and every one of their tokens has `revoked_at` set. + - `resolve_member` returns `is_admin` true after `adm_set_admin(name, true, …)`. + - `adm_set_admin` on a bot → `A bot can't be an admin`. + - With one active admin, `adm_set_admin(that, false, …)` → `Can't remove the last active admin`. With two, it succeeds. + - `delete_scope counts soft-deleted memories`: a scope with 1 live and 1 soft-deleted memory → + `Scope 'x' still holds 2 memories; move, delete or erase them first`. After erasing both, the delete succeeds and + the scope's grants are gone. + - Duplicate scope or member → the exact "already exists" texts. A bad scope name → the exact naming text. + - `adm_grant`/`adm_issue_token` on a deactivated member → `Member 'x' is deactivated`. + - `adm_reactivate_member` → `deactivated_at` is null, and the member still has 0 grants. + - Every successful call adds exactly one `admin_log` row with the right `action`. `issue_token` details hold no + `token_hash` and no `amm_`. + - As `agent_memory_member`: `select from agent_memory.admin_log` and `select agent_memory.adm_create_scope(…)` → + `throws_ok` 42501. +- [ ] **Step 2:** `supabase test db` → FAIL. +- [ ] **Step 3:** Write the migration (columns, constraint, table, functions, revokes). +- [ ] **Step 4:** `supabase db reset && supabase test db` → all files PASS (01–06). +- [ ] **Step 5:** Commit `feat(db): admin flag, deactivation, admin log and core admin functions`. + +### Task 2: Admin-only wrappers for members + +**Files:** +- Modify: `supabase/migrations/20261107150000_admin.sql` (append; still unpushed) +- Create: `supabase/tests/database/07_admin_wrappers.test.sql` + +**Interfaces:** +- Consumes: Task 1's `adm_*`. +- Produces (SECURITY DEFINER, executable by `agent_memory_member` only): + - Private helper `agent_memory.require_admin() returns uuid`: returns `current_member_id()` when that member is active + and `is_admin`, else raises `Admin only` with SQLSTATE `42501`. + - Every wrapper starts with `require_admin()` and passes `p_actor = caller`, `p_label = `. + - `admin_create_scope(p_name text, p_description text) returns uuid` + - `admin_delete_scope(p_name text) returns void` + - `admin_create_member(p_name text, p_kind text, p_email text) returns uuid` + - `admin_deactivate_member(p_name text) returns void`: refuses the caller (`You can't deactivate yourself`) and other admins. + - `admin_grant(p_member text, p_scope text, p_access text) returns void`: refuses other admins; the caller may grant themselves. + - `admin_revoke(p_member text, p_scope text) returns boolean`: same rule. + - `admin_issue_token(p_member text, p_name text, p_hash text) returns uuid`: no expiry; refuses other admins; the caller may issue their own. + - `admin_revoke_token(p_id uuid) returns void`: refuses if the token's owner is another admin. Refuses the caller's own last live token (`You can't revoke your last live token`). + - Listing (return tables; no hashes anywhere): + - `admin_list_scopes() returns table (name text, description text, memories int, deleted int, readers int, writers int)` + - `admin_list_members() returns table (name text, kind text, email text, is_admin boolean, deactivated boolean, live_tokens int)` + - `admin_list_grants(p_scope text, p_member text) returns table (scope text, member text, access text, granted_at timestamptz, granted_by text)`: nulls mean unfiltered. + - `admin_list_tokens(p_member text) returns table (id uuid, name text, created_at timestamptz, last_used_at timestamptz, revoked_at timestamptz)`: refuses another admin's tokens. + - There is no wrapper for `adm_set_admin` or `adm_reactivate_member`. + +- [ ] **Step 1: Write the failing pgTAP test** `07_admin_wrappers.test.sql`, acting as members via + `set_config('agent_memory.member_id', …, true); set local role agent_memory_member;`. Fixture: admins `a1`, `a2`, + non-admin human `h`, bot `b`, deactivated admin `ax`. + - As `h`, `b` and `ax`: each of the 12 wrappers → `throws_ok` 42501 `Admin only`. + - As `a1`: + - creating a scope and a member, granting, and `admin_issue_token(h, …)` all succeed, and the log rows have + `actor_member_id = a1`; + - `admin_deactivate_member('a2')`, `admin_grant('a2', …)`, `admin_issue_token('a2', …)` and `admin_list_tokens('a2')` + → `Member 'a2' is an admin; manage admins from the shell`; + - `revoke_token refuses another admin's token`: a2's token id → the same message; + - `admin_deactivate_member('a1')` → `You can't deactivate yourself`; + - with a1 holding one live token, `admin_revoke_token()` → `You can't revoke your last live token`; + with two, revoking one succeeds; + - `admin_issue_token('a1', …)` succeeds (own laptop). + - `issue_token refuses deactivated and unknown members`: `admin_issue_token('ghost', …)` → `Member 'ghost' not found`. + A deactivated non-admin → `Member 'x' is deactivated`. The `access_tokens` count is unchanged in both cases. + - `member names match exactly`: `admin_grant('H', …)` and `admin_grant('h ', …)` → `Member 'H' not found` and + `Member 'h ' not found`. + - No wrapper can change `is_admin`: `has_function_privilege('agent_memory_member', 'agent_memory.adm_set_admin(text,boolean,uuid,text)', 'execute')` is false. + - `admin_list_members` as a1 lists a2 with `is_admin` true. `admin_list_tokens('h')` columns contain no hash. +- [ ] **Step 2:** `supabase test db` → FAIL. +- [ ] **Step 3:** Append the wrappers to the migration. +- [ ] **Step 4:** `supabase db reset && supabase test db` → all PASS. +- [ ] **Step 5:** Commit `feat(db): admin-only wrappers that never act on another admin`. + +### Task 3: Shell admin script and setup on the core functions + +**Files:** +- Modify: `scripts/lib/admin-db.ts`, `scripts/admin.ts`, `scripts/setup.ts`, `README.md` +- Test: `tests/integration/admin.test.ts`, `tests/integration/setup.test.ts` + +**Interfaces:** +- Consumes: Task 1's `adm_*`, called as postgres with `p_actor = null` and `p_label = grantor()`. +- Produces in `admin-db.ts`: + - **Re-implemented** on `adm_*`, signatures unchanged: `createScope`, `createMember`, `grant`, `revoke`, + `issueToken`, `revokeToken`. `issueToken` keeps generating and hashing in TS and passes the hash. + - **New:** `deleteScope(sql, name): Promise`, `deactivateMember(sql, name): Promise`, + `reactivateMember(sql, name): Promise`, `setAdmin(sql, name, on: boolean): Promise`, + `adminLog(sql, f: { since?: Date; actor?: string; limit?: number }): Promise`, where + `AdminLogRow = { at, actor, action, target, details }` and `actor` is the display name or the label. + - **New** `listMembers(sql): Promise`, where + `MemberRow = { name, kind, email, is_admin, deactivated, live_tokens }`. `listScopes` is unchanged. +- `admin.ts` new commands: `delete-scope `, `deactivate `, `reactivate `, + `set-admin on|off`, `admin-log [--since ] [--actor ] [--limit N]` (default limit 50), + `list-members`. Existing commands and their output stay as they are. +- `setup.ts`: after creating or reusing the member, if it is human, `setAdmin(name, true)` (idempotent). Print + `[n/7] Member '' is an admin`. A bot member is never made admin; print + `Note: no admin yet - run admin.ts set-admin on`. + +- [ ] **Step 1: Write the failing tests:** + - `set-admin` round trip, refusing a bot, refusing the last admin; + - `deactivate` then the token no longer resolves; + - `reactivate`; + - `delete-scope` with memories → the exact count message; + - `admin-log` returns rows newest first, filtered by actor, and its text holds no `amm_`; + - existing admin tests still pass unchanged; + - setup: a fresh human member ends up `is_admin`; a `--bot` setup leaves `is_admin` false and prints the note. +- [ ] **Step 2:** `deno task test:int` → FAIL. +- [ ] **Step 3:** Implement. README: an "Admins" section covering making the first admin, the shell-only commands, + and that admins can do the rest from Claude (Task 4's tool names). +- [ ] **Step 4:** `deno task check && deno task test:unit && deno task test:int` → PASS. +- [ ] **Step 5:** Commit `feat(admin): shell admin script and setup on the shared admin functions`. + +### Task 4: Admin store and the 12 admin MCP tools + +**Files:** +- Create: `supabase/functions/_shared/admin-store.ts`, `supabase/functions/_shared/admin-tools.ts` +- Test: `tests/integration/admin-store.test.ts`, `tests/unit/admin-tools.test.ts` + +**Interfaces:** +- Consumes: Task 2's `admin_*` via `withMember` (db.ts); `generateToken`/`hashToken` (tokens.ts). +- Produces: + - `class PgAdminStore { constructor(sql: Sql, memberId: string) }` with methods: `listScopes()`, + `createScope(name, description?)`, `deleteScope(name)`, `listMembers()`, + `createMember(name, kind: 'human' | 'bot', email?)`, `deactivateMember(name)`, + `listGrants(f?: { scope?: string; member?: string })`, `grant(member, scope, access)`, `revoke(member, scope)`, + `issueToken(member, name): Promise<{ id: string; token: string }>`, `listTokens(member)`, `revokeToken(id)`. + - Error mapping: + - P0001 → `StoreError(message)` with the message unchanged; + - 42501 → `StoreError('Admin only')`; + - 22P02 (bad uuid) → `StoreError('Token not found')`; + - anything else → logged with code and message, then `StoreError('Database error')`. + - `registerAdminTools(server: McpServer, admin: PgAdminStore): void` registers exactly these 12 tools: + `admin_list_scopes`, `admin_create_scope`, `admin_delete_scope`, `admin_list_members`, `admin_create_member`, + `admin_deactivate_member`, `admin_list_grants`, `admin_grant`, `admin_revoke`, `admin_issue_token`, + `admin_list_tokens`, `admin_revoke_token`. + - zod inputs: `name`/`member`/`scope` are strings; `kind` is `enum(['human','bot'])` defaulting to `human`; + `access` is `enum(['read','write'])`; `email`, `description` and the list filters are optional; `id` is a string. + - Each description starts with `Admin:`. + - `admin_issue_token`'s description and result both say the token is shown once and is not stored. The result is + `{ member, name, id, token, note: 'Shown once - give it to the member privately; it is not stored and cannot be shown again.' }`. + - `admin_deactivate_member`'s description says it revokes all tokens and grants, and is undone only from the shell. + +- [ ] **Step 1: Write the failing tests:** + - **Integration, against the local stack:** an admin store onboards a member end to end, and the issued token + resolves via `resolveMember`. Each exact error text from Tasks 1–2 surfaces unchanged through the store. + A non-admin store → `Admin only` on every method. + - **Unit, with a fake store:** `registerAdminTools` registers exactly the 12 names, and each description starts with + `Admin:`. The `admin_issue_token` result has the `note`. A store error becomes `isError: true` with the message. +- [ ] **Step 2:** `deno task test:unit && deno task test:int` → FAIL. +- [ ] **Step 3:** Implement both modules. +- [ ] **Step 4:** Tests and `deno task check` → PASS. +- [ ] **Step 5:** Commit `feat(mcp): admin store and admin tools`. + +### Task 5: Edge Function — admin tools for admins only + +**Files:** +- Modify: `supabase/functions/_shared/db.ts`, `supabase/functions/agent-memory/index.ts` +- Test: `tests/e2e/function.test.ts` + +**Interfaces:** +- Produces: `resolveCaller(sql: Sql, token: string): Promise<{ memberId: string; isAdmin: boolean } | null>` in db.ts, + backed by `resolve_member`. `resolveMember` stays, as a wrapper returning `memberId`, for existing callers. +- `index.ts` registers `registerAdminTools(s, new PgAdminStore(sql, memberId))` only when `isAdmin`. The non-admin + tool list is byte-for-byte unchanged. + +- [ ] **Step 1: Write the failing e2e tests:** + - an admin token's `tools/list` has 11 + 12 = 23 tools; + - a non-admin's and a bot's have exactly the 11 original tools; + - a non-admin calling `admin_create_scope` by name gets the same error as calling an unknown tool name; + - an admin onboards `e2e-new-` end to end (create member, grant, issue token), and the new token's + `list_scopes` shows that grant; + - after `admin_deactivate_member`, the new token gets HTTP 401 on its next request; + - everything is cleaned up in `finally`. +- [ ] **Step 2:** `deno task test:e2e` (with `supabase functions serve agent-memory`) → FAIL. +- [ ] **Step 3:** Implement. +- [ ] **Step 4:** e2e, unit, int, `deno task check` and `supabase test db` → all PASS. +- [ ] **Step 5:** Commit `feat(function): admin tools for admin members`. + +### Task 6: Deploy and verify on the hosted project + +**Files:** none new (README already updated in Task 3). + +- [ ] **Step 1:** `supabase db push --remote` (only `20261107150000_admin.sql` should apply). Then + `supabase functions deploy agent-memory --use-api`. +- [ ] **Step 2:** `deno run --env-file=.env -A scripts/admin.ts set-admin treforsouthwell on`. +- [ ] **Step 3: Hosted check.** A Deno MCP client script in the scratchpad runs with the maintainer's token (from + `.env`), never printing tokens: + - `tools/list` has 23 tools; + - `admin_create_member('hosted-check')`, `admin_grant(… predbat-devs read)` and `admin_issue_token` succeed, and that + token sees only `predbat-devs`; + - `admin_deactivate_member('hosted-check')` → its token gets 401; + - with the bot's token (`.env.bot`), `tools/list` has 11 tools and no `admin_`; + - `admin-log --limit 5` shows the four actions by `treforsouthwell`. +- [ ] **Step 4:** Report the results. The `hosted-check` member stays deactivated, because names stay unique. diff --git a/docs/superpowers/specs/2026-11-07-mcp-admin-design.md b/docs/superpowers/specs/2026-11-07-mcp-admin-design.md new file mode 100644 index 0000000..3d0f22b --- /dev/null +++ b/docs/superpowers/specs/2026-11-07-mcp-admin-design.md @@ -0,0 +1,182 @@ +# Admin through the MCP — design + +Date: 2026-11-07 +Status: draft for approval (builder check done) +Builds on: [the hosted memory design](2026-11-07-supabase-agent-memory-design.md) + +## 1. Intent + +Today every admin task (creating scopes, members, grants and tokens) needs `scripts/admin.ts`. That means a machine with +Deno, the repo, and the database URL with its password. The maintainer wants admins to manage the memory from **any +Claude session**, such as a cloud session or another maintainer's laptop, using only their own MCP token. A shell is +needed once, to create the database. After that, onboarding a new maintainer (create member, grant, issue token) is +something an admin can ask Claude to do. + +## 2. Decisions (the maintainer's) + +- **Members can be admins.** An admin flag on the member, nothing finer: an admin manages the whole install. +- **The first admin comes from setup.** Creating the database is the one shell step. Its setup creates the first member and + makes it an admin. For an install that already exists, one shell command makes a member admin. +- **Admins get admin tools through the MCP:** + - create and delete scopes; + - create and delete members; + - grant and revoke access; + - **issue tokens**, which are shown once in the tool's reply, plus listing and revoking tokens. +- **No token expiry by default** for now. +- **Making someone an admin is not possible through the MCP** for now. Promoting or demoting admins stays a shell step. +- **Admin tools never act on another admin.** Through the MCP an admin cannot: + - deactivate another admin; + - issue, list or revoke another admin's tokens; + - grant or revoke another admin's access. + + Anything involving another admin is a shell step. An admin may act on themselves where it is safe: issue a token for + a new machine, list and revoke their own tokens, grant themselves a scope. They may act on any non-admin member. + This keeps one leaked admin token from shutting out the other admins or acting in their name. + +## 3. Decisions made in the conversation (proposed by Claude, accepted) + +- **Admin tools are only visible to admins.** A non-admin token, including the bot's, never sees them in `tools/list`. + The server also enforces admin rights in the database, so hiding the tools is not the only guard. +- **"Delete member" means deactivate.** The member's tokens are revoked and their grants removed. The member row stays, + so memories keep showing who wrote them. A deactivated member's tokens never authenticate again. +- **Deleting a scope that still holds memories is refused.** Live or soft-deleted, the memories must be gone first, by + moving, deleting or erasing them. Its grants go with the scope. +- **An admin cannot deactivate themselves or remove their own admin rights through the MCP.** With the rule above, no + MCP call can reduce the number of active admins. The last-admin protection therefore only applies to the shell + `set-admin … off`, which refuses to demote the last active admin. +- **Every admin action is recorded:** who did it, when, what, and on which target. Token values are never recorded. + +## 3a. Builder's calls (made by Claude while writing this up; the maintainer can overrule) + +- **A bot can never be an admin.** This is a database rule: a check that only `human` members have the admin flag. + `set-admin` refuses bots, and `setup.ts` makes its member admin only when it is a human. A `--bot` setup leaves the + install without an admin until `set-admin` is run on a human member. +- **What `admin_log` records:** every call to the new admin functions, from the MCP or the shell, plus `set-admin`. + `restore` and `erase` are not added, because `memory_history` already records them with the member who did it. The + log is read from the shell with `admin.ts admin-log [--since …] [--actor …]`. There is no MCP tool for it. +- **Deactivation can be undone, from the shell only.** `admin.ts reactivate ` clears the deactivation. It + restores no grants or tokens: those are granted and issued afresh. Display names stay unique, so a deactivated + member's name is not reused. +- **An admin cannot revoke their own last live token through the MCP**, so they can't cut themselves off by accident. + The shell can still do it. +- **Granting to, or issuing a token for, a deactivated member is refused.** + +## 4. Goals + +1. An admin can onboard a new member end to end through Claude, with no shell: create member, grant scopes, issue token. +2. An admin can offboard a member (deactivate) and tidy scopes through Claude. +3. A non-admin, including the bot, can do none of this, and cannot tell the admin tools exist. This must be proven by tests + against real Postgres, as the original RLS tests are. +4. Nothing that works today changes for non-admins. The existing 11 tools and their behaviour are unchanged. + +## 5. Non-goals + +- Promoting or demoting admins through the MCP. +- Per-scope admins, or any role between member and admin. +- A web UI. +- Admin access to memory content beyond what grants give. An admin can grant themselves a scope, and that grant is the + normal, recorded way to gain access. +- Restore, erase and backup through the MCP. They stay in the admin script. + +## 6. Anti-goals (a failure even if it "works") + +- **A non-admin performing any admin action**, through any path: a tool, a crafted request, or calling the database + functions directly as the member role. +- **Privilege escalation through the MCP**, e.g. an admin tool that can set the admin flag, or a crafted argument that + does. +- **Losing authorship.** Deleting a member must never delete or orphan their memories' `created_by`/`updated_by`. +- **Locking the install out.** No sequence of MCP admin calls may leave it with zero active admins. +- **Token hashes or other members' tokens readable through the MCP.** Listing tokens shows id, name and dates, never + values or hashes. +- **The bot gaining admin.** Any bot member: the database refuses the admin flag on bots. +- **One admin acting on or as another admin through the MCP.** No deactivating them, no tokens issued in their name, no + changing their grants. + +## 7. Constraints + +- **All schema changes are new migration files.** The existing migrations are already applied to the hosted project. + Applying all migrations to an empty database must still build the complete working database. +- **Admin checks are enforced in Postgres**, in SECURITY DEFINER functions that check the calling member's admin flag, + in the same style as `soft_delete`/`touch_accessed`. They must not rest on the Edge Function's tool registration alone. +- **The admin script keeps working** for everything it does today. It also gains the shell-only "make admin" step. +- **The CPU budget** (~1 s per request) applies. Admin calls do no embedding, so this is easy. +- Tool results follow the existing shape (`{ content: [{ type: 'text', text: JSON }] }`, `isError` on failure). Error + messages for non-admins never reveal that admin tools exist. + +## 8. Shape + +### 8.1 Data + +- `members.is_admin boolean not null default false` and `members.deactivated_at timestamptz` (null = active). +- A deactivated member's tokens fail `resolve_token`, even if a token row was somehow left unrevoked. +- `admin_log` table: id, `at`, actor member id, action (e.g. `create_scope`, `grant`, `issue_token`), target, and small + JSON details. Never token values. Not readable by the member role. + +### 8.2 The first admin + +- **`setup.ts`** marks the human member it creates as admin, and also an existing human member it reuses. Re-running + setup is how an install gets its first admin. +- **`admin.ts set-admin on|off`** is the shell-only promote/demote. It refuses bots, and refuses to demote the + last active admin. +- **`admin.ts reactivate `** and **`admin.ts admin-log`** are shell-only too (see §3a). +- **The existing install:** run `set-admin treforsouthwell on` once. + +### 8.3 MCP tools (admins only) + +Names are prefixed `admin_` so they group together and are easy to deny wholesale in a client config: + +| Tool | Does | +|------|------| +| `admin_list_scopes` | every scope, with description, memory counts, and member counts by access | +| `admin_create_scope` | name (same naming rule as today), optional description | +| `admin_delete_scope` | refused while the scope has any memory, live or soft-deleted; removes its grants | +| `admin_list_members` | display name, kind (human/bot), email if any, admin flag, active/deactivated, number of live tokens | +| `admin_create_member` | name, kind (human/bot), optional email (links a Supabase login as today) | +| `admin_deactivate_member` | revokes all tokens and removes all grants; refused for yourself and for the last active admin | +| `admin_list_grants` | optionally filtered by scope or member | +| `admin_grant` | member, scope, read/write (upsert, as today) | +| `admin_revoke` | member, scope | +| `admin_issue_token` | member, token name; returns the token **once**, with a note that it will not be shown again; no expiry | +| `admin_list_tokens` | for a member: id, name, created, last used, revoked; never values or hashes | +| `admin_revoke_token` | token id | + +Member and scope arguments are by name, as in the admin script. + +Every tool that names a member refuses when that member is an admin other than the caller, with a plain "is an +admin; manage admins from the shell" error. Every tool that names the caller refuses where §3 says so: deactivating +yourself, and revoking your last live token. + +### 8.4 Where the logic lives + +- The database exposes one SECURITY DEFINER function per action, executable by the member role. Each first checks that + the calling member (`current_member_id()`) is an active admin, raises a fixed error otherwise, does the work, and + writes `admin_log`. +- The admin script and the MCP tools both call these functions, so the rules exist once. For the admin script, the + actor is recorded as the OS user, as `granted_by` is today. The builder decides how to share them. +- The Edge Function looks up the member's admin flag when it resolves the token, and registers the admin tools only + for admins. + +## 9. Testing + +- **pgTAP, as each member kind** (admin, non-admin, bot, deactivated): + - every admin function refuses non-admins; + - nothing can set `is_admin` except the shell step, and never on a bot; + - every admin function refuses to act on another admin; + - last-admin, self-deactivation and last-own-token protections hold; + - a deactivated member's token stops resolving; + - deleting a non-empty scope is refused; + - `admin_log` is written and not readable by members; + - no token hash is readable. +- **Integration:** each admin tool against the local stack. +- **End to end over real MCP:** an admin token lists the admin tools and can onboard a member end to end, and the + issued token works. A non-admin token's `tools/list` has no `admin_` tools, and calling one by name fails like an + unknown tool. +- **Hosted:** after deploy, onboard and then deactivate a throwaway member through the MCP, and confirm the bot's token + still sees no admin tools. + +## 10. Left to the builder + +- Exact column, function and table names, and the migration layout. +- How the admin script and the MCP share the database functions. +- The exact wording of tool descriptions and errors, within §7. +- Whether `admin_list_scopes` replaces anything in the admin script's output, if that keeps the two consistent. diff --git a/scripts/admin.ts b/scripts/admin.ts index aad32d7..96d31fd 100644 --- a/scripts/admin.ts +++ b/scripts/admin.ts @@ -1,28 +1,40 @@ import { parseArgs } from 'jsr:@std/cli@1.0.9/parse-args'; import { connect } from '../supabase/functions/_shared/db.ts'; import { + adminLog, createMember, createScope, + deactivateMember, type DeletedFilter, type DeletedRow, + deleteScope, eraseMemory, grant, issueToken, listDeleted, listGrants, + listMembers, listScopes, listTokens, memorySummary, parseExpires, + reactivateMember, restoreMemories, revoke, revokeToken, + setAdmin, } from './lib/admin-db.ts'; const USAGE = `Usage: deno run -A scripts/admin.ts ... create-scope [--description ] list-scopes + delete-scope (refused while any memory, live or deleted, remains) create-member [--email
] | --bot (email optional; links a Supabase login) + list-members + deactivate (revokes tokens and grants, drops admin) + reactivate (not admin again until set-admin) + set-admin on|off + admin-log [--since ] [--actor ] [--limit N] (default limit 50) grant read|write revoke list-grants @@ -50,7 +62,7 @@ const DELETED_COLS: (keyof DeletedRow & string)[] = ['id', 'scope', 'deletedAt', /** Returns the process exit code. */ async function main(): Promise { const args = parseArgs(Deno.args, { - string: ['description', 'human', 'email', 'expires', 'scope', 'by', 'since'], + string: ['description', 'human', 'email', 'expires', 'scope', 'by', 'since', 'actor', 'limit'], boolean: ['bot', 'yes'], }); const [cmd, ...p] = args._.map(String); @@ -79,6 +91,60 @@ async function main(): Promise { case 'list-scopes': console.log(table(await listScopes(sql), ['name', 'description'])); break; + case 'delete-scope': + need(1, 'delete-scope '); + await deleteScope(sql, p[0]); + console.log(`Deleted scope '${p[0]}'`); + break; + case 'list-members': + need(0, 'list-members'); + console.log(table(await listMembers(sql), ['name', 'kind', 'email', 'is_admin', 'deactivated', 'live_tokens'])); + break; + case 'deactivate': + need(1, 'deactivate '); + await deactivateMember(sql, p[0]); + console.log(`Deactivated '${p[0]}': tokens revoked, grants removed, admin dropped`); + break; + case 'reactivate': + need(1, 'reactivate '); + await reactivateMember(sql, p[0]); + console.log(`Reactivated '${p[0]}' (no grants or tokens restored; run set-admin to make them an admin)`); + break; + case 'set-admin': { + const usage = 'set-admin on|off'; + need(2, usage); + if (p[1] !== 'on' && p[1] !== 'off') throw new Error(`Usage: ${usage}`); + await setAdmin(sql, p[0], p[1] === 'on'); + console.log(`'${p[0]}' is ${p[1] === 'on' ? 'now' : 'no longer'} an admin`); + break; + } + case 'admin-log': { + need(0, 'admin-log [--since ] [--actor ] [--limit N]'); + let limit = 50; + if (args.limit !== undefined) { + if (!/^\d+$/.test(args.limit) || Number(args.limit) < 1) { + throw new Error(`Invalid --limit '${args.limit}': use a positive whole number`); + } + limit = Number(args.limit); + } + let since: Date | undefined; + if (args.since !== undefined) { + const days = /^(\d+)d$/.exec(args.since); + const d = new Date(args.since); + if (days) since = new Date(Date.now() - Number(days[1]) * 86_400_000); + else if (/^\d{4}-\d{2}-\d{2}/.test(args.since) && !isNaN(d.getTime())) since = d; + else throw new Error(`Invalid --since '${args.since}': use an ISO date or a number of days (7d)`); + } + const rows = await adminLog(sql, { since, actor: args.actor, limit }); + console.log(table(rows.map((r) => ({ ...r, details: JSON.stringify(r.details) })), [ + 'at', + 'actor', + 'action', + 'target', + 'details', + ])); + break; + } case 'create-member': { need(1, 'create-member [--email
] | --bot'); // --human is the older spelling of --email and still works. diff --git a/scripts/backup.ts b/scripts/backup.ts index 2148c1b..2c3260d 100644 --- a/scripts/backup.ts +++ b/scripts/backup.ts @@ -17,6 +17,10 @@ export interface Backup { email: string | null; authUserId: string | null; createdAt: string; + /** Absent in version-1 files written before admin support; read as false. */ + isAdmin?: boolean; + /** Absent in older files; read as null. */ + deactivatedAt?: string | null; }[]; grants: { scope: string; member: string; access: string; grantedAt: string; grantedBy: string | null }[]; memories: { @@ -86,7 +90,8 @@ async function exportSnapshot(sql: Sql, scope?: string): Promise { } const members = await sql` select id, display_name as "displayName", kind, email, auth_user_id as "authUserId", - ${sql.unsafe(TS('created_at'))} as "createdAt" + ${sql.unsafe(TS('created_at'))} as "createdAt", is_admin as "isAdmin", + ${sql.unsafe(TS('deactivated_at'))} as "deactivatedAt" from agent_memory.members where ${scope === undefined ? sql`true` : sql`display_name = any(${[...wanted]}::text[])`} order by display_name`; @@ -119,8 +124,10 @@ export async function restoreBackup(sql: Sql, data: Backup): Promise { for (const m of data.members) { memberIds.set(m.displayName, m.id); await tx` - insert into agent_memory.members (id, display_name, kind, email, auth_user_id, created_at) - values (${m.id}, ${m.displayName}, ${m.kind}, ${m.email}, ${m.authUserId}, (${m.createdAt}::text)::timestamptz)`; + insert into agent_memory.members + (id, display_name, kind, email, auth_user_id, created_at, is_admin, deactivated_at) + values (${m.id}, ${m.displayName}, ${m.kind}, ${m.email}, ${m.authUserId}, (${m.createdAt}::text)::timestamptz, + ${m.isAdmin ?? false}, (${m.deactivatedAt ?? null}::text)::timestamptz)`; } const scopeIds = new Map(); for (const s of data.scopes) { diff --git a/scripts/lib/admin-db.ts b/scripts/lib/admin-db.ts index 67a2698..59da0e1 100644 --- a/scripts/lib/admin-db.ts +++ b/scripts/lib/admin-db.ts @@ -1,8 +1,6 @@ import type { Sql } from '../../supabase/functions/_shared/db.ts'; import { generateToken, hashToken } from '../../supabase/functions/_shared/tokens.ts'; -const SCOPE_NAME = /^[a-z0-9][a-z0-9-]{0,62}$/; - export interface Scope { id: string; name: string; @@ -47,17 +45,20 @@ async function memberId(sql: Sql, name: string): Promise { return r.id; } -export async function createScope(sql: Sql, name: string, description?: string): Promise { - if (!SCOPE_NAME.test(name)) { - throw new Error( - `Invalid scope name '${name}': use 1-63 characters, lowercase letters, digits and hyphens, starting with a letter or digit.`, - ); +/** Run an adm_* call. Their P0001 errors are user-safe: rethrow the message alone, never driver detail. */ +async function adm(fn: () => Promise): Promise { + try { + return await fn(); + } catch (e) { + const err = e as { code?: string; message?: string }; + if (err.code === 'P0001') throw new Error(err.message); + throw e; } - const [dup] = await sql`select 1 from agent_memory.scopes where name = ${name}`; - if (dup) throw new Error(`Scope '${name}' already exists`); - const [r] = await sql` - insert into agent_memory.scopes (name, description) values (${name}, ${description ?? null}) - returning id, name, description`; +} + +export async function createScope(sql: Sql, name: string, description?: string): Promise { + await adm(() => sql`select agent_memory.adm_create_scope(${name}, ${description ?? null}, null, ${grantor()})`); + const [r] = await sql`select id, name, description from agent_memory.scopes where name = ${name}`; return r as Scope; } @@ -72,37 +73,78 @@ export async function createMember( ): Promise { // Email is optional: it is only used to link the member to a Supabase login (auth.users). const email = opts.email?.trim() || null; - const [dup] = await sql`select 1 from agent_memory.members where display_name = ${name}`; - if (dup) throw new Error(`Member '${name}' already exists`); - let authUserId: string | null = null; - if (email) { - // Read-only lookup; nothing is ever written to auth. - const [u] = await sql`select id from auth.users where lower(email) = lower(${email})`; - authUserId = u?.id ?? null; - } + await adm(() => sql`select agent_memory.adm_create_member(${name}, ${opts.kind}, ${email}, null, ${grantor()})`); const [r] = await sql` - insert into agent_memory.members (display_name, kind, email, auth_user_id) - values (${name}, ${opts.kind}, ${email}, ${authUserId}) - returning id, display_name as name, kind, auth_user_id as "authUserId"`; + select id, display_name as name, kind, auth_user_id as "authUserId" + from agent_memory.members where display_name = ${name}`; return r as Member; } export async function grant(sql: Sql, member: string, scope: string, access: 'read' | 'write'): Promise { - if (access !== 'read' && access !== 'write') throw new Error(`Access must be read or write, got '${access}'`); - const m = await memberId(sql, member); - const s = await scopeId(sql, scope); - await sql` - insert into agent_memory.scope_grants (scope_id, member_id, access, granted_by) - values (${s}, ${m}, ${access}, ${grantor()}) - on conflict (scope_id, member_id) - do update set access = excluded.access, granted_by = excluded.granted_by, granted_at = now()`; + await adm(() => sql`select agent_memory.adm_grant(${member}, ${scope}, ${access}, null, ${grantor()})`); } export async function revoke(sql: Sql, member: string, scope: string): Promise { - const m = await memberId(sql, member); - const s = await scopeId(sql, scope); - const r = await sql`delete from agent_memory.scope_grants where scope_id = ${s} and member_id = ${m}`; - return r.count > 0; + const [r] = await adm(() => sql`select agent_memory.adm_revoke(${member}, ${scope}, null, ${grantor()}) as ok`); + return r.ok as boolean; +} + +export async function deleteScope(sql: Sql, name: string): Promise { + await adm(() => sql`select agent_memory.adm_delete_scope(${name}, null, ${grantor()})`); +} + +export async function deactivateMember(sql: Sql, name: string): Promise { + await adm(() => sql`select agent_memory.adm_deactivate_member(${name}, null, ${grantor()})`); +} + +export async function reactivateMember(sql: Sql, name: string): Promise { + await adm(() => sql`select agent_memory.adm_reactivate_member(${name}, null, ${grantor()})`); +} + +export async function setAdmin(sql: Sql, name: string, on: boolean): Promise { + await adm(() => sql`select agent_memory.adm_set_admin(${name}, ${on}, null, ${grantor()})`); +} + +export interface MemberRow { + name: string; + kind: 'human' | 'bot'; + email: string | null; + is_admin: boolean; + deactivated: boolean; + live_tokens: number; +} + +export async function listMembers(sql: Sql): Promise { + return await sql` + select m.display_name as name, m.kind, m.email, m.is_admin, + (m.deactivated_at is not null) as deactivated, + (select count(*)::int from agent_memory.access_tokens t + where t.member_id = m.id and t.revoked_at is null + and (t.expires_at is null or t.expires_at > now())) as live_tokens + from agent_memory.members m order by m.display_name`; +} + +export interface AdminLogRow { + at: Date; + actor: string; + action: string; + target: string; + details: unknown; +} + +/** Admin log, newest first. `actor` matches the member's display name or the recorded label. */ +export async function adminLog( + sql: Sql, + f: { since?: Date; actor?: string; limit?: number } = {}, +): Promise { + return await sql` + select l.at, coalesce(m.display_name, l.actor_label) as actor, l.action, l.target, l.details + from agent_memory.admin_log l + left join agent_memory.members m on m.id = l.actor_member_id + where ${f.since === undefined ? sql`true` : sql`l.at >= ${f.since}`} + and ${f.actor === undefined ? sql`true` : sql`coalesce(m.display_name, l.actor_label) = ${f.actor}`} + order by l.at desc, l.id desc + limit ${f.limit ?? 50}`; } export async function listGrants(sql: Sql): Promise { @@ -126,11 +168,11 @@ export function parseExpires(input: string, now: Date = new Date()): Date { /** Returns the plaintext token. It is not recoverable afterwards: only the hash is stored. */ export async function issueToken(sql: Sql, member: string, name: string, expires?: Date): Promise { - const m = await memberId(sql, member); const token = generateToken(); - await sql` - insert into agent_memory.access_tokens (member_id, name, token_hash, expires_at) - values (${m}, ${name}, ${await hashToken(token)}, ${expires ?? null})`; + const hash = await hashToken(token); + await adm(() => + sql`select agent_memory.adm_issue_token(${member}, ${name}, ${hash}, ${expires ?? null}, null, ${grantor()})` + ); return token; } @@ -143,10 +185,8 @@ export async function listTokens(sql: Sql, member: string): Promise } export async function revokeToken(sql: Sql, id: string): Promise { - const r = await sql` - update agent_memory.access_tokens set revoked_at = now() - where id::text = ${id} and revoked_at is null`; - if (r.count === 0) throw new Error(`Token '${id}' not found or already revoked`); + if (!UUID.test(id)) throw new Error(`Token '${id}' not found or already revoked`); + await adm(() => sql`select agent_memory.adm_revoke_token(${id}::uuid, null, ${grantor()})`); } export async function restoreMemory(sql: Sql, id: string): Promise { diff --git a/scripts/setup.ts b/scripts/setup.ts index d15e48b..2a3203e 100644 --- a/scripts/setup.ts +++ b/scripts/setup.ts @@ -8,7 +8,7 @@ import { parseArgs } from 'jsr:@std/cli@1.0.9/parse-args'; import { connect, type Sql } from '../supabase/functions/_shared/db.ts'; import { hashToken } from '../supabase/functions/_shared/tokens.ts'; import { configureClaude } from './configure-claude.ts'; -import { createMember, createScope, grant, issueToken, listScopes } from './lib/admin-db.ts'; +import { createMember, createScope, grant, issueToken, listScopes, setAdmin } from './lib/admin-db.ts'; import { assertGitIgnored, readEnvFile, upsertEnvVars } from './lib/env-file.ts'; import { defaultRun, redact, type Runner } from './lib/run.ts'; @@ -143,6 +143,12 @@ export async function setup(o: SetupOptions): Promise { } await grant(sql, member, scope, 'write'); log(`[6/7] Member '${member}' (${existing ? 'existing' : kind}) can write to '${scope}'`); + if (kind === 'human') { + await setAdmin(sql, member, true); // idempotent + log(`[6/7] Member '${member}' is an admin`); + } else { + log('Note: no admin yet - run admin.ts set-admin on'); + } // 6. token: reuse the one in the env file when it is still live for this member. const [m] = await sql`select id from agent_memory.members where display_name = ${member}`; diff --git a/scripts/smoke.ts b/scripts/smoke.ts index 8856193..f2fd0c8 100644 --- a/scripts/smoke.ts +++ b/scripts/smoke.ts @@ -41,6 +41,20 @@ async function call(name: string, a: Record): Promise { } } +const BASE_TOOLS = [ + 'list_scopes', + 'store', + 'store_batch', + 'search', + 'recall', + 'find_related', + 'list_recent', + 'update', + 'delete', + 'stats', + 'prune', +]; + let failures = 0; async function step(name: string, fn: () => Promise) { const t0 = performance.now(); @@ -61,8 +75,13 @@ let id = ''; let sibling = ''; await step('tools/list', async () => { - const n = (await client.listTools()).tools.length; - ok(n === 11, `expected 11 tools, got ${n}`); + const names = (await client.listTools()).tools.map((t) => t.name); + const missing = BASE_TOOLS.filter((t) => !names.includes(t)); + ok(missing.length === 0, `missing base tools: ${missing.join(', ')}`); + const extra = names.filter((t) => !BASE_TOOLS.includes(t)); + const stray = extra.filter((t) => !t.startsWith('admin_')); + ok(stray.length === 0, `unexpected non-admin tools: ${stray.join(', ')}`); + console.log(extra.length ? ` saw base + ${extra.length} admin tools (admin token)` : ' saw base tools only'); }); await step('list_scopes', async () => { const r = await call('list_scopes', {}); diff --git a/supabase/functions/_shared/admin-store.ts b/supabase/functions/_shared/admin-store.ts new file mode 100644 index 0000000..b7e7b6f --- /dev/null +++ b/supabase/functions/_shared/admin-store.ts @@ -0,0 +1,177 @@ +import type postgres from 'npm:postgres@3.4.5'; +import { type Sql, withMember } from './db.ts'; +import { StoreError } from './limits.ts'; +import { generateToken, hashToken } from './tokens.ts'; + +type Tx = postgres.TransactionSql; +// deno-lint-ignore no-explicit-any +type Row = Record; + +const iso = (v: Date | string | null): string | null => (v === null ? null : new Date(v).toISOString()); + +export interface AdminScope { + name: string; + description: string | null; + memories: number; + deleted: number; + readers: number; + writers: number; +} +export interface AdminMember { + name: string; + kind: 'human' | 'bot'; + email: string | null; + isAdmin: boolean; + deactivated: boolean; + liveTokens: number; +} +export interface AdminGrant { + scope: string; + member: string; + access: 'read' | 'write'; + grantedAt: string; + grantedBy: string | null; +} +export interface AdminToken { + id: string; + name: string | null; + createdAt: string; + lastUsedAt: string | null; + revokedAt: string | null; +} + +/** + * Admin operations, called as the member. Every call goes through the database's admin_* functions, which check + * the caller is an active admin and apply every rule; this class adds none of its own. + */ +export class PgAdminStore { + constructor(private readonly sql: Sql, private readonly memberId: string) {} + + /** Postgres rule texts are user-safe and pass through verbatim; anything else is logged and hidden. */ + private async run(fn: (tx: Tx) => Promise, onPgError?: (code: string) => StoreError | undefined): Promise { + try { + return await withMember(this.sql, this.memberId, fn); + } catch (e) { + if (e instanceof StoreError) throw e; + const err = e as { code?: string; message?: string }; + if (err.code === 'P0001') throw new StoreError(err.message ?? 'Database error'); + if (err.code === '42501') throw new StoreError('Admin only'); + const mapped = err.code ? onPgError?.(err.code) : undefined; + if (mapped) throw mapped; + console.error('database error', err.code, err.message); + throw new StoreError('Database error'); + } + } + + listScopes(): Promise { + return this.run(async (tx) => { + const rows = await tx`select * from agent_memory.admin_list_scopes()`; + return rows.map((r) => ({ + name: r.name, + description: r.description, + memories: r.memories, + deleted: r.deleted, + readers: r.readers, + writers: r.writers, + })); + }); + } + + createScope(name: string, description?: string): Promise<{ id: string }> { + return this.run(async (tx) => { + const [r] = await tx`select agent_memory.admin_create_scope(${name}, ${description ?? null}) as id`; + return { id: r.id }; + }); + } + + deleteScope(name: string): Promise { + return this.run(async (tx) => { + await tx`select agent_memory.admin_delete_scope(${name})`; + }); + } + + listMembers(): Promise { + return this.run(async (tx) => { + const rows = await tx`select * from agent_memory.admin_list_members()`; + return rows.map((r) => ({ + name: r.name, + kind: r.kind, + email: r.email, + isAdmin: r.is_admin, + deactivated: r.deactivated, + liveTokens: r.live_tokens, + })); + }); + } + + createMember(name: string, kind: 'human' | 'bot', email?: string): Promise<{ id: string }> { + return this.run(async (tx) => { + const [r] = await tx`select agent_memory.admin_create_member(${name}, ${kind}, ${email ?? null}) as id`; + return { id: r.id }; + }); + } + + deactivateMember(name: string): Promise { + return this.run(async (tx) => { + await tx`select agent_memory.admin_deactivate_member(${name})`; + }); + } + + listGrants(f: { scope?: string; member?: string } = {}): Promise { + return this.run(async (tx) => { + const rows = await tx` + select * from agent_memory.admin_list_grants(${f.scope ?? null}, ${f.member ?? null})`; + return rows.map((r) => ({ + scope: r.scope, + member: r.member, + access: r.access, + grantedAt: iso(r.granted_at) as string, + grantedBy: r.granted_by, + })); + }); + } + + grant(member: string, scope: string, access: 'read' | 'write'): Promise { + return this.run(async (tx) => { + await tx`select agent_memory.admin_grant(${member}, ${scope}, ${access})`; + }); + } + + /** True if a grant was removed, false if there was none. */ + revoke(member: string, scope: string): Promise { + return this.run(async (tx) => { + const [r] = await tx`select agent_memory.admin_revoke(${member}, ${scope}) as ok`; + return r.ok as boolean; + }); + } + + /** Issues a token. The plaintext is returned once to the caller and never stored or logged; only its hash is. */ + async issueToken(member: string, name: string): Promise<{ id: string; token: string }> { + const token = generateToken(); + const hash = await hashToken(token); + const id = await this.run(async (tx) => { + const [r] = await tx`select agent_memory.admin_issue_token(${member}, ${name}, ${hash}) as id`; + return r.id as string; + }); + return { id, token }; + } + + listTokens(member: string): Promise { + return this.run(async (tx) => { + const rows = await tx`select * from agent_memory.admin_list_tokens(${member})`; + return rows.map((r) => ({ + id: r.id, + name: r.name, + createdAt: iso(r.created_at) as string, + lastUsedAt: iso(r.last_used_at), + revokedAt: iso(r.revoked_at), + })); + }); + } + + revokeToken(id: string): Promise { + return this.run(async (tx) => { + await tx`select agent_memory.admin_revoke_token(${id})`; + }, (code) => (code === '22P02' ? new StoreError(`Token ${id} not found`) : undefined)); + } +} diff --git a/supabase/functions/_shared/admin-tools.ts b/supabase/functions/_shared/admin-tools.ts new file mode 100644 index 0000000..a51921a --- /dev/null +++ b/supabase/functions/_shared/admin-tools.ts @@ -0,0 +1,137 @@ +import { z } from 'npm:zod@4.6.7'; +import type { McpServer } from 'npm:@modelcontextprotocol/server@2.4.0'; +import type { PgAdminStore } from './admin-store.ts'; +import { failure, success } from './tools.ts'; + +const ISSUE_NOTE = 'Shown once - give it to the member privately; it is not stored and cannot be shown again.'; + +/** Run an admin action; its StoreError text is returned as is, so admins see the exact rule. */ +async function guard(fn: () => Promise) { + try { + return success(await fn()); + } catch (e) { + return failure(e); + } +} + +const MEMBER_NAME_MSG = "Member names can't be blank or start or end with a space"; + +/** Registers the 12 admin tools. Register them for admins only. */ +export function registerAdminTools(server: McpServer, admin: PgAdminStore): void { + server.registerTool('admin_list_scopes', { + description: + 'Admin: List every scope with its description, live and deleted memory counts, and how many members can read and write it.', + inputSchema: z.object({}), + }, () => guard(async () => ({ scopes: await admin.listScopes() }))); + + server.registerTool('admin_create_scope', { + description: + 'Admin: Create a scope. Names are lowercase letters, digits and hyphens, starting with a letter or digit (max 63).', + inputSchema: z.object({ + name: z.string().describe('Scope name'), + description: z.string().optional().describe('What the scope is for'), + }), + }, ({ name, description }) => + guard(async () => { + await admin.createScope(name, description); + return { created: name }; + })); + + server.registerTool('admin_delete_scope', { + description: 'Admin: Delete an empty scope. Refused while it still holds memories.', + inputSchema: z.object({ name: z.string().describe('Scope name') }), + }, ({ name }) => + guard(async () => { + await admin.deleteScope(name); + return { deleted: name }; + })); + + server.registerTool('admin_list_members', { + description: 'Admin: List every member with kind, email, admin and deactivated flags, and live token count.', + inputSchema: z.object({}), + }, () => guard(async () => ({ members: await admin.listMembers() }))); + + server.registerTool('admin_create_member', { + description: + 'Admin: Create a member (human or bot). Members start with no grants and no tokens; use admin_grant and admin_issue_token next. Admins can only be made from the shell.', + inputSchema: z.object({ + name: z.string().min(1, MEMBER_NAME_MSG).regex(/^\S(.*\S)?$/, MEMBER_NAME_MSG).describe('Member name'), + kind: z.enum(['human', 'bot']).default('human').describe('human (default) or bot'), + email: z.string().optional().describe('Email, to link a Supabase login (optional)'), + }), + }, ({ name, kind, email }) => + guard(async () => { + await admin.createMember(name, kind ?? 'human', email); + return { created: name, kind: kind ?? 'human' }; + })); + + server.registerTool('admin_deactivate_member', { + description: + 'Admin: Deactivate a member. This revokes all tokens and grants, and is undone only from the shell. Their memories are kept.', + inputSchema: z.object({ name: z.string().describe('Member name') }), + }, ({ name }) => + guard(async () => { + await admin.deactivateMember(name); + return { deactivated: name }; + })); + + server.registerTool('admin_list_grants', { + description: 'Admin: List scope grants, optionally filtered by scope and/or member.', + inputSchema: z.object({ + scope: z.string().optional().describe('Only grants on this scope'), + member: z.string().optional().describe('Only grants held by this member'), + }), + }, ({ scope, member }) => guard(async () => ({ grants: await admin.listGrants({ scope, member }) }))); + + server.registerTool('admin_grant', { + description: 'Admin: Grant a member read or write access to a scope, replacing any existing grant.', + inputSchema: z.object({ + member: z.string().describe('Member name'), + scope: z.string().describe('Scope name'), + access: z.enum(['read', 'write']).describe('read or write'), + }), + }, ({ member, scope, access }) => + guard(async () => { + await admin.grant(member, scope, access); + return { member, scope, access }; + })); + + server.registerTool('admin_revoke', { + description: "Admin: Remove a member's grant on a scope. Reports whether there was one to remove.", + inputSchema: z.object({ + member: z.string().describe('Member name'), + scope: z.string().describe('Scope name'), + }), + }, ({ member, scope }) => + guard(async () => { + const revoked = await admin.revoke(member, scope); + return { member, scope, revoked }; + })); + + server.registerTool('admin_issue_token', { + description: + 'Admin: Issue an access token for a member. The token is shown once in the result and is not stored; it cannot be shown again, so pass it to the member privately.', + inputSchema: z.object({ + member: z.string().describe('Member name'), + name: z.string().describe('A label for the token, e.g. the device'), + }), + }, ({ member, name }) => + guard(async () => { + const { id, token } = await admin.issueToken(member, name); + return { member, name, id, token, note: ISSUE_NOTE }; + })); + + server.registerTool('admin_list_tokens', { + description: "Admin: List a member's tokens (id, name, created, last used, revoked). Token values are never shown.", + inputSchema: z.object({ member: z.string().describe('Member name') }), + }, ({ member }) => guard(async () => ({ member, tokens: await admin.listTokens(member) }))); + + server.registerTool('admin_revoke_token', { + description: 'Admin: Revoke a token by id (from admin_list_tokens).', + inputSchema: z.object({ id: z.string().describe('Token id') }), + }, ({ id }) => + guard(async () => { + await admin.revokeToken(id); + return { revoked: id }; + })); +} diff --git a/supabase/functions/_shared/db.ts b/supabase/functions/_shared/db.ts index 7e5a119..11daea9 100644 --- a/supabase/functions/_shared/db.ts +++ b/supabase/functions/_shared/db.ts @@ -7,12 +7,25 @@ export function connect(url: string): Sql { return postgres(url, { max: 3, prepare: false }); } -/** Resolve a bearer token to a member id, or null. Malformed tokens never reach the database. */ -export async function resolveMember(sql: Sql, token: string): Promise { +export interface Caller { + memberId: string; + isAdmin: boolean; +} + +/** Resolve a bearer token to its member and admin flag, or null. Malformed tokens never reach the database. */ +export async function resolveCaller(sql: Sql, token: string): Promise { if (!looksLikeToken(token)) return null; const hash = await hashToken(token); - const rows = await sql<{ id: string | null }[]>`select agent_memory.resolve_token(${hash}) as id`; - return rows[0]?.id ?? null; + const rows = await sql< + { member_id: string | null; is_admin: boolean | null }[] + >`select member_id, is_admin from agent_memory.resolve_member(${hash})`; + const r = rows[0]; + return r?.member_id ? { memberId: r.member_id, isAdmin: r.is_admin === true } : null; +} + +/** Resolve a bearer token to a member id, or null. */ +export async function resolveMember(sql: Sql, token: string): Promise { + return (await resolveCaller(sql, token))?.memberId ?? null; } /** Run `fn` in a transaction that acts as the member, so RLS applies. */ diff --git a/supabase/functions/_shared/tools.ts b/supabase/functions/_shared/tools.ts index 8832aac..7f88412 100644 --- a/supabase/functions/_shared/tools.ts +++ b/supabase/functions/_shared/tools.ts @@ -35,10 +35,16 @@ const modeSchema = z // ── Tool result helpers ──────────────────────────────────────────── -function success(data: unknown) { +export function success(data: unknown) { return { content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }] }; } +/** A failure result whose text is the error message alone (admin rule texts are returned verbatim). */ +export function failure(err: unknown) { + const message = err instanceof Error ? err.message : String(err); + return { content: [{ type: 'text' as const, text: message }], isError: true }; +} + function error(prefix: string, err: unknown) { const message = err instanceof Error ? err.message : String(err); return { content: [{ type: 'text' as const, text: `${prefix}: ${message}` }], isError: true }; diff --git a/supabase/functions/agent-memory/index.ts b/supabase/functions/agent-memory/index.ts index 4b041d1..c102bb9 100644 --- a/supabase/functions/agent-memory/index.ts +++ b/supabase/functions/agent-memory/index.ts @@ -1,6 +1,8 @@ import 'jsr:@supabase/functions-js@2/edge-runtime.d.ts'; import { createMcpHandler, McpServer } from 'npm:@modelcontextprotocol/server@2.4.0'; -import { connect, resolveMember } from '../_shared/db.ts'; +import { type Caller, connect, resolveCaller } from '../_shared/db.ts'; +import { PgAdminStore } from '../_shared/admin-store.ts'; +import { registerAdminTools } from '../_shared/admin-tools.ts'; import { GteSmallEmbedder } from '../_shared/embedder.ts'; import { MAX_CONTENT_CHARS } from '../_shared/limits.ts'; import { PgMemoryStore } from '../_shared/pg-store.ts'; @@ -20,21 +22,22 @@ const tooLarge = () => Response.json({ error: 'text too large' }, { status: 413 const unauthorized = () => Response.json({ error: 'invalid or missing token' }, { status: 401 }); /** Identity comes only from the bearer token: nothing else in the request can name a member. */ -async function authenticate(req: Request): Promise { +async function authenticate(req: Request): Promise { const m = /^Bearer\s+(\S+)$/i.exec(req.headers.get('authorization') ?? ''); - return m ? await resolveMember(sql, m[1]) : null; + return m ? await resolveCaller(sql, m[1]) : null; } async function handle(req: Request): Promise { - let memberId: string | null; + let caller: Caller | null; try { - memberId = await authenticate(req); + caller = await authenticate(req); } catch (e) { const err = e as { code?: string; message?: string }; console.error('auth lookup failed', err.code, err.message); return Response.json({ error: 'service unavailable' }, { status: 503 }); } - if (!memberId) return unauthorized(); + if (!caller) return unauthorized(); + const { memberId, isAdmin } = caller; const path = new URL(req.url).pathname.replace(/\/+$/, ''); if (req.method === 'POST' && path.endsWith('/embed')) { @@ -64,6 +67,7 @@ async function handle(req: Request): Promise { const mcp = createMcpHandler(() => { const s = new McpServer({ name: 'agent-memory-supabase', version: VERSION }); registerTools(s, store, embedder); + if (isAdmin) registerAdminTools(s, new PgAdminStore(sql, memberId)); return s; }, { onerror: (e) => console.error('mcp error', e) }); return await mcp.fetch(req); diff --git a/supabase/migrations/20261107150000_admin.sql b/supabase/migrations/20261107150000_admin.sql new file mode 100644 index 0000000..a82efec --- /dev/null +++ b/supabase/migrations/20261107150000_admin.sql @@ -0,0 +1,553 @@ +-- Admin members, deactivation, the admin log, and the postgres-only adm_* core functions. + +alter table agent_memory.members + add column is_admin boolean not null default false, + add column deactivated_at timestamptz, + add constraint members_bot_not_admin check (kind = 'human' or not is_admin); + +create table agent_memory.admin_log ( + id bigint generated always as identity primary key, + at timestamptz not null default now(), + actor_member_id uuid null, + actor_label text not null, + action text not null, + target text not null, + details jsonb not null default '{}' +); +alter table agent_memory.admin_log enable row level security; +revoke all on agent_memory.admin_log from public, anon, authenticated, agent_memory_member; + +-- Token resolution: deactivated members no longer resolve. +create or replace function agent_memory.resolve_token(p_hash text) returns uuid +language plpgsql security definer set search_path = '' +as $$ +declare + v_id uuid; + v_member uuid; + v_last timestamptz; +begin + select t.id, t.member_id, t.last_used_at into v_id, v_member, v_last + from agent_memory.access_tokens t + join agent_memory.members m on m.id = t.member_id + where t.token_hash = p_hash + and t.revoked_at is null + and (t.expires_at is null or t.expires_at > pg_catalog.now()) + and m.deactivated_at is null; + if v_id is null then + return null; + end if; + if v_last is null or v_last < pg_catalog.now() - interval '1 minute' then + update agent_memory.access_tokens set last_used_at = pg_catalog.now() where id = v_id; + end if; + return v_member; +end +$$; + +create function agent_memory.resolve_member(p_hash text) returns table (member_id uuid, is_admin boolean) +language plpgsql security definer set search_path = '' +as $$ +declare + v_member uuid; +begin + v_member := agent_memory.resolve_token(p_hash); + if v_member is null then + return; + end if; + return query select m.id, m.is_admin from agent_memory.members m where m.id = v_member; +end +$$; + +create function agent_memory.adm_create_scope(p_name text, p_description text, p_actor uuid, p_label text) +returns uuid +language plpgsql security definer set search_path = '' +as $$ +declare + v_id uuid; +begin + if p_name is null or p_name !~ '^[a-z0-9][a-z0-9-]{0,62}$' then + raise exception 'Scope names are lowercase letters, digits and hyphens, starting with a letter or digit (max 63)'; + end if; + if exists (select 1 from agent_memory.scopes where name = p_name) then + raise exception 'Scope ''%'' already exists', p_name; + end if; + insert into agent_memory.scopes (name, description) values (p_name, p_description) returning id into v_id; + insert into agent_memory.admin_log (actor_member_id, actor_label, action, target, details) + values (p_actor, p_label, 'create_scope', p_name, pg_catalog.jsonb_build_object('scope', p_name)); + return v_id; +end +$$; + +create function agent_memory.adm_delete_scope(p_name text, p_actor uuid, p_label text) returns void +language plpgsql security definer set search_path = '' +as $$ +declare + v_id uuid; + v_count bigint; +begin + select id into v_id from agent_memory.scopes where name = p_name; + if v_id is null then + raise exception 'Scope ''%'' not found', p_name; + end if; + select pg_catalog.count(*) into v_count from agent_memory.memories where scope_id = v_id; + if v_count > 0 then + raise exception 'Scope ''%'' still holds % memories; move, delete or erase them first', p_name, v_count; + end if; + delete from agent_memory.scopes where id = v_id; -- grants cascade + insert into agent_memory.admin_log (actor_member_id, actor_label, action, target, details) + values (p_actor, p_label, 'delete_scope', p_name, pg_catalog.jsonb_build_object('scope', p_name)); +end +$$; + +create function agent_memory.adm_create_member(p_name text, p_kind text, p_email text, p_actor uuid, p_label text) +returns uuid +language plpgsql security definer set search_path = '' +as $$ +declare + v_id uuid; + v_email text := nullif(pg_catalog.btrim(p_email), ''); + v_auth uuid := null; +begin + if exists (select 1 from agent_memory.members where display_name = p_name) then + raise exception 'Member ''%'' already exists', p_name; + end if; + if v_email is not null then + select u.id into v_auth from auth.users u where pg_catalog.lower(u.email) = pg_catalog.lower(v_email) limit 1; + end if; + insert into agent_memory.members (display_name, kind, email, auth_user_id) + values (p_name, p_kind, v_email, v_auth) returning id into v_id; + insert into agent_memory.admin_log (actor_member_id, actor_label, action, target, details) + values (p_actor, p_label, 'create_member', p_name, pg_catalog.jsonb_build_object('kind', p_kind)); + return v_id; +end +$$; + +-- Serialise admin-flag changes so two concurrent demotions cannot both pass the last-admin check. +create function agent_memory.adm_assert_not_last_admin(p_member uuid) returns void +language plpgsql security definer set search_path = '' +as $$ +begin + perform pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtext('agent_memory.admin_flag')); + if exists (select 1 from agent_memory.members where id = p_member and is_admin and deactivated_at is null) + and (select pg_catalog.count(*) from agent_memory.members where is_admin and deactivated_at is null) <= 1 then + raise exception 'Can''t remove the last active admin'; + end if; +end +$$; + +create function agent_memory.adm_deactivate_member(p_name text, p_actor uuid, p_label text) returns void +language plpgsql security definer set search_path = '' +as $$ +declare + v_id uuid; +begin + select id into v_id from agent_memory.members where display_name = p_name; + if v_id is null then + raise exception 'Member ''%'' not found', p_name; + end if; + perform agent_memory.adm_assert_not_last_admin(v_id); + update agent_memory.access_tokens set revoked_at = pg_catalog.now() where member_id = v_id and revoked_at is null; + delete from agent_memory.scope_grants where member_id = v_id; + update agent_memory.members set deactivated_at = coalesce(deactivated_at, pg_catalog.now()), is_admin = false + where id = v_id; + insert into agent_memory.admin_log (actor_member_id, actor_label, action, target, details) + values (p_actor, p_label, 'deactivate_member', p_name, '{}'); +end +$$; + +create function agent_memory.adm_reactivate_member(p_name text, p_actor uuid, p_label text) returns void +language plpgsql security definer set search_path = '' +as $$ +declare + v_id uuid; +begin + select id into v_id from agent_memory.members where display_name = p_name; + if v_id is null then + raise exception 'Member ''%'' not found', p_name; + end if; + update agent_memory.members set deactivated_at = null where id = v_id; + insert into agent_memory.admin_log (actor_member_id, actor_label, action, target, details) + values (p_actor, p_label, 'reactivate_member', p_name, '{}'); +end +$$; + +create function agent_memory.adm_set_admin(p_name text, p_on boolean, p_actor uuid, p_label text) returns void +language plpgsql security definer set search_path = '' +as $$ +declare + v_id uuid; + v_kind text; +begin + select id, kind into v_id, v_kind from agent_memory.members where display_name = p_name; + if v_id is null then + raise exception 'Member ''%'' not found', p_name; + end if; + if p_on then + if v_kind <> 'human' then + raise exception 'A bot can''t be an admin'; + end if; + else + perform agent_memory.adm_assert_not_last_admin(v_id); + end if; + update agent_memory.members set is_admin = p_on where id = v_id; + insert into agent_memory.admin_log (actor_member_id, actor_label, action, target, details) + values (p_actor, p_label, 'set_admin', p_name, pg_catalog.jsonb_build_object('admin', p_on)); +end +$$; + +create function agent_memory.adm_grant(p_member text, p_scope text, p_access text, p_actor uuid, p_label text) +returns void +language plpgsql security definer set search_path = '' +as $$ +declare + v_member uuid; + v_dead timestamptz; + v_scope uuid; +begin + if p_access is null or p_access not in ('read', 'write') then + raise exception 'Access must be read or write'; + end if; + select id, deactivated_at into v_member, v_dead from agent_memory.members where display_name = p_member; + if v_member is null then + raise exception 'Member ''%'' not found', p_member; + end if; + select id into v_scope from agent_memory.scopes where name = p_scope; + if v_scope is null then + raise exception 'Scope ''%'' not found', p_scope; + end if; + if v_dead is not null then + raise exception 'Member ''%'' is deactivated', p_member; + end if; + insert into agent_memory.scope_grants (scope_id, member_id, access, granted_by) + values (v_scope, v_member, p_access, p_label) + on conflict (scope_id, member_id) + do update set access = excluded.access, granted_by = excluded.granted_by, granted_at = pg_catalog.now(); + insert into agent_memory.admin_log (actor_member_id, actor_label, action, target, details) + values (p_actor, p_label, 'grant', p_member, pg_catalog.jsonb_build_object('scope', p_scope, 'access', p_access)); +end +$$; + +create function agent_memory.adm_revoke(p_member text, p_scope text, p_actor uuid, p_label text) returns boolean +language plpgsql security definer set search_path = '' +as $$ +declare + v_member uuid; + v_scope uuid; + v_n bigint; +begin + select id into v_member from agent_memory.members where display_name = p_member; + if v_member is null then + raise exception 'Member ''%'' not found', p_member; + end if; + select id into v_scope from agent_memory.scopes where name = p_scope; + if v_scope is null then + raise exception 'Scope ''%'' not found', p_scope; + end if; + with d as ( + delete from agent_memory.scope_grants where scope_id = v_scope and member_id = v_member returning 1 + ) + select pg_catalog.count(*) into v_n from d; + if v_n = 0 then + return false; + end if; + insert into agent_memory.admin_log (actor_member_id, actor_label, action, target, details) + values (p_actor, p_label, 'revoke', p_member, pg_catalog.jsonb_build_object('scope', p_scope)); + return true; +end +$$; + +create function agent_memory.adm_issue_token( + p_member text, p_name text, p_hash text, p_expires timestamptz, p_actor uuid, p_label text +) returns uuid +language plpgsql security definer set search_path = '' +as $$ +declare + v_member uuid; + v_dead timestamptz; + v_id uuid; +begin + select id, deactivated_at into v_member, v_dead from agent_memory.members where display_name = p_member; + if v_member is null then + raise exception 'Member ''%'' not found', p_member; + end if; + if v_dead is not null then + raise exception 'Member ''%'' is deactivated', p_member; + end if; + insert into agent_memory.access_tokens (member_id, name, token_hash, expires_at) + values (v_member, p_name, p_hash, p_expires) returning id into v_id; + insert into agent_memory.admin_log (actor_member_id, actor_label, action, target, details) + values (p_actor, p_label, 'issue_token', p_member, + pg_catalog.jsonb_build_object('token_id', v_id, 'name', p_name)); + return v_id; +end +$$; + +create function agent_memory.adm_revoke_token(p_id uuid, p_actor uuid, p_label text) returns void +language plpgsql security definer set search_path = '' +as $$ +declare + v_member text; +begin + select m.display_name into v_member + from agent_memory.access_tokens t join agent_memory.members m on m.id = t.member_id + where t.id = p_id; + if v_member is null then + raise exception 'Token % not found', p_id; + end if; + update agent_memory.access_tokens set revoked_at = coalesce(revoked_at, pg_catalog.now()) where id = p_id; + insert into agent_memory.admin_log (actor_member_id, actor_label, action, target, details) + values (p_actor, p_label, 'revoke_token', v_member, pg_catalog.jsonb_build_object('token_id', p_id)); +end +$$; + +revoke execute on function agent_memory.resolve_token(text) from public; +revoke execute on function agent_memory.resolve_member(text) from public; +revoke execute on function agent_memory.adm_create_scope(text, text, uuid, text) from public; +revoke execute on function agent_memory.adm_delete_scope(text, uuid, text) from public; +revoke execute on function agent_memory.adm_create_member(text, text, text, uuid, text) from public; +revoke execute on function agent_memory.adm_assert_not_last_admin(uuid) from public; +revoke execute on function agent_memory.adm_deactivate_member(text, uuid, text) from public; +revoke execute on function agent_memory.adm_reactivate_member(text, uuid, text) from public; +revoke execute on function agent_memory.adm_set_admin(text, boolean, uuid, text) from public; +revoke execute on function agent_memory.adm_grant(text, text, text, uuid, text) from public; +revoke execute on function agent_memory.adm_revoke(text, text, uuid, text) from public; +revoke execute on function agent_memory.adm_issue_token(text, text, text, timestamptz, uuid, text) from public; +revoke execute on function agent_memory.adm_revoke_token(uuid, uuid, text) from public; + +-- ============================================================================ +-- Member-callable admin_* wrappers. Each runs as owner, checks the caller is an active admin, refuses to +-- act on another admin, then delegates to the matching postgres-only adm_* function. +-- ============================================================================ + +-- Private helper: not executable by agent_memory_member, only reachable from the wrappers below. +create function agent_memory.require_admin() returns uuid +language plpgsql stable security definer set search_path = '' +as $$ +declare + v_id uuid := agent_memory.current_member_id(); +begin + if v_id is null or not exists ( + select 1 from agent_memory.members where id = v_id and is_admin and deactivated_at is null + ) then + raise exception 'Admin only' using errcode = '42501'; + end if; + return v_id; +end +$$; + +create function agent_memory.admin_label(p_id uuid) returns text +language sql stable security definer set search_path = '' +as $$ select display_name from agent_memory.members where id = p_id $$; + +-- Raises if p_name is a member other than the caller who is an admin. +create function agent_memory.assert_not_other_admin(p_name text, p_caller uuid) returns void +language plpgsql stable security definer set search_path = '' +as $$ +begin + if exists ( + select 1 from agent_memory.members where display_name = p_name and id <> p_caller and is_admin + ) then + raise exception 'Member ''%'' is an admin; manage admins from the shell', p_name; + end if; +end +$$; + +create function agent_memory.admin_create_scope(p_name text, p_description text) returns uuid +language plpgsql security definer set search_path = '' +as $$ +declare + v_caller uuid := agent_memory.require_admin(); +begin + return agent_memory.adm_create_scope(p_name, p_description, v_caller, agent_memory.admin_label(v_caller)); +end +$$; + +create function agent_memory.admin_delete_scope(p_name text) returns void +language plpgsql security definer set search_path = '' +as $$ +declare + v_caller uuid := agent_memory.require_admin(); +begin + perform agent_memory.adm_delete_scope(p_name, v_caller, agent_memory.admin_label(v_caller)); +end +$$; + +create function agent_memory.admin_create_member(p_name text, p_kind text, p_email text) returns uuid +language plpgsql security definer set search_path = '' +as $$ +declare + v_caller uuid := agent_memory.require_admin(); +begin + return agent_memory.adm_create_member(p_name, p_kind, p_email, v_caller, agent_memory.admin_label(v_caller)); +end +$$; + +create function agent_memory.admin_deactivate_member(p_name text) returns void +language plpgsql security definer set search_path = '' +as $$ +declare + v_caller uuid := agent_memory.require_admin(); +begin + if exists (select 1 from agent_memory.members where id = v_caller and display_name = p_name) then + raise exception 'You can''t deactivate yourself'; + end if; + perform agent_memory.assert_not_other_admin(p_name, v_caller); + perform agent_memory.adm_deactivate_member(p_name, v_caller, agent_memory.admin_label(v_caller)); +end +$$; + +create function agent_memory.admin_grant(p_member text, p_scope text, p_access text) returns void +language plpgsql security definer set search_path = '' +as $$ +declare + v_caller uuid := agent_memory.require_admin(); +begin + perform agent_memory.assert_not_other_admin(p_member, v_caller); + perform agent_memory.adm_grant(p_member, p_scope, p_access, v_caller, agent_memory.admin_label(v_caller)); +end +$$; + +create function agent_memory.admin_revoke(p_member text, p_scope text) returns boolean +language plpgsql security definer set search_path = '' +as $$ +declare + v_caller uuid := agent_memory.require_admin(); +begin + perform agent_memory.assert_not_other_admin(p_member, v_caller); + return agent_memory.adm_revoke(p_member, p_scope, v_caller, agent_memory.admin_label(v_caller)); +end +$$; + +create function agent_memory.admin_issue_token(p_member text, p_name text, p_hash text) returns uuid +language plpgsql security definer set search_path = '' +as $$ +declare + v_caller uuid := agent_memory.require_admin(); +begin + perform agent_memory.assert_not_other_admin(p_member, v_caller); + return agent_memory.adm_issue_token(p_member, p_name, p_hash, null, v_caller, agent_memory.admin_label(v_caller)); +end +$$; + +create function agent_memory.admin_revoke_token(p_id uuid) returns void +language plpgsql security definer set search_path = '' +as $$ +declare + v_caller uuid := agent_memory.require_admin(); + v_owner uuid; + v_owner_name text; + v_live boolean; +begin + select t.member_id, m.display_name, (t.revoked_at is null and (t.expires_at is null or t.expires_at > pg_catalog.now())) + into v_owner, v_owner_name, v_live + from agent_memory.access_tokens t join agent_memory.members m on m.id = t.member_id + where t.id = p_id; + if v_owner is not null then + perform agent_memory.assert_not_other_admin(v_owner_name, v_caller); + if v_owner = v_caller and v_live then + -- lock the caller's live tokens so two concurrent revokes cannot both pass + perform 1 from agent_memory.access_tokens + where member_id = v_caller and revoked_at is null and (expires_at is null or expires_at > pg_catalog.now()) + for update; + if (select pg_catalog.count(*) from agent_memory.access_tokens + where member_id = v_caller and revoked_at is null and (expires_at is null or expires_at > pg_catalog.now())) <= 1 then + raise exception 'You can''t revoke your last live token'; + end if; + end if; + end if; + perform agent_memory.adm_revoke_token(p_id, v_caller, agent_memory.admin_label(v_caller)); +end +$$; + +create function agent_memory.admin_list_scopes() +returns table (name text, description text, memories int, deleted int, readers int, writers int) +language plpgsql stable security definer set search_path = '' +as $$ +begin + perform agent_memory.require_admin(); + return query + select s.name, s.description, + (select pg_catalog.count(*) from agent_memory.memories x where x.scope_id = s.id and x.deleted_at is null)::int, + (select pg_catalog.count(*) from agent_memory.memories x where x.scope_id = s.id and x.deleted_at is not null)::int, + (select pg_catalog.count(*) from agent_memory.scope_grants g where g.scope_id = s.id and g.access = 'read')::int, + (select pg_catalog.count(*) from agent_memory.scope_grants g where g.scope_id = s.id and g.access = 'write')::int + from agent_memory.scopes s order by s.name; +end +$$; + +create function agent_memory.admin_list_members() +returns table (name text, kind text, email text, is_admin boolean, deactivated boolean, live_tokens int) +language plpgsql stable security definer set search_path = '' +as $$ +begin + perform agent_memory.require_admin(); + return query + select m.display_name, m.kind, m.email, m.is_admin, (m.deactivated_at is not null), + (select pg_catalog.count(*) from agent_memory.access_tokens t + where t.member_id = m.id and t.revoked_at is null and (t.expires_at is null or t.expires_at > pg_catalog.now()))::int + from agent_memory.members m order by m.display_name; +end +$$; + +create function agent_memory.admin_list_grants(p_scope text, p_member text) +returns table (scope text, member text, access text, granted_at timestamptz, granted_by text) +language plpgsql stable security definer set search_path = '' +as $$ +begin + perform agent_memory.require_admin(); + return query + select s.name, m.display_name, g.access, g.granted_at, g.granted_by + from agent_memory.scope_grants g + join agent_memory.scopes s on s.id = g.scope_id + join agent_memory.members m on m.id = g.member_id + where (p_scope is null or s.name = p_scope) and (p_member is null or m.display_name = p_member) + order by s.name, m.display_name; +end +$$; + +create function agent_memory.admin_list_tokens(p_member text) +returns table (id uuid, name text, created_at timestamptz, last_used_at timestamptz, revoked_at timestamptz) +language plpgsql stable security definer set search_path = '' +as $$ +declare + v_caller uuid := agent_memory.require_admin(); + v_member uuid; +begin + perform agent_memory.assert_not_other_admin(p_member, v_caller); + select m.id into v_member from agent_memory.members m where m.display_name = p_member; + if v_member is null then + raise exception 'Member ''%'' not found', p_member; + end if; + return query + select t.id, t.name, t.created_at, t.last_used_at, t.revoked_at + from agent_memory.access_tokens t where t.member_id = v_member order by t.created_at, t.id; +end +$$; + +revoke execute on function agent_memory.require_admin() from public; +revoke execute on function agent_memory.admin_label(uuid) from public; +revoke execute on function agent_memory.assert_not_other_admin(text, uuid) from public; +revoke execute on function agent_memory.admin_create_scope(text, text) from public; +revoke execute on function agent_memory.admin_delete_scope(text) from public; +revoke execute on function agent_memory.admin_create_member(text, text, text) from public; +revoke execute on function agent_memory.admin_deactivate_member(text) from public; +revoke execute on function agent_memory.admin_grant(text, text, text) from public; +revoke execute on function agent_memory.admin_revoke(text, text) from public; +revoke execute on function agent_memory.admin_issue_token(text, text, text) from public; +revoke execute on function agent_memory.admin_revoke_token(uuid) from public; +revoke execute on function agent_memory.admin_list_scopes() from public; +revoke execute on function agent_memory.admin_list_members() from public; +revoke execute on function agent_memory.admin_list_grants(text, text) from public; +revoke execute on function agent_memory.admin_list_tokens(text) from public; + +grant execute on function agent_memory.admin_create_scope(text, text) to agent_memory_member; +grant execute on function agent_memory.admin_delete_scope(text) to agent_memory_member; +grant execute on function agent_memory.admin_create_member(text, text, text) to agent_memory_member; +grant execute on function agent_memory.admin_deactivate_member(text) to agent_memory_member; +grant execute on function agent_memory.admin_grant(text, text, text) to agent_memory_member; +grant execute on function agent_memory.admin_revoke(text, text) to agent_memory_member; +grant execute on function agent_memory.admin_issue_token(text, text, text) to agent_memory_member; +grant execute on function agent_memory.admin_revoke_token(uuid) to agent_memory_member; +grant execute on function agent_memory.admin_list_scopes() to agent_memory_member; +grant execute on function agent_memory.admin_list_members() to agent_memory_member; +grant execute on function agent_memory.admin_list_grants(text, text) to agent_memory_member; +grant execute on function agent_memory.admin_list_tokens(text) to agent_memory_member; diff --git a/supabase/tests/database/06_admin_core.test.sql b/supabase/tests/database/06_admin_core.test.sql new file mode 100644 index 0000000..a2c6704 --- /dev/null +++ b/supabase/tests/database/06_admin_core.test.sql @@ -0,0 +1,136 @@ +begin; +create extension if not exists pgtap with schema extensions; +select plan(51); + +-- Count only this file's log rows: integration runs leave rows in the shared local database (rolled back below). +delete from agent_memory.admin_log; + +-- schema +select has_column('agent_memory'::name, 'members'::name, 'is_admin'::name, 'members.is_admin exists'); +select has_column('agent_memory'::name, 'members'::name, 'deactivated_at'::name, 'members.deactivated_at exists'); +select has_table('agent_memory'::name, 'admin_log'::name, 'admin_log exists'); +select throws_ok( + $$insert into agent_memory.members (display_name, kind, is_admin) values ('robot', 'bot', true)$$, + '23514', null, 'a bot cannot be flagged admin'); + +-- fixtures via the core functions +select lives_ok($$select agent_memory.adm_create_member('alice', 'human', 'Alice@Example.com', null, 'test')$$, 'create member'); +select is((select count(*) from agent_memory.admin_log where action = 'create_member'), 1::bigint, 'create_member logs one row'); +select agent_memory.adm_create_member('bob', 'human', null, null, 'test'); +select agent_memory.adm_create_member('botty', 'bot', null, null, 'test'); +select agent_memory.adm_create_scope('s1', 'first', null, 'test'); +select is((select count(*) from agent_memory.admin_log where action = 'create_scope'), 1::bigint, 'create_scope logs one row'); + +select agent_memory.adm_grant('alice', 's1', 'write', null, 'test'); +select is((select count(*) from agent_memory.admin_log where action = 'grant'), 1::bigint, 'grant logs one row'); +select agent_memory.adm_grant('alice', 's1', 'read', null, 'test'); +select is((select access from agent_memory.scope_grants g join agent_memory.members m on m.id = g.member_id where m.display_name = 'alice'), + 'read', 'grant upserts'); +select throws_ok($$select agent_memory.adm_grant('alice', 's1', 'admin', null, 'test')$$, + 'P0001', 'Access must be read or write', 'bad access refused'); + +select agent_memory.adm_issue_token('alice', 'laptop', 'hash-alice-1', null, null, 'test'); +select is((select count(*) from agent_memory.admin_log where action = 'issue_token'), 1::bigint, 'issue_token logs one row'); +select is((select count(*) from agent_memory.admin_log + where action = 'issue_token' and (details::text like '%token_hash%' or details::text like '%amm_%' or details::text like '%hash-alice-1%')), + 0::bigint, 'issue_token log holds no hash or token'); +select is(agent_memory.resolve_token('hash-alice-1'), + (select id from agent_memory.members where display_name = 'alice'), 'resolve_token finds active member'); + +-- guard in resolve_token itself: a deactivated member with a still-live token must not resolve +insert into agent_memory.members (id, display_name, kind, deactivated_at) + values ('d0000000-0000-0000-0000-0000000000e1', 'erin', 'human', now()); +insert into agent_memory.access_tokens (member_id, name, token_hash) + values ('d0000000-0000-0000-0000-0000000000e1', 'live', 'hash-erin'); +select is((select count(*) from agent_memory.access_tokens where token_hash = 'hash-erin' and revoked_at is null), + 1::bigint, 'precondition: erin''s token is not revoked'); +select is(agent_memory.resolve_token('hash-erin'), null, 'resolve_token ignores an unrevoked token of a deactivated member'); +select is((select count(*) from agent_memory.resolve_member('hash-erin')), 0::bigint, + 'resolve_member returns no rows for an unrevoked token of a deactivated member'); + +-- deactivation +select agent_memory.adm_deactivate_member('alice', null, 'test'); +select is(agent_memory.resolve_token('hash-alice-1'), null, 'deactivated tokens stop resolving'); +select is((select count(*) from agent_memory.resolve_member('hash-alice-1')), 0::bigint, 'resolve_member returns no rows when deactivated'); +select is((select count(*) from agent_memory.scope_grants g join agent_memory.members m on m.id = g.member_id where m.display_name = 'alice'), + 0::bigint, 'deactivation deletes grants'); +select is((select count(*) from agent_memory.access_tokens t join agent_memory.members m on m.id = t.member_id + where m.display_name = 'alice' and t.revoked_at is null), 0::bigint, 'deactivation revokes tokens'); +select is((select count(*) from agent_memory.admin_log where action = 'deactivate_member'), 1::bigint, 'deactivate logs one row'); +select throws_ok($$select agent_memory.adm_grant('alice', 's1', 'read', null, 'test')$$, + 'P0001', 'Member ''alice'' is deactivated', 'grant to deactivated member refused'); +select throws_ok($$select agent_memory.adm_issue_token('alice', 'x', 'h2', null, null, 'test')$$, + 'P0001', 'Member ''alice'' is deactivated', 'token for deactivated member refused'); +select agent_memory.adm_reactivate_member('alice', null, 'test'); +select is((select deactivated_at from agent_memory.members where display_name = 'alice'), null, 'reactivate clears deactivated_at'); +select is((select count(*) from agent_memory.scope_grants g join agent_memory.members m on m.id = g.member_id where m.display_name = 'alice'), + 0::bigint, 'reactivate restores no grants'); +select is((select count(*) from agent_memory.admin_log where action = 'reactivate_member'), 1::bigint, 'reactivate logs one row'); + +-- admin flag +select throws_ok($$select agent_memory.adm_set_admin('botty', true, null, 'test')$$, + 'P0001', 'A bot can''t be an admin', 'bot cannot be admin'); +select agent_memory.adm_set_admin('alice', true, null, 'test'); +select is((select is_admin from agent_memory.resolve_member('hash-alice-1')), null, 'revoked token still does not resolve'); +select agent_memory.adm_issue_token('alice', 'second', 'hash-alice-2', null, null, 'test'); +select is((select is_admin from agent_memory.resolve_member('hash-alice-2')), true, 'resolve_member reports is_admin'); +insert into agent_memory.members (id, display_name, kind, is_admin, deactivated_at) + values ('d0000000-0000-0000-0000-0000000000d1', 'dave', 'human', true, now()); +select throws_ok($$select agent_memory.adm_set_admin('alice', false, null, 'test')$$, + 'P0001', 'Can''t remove the last active admin', 'last admin cannot be demoted, even beside a deactivated admin'); +select throws_ok($$select agent_memory.adm_deactivate_member('alice', null, 'test')$$, + 'P0001', 'Can''t remove the last active admin', 'last admin cannot be deactivated'); +select agent_memory.adm_set_admin('bob', true, null, 'test'); +select lives_ok($$select agent_memory.adm_set_admin('alice', false, null, 'test')$$, 'with two admins, demotion works'); +select is((select count(*) from agent_memory.admin_log where action = 'set_admin'), 3::bigint, 'set_admin logs one row each'); +insert into agent_memory.members (id, display_name, kind, is_admin) + values ('d0000000-0000-0000-0000-0000000000c1', 'carol', 'human', true); +select agent_memory.adm_deactivate_member('carol', null, 'test'); +select agent_memory.adm_reactivate_member('carol', null, 'test'); +select is((select is_admin from agent_memory.members where display_name = 'carol'), false, + 'deactivation removes admin and reactivation does not restore it'); + +-- duplicates and names +select throws_ok($$select agent_memory.adm_create_scope('s1', null, null, 'test')$$, 'P0001', 'Scope ''s1'' already exists', 'dup scope'); +select throws_ok($$select agent_memory.adm_create_member('bob', 'human', null, null, 'test')$$, 'P0001', 'Member ''bob'' already exists', 'dup member'); +select throws_ok($$select agent_memory.adm_create_scope('Bad Name', null, null, 'test')$$, 'P0001', + 'Scope names are lowercase letters, digits and hyphens, starting with a letter or digit (max 63)', 'bad scope name'); + +-- delete scope counts soft-deleted memories +insert into agent_memory.memories (id, scope_id, content, category, embedding, deleted_at) +select v.id::uuid, (select id from agent_memory.scopes where name = 's1'), 'c', 'other', + array_fill(0.1::real, array[384])::extensions.vector, v.d +from (values ('eeeeeeee-0000-0000-0000-000000000001', null::timestamptz), + ('eeeeeeee-0000-0000-0000-000000000002', now())) as v(id, d); +select agent_memory.adm_grant('bob', 's1', 'read', null, 'test'); +select throws_ok($$select agent_memory.adm_delete_scope('s1', null, 'test')$$, 'P0001', + 'Scope ''s1'' still holds 2 memories; move, delete or erase them first', 'delete counts live and soft-deleted'); +select agent_memory.erase('eeeeeeee-0000-0000-0000-000000000001'); +select agent_memory.erase('eeeeeeee-0000-0000-0000-000000000002'); +select lives_ok($$select agent_memory.adm_delete_scope('s1', null, 'test')$$, 'delete empty scope'); +select is((select count(*) from agent_memory.scope_grants), 0::bigint, 'scope grants gone'); + +-- revoke, tokens +select agent_memory.adm_create_scope('s2', null, null, 'test'); +select agent_memory.adm_grant('bob', 's2', 'read', null, 'test'); +select is(agent_memory.adm_revoke('bob', 's2', null, 'test'), true, 'revoke returns true'); +select is(agent_memory.adm_revoke('bob', 's2', null, 'test'), false, 'revoke again returns false'); +select agent_memory.adm_revoke_token((select id from agent_memory.access_tokens where token_hash = 'hash-alice-2'), null, 'test'); +select is(agent_memory.resolve_token('hash-alice-2'), null, 'revoked token stops resolving'); +select throws_ok($$select agent_memory.adm_revoke_token('00000000-0000-0000-0000-000000000000', null, 'test')$$, + 'P0001', 'Token 00000000-0000-0000-0000-000000000000 not found', 'unknown token'); +select is((select count(*) from agent_memory.admin_log where action = 'revoke'), 1::bigint, 'revoke logs only when a grant existed'); +select is((select count(*) from agent_memory.admin_log where action = 'delete_scope'), 1::bigint, 'delete_scope logs one row'); +select is((select count(*) from agent_memory.admin_log where action = 'revoke_token'), 1::bigint, 'revoke_token logs one row'); + +-- member role has no access +set local role agent_memory_member; +select throws_ok($$select * from agent_memory.admin_log$$, '42501', null, 'member cannot read admin_log'); +select throws_ok($$select agent_memory.adm_create_scope('zz', null, null, 'x')$$, '42501', null, 'member cannot call adm_*'); +reset role; +select is((select count(*) from pg_catalog.pg_proc p, (values ('anon'), ('authenticated'), ('service_role'), ('agent_memory_member')) r(rn) + where p.pronamespace = 'agent_memory'::regnamespace and (p.proname like 'adm\_%' or p.proname in ('resolve_member', 'resolve_token')) + and has_function_privilege(r.rn, p.oid, 'execute')), 0::bigint, 'no client role can execute adm_*, resolve_member or resolve_token'); +select is((select count(*) from agent_memory.admin_log), 21::bigint, 'total log rows match successful calls'); +select * from finish(); +rollback; diff --git a/supabase/tests/database/07_admin_wrappers.test.sql b/supabase/tests/database/07_admin_wrappers.test.sql new file mode 100644 index 0000000..03a9189 --- /dev/null +++ b/supabase/tests/database/07_admin_wrappers.test.sql @@ -0,0 +1,187 @@ +begin; +create extension if not exists pgtap with schema extensions; +select plan(68); + +-- Fixtures (as postgres): admins a1, a2; human h; bot b; deactivated admin ax; deactivated plain human x +insert into agent_memory.members (id, display_name, kind, is_admin, deactivated_at) values + ('a1000000-0000-0000-0000-000000000001', 'a1', 'human', true, null), + ('a2000000-0000-0000-0000-000000000002', 'a2', 'human', true, null), + ('c0000000-0000-0000-0000-00000000000c', 'h', 'human', false, null), + ('b0000000-0000-0000-0000-00000000000b', 'b', 'bot', false, null), + ('ae000000-0000-0000-0000-0000000000ae', 'ax', 'human', true, now()), + ('d0000000-0000-0000-0000-0000000000d0', 'x', 'human', false, now()); +insert into agent_memory.scopes (name) values ('s1'); +insert into agent_memory.access_tokens (id, member_id, name, token_hash) values + ('11111111-0000-0000-0000-0000000000a2', 'a2000000-0000-0000-0000-000000000002', 'a2 laptop', 'hash-a2'), + ('11111111-0000-0000-0000-0000000000a1', 'a1000000-0000-0000-0000-000000000001', 'a1 only', 'hash-a1'); + +-- privileges +select ok(not has_function_privilege('agent_memory_member', 'agent_memory.adm_set_admin(text,boolean,uuid,text)', 'execute'), 'member cannot execute adm_set_admin'); +select ok(not has_function_privilege('agent_memory_member', 'agent_memory.adm_reactivate_member(text,uuid,text)', 'execute'), 'member cannot execute adm_reactivate_member'); +select ok(not has_function_privilege('agent_memory_member', 'agent_memory.adm_grant(text,text,text,uuid,text)', 'execute'), 'member cannot execute adm_grant'); +select ok(not has_function_privilege('agent_memory_member', 'agent_memory.require_admin()', 'execute'), 'member cannot execute require_admin'); +select ok(has_function_privilege('agent_memory_member', 'agent_memory.admin_grant(text,text,text)', 'execute'), 'member can execute admin_grant'); +select ok(not has_function_privilege('anon', 'agent_memory.admin_grant(text,text,text)', 'execute'), 'anon cannot execute admin_grant'); +select ok(not has_function_privilege('authenticated', 'agent_memory.admin_list_members()', 'execute'), 'authenticated cannot execute admin_list_members'); + +-- non-admins and the deactivated admin: all 12 wrappers refuse +create temp table callers (who text, id uuid); +insert into callers values + ('h', 'c0000000-0000-0000-0000-00000000000c'), + ('b', 'b0000000-0000-0000-0000-00000000000b'), + ('ax', 'ae000000-0000-0000-0000-0000000000ae'); +grant all on callers to agent_memory_member; + +do $$ +declare + c record; + r text; +begin + for c in select * from callers order by who loop + perform set_config('agent_memory.member_id', c.id::text, true); + set local role agent_memory_member; + for r in select unnest(array[ + $q$select agent_memory.admin_create_scope('zz', null)$q$, + $q$select agent_memory.admin_delete_scope('s1')$q$, + $q$select agent_memory.admin_create_member('zz', 'human', null)$q$, + $q$select agent_memory.admin_deactivate_member('h')$q$, + $q$select agent_memory.admin_grant('h', 's1', 'read')$q$, + $q$select agent_memory.admin_revoke('h', 's1')$q$, + $q$select agent_memory.admin_issue_token('h', 'n', 'hz')$q$, + $q$select agent_memory.admin_revoke_token('11111111-0000-0000-0000-0000000000a2')$q$, + $q$select * from agent_memory.admin_list_scopes()$q$, + $q$select * from agent_memory.admin_list_members()$q$, + $q$select * from agent_memory.admin_list_grants(null, null)$q$, + $q$select * from agent_memory.admin_list_tokens('h')$q$ + ]) loop + begin + execute r; + raise exception 'NOT REFUSED: % as %', r, c.who; + exception when insufficient_privilege then + null; + end; + end loop; + reset role; + end loop; +end $$; +select pass('all 12 wrappers refuse h, b and ax with 42501'); + +-- explicit throws_ok per caller, per wrapper +select set_config('agent_memory.member_id', 'c0000000-0000-0000-0000-00000000000c', true); +set local role agent_memory_member; +select throws_ok($$select agent_memory.admin_create_scope('zz', null)$$, '42501', 'Admin only', 'h: create_scope'); +select throws_ok($$select agent_memory.admin_delete_scope('s1')$$, '42501', 'Admin only', 'h: delete_scope'); +select throws_ok($$select agent_memory.admin_create_member('zz', 'human', null)$$, '42501', 'Admin only', 'h: create_member'); +select throws_ok($$select agent_memory.admin_deactivate_member('b')$$, '42501', 'Admin only', 'h: deactivate_member'); +select throws_ok($$select agent_memory.admin_grant('h', 's1', 'read')$$, '42501', 'Admin only', 'h: grant (even to self)'); +select throws_ok($$select agent_memory.admin_revoke('h', 's1')$$, '42501', 'Admin only', 'h: revoke'); +select throws_ok($$select agent_memory.admin_issue_token('h', 'n', 'hz')$$, '42501', 'Admin only', 'h: issue_token'); +select throws_ok($$select agent_memory.admin_revoke_token('11111111-0000-0000-0000-0000000000a2')$$, '42501', 'Admin only', 'h: revoke_token'); +select throws_ok($$select * from agent_memory.admin_list_scopes()$$, '42501', 'Admin only', 'h: list_scopes'); +select throws_ok($$select * from agent_memory.admin_list_members()$$, '42501', 'Admin only', 'h: list_members'); +select throws_ok($$select * from agent_memory.admin_list_grants(null, null)$$, '42501', 'Admin only', 'h: list_grants'); +select throws_ok($$select * from agent_memory.admin_list_tokens('h')$$, '42501', 'Admin only', 'h: list_tokens'); +reset role; + +select set_config('agent_memory.member_id', 'b0000000-0000-0000-0000-00000000000b', true); +set local role agent_memory_member; +select throws_ok($$select agent_memory.admin_grant('b', 's1', 'write')$$, '42501', 'Admin only', 'bot: grant'); +select throws_ok($$select * from agent_memory.admin_list_members()$$, '42501', 'Admin only', 'bot: list_members'); +reset role; + +select set_config('agent_memory.member_id', 'ae000000-0000-0000-0000-0000000000ae', true); +set local role agent_memory_member; +select throws_ok($$select agent_memory.admin_create_scope('zz', null)$$, '42501', 'Admin only', 'deactivated admin: create_scope'); +select throws_ok($$select * from agent_memory.admin_list_members()$$, '42501', 'Admin only', 'deactivated admin: list_members'); +reset role; + +-- no caller identity at all +select set_config('agent_memory.member_id', '', true); +set local role agent_memory_member; +select throws_ok($$select * from agent_memory.admin_list_scopes()$$, '42501', 'Admin only', 'no member id: refused'); +reset role; + +-- as a1 +select set_config('agent_memory.member_id', 'a1000000-0000-0000-0000-000000000001', true); +set local role agent_memory_member; +select lives_ok($$select agent_memory.admin_create_scope('s2', 'second')$$, 'a1 creates scope'); +select lives_ok($$select agent_memory.admin_create_member('newbie', 'human', null)$$, 'a1 creates member'); +select lives_ok($$select agent_memory.admin_grant('h', 's1', 'write')$$, 'a1 grants h'); +select lives_ok($$select agent_memory.admin_grant('a1', 's1', 'read')$$, 'a1 may grant self'); +select is(agent_memory.admin_revoke('h', 's2'), false, 'revoke of absent grant returns false'); +select is(agent_memory.admin_revoke('h', 's1'), true, 'revoke of present grant returns true'); +select lives_ok($$select agent_memory.admin_issue_token('h', 'h laptop', 'hash-h-1')$$, 'a1 issues token for h'); +reset role; + +select is((select count(*) from agent_memory.admin_log + where actor_member_id = 'a1000000-0000-0000-0000-000000000001' and actor_label = 'a1' + and action in ('create_scope', 'create_member', 'grant', 'revoke', 'issue_token')), 6::bigint, + 'log rows carry a1 as actor with label a1'); +select is((select count(*) from agent_memory.admin_log where details::text like '%hash-h-1%'), 0::bigint, 'log holds no hash'); +select is((select expires_at from agent_memory.access_tokens where token_hash = 'hash-h-1'), null, 'issued token has no expiry'); + +-- other-admin guard +select set_config('agent_memory.member_id', 'a1000000-0000-0000-0000-000000000001', true); +set local role agent_memory_member; +select throws_ok($$select agent_memory.admin_deactivate_member('a2')$$, 'P0001', 'Member ''a2'' is an admin; manage admins from the shell', 'deactivate refuses another admin'); +select throws_ok($$select agent_memory.admin_grant('a2', 's1', 'read')$$, 'P0001', 'Member ''a2'' is an admin; manage admins from the shell', 'grant refuses another admin'); +select throws_ok($$select agent_memory.admin_revoke('a2', 's1')$$, 'P0001', 'Member ''a2'' is an admin; manage admins from the shell', 'revoke refuses another admin'); +select throws_ok($$select agent_memory.admin_issue_token('a2', 'n', 'hash-evil')$$, 'P0001', 'Member ''a2'' is an admin; manage admins from the shell', 'issue_token refuses another admin'); +select throws_ok($$select * from agent_memory.admin_list_tokens('a2')$$, 'P0001', 'Member ''a2'' is an admin; manage admins from the shell', 'list_tokens refuses another admin'); +select throws_ok($$select agent_memory.admin_revoke_token('11111111-0000-0000-0000-0000000000a2')$$, 'P0001', 'Member ''a2'' is an admin; manage admins from the shell', 'revoke_token refuses another admin''s token'); +select throws_ok($$select agent_memory.admin_deactivate_member('a1')$$, 'P0001', 'You can''t deactivate yourself', 'cannot deactivate self'); +-- deactivated admin (is_admin still set in this fixture) is also protected +select throws_ok($$select agent_memory.admin_grant('ax', 's1', 'read')$$, 'P0001', 'Member ''ax'' is an admin; manage admins from the shell', 'flagged-admin ax also protected'); +reset role; + +select is((select revoked_at from agent_memory.access_tokens where id = '11111111-0000-0000-0000-0000000000a2'), null, 'a2 token untouched'); +select is((select count(*) from agent_memory.access_tokens where token_hash = 'hash-evil'), 0::bigint, 'no token issued for a2'); +select is((select deactivated_at from agent_memory.members where display_name = 'a2'), null, 'a2 not deactivated'); +select is((select count(*) from agent_memory.admin_log where target in ('a2', 'ax')), 0::bigint, 'refusals wrote no log rows'); + +-- revoke_token and the last-live-token rule +select set_config('agent_memory.member_id', 'a1000000-0000-0000-0000-000000000001', true); +set local role agent_memory_member; +select throws_ok($$select agent_memory.admin_revoke_token('11111111-0000-0000-0000-0000000000a1')$$, 'P0001', 'You can''t revoke your last live token', 'refuses own last live token'); +select lives_ok($$select agent_memory.admin_issue_token('a1', 'a1 laptop', 'hash-a1-2')$$, 'a1 issues own token'); +select lives_ok($$select agent_memory.admin_revoke_token('11111111-0000-0000-0000-0000000000a1')$$, 'with two live tokens, revoke one'); +select throws_ok($$select agent_memory.admin_revoke_token((select id from agent_memory.admin_list_tokens('a1') where revoked_at is null))$$, + 'P0001', 'You can''t revoke your last live token', 'now the remaining one is last'); +select throws_ok($$select agent_memory.admin_revoke_token('99999999-9999-9999-9999-999999999999')$$, 'P0001', + 'Token 99999999-9999-9999-9999-999999999999 not found', 'unknown token id'); +select lives_ok($$select agent_memory.admin_revoke_token((select id from agent_memory.admin_list_tokens('h') limit 1))$$, 'revoke h token'); +reset role; + +-- token for deactivated / unknown members +select set_config('agent_memory.member_id', 'a1000000-0000-0000-0000-000000000001', true); +create temp table tcount as select count(*) n from agent_memory.access_tokens; +set local role agent_memory_member; +select throws_ok($$select agent_memory.admin_issue_token('ghost', 'n', 'hg')$$, 'P0001', 'Member ''ghost'' not found', 'issue_token unknown member'); +select throws_ok($$select agent_memory.admin_issue_token('x', 'n', 'hx')$$, 'P0001', 'Member ''x'' is deactivated', 'issue_token deactivated member'); +reset role; +select is((select count(*) from agent_memory.access_tokens), (select n from tcount), 'token count unchanged by refusals'); + +-- exact name matching +set local role agent_memory_member; +select throws_ok($$select agent_memory.admin_grant('H', 's1', 'read')$$, 'P0001', 'Member ''H'' not found', 'name match is case sensitive'); +select throws_ok($$select agent_memory.admin_grant('h ', 's1', 'read')$$, 'P0001', 'Member ''h '' not found', 'name match is exact (trailing space)'); +reset role; + +-- listings +set local role agent_memory_member; +select is((select is_admin from agent_memory.admin_list_members() where name = 'a2'), true, 'list_members shows a2 as admin'); +select is((select deactivated from agent_memory.admin_list_members() where name = 'x'), true, 'list_members shows x deactivated'); +select is((select live_tokens from agent_memory.admin_list_members() where name = 'a1'), 1, 'list_members counts a1 live tokens'); +select is((select writers from agent_memory.admin_list_scopes() where name = 's1'), 0, 'list_scopes writers'); +select is((select readers from agent_memory.admin_list_scopes() where name = 's1'), 1, 'list_scopes readers'); +select is((select count(*) from agent_memory.admin_list_grants('s1', null)), 1::bigint, 'list_grants filtered by scope'); +select is((select count(*) from agent_memory.admin_list_grants(null, 'h')), 0::bigint, 'list_grants filtered by member'); +select is((select count(*) from agent_memory.admin_list_grants(null, null)), 1::bigint, 'list_grants unfiltered'); +select is((select count(*) from agent_memory.admin_list_tokens('h')), 1::bigint, 'list_tokens returns h token'); +reset role; +select is((select array_agg(nm order by ord) from pg_proc p, lateral unnest(p.proargnames) with ordinality as u(nm, ord) + where p.pronamespace = 'agent_memory'::regnamespace and p.proname = 'admin_list_tokens' and ord > 1), + array['id', 'name', 'created_at', 'last_used_at', 'revoked_at'], 'list_tokens columns carry no hash'); + +select * from finish(); +rollback; diff --git a/tests/e2e/function.test.ts b/tests/e2e/function.test.ts index fe0d28d..54e2597 100644 --- a/tests/e2e/function.test.ts +++ b/tests/e2e/function.test.ts @@ -4,6 +4,7 @@ import { assert, assertEquals, assertStringIncludes } from '@std/assert'; import { Client, StreamableHTTPClientTransport } from 'npm:@modelcontextprotocol/client@2.4.0'; import { adminSql, makeWorld, type World } from '../helpers/fixtures.ts'; import { generateToken, hashToken } from '../../supabase/functions/_shared/tokens.ts'; +import { setAdmin } from '../../scripts/lib/admin-db.ts'; const URL_ = Deno.env.get('FUNCTION_URL') ?? 'http://127.0.0.1:54321/functions/v1/agent-memory'; @@ -31,6 +32,16 @@ async function post(headers: Record, path = '', body: unknown = return { status: res.status, body: out }; } +/** What a caller sees when it calls a tool: the thrown protocol error, or the tool-error text. */ +async function callOutcome(c: Client, name: string, args: Record): Promise { + try { + const r = await c.callTool({ name, arguments: args }); + return `result:${r.isError ? 'error:' : ''}${text(r)}`; + } catch (e) { + return `thrown:${e instanceof Error ? e.message : e}`; + } +} + Deno.test('edge function end-to-end over MCP', async () => { const sql = adminSql(); let w: World | undefined; @@ -47,6 +58,10 @@ Deno.test('edge function end-to-end over MCP', async () => { clients.push(c); return c; }; + const sfx = crypto.randomUUID().slice(0, 8); + const adminName = `e2e-admin-${sfx}`; + const newName = `e2e-new-${sfx}`; + const newScope = `e2e-scope-${sfx}`; try { const world = await makeWorld(sql); w = world; @@ -156,6 +171,62 @@ Deno.test('edge function end-to-end over MCP', async () => { assertEquals(parse(await c.callTool({ name: 'list_scopes', arguments: {} })), { count: 0, scopes: [] }); }); + await t('admin token sees 23 tools; non-admin and bot see the 11 originals', async () => { + const [a] = await sql` + insert into agent_memory.members (display_name, kind) values (${adminName}, 'human') returning id`; + await setAdmin(sql, adminName, true); + const admin = await issue(a.id); + const names = async (tok: string) => (await (await open(tok)).listTools()).tools.map((x) => x.name); + const adminTools = await names(admin.token); + assertEquals(adminTools.length, 23); + assertEquals(adminTools.filter((n) => n.startsWith('admin_')).length, 12); + const base = await names(rw.token); + assertEquals(base.length, 11); + assert(!base.some((n) => n.startsWith('admin_'))); + assertEquals(await names(none.token), base); + const bot = await issue(world.bw.id); + assertEquals(await names(bot.token), base); + assertEquals(adminTools.slice(0, 11), base); + }); + + await t('non-admin calling admin_create_scope gets the unknown-tool error', async () => { + const c = await open(rw.token); + const a = await callOutcome(c, 'admin_create_scope', { name: newScope }); + const b = await callOutcome(c, 'no_such_tool', { name: newScope }); + assertEquals(a.replace('admin_create_scope', 'X'), b.replace('no_such_tool', 'X')); + const [row] = await sql`select 1 from agent_memory.scopes where name = ${newScope}`; + assertEquals(row, undefined); + }); + + await t('admin onboards a member over MCP; deactivation ends their access', async () => { + const [a] = await sql`select id from agent_memory.members where display_name = ${adminName}`; + const admin = await open((await issue(a.id)).token); + const ok = async (name: string, args: Record) => { + const r = await admin.callTool({ name, arguments: args }); + assert(!r.isError, `${name}: ${text(r)}`); + return parse(r); + }; + await ok('admin_create_member', { name: newName, kind: 'human' }); + await ok('admin_grant', { member: newName, scope: world.alpha.name, access: 'read' }); + const issued = await ok('admin_issue_token', { member: newName, name: 'e2e' }); + assert(typeof issued.token === 'string' && issued.token.startsWith('amm_')); + + const nc = await open(issued.token); + const scopes = parse(await nc.callTool({ name: 'list_scopes', arguments: {} })); + assertEquals(scopes.count, 1); + assertEquals(scopes.scopes[0].scope, world.alpha.name); + assertEquals(scopes.scopes[0].access, 'read'); + assertEquals((await nc.listTools()).tools.length, 11); + + await ok('admin_deactivate_member', { name: newName }); + const r = await post({ authorization: `Bearer ${issued.token}` }, '', { + jsonrpc: '2.0', + id: 1, + method: 'tools/list', + }); + assertEquals(r.status, 401); + }); + await t('/embed rejects oversize and malformed bodies', async () => { const auth = { authorization: `Bearer ${rw.token}` }; const big = await post(auth, '/embed', { text: 'x'.repeat(20_001) }); @@ -181,6 +252,15 @@ Deno.test('edge function end-to-end over MCP', async () => { } finally { try { for (const c of clients) await c.close().catch(() => {}); + // Members this test created (the admin and the onboarded one), with their tokens, grants and log rows. + const created = await sql`select id from agent_memory.members where display_name in (${adminName}, ${newName})`; + const ids = created.map((r) => r.id as string); + await sql`delete from agent_memory.admin_log + where actor_member_id = any(${ids}::uuid[]) or target in (${adminName}, ${newName}, ${newScope}) + or details->>'member' in (${adminName}, ${newName})`; + await sql`delete from agent_memory.access_tokens where member_id = any(${ids}::uuid[])`; + await sql`delete from agent_memory.scope_grants where member_id = any(${ids}::uuid[])`; + await sql`delete from agent_memory.members where id = any(${ids}::uuid[])`; await w?.cleanup(); } finally { await sql.end(); diff --git a/tests/integration/admin-store.test.ts b/tests/integration/admin-store.test.ts new file mode 100644 index 0000000..5c4730f --- /dev/null +++ b/tests/integration/admin-store.test.ts @@ -0,0 +1,217 @@ +import { assert, assertEquals } from '@std/assert'; +import { connect, resolveMember } from '../../supabase/functions/_shared/db.ts'; +import { PgAdminStore } from '../../supabase/functions/_shared/admin-store.ts'; +import { StoreError } from '../../supabase/functions/_shared/limits.ts'; +import { setAdmin } from '../../scripts/lib/admin-db.ts'; +import { adminSql, LOCAL_DB_URL } from '../helpers/fixtures.ts'; + +const sfx = () => crypto.randomUUID().slice(0, 8); + +interface Env { + s: string; + pg: ReturnType; + admin: PgAdminStore; + plain: PgAdminStore; + adminId: string; + plainId: string; + other: string; // a second admin's name + /** Names created during the test, for log cleanup. */ + names: string[]; +} + +async function withEnv(fn: (e: Env) => Promise) { + const pg = adminSql(); + const app = connect(LOCAL_DB_URL); + const s = sfx(); + const mk = async (name: string) => + (await pg`insert into agent_memory.members (display_name, kind) values (${name}, 'human') returning id`)[0] + .id as string; + const adminName = `adm-${s}`, plainName = `plain-${s}`, other = `adm2-${s}`; + const names: string[] = []; + try { + const adminId = await mk(adminName); + const plainId = await mk(plainName); + await mk(other); + await setAdmin(pg, adminName, true); + await setAdmin(pg, other, true); + await fn({ + s, + pg, + admin: new PgAdminStore(app, adminId), + plain: new PgAdminStore(app, plainId), + adminId, + plainId, + other, + names, + }); + } finally { + // members cascade to grants and tokens; the log is keyed by fixed names carrying the suffix. + await pg`delete from agent_memory.members where display_name like ${'%' + s}`; + await pg`delete from agent_memory.scopes where name like ${'%' + s}`; + await pg`delete from agent_memory.admin_log where target like ${'%' + s + '%'} or actor_label like ${'%' + s}`; + await pg`delete from agent_memory.admin_log where actor_member_id is not null and not exists + (select 1 from agent_memory.members m where m.id = actor_member_id) and target like ${'%' + s + '%'}`; + await app.end(); + await pg.end(); + } +} + +const msg = (p: Promise) => + p.then(() => { + throw new Error('expected rejection'); + }, (e) => { + assert(e instanceof StoreError, `expected StoreError, got ${e}`); + return e.message; + }); + +Deno.test('an admin onboards a member end to end; the issued token resolves', async () => { + await withEnv(async ({ admin, s, pg }) => { + const scope = `team-${s}`, member = `newbie-${s}`; + await admin.createScope(scope, 'a scope'); + await admin.createMember(member, 'human', `${member}@example.com`); + await admin.grant(member, scope, 'write'); + const { id, token } = await admin.issueToken(member, 'laptop'); + assert(token.startsWith('amm_')); + const memberId = await resolveMember(pg, token); + assert(memberId); + assertEquals( + (await pg`select display_name from agent_memory.members where id = ${memberId}`)[0].display_name, + member, + ); + + const scopes = await admin.listScopes(); + assertEquals(scopes.find((x) => x.name === scope), { + name: scope, + description: 'a scope', + memories: 0, + deleted: 0, + readers: 0, + writers: 1, + }); + const m = (await admin.listMembers()).find((x) => x.name === member); + assertEquals(m, { + name: member, + kind: 'human', + email: `${member}@example.com`, + isAdmin: false, + deactivated: false, + liveTokens: 1, + }); + const grants = await admin.listGrants({ scope }); + assertEquals(grants.length, 1); + assertEquals(grants[0].member, member); + assertEquals(grants[0].access, 'write'); + assert(typeof grants[0].grantedAt === 'string'); + assertEquals((await admin.listGrants({ member })).length, 1); + assertEquals((await admin.listGrants({ scope, member: `nobody-${s}` })).length, 0); + + const toks = await admin.listTokens(member); + assertEquals(toks.length, 1); + assertEquals(toks[0].id, id); + assertEquals(toks[0].name, 'laptop'); + assertEquals(toks[0].revokedAt, null); + assert(!JSON.stringify(toks).includes(token)); + + await admin.revokeToken(id); + assertEquals(await resolveMember(pg, token), null); + assert((await admin.listTokens(member))[0].revokedAt); + + assertEquals(await admin.revoke(member, scope), true); + assertEquals(await admin.revoke(member, scope), false); + await admin.deactivateMember(member); + assertEquals((await admin.listMembers()).find((x) => x.name === member)?.deactivated, true); + await admin.deleteScope(scope); + assertEquals((await admin.listScopes()).find((x) => x.name === scope), undefined); + }); +}); + +Deno.test('the log never holds the token or its hash', async () => { + await withEnv(async ({ admin, s, pg }) => { + const member = `lg-${s}`; + await admin.createMember(member, 'bot'); + const { token } = await admin.issueToken(member, 'k'); + const { hashToken } = await import('../../supabase/functions/_shared/tokens.ts'); + const hash = await hashToken(token); + const rows = await pg`select details::text as d, target from agent_memory.admin_log where target like ${ + '%' + s + '%' + }`; + assert(rows.length >= 2); + for (const r of rows) assert(!r.d?.includes(token) && !r.d?.includes(hash)); + }); +}); + +Deno.test('rule errors surface verbatim as StoreError', async () => { + await withEnv(async ({ admin, other, s }) => { + const sc = `dup-${s}`; + await admin.createScope(sc); + assertEquals(await msg(admin.createScope(sc)), `Scope '${sc}' already exists`); + assertEquals( + await msg(admin.createScope(`Bad Name ${s}`)), + 'Scope names are lowercase letters, digits and hyphens, starting with a letter or digit (max 63)', + ); + assertEquals(await msg(admin.deleteScope(`nope-${s}`)), `Scope 'nope-${s}' not found`); + assertEquals(await msg(admin.createMember(`adm-${s}`, 'human')), `Member 'adm-${s}' already exists`); + assertEquals(await msg(admin.grant(`ghost-${s}`, sc, 'read')), `Member 'ghost-${s}' not found`); + assertEquals(await msg(admin.listTokens(`ghost-${s}`)), `Member 'ghost-${s}' not found`); + const adminMsg = `Member '${other}' is an admin; manage admins from the shell`; + assertEquals(await msg(admin.deactivateMember(other)), adminMsg); + assertEquals(await msg(admin.grant(other, sc, 'read')), adminMsg); + assertEquals(await msg(admin.revoke(other, sc)), adminMsg); + assertEquals(await msg(admin.issueToken(other, 't')), adminMsg); + assertEquals(await msg(admin.listTokens(other)), adminMsg); + assertEquals(await msg(admin.deactivateMember(`adm-${s}`)), "You can't deactivate yourself"); + assertEquals( + await msg(admin.revokeToken('00000000-0000-0000-0000-000000000000')), + 'Token 00000000-0000-0000-0000-000000000000 not found', + ); + assertEquals(await msg(admin.revokeToken('not-a-uuid')), 'Token not-a-uuid not found'); + }); +}); + +Deno.test('a deactivated member cannot be granted or issued a token', async () => { + await withEnv(async ({ admin, s }) => { + const sc = `d-${s}`, m = `gone-${s}`; + await admin.createScope(sc); + await admin.createMember(m, 'human'); + await admin.deactivateMember(m); + assertEquals(await msg(admin.grant(m, sc, 'read')), `Member '${m}' is deactivated`); + assertEquals(await msg(admin.issueToken(m, 't')), `Member '${m}' is deactivated`); + }); +}); + +Deno.test('a non-admin gets Admin only from every method', async () => { + await withEnv(async ({ plain, s }) => { + const calls: [string, () => Promise][] = [ + ['listScopes', () => plain.listScopes()], + ['createScope', () => plain.createScope(`x-${s}`)], + ['deleteScope', () => plain.deleteScope(`x-${s}`)], + ['listMembers', () => plain.listMembers()], + ['createMember', () => plain.createMember(`x-${s}`, 'human')], + ['deactivateMember', () => plain.deactivateMember(`x-${s}`)], + ['listGrants', () => plain.listGrants()], + ['grant', () => plain.grant(`x-${s}`, `x-${s}`, 'read')], + ['revoke', () => plain.revoke(`x-${s}`, `x-${s}`)], + ['issueToken', () => plain.issueToken(`x-${s}`, 't')], + ['listTokens', () => plain.listTokens(`x-${s}`)], + ['revokeToken', () => plain.revokeToken('00000000-0000-0000-0000-000000000000')], + ]; + for (const [n, f] of calls) assertEquals(await msg(f()), 'Admin only', n); + }); +}); + +Deno.test('an unmapped database error is logged and becomes a generic StoreError', async () => { + const app = connect(LOCAL_DB_URL); + const orig = console.error; + const seen: unknown[][] = []; + console.error = (...a: unknown[]) => void seen.push(a); + try { + // A member id that is not a uuid makes the database raise 22P02, which no method maps except revokeToken. + assertEquals(await msg(new PgAdminStore(app, 'not-a-uuid').listScopes()), 'Database error'); + } finally { + console.error = orig; + await app.end(); + } + assertEquals(seen.length, 1); + assertEquals(seen[0][0], 'database error'); + assertEquals(seen[0][1], '22P02'); +}); diff --git a/tests/integration/admin.test.ts b/tests/integration/admin.test.ts index 9e6de8b..58807cf 100644 --- a/tests/integration/admin.test.ts +++ b/tests/integration/admin.test.ts @@ -1,21 +1,27 @@ import { assert, assertEquals, assertRejects, assertStringIncludes } from '@std/assert'; import { hashToken } from '../../supabase/functions/_shared/tokens.ts'; import { + adminLog, createMember, createScope, + deactivateMember, + deleteScope, eraseMemory, firstLine, grant, issueToken, listDeleted, listGrants, + listMembers, listScopes, listTokens, parseExpires, + reactivateMember, restoreMemories, restoreMemory, revoke, revokeToken, + setAdmin, } from '../../scripts/lib/admin-db.ts'; import { adminSql, LOCAL_DB_URL } from '../helpers/fixtures.ts'; @@ -88,7 +94,7 @@ Deno.test('unknown names and bad scope names give friendly errors', () => await assertRejects(() => revoke(sql, `bot-${s}`, `nope-${s}`), Error, `Scope 'nope-${s}' not found`); await assertRejects(() => issueToken(sql, `ghost-${s}`, 'n'), Error, `Member 'ghost-${s}' not found`); await assertRejects(() => listTokens(sql, `ghost-${s}`), Error, `Member 'ghost-${s}' not found`); - await assertRejects(() => createScope(sql, 'Bad_Name'), Error, "Invalid scope name 'Bad_Name'"); + await assertRejects(() => createScope(sql, 'Bad_Name'), Error, 'Scope names are lowercase letters'); await assertRejects(() => grant(sql, `bot-${s}`, `team-${s}`, 'admin' as 'read'), Error, 'read or write'); })); @@ -312,3 +318,106 @@ Deno.test('restore takes several ids, or filters with --yes', () => const r = await restoreMemories(sql, ['not-a-uuid']); assertEquals(r, { restored: [], missing: ['not-a-uuid'] }); })); + +/** Run with no other active admin, restoring the previous flags afterwards. */ +async function aloneAsAdmin(sql: AdminSql, fn: () => Promise) { + const prior = (await sql`select id from agent_memory.members where is_admin`).map((r) => r.id as string); + await sql`update agent_memory.members set is_admin = false where is_admin`; + try { + await fn(); + } finally { + await sql`update agent_memory.members set is_admin = false where is_admin`; + await sql`update agent_memory.members set is_admin = true where id = any(${prior}::uuid[])`; + } +} + +Deno.test('set-admin round trip, refuses a bot and the last admin', () => + withAdmin(async (sql, s) => { + await aloneAsAdmin(sql, async () => { + await createMember(sql, `ann-${s}`, { kind: 'human' }); + await createMember(sql, `bob-${s}`, { kind: 'human' }); + await createMember(sql, `bot-${s}`, { kind: 'bot' }); + const flag = async (n: string) => + (await sql`select is_admin from agent_memory.members where display_name = ${n}`)[0].is_admin as boolean; + await setAdmin(sql, `ann-${s}`, true); + assertEquals(await flag(`ann-${s}`), true); + await setAdmin(sql, `ann-${s}`, true); // idempotent + await assertRejects(() => setAdmin(sql, `bot-${s}`, true), Error, "A bot can't be an admin"); + await assertRejects(() => setAdmin(sql, `ann-${s}`, false), Error, "Can't remove the last active admin"); + await setAdmin(sql, `bob-${s}`, true); + await setAdmin(sql, `ann-${s}`, false); + assertEquals(await flag(`ann-${s}`), false); + const via = await cli('set-admin', `ann-${s}`, 'on'); + assertEquals(via.code, 0); + assertEquals(await flag(`ann-${s}`), true); + }); + })); + +Deno.test('deactivate stops the token resolving; reactivate restores it but not admin', () => + withAdmin(async (sql, s) => { + await aloneAsAdmin(sql, async () => { + await createMember(sql, `ann-${s}`, { kind: 'human' }); + await createMember(sql, `bob-${s}`, { kind: 'human' }); + await setAdmin(sql, `ann-${s}`, true); + await setAdmin(sql, `bob-${s}`, true); + await createScope(sql, `team-${s}`); + await grant(sql, `ann-${s}`, `team-${s}`, 'write'); + const token = await issueToken(sql, `ann-${s}`, 'laptop'); + assert(await resolve(sql, token)); + await deactivateMember(sql, `ann-${s}`); + assertEquals(await resolve(sql, token), null); + await assertRejects(() => grant(sql, `ann-${s}`, `team-${s}`, 'read'), Error, `Member 'ann-${s}' is deactivated`); + const row = (await listMembers(sql)).find((m) => m.name === `ann-${s}`)!; + assertEquals(row.deactivated, true); + assertEquals(row.is_admin, false); + assertEquals(row.live_tokens, 0); + await reactivateMember(sql, `ann-${s}`); + assertEquals((await listMembers(sql)).find((m) => m.name === `ann-${s}`)!.deactivated, false); + assertEquals((await listMembers(sql)).find((m) => m.name === `ann-${s}`)!.is_admin, false); + assertEquals((await cli('deactivate', `ann-${s}`)).code, 0); + assertEquals((await cli('reactivate', `ann-${s}`)).code, 0); + await assertRejects(() => deactivateMember(sql, `ghost-${s}`), Error, `Member 'ghost-${s}' not found`); + }); + })); + +Deno.test('delete-scope refuses while memories remain, then deletes', () => + withAdmin(async (sql, s) => { + const sc = await createScope(sql, `team-${s}`); + await addMemory(sql, sc.id, 'live one'); + await addMemory(sql, sc.id, 'gone one', true); + await assertRejects( + () => deleteScope(sql, `team-${s}`), + Error, + `Scope 'team-${s}' still holds 2 memories; move, delete or erase them first`, + ); + const r = await cli('delete-scope', `team-${s}`); + assertEquals(r.code, 1); + assertStringIncludes(r.err, `Error: Scope 'team-${s}' still holds 2 memories; move, delete or erase them first`); + const empty = await createScope(sql, `empty-${s}`); + await deleteScope(sql, `empty-${s}`); + assertEquals((await listScopes(sql)).some((x) => x.id === empty.id), false); + })); + +Deno.test('admin-log is newest first, filters by actor, and holds no token', () => + withAdmin(async (sql, s) => { + await createMember(sql, `bot-${s}`, { kind: 'bot' }); + await createScope(sql, `team-${s}`); + await grant(sql, `bot-${s}`, `team-${s}`, 'read'); + await issueToken(sql, `bot-${s}`, 'laptop'); + const rows = (await adminLog(sql, { limit: 200 })).filter((r) => r.target.endsWith(s)); + assertEquals(rows.map((r) => r.action), ['issue_token', 'grant', 'create_scope', 'create_member']); + assertEquals(rows[0].actor, grantorName()); + for (let i = 1; i < rows.length; i++) assert(rows[i - 1].at >= rows[i].at); + assertEquals((await adminLog(sql, { actor: 'nobody-' + s })).length, 0); + assert((await adminLog(sql, { actor: grantorName(), limit: 1 })).length === 1); + const out = (await cli('admin-log', '--limit', '200')).out; + assertStringIncludes(out, `bot-${s}`); + assertEquals(out.includes('amm_'), false); + assertEquals(JSON.stringify(rows).includes('amm_'), false); + const recent = await cli('admin-log', '--since', '1d', '--limit', '3'); + assertEquals(recent.code, 0); + })); + +function grantorName() { + return Deno.env.get('USER') || 'admin'; +} diff --git a/tests/integration/backup.test.ts b/tests/integration/backup.test.ts index f05deae..bf72c0b 100644 --- a/tests/integration/backup.test.ts +++ b/tests/integration/backup.test.ts @@ -32,8 +32,8 @@ async function snapshotRows() { from agent_memory.memories order by id`; const grants = await sql`select scope_id, member_id, access, granted_at::text, granted_by from agent_memory.scope_grants order by member_id`; - const members = - await sql`select id, display_name, kind, email, auth_user_id, created_at::text from agent_memory.members order by id`; + const members = await sql`select id, display_name, kind, email, auth_user_id, created_at::text, + is_admin, deactivated_at::text from agent_memory.members order by id`; const scopes = await sql`select id, description, created_at::text, name from agent_memory.scopes order by name`; return { mem, grants, members, scopes }; } @@ -52,6 +52,9 @@ Deno.test('backup and restore-backup round trip', async () => { values ('bk-ann', 'human', 'ann@example.test', gen_random_uuid()) returning id`; const [bot] = await sql`insert into agent_memory.members (display_name, kind) values ('bk-bot', 'bot') returning id`; + await sql`insert into agent_memory.members (display_name, kind, is_admin) values ('bk-root', 'human', true)`; + await sql`insert into agent_memory.members (display_name, kind, deactivated_at) + values ('bk-gone', 'human', '2026-01-02 03:04:05.678901+00')`; await sql`insert into agent_memory.scope_grants (scope_id, member_id, access, granted_by) values (${a.id}, ${ann.id}, 'write', 'tester'), (${b.id}, ${bot.id}, 'read', 'tester')`; const mk = async (scope: string, content: string, seed: number, by: string, extra = sql`null`) => { @@ -84,6 +87,13 @@ Deno.test('backup and restore-backup round trip', async () => { assertEquals(data.format, 'agent-memory-supabase-backup'); assertEquals(data.version, 1); assertEquals(data.memories.length, 3); + const bkRoot = data.members.find((m: { displayName: string }) => m.displayName === 'bk-root'); + assertEquals(bkRoot.isAdmin, true); + assertEquals(bkRoot.deactivatedAt, null); + assertEquals( + data.members.find((m: { displayName: string }) => m.displayName === 'bk-gone').deactivatedAt, + '2026-01-02T03:04:05.678901Z', + ); assertEquals(data.memories.find((m: { id: string }) => m.id === dead).deletedAt !== null, true); assertEquals(data.memories.find((m: { id: string }) => m.id === live).deletedAt, null); assertEquals(data.memories.find((m: { id: string }) => m.id === live).createdBy, 'bk-ann'); @@ -110,7 +120,12 @@ Deno.test('backup and restore-backup round trip', async () => { const after = await snapshotRows(); assertEquals(after.scopes.length, 2); assert(before.members.some((m) => m.auth_user_id !== null)); - assertEquals(after.members, before.members); // incl. auth_user_id and created_at + assertEquals(after.members, before.members); // incl. auth_user_id, created_at, is_admin, deactivated_at + const flags = new Map(after.members.map((m) => [m.display_name, m])); + assertEquals(flags.get('bk-root')!.is_admin, true); + assertEquals(flags.get('bk-ann')!.is_admin, false); + assertEquals(flags.get('bk-gone')!.deactivated_at, '2026-01-02 03:04:05.678901+00'); + assertEquals(flags.get('bk-root')!.deactivated_at, null); assertEquals(after.scopes, before.scopes); // ids preserved assertEquals(after.mem, before.mem); // includes embedding::text and microsecond timestamps assertEquals(after.grants, before.grants); @@ -119,6 +134,22 @@ Deno.test('backup and restore-backup round trip', async () => { assert(hist.every((h) => h.action === 'insert' && h.member_id === null)); assertEquals((await sql`select count(*)::int as n from agent_memory.access_tokens`)[0].n, 0); + // --- a version-1 file without the admin fields still loads (isAdmin false, deactivatedAt null) + await truncateAll(); + const old = JSON.parse(text); + for (const m of old.members) { + delete m.isAdmin; + delete m.deactivatedAt; + } + await restoreBackup(sql, old); + assertEquals( + (await sql`select count(*)::int as n from agent_memory.members where is_admin or deactivated_at is not null`)[0] + .n, + 0, + ); + await truncateAll(); + await restoreBackup(sql, data); + // --- refuses into a non-empty install const r5 = await cli('restore-backup', full); assertEquals(r5.code, 1); diff --git a/tests/integration/setup.test.ts b/tests/integration/setup.test.ts index 93d66f8..44c394b 100644 --- a/tests/integration/setup.test.ts +++ b/tests/integration/setup.test.ts @@ -167,3 +167,29 @@ Deno.test('refuses to write when the env file is not git-ignored', async () => { assertEquals(c.cmds.length, 0); }); }); + +Deno.test('a human member becomes an admin, and re-running does not fail', async () => { + await withSetup(async (c) => { + const o = { ...c.opts(), member: `ann-${c.s}`, bot: false }; + assertEquals(await setup(o), 0); + const sql = adminSql(); + const admin = async () => + (await sql`select is_admin from agent_memory.members where display_name = ${'ann-' + c.s}`)[0].is_admin; + assertEquals(await admin(), true); + assertStringIncludes(c.lines.join('\n'), `[6/7] Member 'ann-${c.s}' is an admin`); + assertEquals(await setup(o), 0); + assertEquals(await admin(), true); + await sql.end(); + }); +}); + +Deno.test('a bot member is never made admin and the note is printed', async () => { + await withSetup(async (c) => { + assertEquals(await setup(c.opts()), 0); + const sql = adminSql(); + const [r] = await sql`select is_admin from agent_memory.members where display_name = ${'bot-' + c.s}`; + await sql.end(); + assertEquals(r.is_admin, false); + assertStringIncludes(c.lines.join('\n'), 'Note: no admin yet - run admin.ts set-admin on'); + }); +}); diff --git a/tests/unit/admin-tools.test.ts b/tests/unit/admin-tools.test.ts new file mode 100644 index 0000000..46f4f7e --- /dev/null +++ b/tests/unit/admin-tools.test.ts @@ -0,0 +1,138 @@ +import { assert, assertEquals, assertStringIncludes } from '@std/assert'; +import { McpServer } from 'npm:@modelcontextprotocol/server@2.4.0'; +import { registerAdminTools } from '../../supabase/functions/_shared/admin-tools.ts'; +import type { PgAdminStore } from '../../supabase/functions/_shared/admin-store.ts'; +import { StoreError } from '../../supabase/functions/_shared/limits.ts'; + +const NAMES = [ + 'admin_create_member', + 'admin_create_scope', + 'admin_deactivate_member', + 'admin_delete_scope', + 'admin_grant', + 'admin_issue_token', + 'admin_list_grants', + 'admin_list_members', + 'admin_list_scopes', + 'admin_list_tokens', + 'admin_revoke', + 'admin_revoke_token', +]; + +// deno-lint-ignore no-explicit-any +type Calls = Record; +type Reg = Record Promise<{ content: { text: string }[]; isError?: boolean }>; +}>; + +function setup(fail?: Error) { + const calls: Calls = {}; + const rec = (n: string, ...a: unknown[]) => { + (calls[n] ??= []).push(a); + return fail ? Promise.reject(fail) : Promise.resolve(); + }; + const store = { + listScopes: () => rec('listScopes').then(() => [{ name: 's' }]), + createScope: (...a: unknown[]) => rec('createScope', ...a).then(() => ({ id: 'x' })), + deleteScope: (...a: unknown[]) => rec('deleteScope', ...a), + listMembers: () => rec('listMembers').then(() => []), + createMember: (...a: unknown[]) => rec('createMember', ...a).then(() => ({ id: 'x' })), + deactivateMember: (...a: unknown[]) => rec('deactivateMember', ...a), + listGrants: (...a: unknown[]) => rec('listGrants', ...a).then(() => []), + grant: (...a: unknown[]) => rec('grant', ...a), + revoke: (...a: unknown[]) => rec('revoke', ...a).then(() => true), + issueToken: (...a: unknown[]) => rec('issueToken', ...a).then(() => ({ id: 'tid', token: 'amm_secret' })), + listTokens: (...a: unknown[]) => rec('listTokens', ...a).then(() => []), + revokeToken: (...a: unknown[]) => rec('revokeToken', ...a), + } as unknown as PgAdminStore; + const server = new McpServer({ name: 'test', version: '0.0.0' }); + registerAdminTools(server, store); + const reg = (server as unknown as { _registeredTools: Reg })._registeredTools; + return { reg, calls }; +} + +Deno.test('registerAdminTools registers exactly the 12 admin tools, each described as Admin:', () => { + const { reg } = setup(); + assertEquals(Object.keys(reg).sort(), NAMES); + for (const n of NAMES) assert(reg[n].description?.startsWith('Admin:'), `${n} description`); +}); + +Deno.test('admin_issue_token description says shown once and not stored', () => { + const d = setup().reg.admin_issue_token.description ?? ''; + assertStringIncludes(d, 'shown once'); + assertStringIncludes(d, 'not stored'); +}); + +Deno.test('admin_deactivate_member description names the consequences', () => { + const d = setup().reg.admin_deactivate_member.description ?? ''; + assertStringIncludes(d, 'revokes all tokens and grants'); + assertStringIncludes(d, 'shell'); +}); + +Deno.test('admin_issue_token result carries the note and the token', async () => { + const { reg, calls } = setup(); + const r = await reg.admin_issue_token.handler({ member: 'm', name: 'laptop' }, {}); + assertEquals(calls.issueToken, [['m', 'laptop']]); + assertEquals(JSON.parse(r.content[0].text), { + member: 'm', + name: 'laptop', + id: 'tid', + token: 'amm_secret', + note: 'Shown once - give it to the member privately; it is not stored and cannot be shown again.', + }); +}); + +Deno.test('create_member kind defaults to human', async () => { + const { reg, calls } = setup(); + await reg.admin_create_member.handler({ name: 'n' }, {}); + assertEquals(calls.createMember, [['n', 'human', undefined]]); +}); + +Deno.test('list_grants passes optional filters', async () => { + const { reg, calls } = setup(); + await reg.admin_list_grants.handler({ scope: 's' }, {}); + assertEquals(calls.listGrants, [[{ scope: 's', member: undefined }]]); +}); + +Deno.test('a store error becomes isError with the message verbatim, and never echoes a token', async () => { + const { reg } = setup(new StoreError("Member 'x' is an admin; manage admins from the shell")); + for ( + const [n, args] of Object.entries>({ + admin_list_scopes: {}, + admin_create_scope: { name: 'a' }, + admin_delete_scope: { name: 'a' }, + admin_list_members: {}, + admin_create_member: { name: 'a' }, + admin_deactivate_member: { name: 'a' }, + admin_list_grants: {}, + admin_grant: { member: 'm', scope: 's', access: 'read' }, + admin_revoke: { member: 'm', scope: 's' }, + admin_issue_token: { member: 'm', name: 't' }, + admin_list_tokens: { member: 'm' }, + admin_revoke_token: { id: 'i' }, + }) + ) { + const r = await reg[n].handler(args, {}); + assertEquals(r.isError, true, n); + assertEquals(r.content[0].text, "Member 'x' is an admin; manage admins from the shell", n); + } +}); + +Deno.test('admin_create_member rejects blank or padded names and accepts a clean one', () => { + const { reg } = setup(); + const schema = reg.admin_create_member.inputSchema as unknown as { + safeParse: (v: unknown) => { success: boolean; error?: { issues: { message: string }[] } }; + }; + const msg = "Member names can't be blank or start or end with a space"; + for (const bad of ['', 'alice ', ' alice', ' ']) { + const r = schema.safeParse({ name: bad }); + assertEquals(r.success, false, JSON.stringify(bad)); + assert(r.error!.issues.some((i) => i.message === msg), JSON.stringify(bad)); + } + for (const good of ['alice', 'a', 'alice smith']) { + assertEquals(schema.safeParse({ name: good }).success, true, good); + } +});