diff --git a/CLAUDE.md b/CLAUDE.md index 3796f48..d6f5269 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -55,26 +55,28 @@ Keep this accurate — it's the navigation aid. One row per non-test file (`test | `src/main.rs` | entry: CLI parse, Sentry + tracing init, config load, serve with a 10s graceful drain (`DRAIN_DEADLINE`); dispatches `set-auth` (writes creds, then revokes every session) and the admin subcommands. Tests in `src/main_tests.rs` | | `src/cli.rs` | clap command definitions (`serve`/`set-auth`/`jobs`/`job kill`/`sessions [--revoke]`) | | `src/app.rs` | builds the axum router: `/mcp` (rmcp `StreamableHttpService` behind `auth::require_auth`) + the OAuth routes, both behind the `Host` allowlist guard; `/healthz` outside it; the shutdown token that ends every SSE stream. In-process router tests in `src/app_tests.rs` | -| `src/admin.rs` | local admin subcommands (`jobs`/`job kill`/`sessions [--revoke]`): open the existing DB (`Db::open_existing` — no create, no migration) through `jobs::JobRepo` / `oauth` — never builds a `JobStore` (that would start a reaper + reconcile and fail the live server's running rows); `job kill` only renders `jobs::kill_persisted`'s `KillOutcome`. Never prints token values | +| `src/agent.rs` | `Agent`: the OAuth client behind a request or a job — `client_id` + `ClientName` (the DCR `client_name`, untrusted: control/invisible chars stripped, whitespace collapsed, ≤32 chars), shown as `label()` = `#<4-hex of SHA-256(client_id)>`; `Debug` shows only the label. Tests in `src/agent/tests.rs` | +| `src/admin.rs` | local admin subcommands (`jobs` with a `BY` owner column/`job kill`/`sessions [--revoke]`, which also lists each logged-in agent's last activity): open the existing DB (`Db::open_existing` — no create, no migration) through `jobs::JobRepo` / `oauth` — never builds a `JobStore` (that would start a reaper + reconcile and fail the live server's running rows); `job kill` only renders `jobs::kill_persisted`'s `KillOutcome`. Never prints token values | | `src/config.rs` | env + TOML file config; fails fast on missing/empty creds or a non-loopback bind without `MCP_SSH_ALLOWED_HOSTS`; clamps `inline_timeout` ≤60s; `Password` with redacted `Debug`; TOML parse errors scrubbed of the file's text. `db_path()` resolves the DB path alone for the cred-free admin commands | | `src/config/set_auth.rs` | `set-auth`'s config write: atomic replace, 0600 from the first byte, owner adopted from the config dir | | `src/db.rs` | SQLite connection (`rusqlite`, `bundled`): open/create (file 0600, WAL), `open_existing` for the admin CLI, one serialized connection driven via `spawn_blocking`, typed `DbError`. DB at `/var/lib/mcp-ssh/mcp-ssh.db`. Queries live in the repositories (`src/jobs/store.rs`, `src/oauth/store.rs`) | -| `src/db/migrations.rs` | the schema (`jobs` incl. `interactive`, hashed `access_tokens`/`refresh_tokens`/`refresh_tombstones`, `clients`) as ordered forward-only steps versioned by `PRAGMA user_version`, each in its own `BEGIN IMMEDIATE` transaction. Append only | -| `src/auth.rs` | bearer-only guard for `/mcp` (`require_auth`; store outage → 503, not 401; a streaming response keeps re-checking its token — see `src/auth/revalidate.rs`) and `check_login`, the constant-time credential check the consent form uses. No HTTP Basic | +| `src/db/migrations.rs` | the schema (`jobs` incl. `interactive` and the owner's `client_id`/`client_name`, `clients` incl. `client_name`/`last_used_unix`, hashed `access_tokens`/`refresh_tokens`/`refresh_tombstones`, `clients`) as ordered forward-only steps versioned by `PRAGMA user_version`, each in its own `BEGIN IMMEDIATE` transaction. Append only | +| `src/auth.rs` | bearer-only guard for `/mcp` (`require_auth`; puts the bearer's `Agent` in the request extensions for the tools; store outage → 503, not 401; a streaming response keeps re-checking its token — see `src/auth/revalidate.rs`) and `check_login`, the constant-time credential check the consent form uses. No HTTP Basic | | `src/auth/revalidate.rs` | re-checks an open `/mcp` stream's token on an interval (`STREAM_REVALIDATE`, 30s) and ends the body once it is revoked or expired; holds the token hash, never the bearer; a store outage keeps the stream | | `src/oauth/mod.rs` | minimal OAuth 2.1 server wiring: `AuthState` (creds, store, public URL, the stream re-check interval), the public routes (discovery, `/authorize` GET+POST, `/token`, `/register`) with a 64 KiB body limit | | `src/oauth/metadata.rs` | RFC 8414 / RFC 9728 discovery documents; `base_url` from `MCP_SSH_PUBLIC_URL` else the allow-listed `Host` | | `src/oauth/flow.rs` | `/authorize`: GET validates (registered `client_id` + exact `redirect_uri`, else `invalid_request`; PKCE S256) and renders the consent page — never a code; POST takes the single-use CSRF nonce + credentials and only then redirects with a code. Flat delay on a failed login; redirect-URI rule | | `src/oauth/flow/token.rs` | `/token`: `authorization_code` (code + PKCE verifier) and `refresh_token` grants; `no-store`; store outage → 503 | -| `src/oauth/flow/register.rs` | `/register`: Dynamic Client Registration (RFC 7591), bounded URIs per client | +| `src/oauth/flow/register.rs` | `/register`: Dynamic Client Registration (RFC 7591), bounded URIs per client, optional `client_name` cleaned by `ClientName::parse` before it is stored | | `src/oauth/consent.rs` | the consent page HTML: static template, escaped values, `no-store`, CSP `frame-ancestors 'none'`, `X-Frame-Options: DENY` | | `src/oauth/pending.rs` | `Pending`: bounded, TTL'd, single-use in-memory map for consent requests and auth codes (10 min) | | `src/oauth/secret.rs` | random 256-bit tokens, SHA-256 `hash_token` (how tokens are stored and looked up), PKCE S256 + verifier rules | | `src/oauth/store.rs` | `Store`: the OAuth repository facade — lifetimes (access 24h, refresh 30d, family 90d, client grace 7d, ≤1000 clients), codes/consents, issue + validate; typed `GrantError`/`StoreUnavailable`/`RegisterError`. Only token hashes reach the DB | | `src/oauth/store/pair.rs` | token pairs: mint + insert within a login family; refresh rotation with reuse detection (a replayed refresh token revokes its whole family via tombstones) | -| `src/oauth/store/clients.rs` | registered clients: persist `client_id`→redirect URIs (no secrets), cap, exact-match check for `/authorize` | +| `src/oauth/store/clients.rs` | registered clients: persist `client_id`→redirect URIs + cleaned name (no secrets), cap, exact-match check for `/authorize` | +| `src/oauth/store/presence.rs` | who is on the host: `authenticate` (bearer hash → `Agent`, noting last use at most once a minute per client), `active_agents` (used a bearer within `PRESENCE_WINDOW`, 15 min), `logged_in_agents` (for `mcp-ssh sessions`). Never reads a token | | `src/oauth/store/sweep.rs` | `revoke_all` (`sessions --revoke`, `set-auth`) and the reaper's `sweep_expired_access`/`sweep_expired_refresh`/`sweep_stale_clients` — counts only, never a token value | -| `src/jobs/mod.rs` | job engine facade: `JobStore` wiring (`new` spawns the reaper), public types (`JobState`, `RunResult`, `JobSummary`, `JobList`, `JobError`), `list` (paged, ≤200) and `kill` | +| `src/jobs/mod.rs` | job engine facade: `JobStore` wiring (`new` spawns the reaper), public types (`JobState`, `JobMeta` — title + owning `Agent`, `RunResult`, `JobSummary`, `JobList`, `JobError`), `list` (paged, ≤200), `owner` and `kill` | | `src/jobs/run.rs` | launching: reserve id + 0600 log (`create_new`), spawn in its own process group (`sh -c` or `bash -ic`), hand to the supervisor, wait out the inline window | | `src/jobs/supervise.rs` | the supervisor task: owns a job from spawn to its recorded final state (survives request cancellation), enforces the 256 MiB live log cap (`LOG_CAP`; `SIGKILL` past it) — on leftovers too, until the group is gone — maps exit/signal to `JobState` | | `src/jobs/poll.rs` | poll: status + one newest-first page from the live log, else the tail saved in the row | @@ -87,15 +89,16 @@ Keep this accurate — it's the navigation aid. One row per non-test file (`test | `src/jobs/reaper/compact.rs` | log compaction: trim finished jobs' logs to their last 5000 lines (<3h since finish) / 500 after, ≤4 MiB, idempotent marker | | `src/jobs/shell.rs` | `Shell`: how a user command is launched — bare `sh -c` (default) vs. interactive `bash -ic` (sources `~/.bashrc` for aliases/version managers) | | `src/jobs/status.rs` | `JobStatus`: the bare `jobs.status` word (`running`/`exited`/`failed`); the one place the on-disk strings are spelled | -| `src/jobs/store.rs` | `JobRepo`: the `jobs` repository the engine, reaper and admin CLI call (insert, finish with the saved tail — 500 lines, ≤256 KiB — find, paged summaries, listing). No `cmd` text reaches a query or a log line | +| `src/jobs/store.rs` | `JobRepo`: the `jobs` repository the engine, reaper and admin CLI call (insert with the owner, finish with the saved tail — 500 lines, ≤256 KiB — find, owner, paged summaries, listing). No `cmd` text reaches a query or a log line | | `src/jobs/store/row.rs` | row⇄domain mapping: typed rows, `JobState` onto `(status, code, error)` and back | | `src/jobs/store/fail.rs` | recording `failed` for a job this writer may not own (kill, reconcile) — only while the row still reads `running`, or replacing a bare `killed by signal N` the engine recorded; plus re-recording a finished job `failed` when the supervisor killed its leftovers over the log cap | | `src/jobs/store/reap.rs` | the reaper's and reconcile's queries: untracked `running` rows, compaction/eviction candidates, deleting aged-out rows | -| `src/tools/mod.rs` | MCP tool surface (`#[tool_router]`/`#[tool]` from rmcp): 3 tools (`bash`/`job`/`file`) dispatching on `action`, their descriptions, one tracing span per dispatch. Thin adapters over jobs + files | +| `src/tools/mod.rs` | MCP tool surface (`#[tool_router]`/`#[tool]` from rmcp): 3 tools (`bash`/`job`/`file`) dispatching on `action`, their descriptions, one tracing span per dispatch (with the caller's `agent` label). Thin adapters over jobs + files | +| `src/tools/caller.rs` | the calling `Agent` (from the HTTP parts rmcp hands each tool), its span label, and `foreign_owner` — whose job `id` is, when not the caller's | | `src/tools/args.rs` | arg structs for the 3 tools (`BashArgs`/`JobArgs`/`FileArgs`, all `deny_unknown_fields`; `JobAction`/`FileAction`) + `lenient_action` (non-string/missing `action` → `list`, unknown string → error) — schema shape only | | `src/tools/render.rs` | agent-facing wording for `file`: `render_file`/`render_file_error` turn `FileOutcome`/`FileError` into sentences, markers and next-step hints | | `src/tools/reject.rs` | the operator's log line for a `tools/call` refused before dispatch (args `Parameters` rejects, or an unknown tool): tool + fixed reason word + `request_id` — never a key, value or serde message | -| `src/tools/job_render.rs` | agent-facing wording for `bash`/`job`: run/poll replies + the newest-first paging footer, list page + cursor, each `KillOutcome`, `JobError` | +| `src/tools/job_render.rs` | agent-facing wording for `bash`/`job`: run/poll replies + the newest-first paging footer, list page (presence line, `by` per job) + cursor, each `KillOutcome`, the `[started by another agent: …]` note, `JobError` | | `src/tools/files.rs` | file operations' shared types (`FileOutcome`, typed `FileError` — a failed shell op keeps its `ShError`) + `list`/`grep` (shelled-out `ls`/`find -maxdepth 20`/`grep`). Returns facts, never a sentence | | `src/tools/files/read.rs` | `read`: regular files only, forward by line, ≤1000 lines / 64 KiB a page, 8 KiB line clamp, 30s deadline | | `src/tools/files/write.rs` | `write` (atomic temp sibling + rename, keeps mode, writes through a symlink) and `append` | @@ -137,7 +140,7 @@ Current tools (three, constant): | Tool | Params | Does | |---|---|---| | `bash` | `cmd`, `cwd?`, `timeout?`, `bg?`, `interactive?`, `title?` | run a command; inline if fast, else a job id (`bg` backgrounds at once; `timeout` ≤600; `interactive` sources `~/.bashrc` via `bash -ic` for aliases/version managers, default fast `sh -c`; `title` labels the job id as `-HH-MM-SS`) | -| `job` | `action?`, `id?`, `cursor?`, `limit?` | jobs by `action`: `poll` (newest-first page, byte cursor), `list` (default; newest first, ≤200 per page, offset cursor), `kill` (typed outcome) | +| `job` | `action?`, `id?`, `cursor?`, `limit?` | jobs by `action`: `poll` (newest-first page, byte cursor), `list` (default; presence line of agents active in 15 min, then newest first with `by` = `you`/agent label, ≤200 per page, offset cursor), `kill` (typed outcome). Another agent's job is pollable/killable; the reply names its owner | | `file` | `action`, `path?`, `content?`, `pattern?`, `recursive?`, `src?`, `dest?`, `cursor?`, `limit?` | file ops by `action`: `read` (by line, ≤1000/64 KiB a page)/`write` (atomic)/`append`/`delete` (non-empty dir needs `recursive=true`; symlinks never followed)/`list`/`grep`/`move` (never overwrites) | ## Conventions @@ -150,7 +153,7 @@ Non-negotiable: SOLID, SRP, tested code. The bar: idiomatic, boring, readable Ru - Borrow by default (`&str` over `String`, `&[T]` over `Vec<T>`). `.clone()` only when ownership must move — non-obvious clone gets a one-line `// why`. `Arc<T>` for shared read-only; lock only when you mutate shared state, keep the critical section tiny. - Functions do one thing. Need "and" to describe it → split it. Concrete first; introduce a trait when the **second** impl arrives. - Async end-to-end. No `std::sync::Mutex` on the request path — use `tokio::sync`. Never hold a `std::sync` guard across `.await`. No `block_on`; offload blocking I/O with `spawn_blocking`. -- `tracing`, not `println`. Every tool dispatch is a span with `request_id` and `tool` name. A call refused before dispatch logs one `rejected` WARN (tool + reason word) instead. +- `tracing`, not `println`. Every tool dispatch is a span with `request_id`, `tool` name and the caller's `agent` label (never a `client_id`). A call refused before dispatch logs one `rejected` WARN (tool + reason word) instead. - Derive, don't hand-roll (`Debug`, `Clone`, serde). Every public type derives `Debug`. Keep `pub` surface minimal. - Comment the non-obvious *why*, never the *what*. Rename until the code doesn't need the *what*. @@ -224,6 +227,7 @@ Non-negotiable: SOLID, SRP, tested code. The bar: idiomatic, boring, readable Ru ## Context (not in code) - One host, one service user. Targets the box it runs on; not a fan-out / multi-host tool. +- Many agents may share the host at once (one OAuth client each). They see each other (presence, job owners) but are not isolated from each other: awareness, not multi-tenancy. - TLS, multi-host routing, and rate limiting live in the reverse proxy, not here. - NOT building: an SSH client, a fleet orchestrator, a job scheduler, a secrets vault. diff --git a/README.md b/README.md index daef2e2..deea8d2 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,8 @@ You're in your car. From your phone, you point Claude at `https://your-vps/mcp` Want to go further? Run `bash("claude -p 'fix the failing test and push'")` — **one agent supervising another agent** on your VPS. mcp-ssh is just the shell; what you run through it is up to you. +**Several agents, one host.** Any number of MCP clients can connect at once, each with its own login; their commands and jobs run side by side, never queued behind each other. They can see each other: `job(action="list")` opens with who is active (`2 agents active (last 15 min): you (Claude Code#4f2a), cursor#9b1c`) and marks each job `by` you or the agent that started it. Jobs are shared, not isolated — one service user — so an agent can poll or kill another's job, and the reply says whose it is. + ## ⚡ Quickstart **One-liner (Debian/Ubuntu)** — downloads the latest release, asks for a username + password, installs the service, and starts it: @@ -106,9 +108,9 @@ mcp-ssh set-auth admin # prompts for the password mcp-ssh serve # run the server (this is the default) mcp-ssh set-auth <user> # configure the username/password (logs every client out) -mcp-ssh jobs # list running jobs (--all includes finished ones) +mcp-ssh jobs # list running jobs and which agent started each (--all includes finished ones) mcp-ssh job kill <id> # SIGTERM then SIGKILL a job's process group -mcp-ssh sessions # summarise OAuth logins (token counts + next expiry) +mcp-ssh sessions # summarise OAuth logins (token counts, next expiry, each agent's last activity) mcp-ssh sessions --revoke # end every login: all clients must log in again ``` diff --git a/docs/architecture.md b/docs/architecture.md index 36a303f..a1ae986 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -81,8 +81,8 @@ A single SQLite database at `/var/lib/mcp-ssh/mcp-ssh.db` (sibling of the job-lo **In SQLite — durable, survives restarts:** - **OAuth tokens** — `access_tokens` and `refresh_tokens`, stored only as SHA-256 hashes (a copy of the DB yields no usable bearer), each bound to its client and login family. Logins survive a service restart — which matters because the agent can self-update and restart itself. Access tokens last 24h; refresh tokens 30 days, rotated on use, within a 90-day family cap; a replayed (already-rotated) refresh token ends its whole family. -- **Registered clients** — `clients` (`client_id` → redirect URIs, no secrets), capped at 1000; a client at least 7 days old that holds no live token is swept. -- **Job metadata** — id, title, status (`running`/`exited`/`failed`), exit code or error, start/finish time, process group + boot id, and a saved **output tail** (last 500 lines, ≤256 KiB). This is what makes `job(action="list")` show history across restarts. +- **Registered clients** — `clients` (`client_id` → redirect URIs, the cleaned `client_name` it registered, when it last used a bearer; no secrets), capped at 1000; a client at least 7 days old that holds no live token is swept. The last-use time is rewritten at most once a minute per client, so a busy agent's requests stay reads; it is what `job(action="list")`'s presence line and `mcp-ssh sessions` read. +- **Job metadata** — id, title, status (`running`/`exited`/`failed`), exit code or error, start/finish time, process group + boot id, the OAuth client that started it (id + name, so the owner still reads right after the client is swept), and a saved **output tail** (last 500 lines, ≤256 KiB). This is what makes `job(action="list")` show history across restarts. **On the filesystem — the high-frequency path:** diff --git a/docs/changelog/unreleased.md b/docs/changelog/unreleased.md index 79e701b..1f6d33e 100644 --- a/docs/changelog/unreleased.md +++ b/docs/changelog/unreleased.md @@ -1 +1,12 @@ # Unreleased + +### Added + +- **Agents sharing a host can see each other.** `job(action="list")` opens with the agents (OAuth clients) that used the host in the last 15 minutes, the caller marked `you` — e.g. `2 agents active (last 15 min): you (Claude Code#4f2a), cursor#9b1c` — and each job gains `by`: `you`, the agent that started it, or `unknown` for older jobs. Polling or killing another agent's job still works (one service user), and the reply opens with `[started by another agent: …]`. +- `mcp-ssh jobs` shows a `BY` column; `mcp-ssh sessions` lists each logged-in agent with when it was last active. +- An end-to-end test proves two separately logged-in agents run commands and background jobs side by side without waiting on each other. + +### Changed + +- **Schema version 7.** `jobs` gains `client_id`/`client_name`; `clients` gains `client_name`/`last_used_unix`. An older binary, including its admin CLI, refuses a migrated database. A `client_name` from client registration is cleaned before it is stored or shown: control and invisible characters dropped, whitespace collapsed, at most 32 characters. +- `job(action="list")` is no longer bare JSON: the presence line comes first. diff --git a/docs/usage.md b/docs/usage.md index e1a0cd1..228e13e 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -53,7 +53,7 @@ Nothing that can be large is returned whole. Stdout and stderr are merged into o - When older output exists, the footer `[latest N lines shown; earlier output: job(action="poll", id="…", cursor=C)]` names the exact next call. `C` is a **byte offset** into the log (where the page you just got starts) — pass it back verbatim, never compute one. It is absolute, so a running job that keeps appending never re-serves lines as you page back. - Once the live log is gone (trimmed or reaped), `poll` serves the output tail saved when the job finished: its last 500 lines, at most 256 KiB. -**Job history (`job(action="list")`)** is a JSON array of `{"id": …, "state": {"status": …}}`, newest first, at most `limit` (default and maximum 200) per page. When older jobs exist the reply ends with `[older jobs: job(action="list", cursor=N)]`. +**Job history (`job(action="list")`)** opens with a presence line — the agents that used this host in the last 15 minutes, you first — then a JSON array of `{"id": …, "state": {"status": …}, "by": …}`, newest first, at most `limit` (default and maximum 200) per page. When older jobs exist the reply ends with `[older jobs: job(action="list", cursor=N)]`. **Files (`file(action="read")`) page forward by line:** `cursor` is the line to start at (default 0), `limit` the line count (default 200, at most 1000), and a page also stops at 64 KiB. When more remains the reply ends with `[lines A..B of ≥T; next_cursor=B]` — the total is a lower bound, since the file is never scanned to the end. An empty file reads `[empty file]`; a cursor past the end says how many lines the file has. @@ -98,6 +98,21 @@ job(action="list", cursor=200) # the next (older) page job(action="kill", id="job-23-30-07") ``` +**Several agents on one host.** Each MCP client logs in on its own and gets its own bearer; their calls run concurrently (a slow command or job of one never holds up another). An agent is shown by the `client_name` its client registered plus a 4-hex tag that tells two clients of the same name apart (`Claude Code#4f2a`), or `client#<tag>` when it registered none. Names are cleaned before anyone sees them: control and invisible characters are dropped, whitespace collapsed, at most 32 characters. + +``` +job(action="list") +→ 2 agents active (last 15 min): you (Claude Code#4f2a), cursor#9b1c + [ + { "id": "deploy-10-12-03", "state": { "status": "running" }, "by": "cursor#9b1c" }, + { "id": "build-10-11-40", "state": { "status": "exited", "code": 0 }, "by": "you" } + ] +``` + +- `by` is `you`, another agent's label, or `unknown` for a job started before owners were recorded. +- An agent counts as active once it has used its bearer in the last 15 minutes (tracked per client, to the minute). +- Jobs are shared, not isolated: every agent runs as the same service user, so any agent can `poll` or `kill` any job. A reply about another agent's job opens with `[started by another agent: cursor#9b1c]`. + `kill` signals the job's whole process group (`SIGTERM`, a 2s grace, then `SIGKILL`) and only reports success once the group is verifiably gone: | Reply | Meaning | diff --git a/src/admin.rs b/src/admin.rs index ee6eb20..6a275a9 100644 --- a/src/admin.rs +++ b/src/admin.rs @@ -7,6 +7,7 @@ //! `running` rows to `failed`. Here we only ever touch the database directly. use crate::db::{Db, now_unix}; use crate::jobs::{JobId, JobRepo, JobRow, JobStatus, KillOutcome, kill_persisted}; +use crate::oauth::{AgentActivity, Store}; /// Open the database the running server uses — only if it exists and carries this /// binary's schema: no file is created and nothing is migrated, so a typo'd @@ -36,11 +37,27 @@ pub async fn jobs(all: bool) -> anyhow::Result<()> { fn render_jobs(rows: &[JobRow]) -> String { let id_w = rows.iter().map(|r| r.id.len()).max().unwrap_or(2).max(2); + // Who started each job (an agent's label); `-` for rows from before that was + // recorded. Labels are cleaned on read, so they are already printable. + let owners: Vec<String> = rows + .iter() + .map(|r| { + r.owner + .as_ref() + .map_or_else(|| "-".to_string(), |a| a.label()) + }) + .collect(); + let by_w = owners + .iter() + .map(|o| o.chars().count()) + .max() + .unwrap_or(2) + .max(2); let mut out = format!( - "{:<id_w$} {:<8} {:>4} {:<19} {}\n", - "ID", "STATUS", "CODE", "STARTED", "TITLE / ERROR" + "{:<id_w$} {:<8} {:>4} {:<19} {:<by_w$} {}\n", + "ID", "STATUS", "CODE", "STARTED", "BY", "TITLE / ERROR" ); - for r in rows { + for (r, by) in rows.iter().zip(&owners) { let code = r.code.map(|c| c.to_string()).unwrap_or_else(|| "-".into()); // For a failure the error is the useful column; otherwise the title. let note = match (r.status.parse::<JobStatus>(), r.error.as_deref()) { @@ -48,11 +65,12 @@ fn render_jobs(rows: &[JobRow]) -> String { _ => r.title.as_deref().unwrap_or("-"), }; out.push_str(&format!( - "{:<id_w$} {:<8} {:>4} {:<19} {}\n", + "{:<id_w$} {:<8} {:>4} {:<19} {:<by_w$} {}\n", printable(&r.id), printable(&r.status), code, fmt_time(r.started_unix), + by, printable(note), )); } @@ -156,10 +174,12 @@ pub async fn sessions(revoke: bool) -> anyhow::Result<()> { let now = now_unix(); let access = token_stats(&db, "access_tokens", now).await?; let refresh = token_stats(&db, "refresh_tokens", now).await?; + let agents = Store::new(db).logged_in_agents().await?; print!( "{}", render_sessions(&path.display().to_string(), &access, &refresh, now) ); + print!("{}", render_agents(&agents, now)); Ok(()) } @@ -207,6 +227,28 @@ fn render_sessions(db_path: &str, access: &TokenStats, refresh: &TokenStats, now out } +/// One line per client holding a live login, with when it last used a bearer. +fn render_agents(agents: &[AgentActivity], now: i64) -> String { + if agents.is_empty() { + return "agents: none logged in\n".to_string(); + } + let labels: Vec<String> = agents.iter().map(|a| a.agent.label()).collect(); + let w = labels.iter().map(|l| l.chars().count()).max().unwrap_or(0); + let mut out = "agents (logged in, most recently active first):\n".to_string(); + for (activity, label) in agents.iter().zip(&labels) { + let seen = match activity.last_used_unix { + Some(at) => format!( + "last active {} ({} ago)", + fmt_time(at), + humanize_duration(now - at) + ), + None => "not active since this was tracked".to_string(), + }; + out.push_str(&format!(" {label:<w$} {seen}\n")); + } + out +} + // ---- shared formatting ---- /// A Unix timestamp as local `YYYY-MM-DD HH:MM:SS`; the raw number if it's out of range. diff --git a/src/admin/tests.rs b/src/admin/tests.rs index 10da054..5b11202 100644 --- a/src/admin/tests.rs +++ b/src/admin/tests.rs @@ -1,4 +1,5 @@ use super::*; +use crate::agent::Agent; #[test] fn humanize_duration_scales_units() { @@ -20,6 +21,7 @@ fn render_jobs_aligns_and_prefers_error_for_failures() { error: None, started_unix: 1_700_000_000, title: Some("minime-v1".into()), + owner: Some(Agent::new("client-a".into(), Some("Claude Code"))), }, JobRow { id: "job-01".into(), @@ -28,10 +30,16 @@ fn render_jobs_aligns_and_prefers_error_for_failures() { error: Some("server restarted".into()), started_unix: 1_700_000_100, title: None, + owner: None, }, ]; let out = render_jobs(&rows); assert!(out.contains("ID"), "has a header"); + assert!(out.contains("BY"), "has an owner column:\n{out}"); + assert!( + out.contains("Claude Code#") && !out.contains("client-a"), + "owner shown by label, never by client id:\n{out}" + ); // Column width is driven by the longest id, so the short id is padded. assert!( out.contains("job-01 "), @@ -288,3 +296,32 @@ async fn render_sessions_counts_without_leaking_tokens() { ); } } + +#[test] +fn render_agents_shows_label_and_last_active_never_the_client_id() { + let now = 1_700_000_000; + let agents = vec![ + AgentActivity { + agent: Agent::new("client-a".into(), Some("Claude Code")), + last_used_unix: Some(now - 180), + }, + AgentActivity { + agent: Agent::new("client-b".into(), None), + last_used_unix: None, + }, + ]; + let out = render_agents(&agents, now); + assert!( + out.contains("Claude Code#") && out.contains("(3m ago)"), + "{out}" + ); + assert!( + out.contains("client#") && out.contains("not active since"), + "{out}" + ); + assert!( + !out.contains("client-a") && !out.contains("client-b"), + "{out}" + ); + assert_eq!(render_agents(&[], now), "agents: none logged in\n"); +} diff --git a/src/agent.rs b/src/agent.rs new file mode 100644 index 0000000..a6df6b6 --- /dev/null +++ b/src/agent.rs @@ -0,0 +1,107 @@ +//! Who is calling: the OAuth client a bearer was issued to. Every `/mcp` request +//! carries one (`auth::require_auth` puts it in the request extensions), every job +//! records the one that started it, and agents see each other through it. +//! +//! The display name comes from Dynamic Client Registration (`client_name`), which +//! anyone can send — untrusted input that ends up in an agent's context and an +//! operator's terminal. [`ClientName::parse`] is the one gate it passes through. +use sha2::{Digest, Sha256}; + +/// Longest client name kept, in characters. Long enough for `Claude Code`, +/// `cursor-vscode`; short enough that a hostile name can't crowd a listing. +const MAX_NAME_CHARS: usize = 32; + +/// A `client_name` fit to show: no control or invisible-formatting characters +/// (escape sequences, newlines that forge lines, bidi overrides), whitespace runs +/// collapsed to one space, at most [`MAX_NAME_CHARS`] characters. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ClientName(String); + +impl ClientName { + /// The cleaned name, or `None` when nothing printable is left. + pub fn parse(raw: &str) -> Option<Self> { + // Whitespace controls (`\n`, `\t`) separate words; the join below makes + // each a single space. + let visible: String = raw + .chars() + .filter(|&c| c.is_whitespace() || !hidden(c)) + .collect(); + let words = visible.split_whitespace().collect::<Vec<_>>().join(" "); + let bounded: String = words.chars().take(MAX_NAME_CHARS).collect(); + let name = bounded.trim_end(); + (!name.is_empty()).then(|| Self(name.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// Characters that never belong in a displayed name: controls (C0, DEL, C1) and +/// the zero-width / bidi-override formatting marks that disguise what is shown. +fn hidden(c: char) -> bool { + c.is_control() + || matches!(c, + '\u{00AD}' // soft hyphen + | '\u{200B}'..='\u{200F}' // zero-width, LRM/RLM + | '\u{202A}'..='\u{202E}' // bidi embeddings/overrides + | '\u{2060}'..='\u{2064}' // word joiner, invisible operators + | '\u{2066}'..='\u{2069}' // bidi isolates + | '\u{FEFF}' // BOM / zero-width no-break space + ) +} + +/// An OAuth client, as agents and the operator see it. `Debug` shows only the +/// label: the `client_id` is public, but it is still never logged. +#[derive(Clone, PartialEq, Eq)] +pub struct Agent { + client_id: String, + name: Option<ClientName>, +} + +impl std::fmt::Debug for Agent { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("Agent").field(&self.label()).finish() + } +} + +impl Agent { + /// `name` is re-cleaned here, so a row written by an older binary (or edited by + /// hand) renders as safely as a fresh registration. + pub fn new(client_id: String, name: Option<&str>) -> Self { + Self { + client_id, + name: name.and_then(ClientName::parse), + } + } + + /// An agent from a row's nullable `(client_id, client_name)` columns; `None` + /// for a row written before jobs recorded who started them. + pub fn from_columns(client_id: Option<String>, name: Option<String>) -> Option<Self> { + client_id.map(|id| Self::new(id, name.as_deref())) + } + + pub fn client_id(&self) -> &str { + &self.client_id + } + + pub fn name(&self) -> Option<&str> { + self.name.as_ref().map(ClientName::as_str) + } + + /// `<name>#<tag>`, or `client#<tag>` for a client that registered no name. The + /// tag tells two clients with the same name apart (two Claude Code sessions) + /// and is derived from a hash, so no part of the `client_id` is shown. + pub fn label(&self) -> String { + format!("{}#{}", self.name().unwrap_or("client"), self.tag()) + } + + /// First 4 hex digits of SHA-256(`client_id`). + fn tag(&self) -> String { + let digest = Sha256::digest(self.client_id.as_bytes()); + format!("{:02x}{:02x}", digest[0], digest[1]) + } +} + +#[cfg(test)] +mod tests; diff --git a/src/agent/tests.rs b/src/agent/tests.rs new file mode 100644 index 0000000..9720d0a --- /dev/null +++ b/src/agent/tests.rs @@ -0,0 +1,66 @@ +use super::*; + +#[test] +fn a_plain_name_is_kept() { + assert_eq!( + ClientName::parse("Claude Code").unwrap().as_str(), + "Claude Code" + ); +} + +#[test] +fn control_and_invisible_characters_are_stripped() { + let name = ClientName::parse("evil\u{1b}[31m\nrow\u{202E}x\u{200B}y\u{7f}\u{9b}").unwrap(); + assert_eq!(name.as_str(), "evil[31m rowxy"); + assert!(!name.as_str().chars().any(char::is_control)); +} + +#[test] +fn whitespace_collapses_and_length_is_bounded() { + let name = ClientName::parse(&format!(" a \t\t b {}", "z".repeat(500))).unwrap(); + assert!(name.as_str().starts_with("a b zz"), "{name:?}"); + assert_eq!(name.as_str().chars().count(), MAX_NAME_CHARS); + // Bounded in characters, never cut inside a multi-byte one. + let wide = ClientName::parse(&"é".repeat(100)).unwrap(); + assert_eq!(wide.as_str().chars().count(), MAX_NAME_CHARS); +} + +#[test] +fn nothing_printable_is_no_name() { + for raw in ["", " ", "\u{1b}\u{7}\n", "\u{200B}\u{FEFF}"] { + assert_eq!(ClientName::parse(raw), None, "{raw:?}"); + } +} + +#[test] +fn label_is_name_plus_a_hash_tag_never_the_client_id() { + let named = Agent::new("client-id-123".into(), Some("cursor")); + let label = named.label(); + let (name, tag) = label.split_once('#').unwrap(); + assert_eq!(name, "cursor"); + assert_eq!(tag.len(), 4); + assert!(tag.chars().all(|c| c.is_ascii_hexdigit()), "{tag}"); + assert!(!label.contains("client-id"), "{label}"); + + let anonymous = Agent::new("client-id-123".into(), None); + assert_eq!(anonymous.label(), format!("client#{tag}")); + // Same name, different client: told apart by the tag. + assert_ne!(Agent::new("other".into(), Some("cursor")).label(), label); +} + +#[test] +fn debug_shows_the_label_not_the_client_id() { + let agent = Agent::new("secret-looking-id".into(), Some("cursor")); + let shown = format!("{agent:?}"); + assert!( + shown.contains("cursor#") && !shown.contains("secret-looking-id"), + "{shown}" + ); +} + +#[test] +fn from_columns_needs_a_client_id_and_recleans_the_name() { + assert_eq!(Agent::from_columns(None, Some("x".into())), None); + let agent = Agent::from_columns(Some("id".into()), Some("a\nb".into())).unwrap(); + assert_eq!(agent.name(), Some("a b")); +} diff --git a/src/app.rs b/src/app.rs index 373d165..a1a639c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -29,8 +29,9 @@ pub fn build( http.allowed_hosts = allowed_hosts.clone(); http.cancellation_token = shutdown; + let agents = auth_state.store.clone(); let service = StreamableHttpService::new( - move || Ok(tools::Tools::new(store.clone())), + move || Ok(tools::Tools::new(store.clone(), agents.clone())), Arc::new(LocalSessionManager::default()), http, ); diff --git a/src/app_tests.rs b/src/app_tests.rs index 589e161..f4a8232 100644 --- a/src/app_tests.rs +++ b/src/app_tests.rs @@ -625,7 +625,8 @@ async fn tools_call_exercises_bash_file_and_job() { "file read content: {read_text}" ); - // ── job: list → valid JSON (array, possibly empty since bash ran inline) ─ + // ── job: list → the presence line (the caller, as `you`: the bearer's + // client reached the tool through rmcp), then a JSON array ─ let job_msg = call_tool( app.clone(), &token, @@ -638,7 +639,18 @@ async fn tools_call_exercises_bash_file_and_job() { let job_text = job_msg["result"]["content"][0]["text"] .as_str() .expect("job list result must have text content"); - serde_json::from_str::<serde_json::Value>(job_text).expect("job list must return valid JSON"); + let (presence, json) = job_text.split_once('\n').expect("presence line, then JSON"); + assert!( + presence.starts_with("1 agent active (last 15 min): you (client#"), + "{presence}" + ); + let jobs = serde_json::from_str::<serde_json::Value>(json).expect("job list must be JSON"); + let jobs = jobs.as_array().expect("an array"); + assert!(!jobs.is_empty(), "the inline bash call is listed"); + assert!( + jobs.iter().all(|job| job["by"] == "you"), + "the caller's own jobs read `by: you`: {jobs:?}" + ); } /// A call rmcp refuses before dispatch (here a misspelt param) used to leave the diff --git a/src/auth.rs b/src/auth.rs index d772fe2..c5135ed 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -56,15 +56,17 @@ fn bearer(headers: &HeaderMap) -> Option<&str> { } /// Middleware guarding `/mcp`. Only a valid OAuth bearer token lets a request -/// through. A token store that can't answer is a 503 (retry), not a 401 — a 401 -/// would send every client back through the login flow during a DB blip. A -/// streaming response keeps checking its token for as long as it stays open. -pub async fn require_auth(State(st): State<AuthState>, req: Request, next: Next) -> Response { - let headers = req.headers(); - if let Some(token) = bearer(headers) { +/// through, carrying the [`Agent`](crate::agent::Agent) it was issued to as a request extension (the +/// tools attribute jobs to it). A token store that can't answer is a 503 (retry), +/// not a 401 — a 401 would send every client back through the login flow during +/// a DB blip. A streaming response keeps checking its token for as long as it +/// stays open. +pub async fn require_auth(State(st): State<AuthState>, mut req: Request, next: Next) -> Response { + if let Some(token) = bearer(req.headers()) { let token_hash = hash_token(token); - match st.store.validate_hash(&token_hash).await { - Ok(true) => { + match st.store.authenticate(&token_hash).await { + Ok(Some(agent)) => { + req.extensions_mut().insert(agent); let response = next.run(req).await; return revalidate::end_when_revoked( response, @@ -73,11 +75,11 @@ pub async fn require_auth(State(st): State<AuthState>, req: Request, next: Next) st.revalidate_every, ); } - Ok(false) => {} + Ok(None) => {} Err(_) => return unavailable(), } } - unauthorized(st.public_url.as_deref(), headers) + unauthorized(st.public_url.as_deref(), req.headers()) } fn unavailable() -> Response { diff --git a/src/db/migrations.rs b/src/db/migrations.rs index 93c4f7a..ca1d26a 100644 --- a/src/db/migrations.rs +++ b/src/db/migrations.rs @@ -17,6 +17,7 @@ const MIGRATIONS: &[Migration] = &[ constrain_jobs, hash_and_bind_tokens, add_job_interactive, + add_agent_identity, ]; /// The newest schema version this binary understands. @@ -173,6 +174,19 @@ fn add_job_interactive(tx: &Transaction) -> rusqlite::Result<()> { tx.execute_batch("ALTER TABLE jobs ADD COLUMN interactive INTEGER NOT NULL DEFAULT 0;") } +/// v7: which OAuth client started a job (its id and the name it registered, kept +/// on the row so the owner still reads right after the client is swept), the +/// registered name on `clients`, and when each client last used a token — what +/// lets agents sharing the host see each other. Older rows have no owner. +fn add_agent_identity(tx: &Transaction) -> rusqlite::Result<()> { + tx.execute_batch( + "ALTER TABLE jobs ADD COLUMN client_id TEXT; + ALTER TABLE jobs ADD COLUMN client_name TEXT; + ALTER TABLE clients ADD COLUMN client_name TEXT; + ALTER TABLE clients ADD COLUMN last_used_unix INTEGER;", + ) +} + /// `table`/`column` are compile-time constants (never user input), so /// interpolating them into the pragma is injection-safe. fn has_column(conn: &Connection, table: &str, column: &str) -> rusqlite::Result<bool> { diff --git a/src/db/tests.rs b/src/db/tests.rs index 2669497..844909f 100644 --- a/src/db/tests.rs +++ b/src/db/tests.rs @@ -131,8 +131,9 @@ async fn a_legacy_v0_database_migrates_to_the_latest_schema() { // column the migrations added. db.call(|c| { c.execute( - "INSERT INTO jobs (id, title, status, started_unix, output_tail, pgid, boot_id, finished_unix) \ - VALUES ('new', 't', 'running', 1, NULL, 2, 'boot', NULL)", + "INSERT INTO jobs (id, title, status, started_unix, output_tail, pgid, boot_id, finished_unix, \ + client_id, client_name) \ + VALUES ('new', 't', 'running', 1, NULL, 2, 'boot', NULL, 'c1', 'Claude Code')", [], ) }) @@ -288,3 +289,29 @@ async fn open_existing_waits_out_the_servers_write_lock() { .expect("write waits for the server's transaction"); holder.await.unwrap().unwrap(); } + +/// v7: a job from before owners were recorded keeps no owner; clients gain a +/// name and a last-use time, both empty for an existing registration. +#[tokio::test] +async fn v7_adds_owner_and_presence_columns_empty_for_existing_rows() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("legacy.db"); + legacy_v0(&path); + let db = Db::open(&path).unwrap(); + let (job_owner, client): (Option<String>, (Option<String>, Option<i64>)) = db + .call(|c| { + let owner = c.query_row("SELECT client_id FROM jobs WHERE id = 'old'", [], |r| { + r.get(0) + })?; + let client = c.query_row( + "SELECT client_name, last_used_unix FROM clients WHERE client_id = 'c1'", + [], + |r| Ok((r.get(0)?, r.get(1)?)), + )?; + Ok((owner, client)) + }) + .await + .unwrap(); + assert_eq!(job_owner, None); + assert_eq!(client, (None, None)); +} diff --git a/src/jobs/mod.rs b/src/jobs/mod.rs index 9fd3583..1973ff5 100644 --- a/src/jobs/mod.rs +++ b/src/jobs/mod.rs @@ -33,6 +33,8 @@ pub(crate) use signal::{KillOutcome, kill_persisted}; pub use status::JobStatus; pub(crate) use store::{JobRepo, JobRow}; +use crate::agent::Agent; + #[derive(Debug, Clone, serde::Serialize)] #[serde(tag = "status", rename_all = "snake_case")] pub enum JobState { @@ -41,6 +43,24 @@ pub enum JobState { Failed { error: String }, } +/// What labels a job besides its id: the agent's `title` (never command text) and +/// the agent that started it (`None` only where no caller is known). +#[derive(Debug, Clone, Default)] +pub struct JobMeta { + pub title: Option<String>, + pub owner: Option<Agent>, +} + +#[cfg(test)] +impl JobMeta { + pub fn titled(title: String) -> Self { + Self { + title: Some(title), + owner: None, + } + } +} + /// Most rows one `job(action="list")` page returns. pub const MAX_LIST_PAGE: usize = 200; @@ -77,11 +97,13 @@ pub enum RunResult { /// Public, per-job metadata for `job(action="list")`. Deliberately omits the /// command text: a command can carry a secret in its leading tokens /// (`PGPASSWORD=…`, bearer headers, pasted tokens), and this is returned in -/// ordinary MCP responses — so the listing exposes only the id and status. -#[derive(Debug, serde::Serialize)] +/// ordinary MCP responses — so the listing exposes only the id, the status and +/// who started it (`None` for a job from before that was recorded). +#[derive(Debug)] pub struct JobSummary { pub id: JobId, pub state: JobState, + pub owner: Option<Agent>, } /// One page of `job(action="list")`, newest start first. @@ -178,6 +200,12 @@ impl JobStore { Ok(JobList { jobs, next_cursor }) } + /// The agent that started job `id`. `Ok(None)` for an unknown id, or a job + /// from before owners were recorded. + pub async fn owner(&self, id: &JobId) -> Result<Option<Agent>, JobError> { + Ok(self.repo.owner(id).await?) + } + /// Kill a job's process group — through the in-process handle when this /// process tracks it, else through its persisted row (a job whose group /// outlived the process that started it is still killable). diff --git a/src/jobs/run.rs b/src/jobs/run.rs index dbdcbc0..e4b3804 100644 --- a/src/jobs/run.rs +++ b/src/jobs/run.rs @@ -12,7 +12,9 @@ use tokio::sync::{Mutex, oneshot, watch}; use super::log::{DEFAULT_PAGE, TailBudget, read_tail}; use super::supervise::{Supervised, supervise}; -use super::{Job, JobError, JobId, JobState, JobStore, ProcessGroupId, RunResult, Shell, id}; +use super::{ + Job, JobError, JobId, JobMeta, JobState, JobStore, ProcessGroupId, RunResult, Shell, id, +}; /// Single-quote a path for safe interpolation into a shell command. The job log /// path is engine-controlled, but quoting keeps an odd `job_dir` (spaces, `$`) @@ -41,7 +43,8 @@ impl JobStore { /// Spawn `cmd`. With `background`, return a job id immediately; otherwise wait /// up to the inline window and return output if it finishes in time. /// `interactive` runs it through `~/.bashrc` (aliases, version managers); - /// otherwise the fast bare `sh -c` is used. + /// otherwise the fast bare `sh -c` is used. `meta` names the job (`title`) and + /// the agent it is recorded as started by. pub async fn run( &self, cmd: String, @@ -49,7 +52,7 @@ impl JobStore { timeout_secs: Option<u64>, background: bool, interactive: bool, - title: Option<String>, + meta: JobMeta, ) -> Result<RunResult, JobError> { if let Some(dir) = &cwd { check_cwd(dir).await?; @@ -59,7 +62,7 @@ impl JobStore { // tokens, and the id ends up in replies, `job(list)`, logs, and the log // filename. The normalized label is also what the row stores, so an // operator's terminal never renders a raw agent string. - let label = title.as_deref().and_then(id::normalize_title); + let label = meta.title.as_deref().and_then(id::normalize_title); let (id, log_path) = self .reserve_log(label.as_deref()) .await @@ -116,7 +119,10 @@ impl JobStore { Supervised { id: id.clone(), job, - label, + meta: JobMeta { + title: label, + owner: meta.owner, + }, log_cap: self.log_cap, done: done_tx, }, diff --git a/src/jobs/signal/tests.rs b/src/jobs/signal/tests.rs index 9b03f46..d18457c 100644 --- a/src/jobs/signal/tests.rs +++ b/src/jobs/signal/tests.rs @@ -1,6 +1,6 @@ use super::*; use crate::db::Db; -use crate::jobs::{JobId, JobRepo}; +use crate::jobs::{JobId, JobMeta, JobRepo}; fn repo() -> (JobRepo, Db) { let db = Db::memory(); @@ -231,7 +231,14 @@ async fn a_kill_that_did_not_take_is_not_blamed_for_the_job_s_later_exit() { let dir = tempfile::tempdir().unwrap().keep(); let store = JobStore::new(dir, Duration::from_secs(5), Shell::sh(), Db::memory()).unwrap(); let RunResult::Backgrounded { id } = store - .run("sleep 0.5; exit 3".into(), None, None, true, false, None) + .run( + "sleep 0.5; exit 3".into(), + None, + None, + true, + false, + JobMeta::default(), + ) .await .unwrap() else { diff --git a/src/jobs/store.rs b/src/jobs/store.rs index 78c8183..e2a2bf5 100644 --- a/src/jobs/store.rs +++ b/src/jobs/store.rs @@ -15,7 +15,8 @@ use std::path::Path; use rusqlite::OptionalExtension; use super::log::{self, TailBudget, TailPage}; -use super::{JobId, JobState, JobStatus, JobSummary, ProcessGroupId}; +use super::{JobId, JobMeta, JobState, JobStatus, JobSummary, ProcessGroupId}; +use crate::agent::Agent; use crate::db::{Db, now_unix}; mod fail; @@ -55,15 +56,15 @@ impl JobRepo { &self.db } - /// Record a newly launched job as `running`. `title` is the normalized label - /// (never command text); `pgid` + `boot_id` are persisted so `mcp-ssh job kill` + /// Record a newly launched job as `running`. `meta` holds the normalized title + /// (never command text) and the agent that started it; `pgid` + `boot_id` are persisted so `mcp-ssh job kill` /// can signal the group after the launching process is gone — and refuse to /// once the host has rebooted and the number may name another group. /// `interactive` is persisted so that kill escalates as a live one would. pub(super) async fn insert_running( &self, id: &JobId, - title: Option<String>, + meta: &JobMeta, started_unix: i64, pgid: Option<ProcessGroupId>, boot_id: Option<String>, @@ -71,12 +72,20 @@ impl JobRepo { ) -> rusqlite::Result<()> { let row_id = id.as_ref().to_string(); let pgid = pgid.map(|p| i64::from(p.get())); + let title = meta.title.clone(); + let client_id = meta.owner.as_ref().map(|a| a.client_id().to_string()); + let client_name = meta + .owner + .as_ref() + .and_then(|a| a.name()) + .map(str::to_string); self.db .call(move |conn| { conn.execute( "INSERT INTO jobs \ - (id, title, status, started_unix, pgid, boot_id, interactive) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + (id, title, status, started_unix, pgid, boot_id, interactive, \ + client_id, client_name) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", rusqlite::params![ row_id, title, @@ -84,7 +93,9 @@ impl JobRepo { started_unix, pgid, boot_id, - interactive + interactive, + client_id, + client_name ], ) }) @@ -187,7 +198,7 @@ impl JobRepo { .db .call(move |conn| { let mut stmt = conn.prepare( - "SELECT id, status, code, error FROM jobs \ + "SELECT id, status, code, error, client_id, client_name FROM jobs \ ORDER BY started_unix DESC, id DESC LIMIT ?1 OFFSET ?2", )?; let mapped = stmt.query_map([fetch, offset], |r| { @@ -198,6 +209,7 @@ impl JobRepo { r.get::<_, Option<i64>>(2)?, r.get::<_, Option<String>>(3)?, ), + owner: Agent::from_columns(r.get(4)?, r.get(5)?), }) })?; let mut rows = Vec::new(); @@ -219,6 +231,24 @@ impl JobRepo { Ok((rows, more)) } + /// The agent recorded as starting job `id`; `None` for no such row, or a row + /// from before owners were recorded. + pub(super) async fn owner(&self, id: &JobId) -> rusqlite::Result<Option<Agent>> { + let row_id = id.as_ref().to_string(); + let columns = self + .db + .call(move |conn| { + conn.query_row( + "SELECT client_id, client_name FROM jobs WHERE id = ?1", + [row_id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional() + }) + .await?; + Ok(columns.and_then(|(client_id, name)| Agent::from_columns(client_id, name))) + } + /// Rows behind `mcp-ssh jobs`: active jobs by default, or every job newest /// first with `all` (capped, so a long-lived box's history can't flood the /// terminal). @@ -226,10 +256,10 @@ impl JobRepo { self.db .call(move |conn| { let sql = if all { - "SELECT id, status, code, error, started_unix, title \ + "SELECT id, status, code, error, started_unix, title, client_id, client_name \ FROM jobs ORDER BY started_unix DESC LIMIT 200" } else { - "SELECT id, status, code, error, started_unix, title \ + "SELECT id, status, code, error, started_unix, title, client_id, client_name \ FROM jobs WHERE status = ?1 ORDER BY started_unix DESC" }; let mut stmt = conn.prepare(sql)?; diff --git a/src/jobs/store/row.rs b/src/jobs/store/row.rs index cd7ca85..e2524c6 100644 --- a/src/jobs/store/row.rs +++ b/src/jobs/store/row.rs @@ -1,6 +1,7 @@ //! The row⇄domain mapping for `jobs`: the typed rows queries return, and //! `JobState` onto the `(status, code, error)` columns and back — so a status word //! is spelled (via `JobStatus`) and read in exactly one place. +use crate::agent::Agent; use crate::jobs::{JobId, JobState, JobStatus}; /// A job's durable row, mapped back onto the domain types. `tail` is the bounded @@ -55,6 +56,8 @@ pub(crate) struct JobRow { pub(crate) error: Option<String>, pub(crate) started_unix: i64, pub(crate) title: Option<String>, + /// Who started it; `None` for a row from before that was recorded. + pub(crate) owner: Option<Agent>, } /// Map a `JobState` onto the DB row's `(status, code, error)` columns. @@ -98,5 +101,6 @@ pub(super) fn job_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<JobRow> { error: r.get(3)?, started_unix: r.get(4)?, title: r.get(5)?, + owner: Agent::from_columns(r.get(6)?, r.get(7)?), }) } diff --git a/src/jobs/store/tests.rs b/src/jobs/store/tests.rs index a3aa4a6..02151bb 100644 --- a/src/jobs/store/tests.rs +++ b/src/jobs/store/tests.rs @@ -58,7 +58,7 @@ async fn insert_running_writes_the_columns_the_inline_sql_did() { let id = JobId::from("job-10-00-00"); repo.insert_running( &id, - Some("deploy".into()), + &JobMeta::titled("deploy".into()), 1_700_000_000, ProcessGroupId::new(4242), Some("boot-a".into()), @@ -91,7 +91,7 @@ async fn finish_records_the_final_state_and_a_bounded_tail() { let repo = repo(); let id = JobId::from("job-10-00-01"); - repo.insert_running(&id, None, now_unix(), None, None, false) + repo.insert_running(&id, &JobMeta::default(), now_unix(), None, None, false) .await .unwrap(); repo.finish(&id, &log, &JobState::Exited { code: 7 }).await; @@ -117,7 +117,7 @@ async fn finish_byte_caps_the_tail_of_one_huge_line() { .unwrap(); let repo = repo(); let id = JobId::from("job-huge"); - repo.insert_running(&id, None, now_unix(), None, None, false) + repo.insert_running(&id, &JobMeta::default(), now_unix(), None, None, false) .await .unwrap(); repo.finish(&id, &log, &JobState::Exited { code: 0 }).await; @@ -137,7 +137,7 @@ async fn finish_byte_caps_the_tail_of_one_huge_line() { async fn finish_records_the_status_even_when_the_log_is_gone() { let repo = repo(); let id = JobId::from("job-nolog"); - repo.insert_running(&id, None, now_unix(), None, None, false) + repo.insert_running(&id, &JobMeta::default(), now_unix(), None, None, false) .await .unwrap(); repo.finish( @@ -156,7 +156,7 @@ async fn finish_records_the_status_even_when_the_log_is_gone() { async fn a_recorded_kill_reason_survives_the_waiter_s_exit() { let repo = repo(); let id = JobId::from("job-cli-killed"); - repo.insert_running(&id, None, now_unix(), None, None, false) + repo.insert_running(&id, &JobMeta::default(), now_unix(), None, None, false) .await .unwrap(); repo.mark_killed(&id, "killed via mcp-ssh kill") @@ -176,7 +176,7 @@ async fn a_recorded_kill_reason_survives_the_waiter_s_exit() { // The other order: the waiter recorded the bare signal death first. The // kill's reason still lands — it is what that signal was. let id = JobId::from("job-waiter-first"); - repo.insert_running(&id, None, now_unix(), None, None, false) + repo.insert_running(&id, &JobMeta::default(), now_unix(), None, None, false) .await .unwrap(); let died = JobState::Failed { @@ -194,7 +194,7 @@ async fn a_recorded_kill_reason_survives_the_waiter_s_exit() { async fn find_maps_rows_back_onto_job_state() { let repo = repo(); let failed = JobId::from("job-b"); - repo.insert_running(&failed, None, now_unix(), None, None, false) + repo.insert_running(&failed, &JobMeta::default(), now_unix(), None, None, false) .await .unwrap(); repo.finish( @@ -217,9 +217,16 @@ async fn find_maps_rows_back_onto_job_state() { async fn summaries_page_newest_first() { let repo = repo(); for (id, started) in [("b-late", 30), ("a-early", 10), ("z-mid", 20)] { - repo.insert_running(&JobId::from(id), None, started, None, None, false) - .await - .unwrap(); + repo.insert_running( + &JobId::from(id), + &JobMeta::default(), + started, + None, + None, + false, + ) + .await + .unwrap(); } let (page, more) = repo.summaries(0, 2).await.unwrap(); let ids: Vec<&str> = page.iter().map(|s| s.id.as_ref()).collect(); @@ -235,9 +242,16 @@ async fn summaries_page_newest_first() { #[tokio::test] async fn summaries_skip_a_corrupt_row() { let repo = repo(); - repo.insert_running(&JobId::from("good"), None, 10, None, None, false) - .await - .unwrap(); + repo.insert_running( + &JobId::from("good"), + &JobMeta::default(), + 10, + None, + None, + false, + ) + .await + .unwrap(); // A blob where the id text should be: the row can't be mapped. seed_raw( &repo, @@ -256,7 +270,7 @@ async fn untracked_running_skips_live_ids() { let (ghost, mine) = (JobId::from("job-ghost"), JobId::from("job-mine")); repo.insert_running( &ghost, - None, + &JobMeta::default(), boot - 3600, ProcessGroupId::new(2_000_000_000), Some("boot-a".into()), @@ -264,7 +278,7 @@ async fn untracked_running_skips_live_ids() { ) .await .unwrap(); - repo.insert_running(&mine, None, boot, None, None, false) + repo.insert_running(&mine, &JobMeta::default(), boot, None, None, false) .await .unwrap(); @@ -288,7 +302,7 @@ async fn untracked_running_skips_live_ids() { async fn a_finished_row_keeps_its_own_state_when_a_kill_is_recorded() { let repo = repo(); let id = JobId::from("job-done"); - repo.insert_running(&id, None, now_unix(), None, None, false) + repo.insert_running(&id, &JobMeta::default(), now_unix(), None, None, false) .await .unwrap(); repo.finish( @@ -312,7 +326,7 @@ async fn leftovers_killed_re_records_a_finished_row_only() { let repo = repo(); let (done, live) = (JobId::from("job-done"), JobId::from("job-live")); for id in [&done, &live] { - repo.insert_running(id, None, now_unix(), None, None, false) + repo.insert_running(id, &JobMeta::default(), now_unix(), None, None, false) .await .unwrap(); } @@ -369,10 +383,17 @@ async fn kill_target_reads_status_pgid_and_boot_verbatim() { async fn reap_rows_age_from_the_finish() { let repo = repo(); let (old, fresh) = (JobId::from("job-old"), JobId::from("job-fresh")); - repo.insert_running(&old, None, 100, ProcessGroupId::new(7), None, false) - .await - .unwrap(); - repo.insert_running(&fresh, None, 300, None, None, false) + repo.insert_running( + &old, + &JobMeta::default(), + 100, + ProcessGroupId::new(7), + None, + false, + ) + .await + .unwrap(); + repo.insert_running(&fresh, &JobMeta::default(), 300, None, None, false) .await .unwrap(); repo.finish( @@ -407,10 +428,10 @@ async fn reap_rows_age_from_the_finish() { async fn listing_filters_active_unless_all() { let repo = repo(); let (a, b) = (JobId::from("a"), JobId::from("b")); - repo.insert_running(&a, Some("first".into()), 10, None, None, false) + repo.insert_running(&a, &JobMeta::titled("first".into()), 10, None, None, false) .await .unwrap(); - repo.insert_running(&b, None, 20, None, None, false) + repo.insert_running(&b, &JobMeta::default(), 20, None, None, false) .await .unwrap(); repo.finish( diff --git a/src/jobs/supervise.rs b/src/jobs/supervise.rs index 3c2fc29..b34feaf 100644 --- a/src/jobs/supervise.rs +++ b/src/jobs/supervise.rs @@ -6,7 +6,7 @@ use std::{collections::HashMap, os::unix::process::ExitStatusExt, sync::Arc, tim use tokio::sync::{Mutex, oneshot, watch}; use super::signal::{self, Escalation, Kill, Probe, escalate, probe}; -use super::{Job, JobError, JobId, JobRepo, JobState, ProcessGroupId, store}; +use super::{Job, JobError, JobId, JobMeta, JobRepo, JobState, ProcessGroupId, store}; /// Most bytes a job's live log may reach. Past it the job's group is killed and it /// finishes `failed` — a runaway writer must not fill the volume the database @@ -23,7 +23,8 @@ const LOG_CAP_EVERY: Duration = Duration::from_millis(100); pub(super) struct Supervised { pub(super) id: JobId, pub(super) job: Arc<Job>, - pub(super) label: Option<String>, + /// The normalized title and the owning agent, as the row records them. + pub(super) meta: JobMeta, pub(super) log_cap: u64, pub(super) done: watch::Sender<bool>, } @@ -47,7 +48,7 @@ pub(super) async fn supervise( let Supervised { id, job, - label, + meta, log_cap, done, } = s; @@ -55,7 +56,7 @@ pub(super) async fn supervise( let inserted = repo .insert_running( &id, - label, + &meta, crate::db::now_unix(), job.pgid, signal::boot_id(), diff --git a/src/jobs/tests.rs b/src/jobs/tests.rs index 5633644..9ac65b9 100644 --- a/src/jobs/tests.rs +++ b/src/jobs/tests.rs @@ -66,7 +66,7 @@ fn alive(pid: &str) -> bool { async fn bg(store: &JobStore, cmd: &str) -> JobId { match store - .run(cmd.into(), None, None, true, false, None) + .run(cmd.into(), None, None, true, false, JobMeta::default()) .await .unwrap() { @@ -125,7 +125,7 @@ async fn interactive_shell_expands_rc_aliases_without_leaking_startup_noise() { .unwrap(); let r = store - .run("greet".into(), None, None, false, true, None) + .run("greet".into(), None, None, false, true, JobMeta::default()) .await .unwrap(); let RunResult::Inline { state, page, .. } = r else { @@ -143,7 +143,14 @@ async fn interactive_shell_expands_rc_aliases_without_leaking_startup_noise() { #[tokio::test] async fn fast_command_returns_inline() { let r = store(Duration::from_secs(5)) - .run("echo hello".into(), None, None, false, false, None) + .run( + "echo hello".into(), + None, + None, + false, + false, + JobMeta::default(), + ) .await .unwrap(); let RunResult::Inline { state, page, .. } = r else { @@ -186,7 +193,14 @@ async fn job_dir_and_logs_are_owner_only() { let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; assert_eq!(mode(&dir), 0o700, "a loose pre-existing dir is tightened"); let RunResult::Inline { id, .. } = store - .run("echo s3cret".into(), None, None, false, false, None) + .run( + "echo s3cret".into(), + None, + None, + false, + false, + JobMeta::default(), + ) .await .unwrap() else { @@ -206,7 +220,7 @@ async fn title_labels_the_id_and_the_row_stores_it_normalized() { None, true, false, - Some("deploy check\x1b[2J\nforged".into()), + JobMeta::titled("deploy check\x1b[2J\nforged".into()), ) .await .unwrap(); @@ -240,7 +254,7 @@ async fn a_bad_cwd_is_named_and_leaves_nothing_behind() { None, false, false, - None, + JobMeta::default(), ) .await else { @@ -255,7 +269,14 @@ async fn a_bad_cwd_is_named_and_leaves_nothing_behind() { std::fs::write(&file, "").unwrap(); let file = file.to_string_lossy().into_owned(); let Err(error) = store - .run("true".into(), Some(file), None, false, false, None) + .run( + "true".into(), + Some(file), + None, + false, + false, + JobMeta::default(), + ) .await else { panic!("a file cwd must fail"); @@ -279,7 +300,14 @@ async fn inline_overflow_surfaces_id_and_remains_pollable() { let store = store(Duration::from_secs(5)); let n = DEFAULT_PAGE + 50; let r = store - .run(format!("seq 1 {n}"), None, None, false, false, None) + .run( + format!("seq 1 {n}"), + None, + None, + false, + false, + JobMeta::default(), + ) .await .unwrap(); let RunResult::Inline { id, page, .. } = r else { @@ -311,7 +339,7 @@ async fn concurrent_launches_never_share_an_id_or_a_log() { None, true, false, - Some("race".into()), + JobMeta::titled("race".into()), ) .await }) @@ -343,7 +371,7 @@ async fn slow_command_backgrounds_then_completes() { None, false, false, - None, + JobMeta::default(), ) .await .unwrap(); @@ -363,7 +391,14 @@ async fn slow_command_backgrounds_then_completes() { async fn a_signal_death_is_reported_by_signal() { let store = store(Duration::from_secs(5)); let RunResult::Inline { state, .. } = store - .run("kill -9 $$".into(), None, None, false, false, None) + .run( + "kill -9 $$".into(), + None, + None, + false, + false, + JobMeta::default(), + ) .await .unwrap() else { @@ -412,7 +447,7 @@ async fn started_interactive_job() -> (JobStore, JobId) { None, true, true, - None, + JobMeta::default(), ) .await .unwrap() @@ -510,7 +545,14 @@ async fn kill_unknown_and_finished_say_which() { KillOutcome::Unknown )); let RunResult::Inline { id, .. } = store - .run("echo bye".into(), None, None, false, false, None) + .run( + "echo bye".into(), + None, + None, + false, + false, + JobMeta::default(), + ) .await .unwrap() else { @@ -534,7 +576,7 @@ async fn kill_of_a_finished_job_reaches_what_it_left_running() { None, false, false, - None, + JobMeta::default(), ) .await .unwrap() @@ -668,7 +710,7 @@ async fn leftovers_past_the_log_cap_are_killed_and_the_job_says_why() { None, false, false, - None, + JobMeta::default(), ) .await .unwrap() @@ -720,7 +762,7 @@ async fn a_cancelled_launch_still_finishes_its_job() { None, false, false, - Some("cancel".into()), + JobMeta::titled("cancel".into()), ), ) .await; @@ -757,7 +799,14 @@ async fn a_job_whose_row_cannot_be_written_is_refused() { .await .unwrap(); let result = store - .run("sleep 300".into(), None, None, true, false, None) + .run( + "sleep 300".into(), + None, + None, + true, + false, + JobMeta::default(), + ) .await; assert!(matches!(result, Err(JobError::Store(_)))); assert!(store.jobs.lock().await.is_empty(), "not tracked"); @@ -792,7 +841,14 @@ async fn list_pages_newest_first() { let store = store(Duration::from_secs(5)); for title in ["a", "b", "c"] { store - .run("true".into(), None, None, false, false, Some(title.into())) + .run( + "true".into(), + None, + None, + false, + false, + JobMeta::titled(title.into()), + ) .await .unwrap(); // Distinct start seconds order the rows. @@ -820,7 +876,7 @@ async fn list_and_poll_survive_a_restart() { None, false, false, - None, + JobMeta::default(), ) .await .unwrap() @@ -921,7 +977,7 @@ async fn restart_never_reuses_a_retained_job_id() { None, false, false, - Some("t".into()), + JobMeta::titled("t".into()), ) .await .unwrap() @@ -937,7 +993,7 @@ async fn restart_never_reuses_a_retained_job_id() { None, false, false, - Some("t".into()), + JobMeta::titled("t".into()), ) .await .unwrap() @@ -990,3 +1046,48 @@ async fn store_failures_surface_as_errors() { Err(JobError::Store(_)) )); } + +/// Every job records the agent that started it: `owner` reads it back (live or +/// from the row) and `list` carries it per job; a job with no known caller has +/// no owner. +#[tokio::test] +async fn a_job_records_the_agent_that_started_it() { + let store = store(Duration::from_secs(5)); + let alpha = crate::agent::Agent::new("client-alpha".into(), Some("alpha")); + let r = store + .run( + "true".into(), + None, + None, + false, + false, + JobMeta { + title: Some("owned".into()), + owner: Some(alpha.clone()), + }, + ) + .await + .unwrap(); + let RunResult::Inline { id: owned, .. } = r else { + panic!("`true` finishes inline"); + }; + let anonymous = bg(&store, "true").await; + + assert_eq!(store.owner(&owned).await.unwrap(), Some(alpha.clone())); + assert_eq!(store.owner(&anonymous).await.unwrap(), None); + assert_eq!( + store.owner(&JobId::from("no-such-job")).await.unwrap(), + None + ); + + let page = store.list(0, None).await.unwrap(); + let owner_of = |id: &JobId| { + page.jobs + .iter() + .find(|job| &job.id == id) + .map(|job| job.owner.clone()) + .expect("listed") + }; + assert_eq!(owner_of(&owned), Some(alpha)); + assert_eq!(owner_of(&anonymous), None); +} diff --git a/src/main.rs b/src/main.rs index 4350486..077fea9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ //! mcp-ssh — remote shell + file access for AI agents over authenticated MCP-HTTP. mod admin; +mod agent; mod app; mod auth; mod cli; diff --git a/src/oauth/flow/register.rs b/src/oauth/flow/register.rs index 03a657b..28431e5 100644 --- a/src/oauth/flow/register.rs +++ b/src/oauth/flow/register.rs @@ -8,6 +8,7 @@ use axum::{ use serde_json::json; use super::{is_allowed_redirect, json_error}; +use crate::agent::ClientName; use crate::oauth::AuthState; use crate::oauth::store::RegisterError; @@ -15,18 +16,24 @@ use crate::oauth::store::RegisterError; const MAX_REDIRECT_URIS: usize = 5; /// `/register` — minimal Dynamic Client Registration (RFC 7591). Clients are -/// public (PKCE, no secret), so the only thing persisted is the `client_id` → -/// `redirect_uri` binding that `/authorize` then enforces. Bounded: a few short -/// URIs per client, and a cap on clients overall. +/// public (PKCE, no secret), so what is persisted is the `client_id` → +/// `redirect_uri` binding that `/authorize` then enforces, plus the optional +/// `client_name` other agents see it by — cleaned by [`ClientName::parse`], +/// never echoed raw. Bounded: a few short URIs per client, and a cap on clients +/// overall. pub async fn register( State(st): State<AuthState>, body: Option<Json<serde_json::Value>>, ) -> Response { + let name = body + .as_ref() + .and_then(|Json(b)| b.get("client_name")?.as_str()) + .and_then(ClientName::parse); let redirect_uris = match registered_redirect_uris(body) { Ok(uris) => uris, Err(error) => return json_error(StatusCode::BAD_REQUEST, error), }; - let client_id = match st.store.register_client(&redirect_uris).await { + let client_id = match st.store.register_client(&redirect_uris, name).await { Ok(id) => id, Err(RegisterError::Full | RegisterError::Unavailable) => { return json_error(StatusCode::SERVICE_UNAVAILABLE, "temporarily_unavailable"); diff --git a/src/oauth/mod.rs b/src/oauth/mod.rs index 36a318e..ac505bb 100644 --- a/src/oauth/mod.rs +++ b/src/oauth/mod.rs @@ -23,7 +23,8 @@ mod store; pub use metadata::base_url; pub use secret::hash_token; pub use store::{ - Store, revoke_all, sweep_expired_access, sweep_expired_refresh, sweep_stale_clients, + AgentActivity, PRESENCE_WINDOW, Store, StoreUnavailable, revoke_all, sweep_expired_access, + sweep_expired_refresh, sweep_stale_clients, }; /// Largest request body the OAuth routes accept. Every legitimate body (a token diff --git a/src/oauth/store.rs b/src/oauth/store.rs index 9b07fb4..86896c2 100644 --- a/src/oauth/store.rs +++ b/src/oauth/store.rs @@ -14,7 +14,7 @@ //! so an outage is a 503 with a journal line, not an "invalid token". use std::time::Duration; -use rusqlite::{OptionalExtension, Transaction, TransactionBehavior}; +use rusqlite::{Connection, OptionalExtension, Transaction, TransactionBehavior}; use super::pending::Pending; use super::secret::{hash_token, random_token, verify_pkce}; @@ -22,9 +22,11 @@ use crate::db::{Db, now_unix}; mod clients; mod pair; +mod presence; mod sweep; use pair::{Grant, Rotation, hashes, insert_pair, new_tokens, rotate}; +pub use presence::{AgentActivity, PRESENCE_WINDOW}; pub use sweep::{revoke_all, sweep_expired_access, sweep_expired_refresh, sweep_stale_clients}; const CODE_TTL: Duration = Duration::from_secs(600); @@ -214,23 +216,7 @@ impl Store { let hash = token_hash.to_owned(); // moves into the blocking DB call let now = now_unix(); self.db - .call(move |conn| { - let expiry: Option<i64> = conn - .query_row( - "SELECT expires_unix FROM access_tokens WHERE token_hash = ?1", - [&hash], - |row| row.get(0), - ) - .optional()?; - match expiry { - Some(exp) if exp > now => Ok(true), - Some(_) => { - conn.execute("DELETE FROM access_tokens WHERE token_hash = ?1", [&hash])?; - Ok(false) - } - None => Ok(false), - } - }) + .call(move |conn| live_token_client(conn, &hash, now).map(|client| client.is_some())) .await .map_err(|e| unavailable("validate", e)) } @@ -253,6 +239,27 @@ impl Store { } } +/// The client a live access token (by hash) was issued to; `None` when the token +/// is unknown or expired. An expired row is evicted on the way out, so the table +/// doesn't accumulate dead rows. +fn live_token_client(conn: &Connection, hash: &str, now: i64) -> rusqlite::Result<Option<String>> { + let row: Option<(i64, String)> = conn + .query_row( + "SELECT expires_unix, client_id FROM access_tokens WHERE token_hash = ?1", + [hash], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?; + match row { + Some((expires, client)) if expires > now => Ok(Some(client)), + Some(_) => { + conn.execute("DELETE FROM access_tokens WHERE token_hash = ?1", [hash])?; + Ok(None) + } + None => Ok(None), + } +} + /// Log a store failure at the boundary: the operation and the rusqlite error, /// which never carries a bound parameter (so never a token hash or value). fn unavailable(op: &'static str, error: rusqlite::Error) -> StoreUnavailable { diff --git a/src/oauth/store/clients.rs b/src/oauth/store/clients.rs index 9a0f1c1..d580402 100644 --- a/src/oauth/store/clients.rs +++ b/src/oauth/store/clients.rs @@ -3,6 +3,7 @@ use rusqlite::{OptionalExtension, Transaction, TransactionBehavior}; use super::{RegisterError, Store, StoreUnavailable, unavailable}; +use crate::agent::ClientName; use crate::db::now_unix; use crate::oauth::secret::random_token; @@ -12,12 +13,18 @@ pub(super) const MAX_CLIENTS: i64 = 1000; impl Store { /// Register a client: mint an id and bind it to the redirect URIs that may - /// receive its auth codes. Duplicate URIs collapse to one row. The returned - /// `client_id` is public data, but it is still never logged. - pub async fn register_client(&self, redirect_uris: &[String]) -> Result<String, RegisterError> { + /// receive its auth codes, recording the (already cleaned) name it goes by. + /// Duplicate URIs collapse to one row. The returned `client_id` is public + /// data, but it is still never logged. + pub async fn register_client( + &self, + redirect_uris: &[String], + name: Option<ClientName>, + ) -> Result<String, RegisterError> { let client_id = random_token(); let id = client_id.clone(); // the closure must own its inputs ('static) let uris = redirect_uris.to_vec(); + let name = name.map(|n| n.as_str().to_string()); let now = now_unix(); let registered = self .db @@ -33,9 +40,10 @@ impl Store { } for uri in &uris { tx.execute( - "INSERT OR IGNORE INTO clients (client_id, redirect_uri, created_unix) \ - VALUES (?1, ?2, ?3)", - (&id, uri, now), + "INSERT OR IGNORE INTO clients \ + (client_id, redirect_uri, created_unix, client_name) \ + VALUES (?1, ?2, ?3, ?4)", + (&id, uri, now, &name), )?; } tx.commit()?; diff --git a/src/oauth/store/presence.rs b/src/oauth/store/presence.rs new file mode 100644 index 0000000..fad49d4 --- /dev/null +++ b/src/oauth/store/presence.rs @@ -0,0 +1,105 @@ +//! Who is using this host: the agent (OAuth client) behind a bearer, when each +//! client last used one, and which were active recently. One host, one service +//! user — this is awareness between agents, not isolation. Only ids, names and +//! timestamps are read; never a token. +use std::time::Duration; + +use super::{Store, StoreUnavailable, live_token_client, secs, unavailable}; +use crate::agent::Agent; +use crate::db::now_unix; + +/// How recently a client must have used a bearer to count as active. +pub const PRESENCE_WINDOW: Duration = Duration::from_secs(15 * 60); +/// A client's last-use time is rewritten at most this often (seconds), so a busy +/// agent's requests stay reads, not a write each. +const TOUCH_EVERY: i64 = 60; +/// Most agents one presence listing names. Only an operator-approved login can be +/// active, so this is far above any real count. +const MAX_LISTED: i64 = 50; + +/// A client holding a live login, and when it last used a bearer (`None`: not +/// since this was tracked). +#[derive(Debug)] +pub struct AgentActivity { + pub agent: Agent, + pub last_used_unix: Option<i64>, +} + +impl Store { + /// The agent behind a live bearer (by hash), noting that it was just used. + /// `None` when the token is unknown or expired. + pub async fn authenticate(&self, token_hash: &str) -> Result<Option<Agent>, StoreUnavailable> { + let hash = token_hash.to_owned(); // moves into the blocking DB call + let now = now_unix(); + self.db + .call(move |conn| { + let Some(client_id) = live_token_client(conn, &hash, now)? else { + return Ok(None); + }; + // Aggregates always yield one row: NULLs for a client with no + // registration row (one swept after its token was issued). + let (name, last_used): (Option<String>, Option<i64>) = conn.query_row( + "SELECT MAX(client_name), MAX(last_used_unix) FROM clients \ + WHERE client_id = ?1", + [&client_id], + |r| Ok((r.get(0)?, r.get(1)?)), + )?; + if last_used.is_none_or(|at| now - at >= TOUCH_EVERY) { + conn.execute( + "UPDATE clients SET last_used_unix = ?1 WHERE client_id = ?2", + (now, &client_id), + )?; + } + Ok(Some(Agent::new(client_id, name.as_deref()))) + }) + .await + .map_err(|e| unavailable("authenticate", e)) + } + + /// Agents that used a bearer within [`PRESENCE_WINDOW`], most recent first. + pub async fn active_agents(&self) -> Result<Vec<Agent>, StoreUnavailable> { + let since = now_unix().saturating_sub(secs(PRESENCE_WINDOW)); + self.db + .call(move |conn| { + let mut stmt = conn.prepare( + "SELECT client_id, MAX(client_name) FROM clients \ + WHERE last_used_unix >= ?1 GROUP BY client_id \ + ORDER BY MAX(last_used_unix) DESC LIMIT ?2", + )?; + stmt.query_map((since, MAX_LISTED), |r| { + Ok(Agent::new( + r.get(0)?, + r.get::<_, Option<String>>(1)?.as_deref(), + )) + })? + .collect() + }) + .await + .map_err(|e| unavailable("active_agents", e)) + } + + /// Every client holding a live access or refresh token, most recently used + /// first — the `mcp-ssh sessions` view. + pub async fn logged_in_agents(&self) -> Result<Vec<AgentActivity>, StoreUnavailable> { + let now = now_unix(); + self.db + .call(move |conn| { + let mut stmt = conn.prepare( + "SELECT client_id, MAX(client_name), MAX(last_used_unix) FROM clients \ + WHERE client_id IN ( \ + SELECT client_id FROM access_tokens WHERE expires_unix > ?1 \ + UNION SELECT client_id FROM refresh_tokens WHERE expires_unix > ?1) \ + GROUP BY client_id ORDER BY MAX(last_used_unix) DESC NULLS LAST", + )?; + stmt.query_map([now], |r| { + Ok(AgentActivity { + agent: Agent::new(r.get(0)?, r.get::<_, Option<String>>(1)?.as_deref()), + last_used_unix: r.get(2)?, + }) + })? + .collect() + }) + .await + .map_err(|e| unavailable("logged_in_agents", e)) + } +} diff --git a/src/oauth/store/tests.rs b/src/oauth/store/tests.rs index ce65471..c2fb32f 100644 --- a/src/oauth/store/tests.rs +++ b/src/oauth/store/tests.rs @@ -44,9 +44,9 @@ async fn drop_table(db: &Db, table: &'static str) { async fn a_client_is_bound_to_exactly_the_uris_it_registered() { let store = store(); let uris = ["http://localhost/cb".to_string(), "https://app/cb".into()]; - let client_id = store.register_client(&uris).await.unwrap(); + let client_id = store.register_client(&uris, None).await.unwrap(); let other = store - .register_client(&["https://other/cb".into()]) + .register_client(&["https://other/cb".into()], None) .await .unwrap(); let unknown = "never-registered".to_string(); @@ -73,7 +73,7 @@ async fn registering_the_same_uri_twice_is_one_binding() { let store = store(); let uri = "https://app/cb".to_string(); let client_id = store - .register_client(&[uri.clone(), uri.clone()]) + .register_client(&[uri.clone(), uri.clone()], None) .await .unwrap(); assert!( @@ -102,7 +102,7 @@ async fn registration_is_refused_once_the_client_table_is_full() { .await .unwrap(); assert_eq!( - store.register_client(&["https://b/cb".into()]).await, + store.register_client(&["https://b/cb".into()], None).await, Err(RegisterError::Full) ); } @@ -413,3 +413,135 @@ fn tokens_debug_is_redacted() { let shown = format!("{tokens:?}"); assert!(!shown.contains(&tokens.access) && !shown.contains(&tokens.refresh)); } + +// ---- presence ---- + +/// A live token for a freshly registered client named `name`; returns the bearer. +async fn login_as(store: &Store, name: Option<&str>) -> String { + let client = store + .register_client(&[CB.into()], name.and_then(crate::agent::ClientName::parse)) + .await + .unwrap(); + let code = store + .new_code(ConsentRequest { + client_id: client.clone(), + ..request(&client) + }) + .await + .unwrap(); + store + .redeem(&code, VERIFIER, CB, Some(&client)) + .await + .unwrap() + .access +} + +async fn last_used(db: &Db) -> Vec<Option<i64>> { + db.call(|conn| { + let mut stmt = conn.prepare("SELECT last_used_unix FROM clients")?; + stmt.query_map([], |r| r.get(0))?.collect() + }) + .await + .unwrap() +} + +#[tokio::test] +async fn authenticate_names_the_agent_and_marks_it_active() { + let db = Db::memory(); + let store = Store::new(db.clone()); + let bearer = login_as(&store, Some("cursor")).await; + assert_eq!(last_used(&db).await, [None], "not active before any use"); + + let agent = store + .authenticate(&hash_token(&bearer)) + .await + .unwrap() + .unwrap(); + assert_eq!(agent.name(), Some("cursor")); + let first = last_used(&db).await; + assert!(first[0].is_some(), "the use is recorded"); + + // A second use within a minute is a read: the time doesn't move. + store + .authenticate(&hash_token(&bearer)) + .await + .unwrap() + .unwrap(); + assert_eq!(last_used(&db).await, first); + + assert_eq!( + store.authenticate(&hash_token("unknown")).await.unwrap(), + None + ); +} + +#[tokio::test] +async fn an_expired_bearer_authenticates_no_one_and_is_evicted() { + let db = Db::memory(); + let store = Store::new(db.clone()); + let bearer = login_as(&store, None).await; + db.call(|c| c.execute("UPDATE access_tokens SET expires_unix = 1", [])) + .await + .unwrap(); + assert_eq!( + store.authenticate(&hash_token(&bearer)).await.unwrap(), + None + ); + assert_eq!(row_count(&db, "access_tokens").await, 0); +} + +#[tokio::test] +async fn active_agents_are_those_seen_in_the_window_newest_first() { + let db = Db::memory(); + let store = Store::new(db.clone()); + let (a, b) = ( + login_as(&store, Some("alpha")).await, + login_as(&store, Some("beta")).await, + ); + let _idle = login_as(&store, Some("idle")).await; + store.authenticate(&hash_token(&a)).await.unwrap(); + store.authenticate(&hash_token(&b)).await.unwrap(); + // `alpha` was last seen long ago: outside the window. + let stale = now_unix() - secs(PRESENCE_WINDOW) - 1; + let alpha = store.authenticate(&hash_token(&a)).await.unwrap().unwrap(); + let id = alpha.client_id().to_string(); + db.call(move |c| { + c.execute( + "UPDATE clients SET last_used_unix = ?1 WHERE client_id = ?2", + (stale, id), + ) + }) + .await + .unwrap(); + + let active = store.active_agents().await.unwrap(); + let names: Vec<_> = active.iter().map(|a| a.name()).collect(); + assert_eq!(names, [Some("beta")]); + + let logged_in = store.logged_in_agents().await.unwrap(); + let names: Vec<_> = logged_in.iter().map(|a| a.agent.name()).collect(); + assert_eq!( + names, + [Some("beta"), Some("alpha"), Some("idle")], + "most recent first, never-used last" + ); + assert_eq!(logged_in[2].last_used_unix, None); +} + +#[tokio::test] +async fn a_client_name_is_stored_cleaned() { + let db = Db::memory(); + let store = Store::new(db.clone()); + let bearer = login_as(&store, Some("bad\u{1b}[2J\nname")).await; + let agent = store + .authenticate(&hash_token(&bearer)) + .await + .unwrap() + .unwrap(); + assert_eq!(agent.name(), Some("bad[2J name")); + let stored: String = db + .call(|c| c.query_row("SELECT client_name FROM clients", [], |r| r.get(0))) + .await + .unwrap(); + assert_eq!(stored, "bad[2J name"); +} diff --git a/src/tools/caller.rs b/src/tools/caller.rs new file mode 100644 index 0000000..93c60e6 --- /dev/null +++ b/src/tools/caller.rs @@ -0,0 +1,39 @@ +//! Who is calling: the agent behind a tool call, and how its jobs read to others. +use rmcp::model::Extensions; + +use super::Tools; +use crate::agent::Agent; +use crate::jobs::JobId; + +/// The agent this call came from: `auth::require_auth` puts it on the HTTP +/// request, and rmcp hands the request's parts to the tool. `None` only off the +/// HTTP path (in-process tests). +pub(super) fn caller(extensions: &Extensions) -> Option<Agent> { + extensions + .get::<axum::http::request::Parts>()? + .extensions + .get::<Agent>() + .cloned() +} + +/// The span's `agent` field: a label (a cleaned name + hash tag), never an id. +pub(super) fn label(agent: Option<&Agent>) -> String { + agent.map_or_else(|| "-".to_string(), Agent::label) +} + +impl Tools { + /// The label of the agent that started job `id`, when that is someone other + /// than `caller` — one host, one service user, so another agent's job stays + /// pollable and killable, but the reply says whose it is. A failed lookup + /// only loses the note. + pub(super) async fn foreign_owner(&self, id: &JobId, caller: Option<&Agent>) -> Option<String> { + match self.jobs.owner(id).await { + Ok(Some(owner)) if caller != Some(&owner) => Some(owner.label()), + Ok(_) => None, + Err(error) => { + tracing::warn!(%error, "could not read the job's owner"); + None + } + } + } +} diff --git a/src/tools/job_render.rs b/src/tools/job_render.rs index bef24be..2d20e37 100644 --- a/src/tools/job_render.rs +++ b/src/tools/job_render.rs @@ -4,7 +4,9 @@ use rmcp::model::CallToolResult; use super::{err, ok}; +use crate::agent::Agent; use crate::jobs::{JobError, JobId, JobList, JobState, KillOutcome, RunResult, TailPage}; +use crate::oauth::{PRESENCE_WINDOW, StoreUnavailable}; /// A `bash` call's reply. `background` is whether the caller asked for `bg`, so a /// backgrounded job reads as started rather than as "still running". @@ -21,29 +23,60 @@ pub(super) fn run(result: Result<RunResult, JobError>, background: bool) -> Call } } -/// A `job(action="poll")` reply. +/// A `job(action="poll")` reply. `foreign` labels the job's owner when that is +/// another agent. pub(super) fn poll( id: &JobId, result: Result<Option<(JobState, TailPage)>, JobError>, + foreign: Option<&str>, ) -> CallToolResult { match result { - Ok(Some((state, page))) => ok(state_and_page(id, &state, &page)), + Ok(Some((state, page))) => ok(owner_note(foreign, state_and_page(id, &state, &page))), Ok(None) => err(format!("no such job: {id}")), Err(e) => err(job_error(&e)), } } -/// A `job(action="list")` reply: one page of `{id, status}` objects, newest -/// first, and the cursor for the next page when there is one. -pub(super) fn list(result: Result<JobList, JobError>) -> CallToolResult { +/// One `job(action="list")` entry: who started it is `by` — `you`, another +/// agent's label, or `unknown` for a job from before owners were recorded. +#[derive(serde::Serialize)] +struct ListedJob<'a> { + id: &'a JobId, + state: &'a JobState, + by: String, +} + +/// A `job(action="list")` reply: the presence line (which agents are on this +/// host), then one page of `{id, state, by}` objects, newest first, and the +/// cursor for the next page when there is one. +pub(super) fn list( + result: Result<JobList, JobError>, + caller: Option<&Agent>, + active: Result<Vec<Agent>, StoreUnavailable>, +) -> CallToolResult { let list = match result { Ok(list) => list, Err(e) => return err(job_error(&e)), }; - let mut out = match serde_json::to_string_pretty(&list.jobs) { - Ok(json) => json, + let rows: Vec<ListedJob> = list + .jobs + .iter() + .map(|job| ListedJob { + id: &job.id, + state: &job.state, + by: match &job.owner { + Some(owner) if caller == Some(owner) => "you".to_string(), + Some(owner) => owner.label(), + None => "unknown".to_string(), + }, + }) + .collect(); + let mut out = presence(caller, active); + out.push('\n'); + match serde_json::to_string_pretty(&rows) { + Ok(json) => out.push_str(&json), Err(e) => return err(format!("could not render the job list: {e}")), - }; + } if let Some(next) = list.next_cursor { out.push_str(&format!( "\n[older jobs: job(action=\"list\", cursor={next})]" @@ -52,32 +85,73 @@ pub(super) fn list(result: Result<JobList, JobError>) -> CallToolResult { ok(out) } -/// A `job(action="kill")` reply — each outcome says what actually happened. -pub(super) fn kill(id: &JobId, result: Result<KillOutcome, JobError>) -> CallToolResult { +/// Which agents used this host within [`PRESENCE_WINDOW`], the caller first and +/// marked `you`: `2 agents active (last 15 min): you (claude-code#4f2a), cursor#9b1c`. +fn presence(caller: Option<&Agent>, active: Result<Vec<Agent>, StoreUnavailable>) -> String { + let Ok(active) = active else { + return "(which agents are active is unavailable right now)".to_string(); + }; + let you = caller.map(|me| format!("you ({})", me.label())); + let others = active + .iter() + .filter(|agent| caller != Some(*agent)) + .map(Agent::label); + let names: Vec<String> = you.into_iter().chain(others).collect(); + let minutes = PRESENCE_WINDOW.as_secs() / 60; + let plural = if names.len() == 1 { "" } else { "s" }; + format!( + "{} agent{plural} active (last {minutes} min): {}", + names.len(), + names.join(", ") + ) +} + +/// Prefix a reply about another agent's job with whose it is. +fn owner_note(foreign: Option<&str>, text: String) -> String { + match foreign { + Some(owner) => format!("[started by another agent: {owner}]\n{text}"), + None => text, + } +} + +/// A `job(action="kill")` reply — each outcome says what actually happened, and +/// whose job it was when `foreign` names another agent. +pub(super) fn kill( + id: &JobId, + result: Result<KillOutcome, JobError>, + foreign: Option<&str>, +) -> CallToolResult { + match kill_sentence(id, result) { + Ok(text) => ok(owner_note(foreign, text)), + Err(text) => err(owner_note(foreign, text)), + } +} + +fn kill_sentence(id: &JobId, result: Result<KillOutcome, JobError>) -> Result<String, String> { let outcome = match result { Ok(outcome) => outcome, - Err(e) => return err(job_error(&e)), + Err(e) => return Err(job_error(&e)), }; match outcome { - KillOutcome::Killed => ok(format!("killed {id}")), - KillOutcome::KilledLeftovers => ok(format!( + KillOutcome::Killed => Ok(format!("killed {id}")), + KillOutcome::KilledLeftovers => Ok(format!( "job {id} had already finished; killed the processes it left running" )), - KillOutcome::Unknown => err(format!("no such job: {id}")), - KillOutcome::NotRunning { status } => err(format!( + KillOutcome::Unknown => Err(format!("no such job: {id}")), + KillOutcome::NotRunning { status } => Err(format!( "job {id} is not running (status: {status}) — nothing to kill" )), - KillOutcome::NoProcessGroup => err(format!( + KillOutcome::NoProcessGroup => Err(format!( "job {id} has no recorded process group — it cannot be killed" )), - KillOutcome::CorruptProcessGroup { pgid } => err(format!( + KillOutcome::CorruptProcessGroup { pgid } => Err(format!( "job {id} has a corrupt process group id ({pgid}) — refusing to signal it" )), - KillOutcome::Survived { pgid } => err(format!( + KillOutcome::Survived { pgid } => Err(format!( "job {id} (process group {}) survived TERM then KILL — still running", pgid.get() )), - KillOutcome::NotSignalled { error } => err(format!( + KillOutcome::NotSignalled { error } => Err(format!( "could not signal job {id}: {error} — it may still be running" )), } diff --git a/src/tools/mod.rs b/src/tools/mod.rs index 2100873..df194da 100644 --- a/src/tools/mod.rs +++ b/src/tools/mod.rs @@ -8,8 +8,8 @@ use rmcp::{ common::RequestId, router::tool::ToolRouter, tool::ToolCallContext, wrapper::Parameters, }, model::{ - CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, ServerCapabilities, - ServerConfig, + CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Extensions, + ServerCapabilities, ServerConfig, }, service::RequestContext, tool, tool_handler, tool_router, @@ -17,28 +17,36 @@ use rmcp::{ // `RequestId` above is rmcp's extractor for the per-call JSON-RPC request id. use tracing::Instrument; -use crate::jobs::{JobId, JobStore}; +use std::sync::Arc; + +use crate::jobs::{JobId, JobMeta, JobStore}; +use crate::oauth::Store; mod args; +mod caller; mod files; mod job_render; mod reject; mod render; use args::{BashArgs, FileAction, FileArgs, JobAction, JobArgs}; +use caller::{caller, label}; use render::{render_file, render_file_error}; #[derive(Clone)] pub struct Tools { jobs: JobStore, + /// Who else is on the host: the OAuth store's record of recent bearer use. + agents: Arc<Store>, tool_router: ToolRouter<Self>, } #[tool_router] impl Tools { - pub fn new(jobs: JobStore) -> Self { + pub fn new(jobs: JobStore, agents: Arc<Store>) -> Self { Self { jobs, + agents, tool_router: Self::tool_router(), } } @@ -57,7 +65,11 @@ impl Tools { title, }): Parameters<BashArgs>, RequestId(request_id): RequestId, + extensions: Extensions, ) -> Result<CallToolResult, McpError> { + let caller = caller(&extensions); + let span = + tracing::info_span!("tool", tool = "bash", %request_id, agent = label(caller.as_ref())); async move { // Emit inside the span so the prod subscriber (FmtSpan::NONE) logs the // dispatch with the span's `tool`/`request_id`; a bare span logs nothing. @@ -75,7 +87,10 @@ impl Tools { timeout, background, interactive.unwrap_or(false), - title, + JobMeta { + title, + owner: caller, + }, ) .await; job_render::run(run, background) @@ -83,28 +98,37 @@ impl Tools { log_outcome(&result); Ok(result) } - .instrument(tracing::info_span!("tool", tool = "bash", %request_id)) + .instrument(span) .await } #[tool( - description = "Manage background jobs created by `bash`. action=poll returns job `id`'s status + output newest-first: call it with no cursor to see the most recent output, then page *back* through history with the cursor the reply names (each page is itself in chronological order). action=list lists jobs newest first, paged by cursor/limit. action=kill kills job `id`'s whole process group (and processes a finished job left running)." + description = "Manage background jobs created by `bash`. action=poll returns job `id`'s status + output newest-first: call it with no cursor to see the most recent output, then page *back* through history with the cursor the reply names (each page is itself in chronological order). action=list lists jobs newest first, paged by cursor/limit; it opens with which agents (OAuth clients) used this host in the last 15 min, you first, and each job's `by` is `you` or the agent that started it. action=kill kills job `id`'s whole process group (and processes a finished job left running). Jobs are shared between agents on the host: you can poll or kill another agent's job, and the reply says whose it is." )] async fn job( &self, Parameters(args): Parameters<JobArgs>, RequestId(request_id): RequestId, + extensions: Extensions, ) -> Result<CallToolResult, McpError> { + let caller = caller(&extensions); // `action` is a fixed word only — never the raw string an unknown one carried. - let span = - tracing::info_span!("tool", tool = "job", action = args.action.name(), %request_id); + let span = tracing::info_span!( + "tool", + tool = "job", + action = args.action.name(), + %request_id, + agent = label(caller.as_ref()) + ); async move { tracing::info!("dispatch"); let id = non_empty(args.id).map(JobId::from); let result = match args.action { JobAction::Poll => match id { Some(id) => { - job_render::poll(&id, self.jobs.poll(&id, args.cursor, args.limit).await) + let polled = self.jobs.poll(&id, args.cursor, args.limit).await; + let foreign = self.foreign_owner(&id, caller.as_ref()).await; + job_render::poll(&id, polled, foreign.as_deref()) } None => err("poll requires `id`"), }, @@ -112,10 +136,17 @@ impl Tools { let cursor = args .cursor .map_or(0, |c| usize::try_from(c).unwrap_or(usize::MAX)); - job_render::list(self.jobs.list(cursor, args.limit).await) + let page = self.jobs.list(cursor, args.limit).await; + let active = self.agents.active_agents().await; + job_render::list(page, caller.as_ref(), active) } JobAction::Kill => match id { - Some(id) => job_render::kill(&id, self.jobs.kill(&id).await), + Some(id) => { + // Read the owner first: a kill can't change it, but the + // reaper may drop a finished row right after. + let foreign = self.foreign_owner(&id, caller.as_ref()).await; + job_render::kill(&id, self.jobs.kill(&id).await, foreign.as_deref()) + } None => err("kill requires `id`"), }, JobAction::Unknown(action) => job_render::unknown_action(&action), @@ -134,9 +165,16 @@ impl Tools { &self, Parameters(args): Parameters<FileArgs>, RequestId(request_id): RequestId, + extensions: Extensions, ) -> Result<CallToolResult, McpError> { // `action` is the enum name only — never a path, pattern or content. - let span = tracing::info_span!("tool", tool = "file", action = ?args.action, %request_id); + let span = tracing::info_span!( + "tool", + tool = "file", + action = ?args.action, + %request_id, + agent = label(caller(&extensions).as_ref()) + ); async move { tracing::info!("dispatch"); let recursive = args.recursive.unwrap_or(false); @@ -212,7 +250,7 @@ impl ServerHandler for Tools { ServerConfig::new(ServerCapabilities::builder().enable_tools().build()).with_instructions( "Remote shell + file access for one host. Three tools: `bash` runs a command \ (auto-backgrounds slow ones, returning a job id); `job` (action=poll/list/kill) \ - monitors jobs with paginated output; `file` (action=read/write/append/delete/list/grep/move) \ + monitors jobs with paginated output and shows which other agents share the host; `file` (action=read/write/append/delete/list/grep/move) \ operates locally as the service user.", ) } diff --git a/src/tools/tests.rs b/src/tools/tests.rs index 06e4745..34f1274 100644 --- a/src/tools/tests.rs +++ b/src/tools/tests.rs @@ -131,7 +131,10 @@ async fn file_dispatch_renders_outcomes_and_next_step_hints() { let dir = tempfile::tempdir().unwrap(); let path = |name: &str| dir.path().join(name).to_string_lossy().into_owned(); let call = async |args: FileArgs| { - let r = tools.file(Parameters(args), req()).await.unwrap(); + let r = tools + .file(Parameters(args), req(), Extensions::default()) + .await + .unwrap(); result_text(&r) }; @@ -221,7 +224,11 @@ async fn file_dispatch_rejects_missing_arguments() { ), ] { let r = tools - .file(Parameters(args), RequestId(NumberOrString::Number(1))) + .file( + Parameters(args), + RequestId(NumberOrString::Number(1)), + Extensions::default(), + ) .await .unwrap(); assert_eq!(result_text(&r), (want.to_string(), true)); @@ -255,7 +262,11 @@ async fn file_dispatch_rejects_missing_arguments() { ), ] { let r = tools - .file(Parameters(args), RequestId(NumberOrString::Number(1))) + .file( + Parameters(args), + RequestId(NumberOrString::Number(1)), + Extensions::default(), + ) .await .unwrap(); assert_eq!(result_text(&r), (want.to_string(), true)); @@ -281,6 +292,7 @@ async fn file_delete_of_populated_dir_requires_recursive() { .file( Parameters(delete(None)), RequestId(NumberOrString::Number(1)), + Extensions::default(), ) .await .unwrap(); @@ -292,6 +304,7 @@ async fn file_delete_of_populated_dir_requires_recursive() { .file( Parameters(delete(Some(true))), RequestId(NumberOrString::Number(2)), + Extensions::default(), ) .await .unwrap(); @@ -325,6 +338,7 @@ async fn file_dispatch_logs_action_and_outcome_not_path_or_content() { ..file_args(FileAction::Write) }), RequestId(NumberOrString::Number(9)), + Extensions::default(), ) .await .unwrap(); @@ -362,7 +376,11 @@ fn job_args(action: JobAction, id: Option<&str>) -> JobArgs { async fn call_bash(tools: &Tools, args: BashArgs) -> (String, bool) { let r = tools - .bash(Parameters(args), RequestId(NumberOrString::Number(1))) + .bash( + Parameters(args), + RequestId(NumberOrString::Number(1)), + Extensions::default(), + ) .await .unwrap(); result_text(&r) @@ -370,7 +388,11 @@ async fn call_bash(tools: &Tools, args: BashArgs) -> (String, bool) { async fn call_job(tools: &Tools, args: JobArgs) -> (String, bool) { let r = tools - .job(Parameters(args), RequestId(NumberOrString::Number(1))) + .job( + Parameters(args), + RequestId(NumberOrString::Number(1)), + Extensions::default(), + ) .await .unwrap(); result_text(&r) @@ -466,7 +488,7 @@ async fn job_kill_wording_per_outcome() { (format!("killed {running}"), false) ); - let rendered = |o| result_text(&job_render::kill(&JobId::from("j"), Ok(o))); + let rendered = |o| result_text(&job_render::kill(&JobId::from("j"), Ok(o), None)); assert!( rendered(KillOutcome::KilledLeftovers) .0 @@ -489,6 +511,7 @@ async fn job_kill_wording_per_outcome() { let (out, is_err) = result_text(&job_render::kill( &JobId::from("j"), Err(crate::jobs::JobError::Store(rusqlite::Error::InvalidQuery)), + None, )); assert!( is_err && out == "job store unavailable — try again shortly", @@ -507,7 +530,7 @@ async fn job_list_is_a_bounded_page_with_a_cursor() { db.clone(), ) .unwrap(); - let tools = Tools::new(store); + let tools = Tools::new(store, Arc::new(Store::new(crate::db::Db::memory()))); db.call(|c| { let tx = c.unchecked_transaction()?; for i in 0..5000 { @@ -542,6 +565,7 @@ async fn job_dispatch_logs_action_and_outcome() { .job( Parameters(job_args(JobAction::Poll, Some("nope"))), RequestId(NumberOrString::Number(5)), + Extensions::default(), ) .await .unwrap(); @@ -561,7 +585,7 @@ fn tools() -> Tools { crate::db::Db::memory(), ) .unwrap(); - Tools::new(store) + Tools::new(store, Arc::new(Store::new(crate::db::Db::memory()))) } /// Every tool dispatch emits an event inside a span carrying `tool` + @@ -584,6 +608,7 @@ async fn bash_dispatch_emits_event_with_tool_and_request_id() { title: None, }), RequestId(NumberOrString::Number(42)), + Extensions::default(), ) .await .unwrap(); @@ -777,3 +802,107 @@ fn advertised_input_schemas_are_the_arg_structs() { ); } } + +// ---- agents: presence, `by`, owner notes ---- + +fn agent(id: &str, name: &str) -> crate::agent::Agent { + crate::agent::Agent::new(id.into(), Some(name)) +} + +fn summary(id: &str, owner: Option<crate::agent::Agent>) -> crate::jobs::JobSummary { + crate::jobs::JobSummary { + id: JobId::from(id), + state: crate::jobs::JobState::Running, + owner, + } +} + +#[test] +fn job_list_opens_with_presence_and_marks_each_owner() { + let (me, other) = (agent("me", "claude-code"), agent("other", "cursor")); + let page = crate::jobs::JobList { + jobs: vec![ + summary("mine", Some(me.clone())), + summary("theirs", Some(other.clone())), + summary("legacy", None), + ], + next_cursor: None, + }; + let active = Ok(vec![other.clone(), me.clone()]); + let (out, is_err) = result_text(&job_render::list(Ok(page), Some(&me), active)); + assert!(!is_err, "{out}"); + let (presence, json) = out.split_once('\n').unwrap(); + assert_eq!( + presence, + format!( + "2 agents active (last 15 min): you ({}), {}", + me.label(), + other.label() + ) + ); + let rows: serde_json::Value = serde_json::from_str(json).unwrap(); + let by: Vec<&str> = rows + .as_array() + .unwrap() + .iter() + .map(|r| r["by"].as_str().unwrap()) + .collect(); + assert_eq!(by, ["you", other.label().as_str(), "unknown"]); +} + +#[test] +fn presence_counts_the_caller_even_when_not_yet_recorded_or_unreadable() { + let me = agent("me", "solo"); + let empty = crate::jobs::JobList { + jobs: vec![], + next_cursor: None, + }; + let (out, _) = result_text(&job_render::list(Ok(empty), Some(&me), Ok(vec![]))); + assert!( + out.starts_with(&format!( + "1 agent active (last 15 min): you ({})\n", + me.label() + )), + "{out}" + ); + let empty = crate::jobs::JobList { + jobs: vec![], + next_cursor: None, + }; + let down = Err(crate::oauth::StoreUnavailable); + let (out, is_err) = result_text(&job_render::list(Ok(empty), Some(&me), down)); + assert!( + !is_err && out.starts_with("(which agents are active is unavailable"), + "{out}" + ); +} + +#[test] +fn poll_and_kill_of_another_agents_job_say_whose_it_is() { + let page = crate::jobs::TailPage { + lines: vec!["hello".into()], + older: None, + }; + let id = JobId::from("theirs"); + let polled = Ok(Some((crate::jobs::JobState::Running, page))); + let (out, is_err) = result_text(&job_render::poll(&id, polled, Some("cursor#9b1c"))); + assert!(!is_err); + assert!( + out.starts_with("[started by another agent: cursor#9b1c]\n{\"status\":\"running\"}"), + "{out}" + ); + + let (out, is_err) = result_text(&job_render::kill( + &id, + Ok(KillOutcome::Killed), + Some("cursor#9b1c"), + )); + assert!(!is_err); + assert_eq!( + out, + "[started by another agent: cursor#9b1c]\nkilled theirs" + ); + // Your own job reads as before. + let (out, _) = result_text(&job_render::kill(&id, Ok(KillOutcome::Killed), None)); + assert_eq!(out, "killed theirs"); +} diff --git a/tests/e2e/agents.rs b/tests/e2e/agents.rs new file mode 100644 index 0000000..fd03923 --- /dev/null +++ b/tests/e2e/agents.rs @@ -0,0 +1,234 @@ +//! Several agents on one host: two independently registered OAuth clients, each +//! with its own bearer and session, working at the same time — and seeing each +//! other in `job(action="list")`, in replies about each other's jobs, and in the +//! admin CLI. +use std::process::Command; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use crate::client::{Session, job_id, poll_until}; +use crate::harness::Server; + +/// Concurrency: neither agent waits on the other. Both background a slow job in +/// the same second under the same title (two distinct ids); while one sits in a +/// 2 s inline call, the other's quick commands return at once; and the two slow +/// jobs run side by side — each agent polls its own to completion in about one +/// job's time, not two. +#[tokio::test] +async fn two_agents_run_commands_and_jobs_concurrently() { + let server = Server::start().await; + let (mut alpha, mut beta) = tokio::join!(server.session_as("alpha"), server.session_as("beta")); + + let started = Instant::now(); + let slow = |who: &str| json!({ "cmd": format!("sleep 3; echo {who}-done"), "bg": true, "title": "slow" }); + let (a, b) = tokio::join!( + alpha.call("bash", slow("alpha")), + beta.call("bash", slow("beta")) + ); + assert!(!a.is_error && !b.is_error, "{a:?} {b:?}"); + let (alpha_job, beta_job) = (job_id(&a.text, "slow"), job_id(&b.text, "slow")); + assert_ne!( + alpha_job, beta_job, + "same title, same second: still two jobs" + ); + + let (held, quick) = tokio::join!( + async { + let at = Instant::now(); + let r = alpha + .call( + "bash", + json!({ "cmd": "sleep 2; echo alpha-inline", "timeout": 10 }), + ) + .await; + (r, at.elapsed()) + }, + async { + let at = Instant::now(); + let mut replies = Vec::new(); + for i in 0..5 { + let cmd = format!("echo beta-quick-{i}"); + replies.push(beta.call("bash", json!({ "cmd": cmd })).await); + } + (replies, at.elapsed()) + } + ); + let (inline, held_for) = held; + assert!(inline.text.contains("alpha-inline"), "{inline:?}"); + assert!(held_for >= Duration::from_secs(2), "{held_for:?}"); + let (replies, quick_for) = quick; + for (i, r) in replies.iter().enumerate() { + assert!( + !r.is_error && r.text.contains(&format!("beta-quick-{i}")), + "beta's command ran inline, not stuck behind alpha's: {r:?}" + ); + } + assert!( + quick_for < Duration::from_millis(1500), + "beta's 5 quick commands waited on alpha's 2 s call: {quick_for:?}" + ); + + let (a, b) = tokio::join!( + poll_until(&mut alpha, &alpha_job, "alpha-done"), + poll_until(&mut beta, &beta_job, "beta-done") + ); + assert!( + !a.contains("beta-done") && !b.contains("alpha-done"), + "{a} {b}" + ); + assert!( + started.elapsed() < Duration::from_millis(5500), + "two 3 s jobs ran one after the other: {:?}", + started.elapsed() + ); +} + +/// Awareness: each agent's `job(action="list")` opens with who is active (the +/// caller as `you`), each job says `by` whom; another agent's job can still be +/// polled and killed, and the reply says whose it is. A hostile `client_name` +/// reaches no one with its control characters. The admin CLI shows owners and +/// last-active times. +#[tokio::test] +async fn agents_see_each_other_and_whose_job_is_whose() { + let server = Server::start().await; + let mut alpha = server.session_as("alpha").await; + let mut beta = server.session_as("beta").await; + let mut hostile = server.session_as("evil\u{1b}[31m\nforged-row").await; + + let r = alpha + .call( + "bash", + json!({ "cmd": "sleep 30", "bg": true, "title": "alpha-job" }), + ) + .await; + let alpha_job = job_id(&r.text, "alpha-job"); + let r = beta + .call( + "bash", + json!({ "cmd": "echo beta-out", "bg": true, "title": "beta-job" }), + ) + .await; + let beta_job = job_id(&r.text, "beta-job"); + hostile.call("job", json!({ "action": "list" })).await; + + let (presence, jobs) = list(&mut alpha).await; + assert!( + presence.starts_with("3 agents active (last 15 min): you (alpha#"), + "{presence}" + ); + assert!( + presence.contains("beta#") && presence.contains("evil[31m forged-row#"), + "{presence}" + ); + let alpha_label = between(&presence, "you (", ")"); + assert_eq!(by(&jobs, &alpha_job), "you"); + let beta_label = by(&jobs, &beta_job); + assert!(beta_label.starts_with("beta#"), "{beta_label}"); + + // Beta sees the same jobs from its side. + let (presence, jobs) = list(&mut beta).await; + assert!( + presence.starts_with(&format!( + "3 agents active (last 15 min): you ({beta_label})" + )), + "{presence}" + ); + assert_eq!(by(&jobs, &alpha_job), alpha_label); + assert_eq!(by(&jobs, &beta_job), "you"); + + // Shared, not isolated: beta can poll and kill alpha's job — told whose it is. + let note = format!("[started by another agent: {alpha_label}]"); + let r = beta + .call("job", json!({ "action": "poll", "id": alpha_job })) + .await; + assert!(!r.is_error && r.text.starts_with(¬e), "{r:?}"); + let r = beta + .call("job", json!({ "action": "poll", "id": beta_job })) + .await; + assert!(!r.text.contains("another agent"), "own job, no note: {r:?}"); + let r = beta + .call("job", json!({ "action": "kill", "id": alpha_job })) + .await; + assert!( + !r.is_error && r.text == format!("{note}\nkilled {alpha_job}"), + "{r:?}" + ); + let r = alpha + .call("job", json!({ "action": "poll", "id": alpha_job })) + .await; + assert!( + r.text.contains("killed") && !r.text.contains("another agent"), + "{r:?}" + ); + + let jobs_cli = admin(&server, &["jobs", "--all"]); + assert!(jobs_cli.contains("BY"), "{jobs_cli}"); + for (job, owner) in [(&alpha_job, &alpha_label), (&beta_job, &beta_label)] { + let row = jobs_cli + .lines() + .find(|l| l.starts_with(job.as_str())) + .expect("listed"); + assert!(row.contains(owner.as_str()), "{row}"); + } + let sessions = admin(&server, &["sessions"]); + assert!( + sessions.contains(&alpha_label) && sessions.contains("last active"), + "{sessions}" + ); + for out in [&jobs_cli, &sessions] { + assert!( + !out.contains('\u{1b}'), + "a control character reached the terminal: {out:?}" + ); + } +} + +/// `job(action="list")` split into its presence line and its job rows. +async fn list(s: &mut Session) -> (String, Vec<Value>) { + let r = s.call("job", json!({ "action": "list" })).await; + assert!(!r.is_error, "{r:?}"); + assert!( + !r.text.contains('\u{1b}'), + "a control character reached the agent: {r:?}" + ); + let (presence, json) = r.text.split_once('\n').expect("presence line, then JSON"); + let jobs: Vec<Value> = serde_json::from_str(json).expect("job rows"); + (presence.to_string(), jobs) +} + +fn by(jobs: &[Value], id: &str) -> String { + let job = jobs + .iter() + .find(|j| j["id"] == id) + .unwrap_or_else(|| panic!("{id} not listed: {jobs:?}")); + job["by"].as_str().expect("by").to_string() +} + +fn between(s: &str, open: &str, close: &str) -> String { + let start = s.find(open).expect("open") + open.len(); + let len = s[start..].find(close).expect("close"); + s[start..start + len].to_string() +} + +/// Run an admin subcommand against the server's database, as the operator would. +fn admin(server: &Server, args: &[&str]) -> String { + let out = Command::new(env!("CARGO_BIN_EXE_mcp-ssh")) + .args(args) + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap_or_default()) + .env( + "MCP_SSH_CONFIG", + server.dir.path().join("absent-config.toml"), + ) + .env("MCP_SSH_DB", server.db_path()) + .env("RUST_LOG", "warn") + .output() + .expect("run mcp-ssh admin command"); + assert!( + out.status.success(), + "{args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8(out.stdout).expect("utf-8") +} diff --git a/tests/e2e/harness.rs b/tests/e2e/harness.rs index bb66f8a..fba9ef0 100644 --- a/tests/e2e/harness.rs +++ b/tests/e2e/harness.rs @@ -11,7 +11,7 @@ use std::time::{Duration, Instant}; use reqwest::Client; use crate::client::Session; -use crate::oauth::login; +use crate::oauth::{login, login_as}; pub const USER: &str = "e2e"; pub const PASS: &str = "e2e-password"; @@ -117,6 +117,13 @@ impl Server { let token = login(&self.base).await; Session::open(&self.base, &token).await } + + /// [`Server::session`] as its own OAuth client, registered as `client_name` + /// — one per agent sharing the host. + pub async fn session_as(&self, client_name: &str) -> Session { + let token = login_as(&self.base, Some(client_name)).await; + Session::open(&self.base, &token).await + } } impl Drop for Server { diff --git a/tests/e2e/main.rs b/tests/e2e/main.rs index 7c6511c..47fbe9e 100644 --- a/tests/e2e/main.rs +++ b/tests/e2e/main.rs @@ -6,6 +6,7 @@ mod client; mod harness; mod oauth; +mod agents; mod auth; mod files; mod jobs; diff --git a/tests/e2e/oauth.rs b/tests/e2e/oauth.rs index 3f1127b..2098ae2 100644 --- a/tests/e2e/oauth.rs +++ b/tests/e2e/oauth.rs @@ -16,10 +16,20 @@ pub const REDIRECT: &str = "http://localhost/cb"; /// register → GET /authorize (consent page) → POST /authorize → /token, as the /// headless `bin/mcp-token` does. Returns the access token. pub async fn login(base: &str) -> String { + login_as(base, None).await +} + +/// [`login`] as a client that registers `client_name` (what other agents see it +/// by), or none. +pub async fn login_as(base: &str, client_name: Option<&str>) -> String { let http = http(); + let mut registration = json!({ "redirect_uris": [REDIRECT] }); + if let Some(name) = client_name { + registration["client_name"] = json!(name); + } let reg: Value = http .post(format!("{base}/register")) - .json(&json!({ "redirect_uris": [REDIRECT] })) + .json(®istration) .send() .await .expect("register")