diff --git a/docs/api-coverage.md b/docs/api-coverage.md index beb0b72..a05d8da 100644 --- a/docs/api-coverage.md +++ b/docs/api-coverage.md @@ -73,6 +73,23 @@ one from the CLI, or reuse the UUID supplied with `--idempotency-key`. | `POST /v1/gateway/describe` | `connections describe ID TOOL` | | `POST /v1/gateway/call` | `connections call ID TOOL --arguments JSON` | | `POST /mcp` (JSON-RPC `tools/list`) | `mcp tools [NAME]` | +| `GET /v1/identities` | `identities list` | +| `POST /v1/identities` | `identities create --data JSON` | +| `GET /v1/identities/{id}` | `identities get IDENTITY`, `identities permissions IDENTITY` | +| `PUT /v1/identities/{id}` | `identities update`, `enable`, `disable`, `permissions --allow/--deny` | +| `DELETE /v1/identities/{id}` | `identities delete IDENTITY` | +| `PUT /v1/identities/{id}/grants` | `identities access IDENTITY MEMBER [--assume] [--manage]` | +| `PUT /v1/identities/{id}/accounts/{connectionId}` | `identities account IDENTITY CONNECTION_ID` | +| `GET /v1/identities/{id}/sessions` | `identities sessions list IDENTITY` | +| `POST /v1/identities/{id}/sessions` | `identities sessions start IDENTITY --label LABEL` | +| `DELETE /v1/identities/{id}/sessions/{sessionId}` | `identities sessions revoke IDENTITY SESSION_ID` | + +Identity routes come from platform `640c00b`. +Identity commands resolve names with `GET /v1/identities` and member emails with +`/v1/auth/organization/list-members`, because identity routes accept only full IDs. +Updates read the identity first and send its whole configuration with the change. +To compare supplied grants, they look up your member ID with `/v1/whoami` and a member list +filtered by your user ID. Auth commands use `/v1/auth/device/code`, `/device/token`, `/get-session`, and `/sign-out`. Organization commands use Better Auth's `/v1/auth/organization/*` routes; organization diff --git a/docs/cli-reference.md b/docs/cli-reference.md index b1d09a7..2597ff8 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -43,6 +43,8 @@ For example, use `adapt org members ls` or `adapt sandbox ls --all`. | `registry` | `list`, `create`, `update`, `delete` | | `connections` | `list`, `get`, `create`, `update`, `delete`, `refresh`, `grant`, `oauth`, `oauth-complete`, `calls`, `principals`, `search`, `describe`, `call` | | `keys` | `list`, `create`, `delete` | +| `identities` | `list`, `get`, `create`, `update`, `enable`, `disable`, `delete`, `permissions`, `access`, `account` | +| `identities sessions` | `list`, `start`, `revoke` | | `sessions` | `list`, `revoke`, `revoke-others` | | `mcp` | `list`, `revoke`, `tools` | | `events` | Show organization changes, or personal changes with `--personal` | @@ -376,6 +378,7 @@ The Platform API must support resource ID prefixes. Authentication and organization commands require exact identifiers. This includes `--org`, members, invitations, keys, sessions, and grant principals. +Identity commands accept a full identity ID or an exact identity name; see [Identities](#identities). `org use` accepts a full organization ID or an exact slug. Pagination cursors, idempotency keys, and credential tokens also require exact values. @@ -517,6 +520,115 @@ To revoke the key, use `adapt keys delete KEY_ID`. Logout always uses the saved credential. It never revokes a key from `ADAPT_TOKEN`. +## Identities + +An identity is a set of permissions, tools, and secrets that members assume through expiring sessions. +Identity commands use your browser sign-in. +Platform refuses them for API keys and identity tokens. + +```sh +adapt identities list +adapt identities create --name deploy-bot --allow sandboxes:write --allow commands:write --max-session 1800 +adapt identities create --data @identity.json +adapt identities get deploy-bot +adapt identities update deploy-bot --data '{"maxSessionSeconds":7200}' +adapt identities disable deploy-bot +adapt identities enable deploy-bot +adapt identities delete deploy-bot +``` + +`create` builds the request from `--data` and then its options, which override fields in the JSON. +Permissions start empty, and `--allow` adds actions as in [Permissions](#permissions). +Use `--data` for connections, secrets, and member access. +Only organization owners and admins can create identities, and the creator can assume and manage the new identity. + +Commands accept a full identity ID or an exact name. +Names match without case sensitivity. +The CLI looks names up among the identities that you can assume or manage. + +`update` changes only the fields in its JSON and keeps the others. +A top-level field replaces its whole value, so `permissions` replaces every resource's actions. +Include `version` to refuse the change if the identity has changed since you read it. +Supplied `grants` set every other member's access; Platform keeps your own. +The CLI compares them by each member's access, so applying the same list again saves nothing. +`enable` and `disable` change only `enabled`. + +Platform ends an identity's active sessions when its settings, permissions, or member access change. +Changing your account choice ends your own sessions. +If a command would leave every setting as it is, the CLI does not save, and sessions continue. + +Platform checks the identity's connections again on every save. +If a connection was removed or its allowed tools changed, every save fails until `update` supplies corrected `connections`. +This includes `disable`. +`delete` still works. + +### Permissions + +An identity's sessions can read, write, or use each resource: + +| Resource | Actions | +| --- | --- | +| `sandboxes`, `commands`, `volumes` | `read`, `write` | +| `images`, `endpoints`, `registries`, `models` | `read`, `write`, `use` | +| `mcp-tools`, `secrets` | `read`, `use` | + +```sh +adapt identities permissions deploy-bot +adapt identities permissions deploy-bot --allow sandboxes:write --allow images:use --deny volumes:write +``` + +API names such as `execs`, `ingresses`, and `registryCredentials` also work. +Allowing `write` or `use` also allows `read`. +You can deny `read` separately afterward. +Platform refuses permissions beyond your own access. + +### Member access + +```sh +adapt identities access deploy-bot ana@example.com --assume +adapt identities access deploy-bot MEMBER_ID --assume --manage +adapt identities access deploy-bot ana@example.com +``` + +`--assume` lets a member start sessions. +`--manage` lets a member change the identity. +Without either option, the command removes the member's access. +If the member already has the requested access, the CLI does not save, and the identity's sessions continue. +Use a member ID from `adapt org members list` or the member's email. +Organization owners and admins can manage every identity. + +### Personal accounts + +Some connections require each person's own account. +For those connections, choose your personal connection to the same MCP server: + +```sh +adapt identities account deploy-bot CONNECTION_ID --use PERSONAL_CONNECTION_ID +adapt identities account deploy-bot CONNECTION_ID --clear +``` + +Platform never substitutes a shared account. + +### Sessions + +```sh +adapt identities sessions start deploy-bot --label "nightly deploy" --duration 1800 +adapt identities sessions list deploy-bot +adapt identities sessions revoke deploy-bot SESSION_ID +``` + +`sessions start` prints the session token once in its response. +The CLI never saves it. +Give the token to one process as `ADAPT_TOKEN`; it works with Platform APIs and MCP until it expires or is revoked. +The duration defaults to the identity's maximum session length. +Sessions cannot be extended. + +`sessions list` shows your sessions, or every member's sessions if you manage the identity. +`sessions revoke` checks the session list afterward and fails if Platform found no matching session. + +When a session expires or is revoked, requests that use its token fail with `401`. +Start a new session to continue. + ## Platform MCP tools Platform hosts an MCP server at `/mcp` on the API origin. diff --git a/skills/adapt/SKILL.md b/skills/adapt/SKILL.md index 3acb4d1..7333f4e 100644 --- a/skills/adapt/SKILL.md +++ b/skills/adapt/SKILL.md @@ -117,6 +117,24 @@ describe the message-posting tool and use that channel ID. Listing channels is a separate action from sending a message. Inspect tool results for reported errors as well as the CLI exit status. +## Identities + +```sh +adapt identities list +adapt identities create --name NAME --allow sandboxes:write --allow commands:write +adapt identities permissions IDENTITY +adapt identities sessions start IDENTITY --label "LABEL" --duration 1800 +``` + +Identities are organization-owned sets of permissions, tools, and secrets. +Identity commands need the user's browser sign-in, not an API key. IDENTITY is +a full ID or an exact name. `update --data` changes only the fields given; +`permissions --allow RESOURCE:ACTION` and `--deny` change single actions (read, +write, use). Any change to an identity ends its active sessions. `sessions +start` prints a token once: pass it only to the process that needs it as +`ADAPT_TOKEN`, and never print or store it. An expired or revoked identity +session returns 401; start a new session rather than signing in again. + ## Platform MCP server ```sh diff --git a/src/api.rs b/src/api.rs index 52fbdef..5fbd998 100644 --- a/src/api.rs +++ b/src/api.rs @@ -278,8 +278,25 @@ impl fmt::Display for ApiError { if let Some(retry) = &self.retry_after { write!(f, "; retry after {}", output::safe(retry))?; } + // Identity tokens come from a session, not a login, so signing in again won't help. + // Only Platform's identity-token errors start this way; other messages may + // mention identity sessions in passing. + let identity_session = self.message.starts_with("This identity session"); if self.status == StatusCode::UNAUTHORIZED { - write!(f, "; run `adapt auth login` to sign in again")?; + if identity_session { + write!( + f, + "; start a new one with `adapt identities sessions start`" + )?; + } else { + write!(f, "; run `adapt auth login` to sign in again")?; + } + } + if self.status == StatusCode::FORBIDDEN && identity_session { + write!( + f, + "; an identity session works only in its own organization, so remove --org or ADAPT_ORG_ID" + )?; } if self.code == "ORGANIZATION_REQUIRED" { write!(f, "; run `adapt org list` then `adapt org use ID`")?; diff --git a/src/cli.rs b/src/cli.rs index a1c1173..7a0441e 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,4 +1,6 @@ -use crate::input::{ResourceRef, image_name, pair, search_text}; +use crate::input::{ + ResourceRef, identity_name, identity_ref, image_name, pair, search_text, session_label, +}; use clap::{Args, Parser, Subcommand, ValueEnum}; use std::path::PathBuf; use uuid::Uuid; @@ -8,7 +10,7 @@ use uuid::Uuid; name = "adapt", version, about = "Adapt Platform CLI", - after_help = "Start here: adapt auth login\nUse --json for scripting. Run any command with --help for details.\nCore resource IDs accept full UUIDs or unambiguous hexadecimal prefixes. Auth and organization IDs require full UUIDs." + after_help = "Start here: adapt auth login\nUse --json for scripting. Run any command with --help for details.\nCore resource IDs accept full UUIDs or unambiguous hexadecimal prefixes. Identities accept a full UUID or exact name. Auth and organization IDs require full UUIDs." )] pub struct Cli { /// Saved connection profile @@ -78,6 +80,9 @@ pub enum Command { /// Manage organization API keys #[command(subcommand)] Keys(KeyCommand), + /// Manage identities: scoped permissions, tools, and sessions for people and agents + #[command(subcommand, visible_alias = "identity")] + Identities(IdentityCommand), /// Manage your browser and CLI sessions #[command(subcommand)] Sessions(SessionCommand), @@ -678,6 +683,146 @@ pub enum KeyCommand { }, } +#[derive(Subcommand)] +#[command( + after_help = "IDENTITY is a full ID or an exact identity name (ignoring case).\nIdentity commands use your browser sign-in; API keys and identity tokens cannot manage or assume identities.\nChanging an identity's settings, permissions, or member access ends its active sessions." +)] +pub enum IdentityCommand { + /// List identities you can assume or manage + #[command(visible_alias = "ls")] + List(Page), + /// Show an identity's configuration, member access, and your account bindings + Get { + #[arg(value_name = "IDENTITY", value_parser = identity_ref)] + identity: String, + }, + /// Create an identity from flags, JSON, or both; you get assume and manage access + #[command( + after_help = "Flags override fields in --data. Permissions start empty; add actions with --allow.\nJSON fields: name, permissions, description, enabled, connections, environmentVariableSetIds, maxSessionSeconds, grants.\nOnly organization owners and admins can create identities." + )] + Create(IdentityCreate), + /// Change only the fields in the JSON; other fields keep their current values + #[command( + after_help = "Top-level fields replace the current value whole, so `permissions` replaces every resource.\nUse `adapt identities permissions` to change single actions.\nOmit `version` to update the current version; include it to refuse a stale edit." + )] + Update { + #[arg(value_name = "IDENTITY", value_parser = identity_ref)] + identity: String, + #[command(flatten)] + data: Data, + }, + /// Allow new sessions + Enable { + #[arg(value_name = "IDENTITY", value_parser = identity_ref)] + identity: String, + }, + /// Block new sessions and end active ones + Disable { + #[arg(value_name = "IDENTITY", value_parser = identity_ref)] + identity: String, + }, + /// Delete an identity and end its sessions + Delete { + #[arg(value_name = "IDENTITY", value_parser = identity_ref)] + identity: String, + }, + /// Show or change what the identity's sessions can do: Read, Write, or Use per resource + #[command( + after_help = "Resources: sandboxes, commands, volumes (read, write); images, endpoints, registries, models (read, write, use); mcp-tools, secrets (read, use).\nAPI names such as execs or ingresses also work. Allowing write or use also allows read." + )] + Permissions { + #[arg(value_name = "IDENTITY", value_parser = identity_ref)] + identity: String, + /// Add an action, e.g. sandboxes:write (repeatable) + #[arg(long, value_name = "RESOURCE:ACTION", value_parser = crate::identities::permission)] + allow: Vec, + /// Remove an action, e.g. volumes:write (repeatable) + #[arg(long, value_name = "RESOURCE:ACTION", value_parser = crate::identities::permission)] + deny: Vec, + }, + /// Set a member's access to the identity; with neither flag, removes it + Access { + #[arg(value_name = "IDENTITY", value_parser = identity_ref)] + identity: String, + /// Member ID from `adapt org members list`, or the member's email + member: String, + /// Allow the member to start sessions as this identity + #[arg(long)] + assume: bool, + /// Allow the member to change this identity + #[arg(long)] + manage: bool, + }, + /// Choose your personal account for a connection that uses personal accounts + Account { + #[arg(value_name = "IDENTITY", value_parser = identity_ref)] + identity: String, + /// The identity's organization connection ID + connection: Uuid, + /// Your personal connection to the same MCP server + #[arg( + long = "use", + value_name = "PERSONAL_CONNECTION_ID", + required_unless_present = "clear", + conflicts_with = "clear" + )] + account: Option, + /// Remove your account choice + #[arg(long)] + clear: bool, + }, + /// Start, list, and revoke identity sessions + #[command(subcommand)] + Sessions(IdentitySessionCommand), +} + +#[derive(Args)] +pub struct IdentityCreate { + /// Unique in the organization, ignoring case + #[arg(long, value_parser = identity_name, required_unless_present = "data")] + pub name: Option, + #[arg(long)] + pub description: Option, + /// Allow an action, e.g. sandboxes:write (repeatable); write and use also allow read + #[arg(long, value_name = "RESOURCE:ACTION", value_parser = crate::identities::permission)] + pub allow: Vec, + /// Longest session in seconds; Platform's default is 3600 + #[arg(long, value_name = "SECONDS", value_parser = clap::value_parser!(u32).range(300..=86400))] + pub max_session: Option, + /// Request JSON: inline, @file.json, or - for stdin + #[arg(long, short = 'd')] + pub data: Option, +} + +#[derive(Subcommand)] +pub enum IdentitySessionCommand { + /// List sessions: yours, or everyone's if you manage the identity + #[command(visible_alias = "ls")] + List { + #[arg(value_name = "IDENTITY", value_parser = identity_ref)] + identity: String, + #[command(flatten)] + page: Page, + }, + /// Start a session and print its token once; the token is never saved + Start { + #[arg(value_name = "IDENTITY", value_parser = identity_ref)] + identity: String, + /// Shown to identity managers in session lists + #[arg(long, value_parser = session_label)] + label: String, + /// Lifetime in seconds; defaults to the identity's maximum + #[arg(long, value_name = "SECONDS", value_parser = clap::value_parser!(u32).range(300..=86400))] + duration: Option, + }, + /// Revoke a session + Revoke { + #[arg(value_name = "IDENTITY", value_parser = identity_ref)] + identity: String, + session: Uuid, + }, +} + #[derive(Subcommand)] pub enum SessionCommand { #[command(visible_alias = "ls")] diff --git a/src/commands.rs b/src/commands.rs index d6788ef..3d1ca30 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -3,7 +3,7 @@ use crate::{ auth, cli::*, config::{self, Config, Credential, CredentialKind}, - input, mcp, output, shell, skill, stream, + identities, input, mcp, output, shell, skill, stream, }; use anyhow::{Context, Result, bail}; use clap::ValueEnum; @@ -186,6 +186,7 @@ pub async fn run(cli: Cli) -> Result { }, Command::Connections(command) => connections(&api, command).await?, Command::Keys(command) => keys(&api, command).await?, + Command::Identities(command) => return identities::run(&api, command, cli.json).await, Command::Sessions(command) => match command { SessionCommand::List => api.get("/v1/auth/sessions").await?, SessionCommand::Revoke { id } => api.post("/v1/auth/sessions/revoke", &json!({"id":id.to_string()})).await?, diff --git a/src/identities.rs b/src/identities.rs new file mode 100644 index 0000000..691e9da --- /dev/null +++ b/src/identities.rs @@ -0,0 +1,961 @@ +//! Identity commands: organization-owned permission sets that members assume +//! through expiring, scoped sessions (`/v1/identities`). +//! +//! Platform accepts only full UUIDs in identity routes, so names are resolved +//! here. Updates replace an identity's whole configuration and reset omitted +//! fields to defaults, so every change merges onto the current configuration. + +use crate::{ + api::{Api, ApiError}, + cli::{IdentityCommand, IdentityCreate, IdentitySessionCommand, Page}, + commands::resource_id, + input, output, +}; +use anyhow::{Context, Result, anyhow, bail}; +use reqwest::{Method, StatusCode}; +use serde_json::{Map, Value, json}; +use std::{ + collections::{BTreeMap, BTreeSet}, + io::{self, Write}, +}; +use uuid::Uuid; + +const ROOT: &str = "/v1/identities"; +/// The configuration fields an update carries forward from the current identity. +/// `grants` is left out: omitting it keeps member access as it is. +const CONFIG_FIELDS: [&str; 7] = [ + "name", + "description", + "enabled", + "permissions", + "connections", + "environmentVariableSetIds", + "maxSessionSeconds", +]; +const ENDS_SESSIONS: &str = + "Platform ends an identity's active sessions when its settings or member access change."; +const ACTIONS: [&str; 3] = ["read", "write", "use"]; +/// Permission resources Platform requires in every identity request. +const REQUIRED_RESOURCES: [&str; 4] = ["volumes", "sandboxes", "execs", "ingresses"]; + +/// CLI name, API key, and the actions Platform checks, matching the dashboard's grid. +const RESOURCES: [(&str, &str, &[&str]); 9] = [ + ("sandboxes", "sandboxes", &["read", "write"]), + ("commands", "execs", &["read", "write"]), + ("volumes", "volumes", &["read", "write"]), + ("images", "images", &["read", "write", "use"]), + ("endpoints", "ingresses", &["read", "write", "use"]), + ( + "registries", + "registryCredentials", + &["read", "write", "use"], + ), + ("models", "modelGateway", &["read", "write", "use"]), + ("mcp-tools", "gateway", &["read", "use"]), + ("secrets", "environmentVariables", &["read", "use"]), +]; + +#[derive(Clone, Debug, PartialEq)] +pub struct Permission { + /// The API's resource key, e.g. `execs`. + pub resource: &'static str, + pub action: &'static str, +} + +/// Parses RESOURCE:ACTION, accepting dashboard names (`commands`) and API keys (`execs`). +pub fn permission(value: &str) -> Result { + let (resource, action) = value + .trim() + .split_once(':') + .ok_or("Use RESOURCE:ACTION, e.g. sandboxes:write")?; + let resource = resource.trim().to_ascii_lowercase(); + let action = action.trim().to_ascii_lowercase(); + let (name, key, actions) = RESOURCES + .iter() + .find(|(name, key, _)| resource == *name || resource == key.to_ascii_lowercase()) + .ok_or_else(|| { + format!( + "Unknown resource \"{resource}\"; use one of {}", + RESOURCES.map(|(name, ..)| name).join(", ") + ) + })?; + let action = actions + .iter() + .find(|candidate| **candidate == action) + .ok_or_else(|| format!("{name} accepts {}", actions.join(", ")))?; + Ok(Permission { + resource: key, + action, + }) +} + +pub async fn run(api: &Api, command: IdentityCommand, json: bool) -> Result { + if let Some(result) = dispatch(api, command, json).await.map_err(explain)? { + output::detail(&result, json)?; + } + Ok(0) +} + +/// Returns a value to print, or None when the command printed its own output. +async fn dispatch(api: &Api, command: IdentityCommand, json: bool) -> Result> { + let result = match command { + IdentityCommand::List(page) => { + let result = api.list(ROOT, "identities", &page, false, &[]).await?; + print_rows( + &result, + "identities", + &["id", "name", "enabled", "access"], + identity_row, + json, + )?; + return Ok(None); + } + IdentityCommand::Get { identity } => api.get(&path(resolve(api, &identity).await?)).await?, + IdentityCommand::Create(args) => api.post(ROOT, &creation(args)?).await?, + IdentityCommand::Update { identity, data } => { + let Value::Object(changes) = input::object(Some(&data.data))? else { + unreachable!("input::object returns an object") + }; + save(api, resolve(api, &identity).await?, changes).await? + } + IdentityCommand::Enable { identity } => set_enabled(api, &identity, true).await?, + IdentityCommand::Disable { identity } => set_enabled(api, &identity, false).await?, + IdentityCommand::Delete { identity } => { + let id = resolve(api, &identity).await?; + api.json(Method::DELETE, &path(id), None, &[], None).await?; + json!({"deleted": id.to_string()}) + } + IdentityCommand::Permissions { + identity, + allow, + deny, + } => { + let id = resolve(api, &identity).await?; + let mut result = api.get(&path(id)).await?; + if !allow.is_empty() || !deny.is_empty() { + let mut permissions = result["permissions"] + .as_object() + .cloned() + .context("Identity response is missing its permissions")?; + apply(&mut permissions, &allow, &deny)?; + let changes = + Map::from_iter([("permissions".to_owned(), Value::Object(permissions))]); + result = save_from(api, id, &result, changes).await?; + } + print_permissions(&result, json)?; + return Ok(None); + } + IdentityCommand::Access { + identity, + member, + assume, + manage, + } => { + let id = resolve(api, &identity).await?; + let member = member_id(api, &member).await?; + let summary = json!({"identityId": id.to_string(), "memberId": member.to_string(), "canAssume": assume, "canManage": manage}); + // Platform ends the identity's sessions on every access change, so skip + // one that changes nothing. Only managers see grants; others get the + // server's answer. + let current = api.get(&path(id)).await?; + if current["canManage"] == true && held_access(¤t, member) == (assume, manage) { + eprintln!( + "This member already has that access. Nothing was saved, and the identity's sessions continue." + ); + return Ok(Some(summary)); + } + api.json( + Method::PUT, + &format!("{}/grants", path(id)), + Some(&json!({"memberId": member.to_string(), "canAssume": assume, "canManage": manage})), + &[], + None, + ) + .await?; + changed(summary) + } + IdentityCommand::Account { + identity, + connection, + account, + clear: _, + } => { + let id = resolve(api, &identity).await?; + api.json( + Method::PUT, + &format!("{}/accounts/{connection}", path(id)), + Some(&json!({ "accountId": account.map(|id| id.to_string()) })), + &[], + None, + ) + .await?; + eprintln!( + "Platform ends your active sessions of this identity when your account choice changes." + ); + json!({"identityId": id.to_string(), "connectionId": connection.to_string(), "accountId": account.map(|id| id.to_string())}) + } + IdentityCommand::Sessions(command) => return sessions(api, command, json).await, + }; + Ok(Some(result)) +} + +async fn sessions(api: &Api, command: IdentitySessionCommand, json: bool) -> Result> { + let result = match command { + IdentitySessionCommand::List { identity, page } => { + let id = resolve(api, &identity).await?; + let result = api + .list( + &format!("{}/sessions", path(id)), + "sessions", + &page, + false, + &[], + ) + .await?; + print_rows( + &result, + "sessions", + &["id", "label", "user", "status", "expires"], + session_row, + json, + )?; + return Ok(None); + } + IdentitySessionCommand::Start { + identity, + label, + duration, + } => { + let id = resolve(api, &identity).await?; + let mut body = json!({ "label": label }); + input::put(&mut body, "durationSeconds", duration)?; + let result = api.post(&format!("{}/sessions", path(id)), &body).await?; + eprintln!( + "Started identity session {} (expires {}). The token below is shown once and is not saved; pass it to one process as ADAPT_TOKEN.", + output::safe(result["session"]["id"].as_str().unwrap_or("?")), + output::safe(result["session"]["expiresAt"].as_str().unwrap_or("?")), + ); + result + } + IdentitySessionCommand::Revoke { identity, session } => { + let id = resolve(api, &identity).await?; + let sessions = format!("{}/sessions", path(id)); + api.json( + Method::DELETE, + &format!("{sessions}/{session}"), + None, + &[], + None, + ) + .await?; + // Platform answers 204 even when nothing matched, so confirm the result. + let all = api + .list(&sessions, "sessions", &every_page(), false, &[]) + .await?; + let found = all["sessions"] + .as_array() + .and_then(|rows| rows.iter().find(|row| row["id"] == session.to_string())) + .cloned() + .with_context(|| { + format!("This identity has no session {session} that you can revoke") + })?; + if found["revokedAt"].is_null() && found["active"] == true { + bail!("Platform did not revoke session {session}"); + } + found + } + }; + Ok(Some(result)) +} + +/// Builds a create request from `--data`, then flags. Permissions always include +/// the resources Platform requires, so flags alone make a valid request. +fn creation(args: IdentityCreate) -> Result { + let mut body = input::object(args.data.as_deref())?; + input::put(&mut body, "name", args.name)?; + input::put(&mut body, "description", args.description)?; + input::put(&mut body, "maxSessionSeconds", args.max_session)?; + let mut permissions = match body["permissions"].take() { + Value::Object(permissions) => permissions, + Value::Null => Map::new(), + _ => bail!("permissions must be a JSON object"), + }; + for resource in REQUIRED_RESOURCES { + permissions.entry(resource).or_insert_with(|| json!([])); + } + apply(&mut permissions, &args.allow, &[])?; + body["permissions"] = Value::Object(permissions); + Ok(body) +} + +/// The member's current (assume, manage) access, or none without a grant. +fn held_access(identity: &Value, member: Uuid) -> (bool, bool) { + identity["grants"] + .as_array() + .and_then(|grants| { + grants + .iter() + .find(|grant| grant["memberId"] == member.to_string()) + }) + .map_or((false, false), |grant| { + (grant["canAssume"] == true, grant["canManage"] == true) + }) +} + +fn path(id: Uuid) -> String { + format!("{ROOT}/{id}") +} + +fn every_page() -> Page { + Page { + all: true, + ..Page::default() + } +} + +/// A full UUID is always an ID. Anything else is an exact name, ignoring case, +/// among the identities the caller can assume or manage. +async fn resolve(api: &Api, identity: &str) -> Result { + if let Ok(id) = identity.parse() { + return Ok(id); + } + let all = api + .list(ROOT, "identities", &every_page(), false, &[]) + .await?; + let wanted = identity.to_lowercase(); + let matches: Vec<&Value> = all["identities"] + .as_array() + .context("Invalid identity list")? + .iter() + .filter(|row| { + row["name"] + .as_str() + .is_some_and(|name| name.to_lowercase() == wanted) + }) + .collect(); + match matches.as_slice() { + [one] => resource_id(one), + [] => bail!( + "No identity named \"{}\" that you can assume or manage. Run `adapt identities list` to see them", + output::safe(identity) + ), + many => bail!( + "\"{}\" names {} identities ({}); use an ID instead", + output::safe(identity), + many.len(), + many.iter() + .filter_map(|row| row["id"].as_str()) + .collect::>() + .join(", ") + ), + } +} + +async fn set_enabled(api: &Api, identity: &str, enabled: bool) -> Result { + let changes = Map::from_iter([("enabled".to_owned(), json!(enabled))]); + save(api, resolve(api, identity).await?, changes).await +} + +async fn save(api: &Api, id: Uuid, changes: Map) -> Result { + let current = api.get(&path(id)).await?; + save_from(api, id, ¤t, changes).await +} + +/// Merges top-level `changes` onto `current` and saves with its version, so the +/// server's version check refuses an edit made from an older configuration. +/// Platform ends the identity's sessions on every save, so an edit that changes +/// nothing is not sent. +async fn save_from( + api: &Api, + id: Uuid, + current: &Value, + changes: Map, +) -> Result { + let body = merged(current, changes)?; + // Supplied grants are compared last, because that needs the caller's member ID. + let grants_unchanged = || async { + match body.get("grants") { + None => Ok(true), + Some(grants) => { + Ok::<_, anyhow::Error>(same_grants(current, grants, caller_member(api).await?)) + } + } + }; + if unchanged(current, &body) && grants_unchanged().await? { + eprintln!( + "The identity already has these settings. Nothing was saved, and its sessions continue." + ); + return Ok(current.clone()); + } + let saved = api + .json(Method::PUT, &path(id), Some(&body), &[], None) + .await?; + eprintln!("{ENDS_SESSIONS}"); + Ok(saved) +} + +/// True when every configuration field the save would send already has that +/// value. `grants` is compared separately by `same_grants`. +fn unchanged(current: &Value, body: &Value) -> bool { + body.as_object().is_some_and(|fields| { + fields.iter().all(|(field, value)| { + matches!(field.as_str(), "version" | "grants") || current.get(field) == Some(value) + }) + }) +} + +/// Whether supplied `grants` leave member access as it is. Platform keeps the +/// caller's own grant, gives each listed member its access, and removes every +/// other member, so the comparison ignores order and the name and email fields +/// that responses add. Input Platform would reject, such as a duplicate member or +/// a different access for the caller, counts as a change so its error is shown. +fn same_grants(current: &Value, supplied: &Value, me: Uuid) -> bool { + let me = me.to_string(); + let access = |grant: &Value| (grant["canAssume"] == true, grant["canManage"] == true); + let member = |grant: &Value| grant["memberId"].as_str().map(str::to_ascii_lowercase); + let held: BTreeMap = current["grants"] + .as_array() + .into_iter() + .flatten() + .filter_map(|grant| Some((member(grant)?, access(grant)))) + .filter(|(_, access)| *access != (false, false)) + .collect(); + let mine = held.get(&me).copied().unwrap_or((false, false)); + let Some(supplied) = supplied.as_array() else { + return false; + }; + let mut seen = BTreeSet::new(); + let mut wanted = BTreeMap::new(); + for grant in supplied { + let Some(id) = member(grant) else { + return false; + }; + if !seen.insert(id.clone()) || (id == me && access(grant) != mine) { + return false; + } + if id != me && access(grant) != (false, false) { + wanted.insert(id, access(grant)); + } + } + if mine != (false, false) { + wanted.insert(me, mine); + } + wanted == held +} + +/// The caller's member ID in the selected organization. +async fn caller_member(api: &Api) -> Result { + let caller = api.get("/v1/whoami").await?; + let user = caller["userId"] + .as_str() + .context("Platform did not return the signed-in user's ID")?; + let organization = api + .organization + .as_deref() + .context("Select an organization with `adapt org use ID` or --org ID")?; + let page = api + .json( + Method::GET, + "/v1/auth/organization/list-members", + None, + &[ + ("organizationId".into(), organization.into()), + ("filterField".into(), "userId".into()), + ("filterValue".into(), user.into()), + ], + None, + ) + .await?; + page["members"] + .as_array() + .and_then(|members| members.iter().find(|row| row["userId"] == user)) + .context("You are not a member of this organization") + .and_then(resource_id) +} + +fn merged(current: &Value, mut changes: Map) -> Result { + let version = current["version"] + .as_u64() + .context("Identity response is missing its version")?; + if let Some(expected) = changes.remove("version") + && expected.as_u64() != Some(version) + { + bail!( + "This identity is at version {version}, not {expected}. Run `adapt identities get` and apply your change to the current configuration" + ); + } + let mut body: Map = CONFIG_FIELDS + .iter() + .filter_map(|field| { + current + .get(*field) + .map(|value| ((*field).to_owned(), value.clone())) + }) + .collect(); + body.extend(changes); + body.insert("version".into(), json!(version)); + Ok(Value::Object(body)) +} + +/// Applies allowed actions, then denied ones. Allowing write or use also allows +/// read, as in the dashboard; read can still be denied on its own afterwards. +fn apply( + permissions: &mut Map, + allow: &[Permission], + deny: &[Permission], +) -> Result<()> { + if let Some(both) = allow.iter().find(|p| deny.contains(p)) { + bail!( + "{}:{} is both allowed and denied", + both.resource, + both.action + ); + } + // Leaves a resource untouched when it already matches, so a no-op request + // produces an identical configuration and nothing is saved. + let mut edit = |resource: &str, action: &str, keep: bool| -> Result<()> { + let held = permissions + .get(resource) + .and_then(Value::as_array) + .is_some_and(|actions| actions.iter().any(|existing| existing == action)); + if held == keep { + return Ok(()); + } + let actions = permissions + .entry(resource) + .or_insert_with(|| json!([])) + .as_array_mut() + .with_context(|| format!("Identity permissions for {resource} are not a list"))?; + if keep { + actions.push(json!(action)); + actions.sort_by_key(|existing| ACTIONS.iter().position(|a| existing == a)); + } else { + actions.retain(|existing| existing != action); + } + Ok(()) + }; + for permission in allow { + if permission.action != "read" { + edit(permission.resource, "read", true)?; + } + edit(permission.resource, permission.action, true)?; + } + for permission in deny { + edit(permission.resource, permission.action, false)?; + } + Ok(()) +} + +/// Resolves an email to the member ID that grants use; a UUID is taken as a member ID. +async fn member_id(api: &Api, member: &str) -> Result { + if let Ok(id) = member.parse() { + return Ok(id); + } + if !member.contains('@') { + bail!("Use a member ID from `adapt org members list` or the member's email"); + } + let organization = api + .organization + .as_deref() + .context("Select an organization with `adapt org use ID` or --org ID")?; + let wanted = member.trim().to_lowercase(); + let mut offset = 0; + loop { + let page = api + .json( + Method::GET, + "/v1/auth/organization/list-members", + None, + &[ + ("organizationId".into(), organization.into()), + ("limit".into(), "50".into()), + ("offset".into(), offset.to_string()), + ], + None, + ) + .await?; + let members = page["members"].as_array().context("Invalid member list")?; + if let Some(found) = members.iter().find(|row| { + row["user"]["email"] + .as_str() + .is_some_and(|email| email.to_lowercase() == wanted) + }) { + return resource_id(found); + } + offset += members.len(); + if members.is_empty() || offset as u64 >= page["total"].as_u64().unwrap_or(0) { + bail!( + "No member of this organization has the email {}", + output::safe(member) + ); + } + } +} + +fn changed(result: Value) -> Value { + eprintln!("{ENDS_SESSIONS}"); + result +} + +/// Adds identity-specific advice to Platform errors. +fn explain(error: anyhow::Error) -> anyhow::Error { + let Some(failure) = error.downcast_ref::() else { + return error; + }; + let hint = match failure.status { + StatusCode::FORBIDDEN if failure.message.starts_with("Use your signed-in account") => { + "identity commands use your browser sign-in (`adapt auth login`), not an API key or identity token; unset ADAPT_TOKEN if it holds one" + } + StatusCode::BAD_REQUEST if failure.message.contains("current member") => { + "pass a member ID from `adapt org members list` (not a user ID) or the member's email" + } + _ => return error, + }; + anyhow!("{failure}; {hint}") +} + +fn print_rows( + result: &Value, + field: &str, + columns: &[&str], + row: fn(&Value) -> Value, + json: bool, +) -> Result<()> { + if !output::tables(json) { + return output::print(result, json); + } + let rows: Vec = result[field] + .as_array() + .map(|items| items.iter().map(row).collect()) + .unwrap_or_default(); + let mut out = io::stdout().lock(); + if rows.is_empty() { + writeln!(out, "No results.")?; + } else { + output::table(&mut out, columns, &rows)?; + } + if let Some(cursor) = result["nextCursor"].as_str() { + writeln!( + out, + "\nNext page: rerun with --cursor {cursor} (or use --all)" + )?; + } + Ok(()) +} + +fn identity_row(identity: &Value) -> Value { + let access = match (identity["canAssume"] == true, identity["canManage"] == true) { + (true, true) => json!("assume, manage"), + (true, false) => json!("assume"), + (false, true) => json!("manage"), + (false, false) => Value::Null, + }; + json!({ + "id": identity["id"], + "name": identity["name"], + "enabled": if identity["enabled"] == true { "yes" } else { "no" }, + "access": access, + }) +} + +fn session_row(session: &Value) -> Value { + let status = if session["active"] == true { + "active" + } else if !session["revokedAt"].is_null() { + "revoked" + } else { + "inactive" + }; + json!({ + "id": session["id"], + "label": session["label"], + "user": session["userName"], + "status": status, + "expires": session["expiresAt"], + }) +} + +fn print_permissions(identity: &Value, json: bool) -> Result<()> { + let permissions = &identity["permissions"]; + if !output::tables(json) { + return output::print( + &json!({ + "id": identity["id"], + "name": identity["name"], + "version": identity["version"], + "permissions": permissions, + }), + json, + ); + } + output::table( + &mut io::stdout().lock(), + &["resource", "read", "write", "use"], + &grid(permissions), + )?; + Ok(()) +} + +/// One row per dashboard resource, plus any other resource the identity holds. +fn grid(permissions: &Value) -> Vec { + let cell = |resource: &str, action: &str, offered: bool| { + let held = permissions[resource] + .as_array() + .is_some_and(|actions| actions.iter().any(|a| a == action)); + match (offered, held) { + (_, true) => json!("yes"), + (true, false) => json!("no"), + (false, false) => Value::Null, + } + }; + let row = |name: &str, key: &str, offered: &[&str]| { + let mut row = json!({ "resource": name }); + for action in ACTIONS { + row[action] = cell(key, action, offered.contains(&action)); + } + row + }; + let mut rows: Vec = RESOURCES + .iter() + .map(|(name, key, offered)| row(name, key, offered)) + .collect(); + if let Some(all) = permissions.as_object() { + for (key, actions) in all { + let known = RESOURCES.iter().any(|(_, k, _)| k == key); + if !known && actions.as_array().is_some_and(|a| !a.is_empty()) { + rows.push(row(key, key, &[])); + } + } + } + rows +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn permission_accepts_dashboard_and_api_names() { + let expected = Permission { + resource: "execs", + action: "write", + }; + assert_eq!(permission("commands:write").unwrap(), expected); + assert_eq!(permission(" Execs:WRITE ").unwrap(), expected); + assert_eq!( + permission("registryCredentials:use").unwrap(), + Permission { + resource: "registryCredentials", + action: "use" + } + ); + assert_eq!(permission("mcp-tools:use").unwrap().resource, "gateway"); + } + + #[test] + fn permission_rejects_actions_platform_does_not_check() { + assert_eq!( + permission("sandboxes:use").unwrap_err(), + "sandboxes accepts read, write" + ); + assert_eq!( + permission("secrets:write").unwrap_err(), + "secrets accepts read, use" + ); + assert!( + permission("billing:read") + .unwrap_err() + .starts_with("Unknown resource") + ); + assert!( + permission("sandboxes") + .unwrap_err() + .starts_with("Use RESOURCE:ACTION") + ); + assert!(permission("sandboxes:delete").is_err()); + } + + #[test] + fn allowing_write_or_use_adds_read_and_denials_apply_last() { + let mut permissions = Map::from_iter([ + ("sandboxes".to_owned(), json!(["read"])), + ("volumes".to_owned(), json!(["read", "write"])), + ]); + let allow = [ + permission("images:use").unwrap(), + permission("sandboxes:write").unwrap(), + ]; + let deny = [ + permission("volumes:write").unwrap(), + permission("sandboxes:read").unwrap(), + ]; + apply(&mut permissions, &allow, &deny).unwrap(); + assert_eq!(permissions["images"], json!(["read", "use"])); + assert_eq!(permissions["sandboxes"], json!(["write"])); + assert_eq!(permissions["volumes"], json!(["read"])); + } + + #[test] + fn requests_that_already_hold_leave_permissions_untouched() { + let original = Map::from_iter([("images".to_owned(), json!(["use", "read"]))]); + let mut permissions = original.clone(); + let allow = [permission("images:use").unwrap()]; + let deny = [permission("volumes:write").unwrap()]; + apply(&mut permissions, &allow, &deny).unwrap(); + assert_eq!(permissions, original); + } + + #[test] + fn unchanged_compares_only_the_fields_a_save_sends() { + let current = json!({"version": 2, "enabled": true, "name": "bot", "canManage": true}); + assert!(unchanged( + ¤t, + &json!({"version": 2, "enabled": true, "name": "bot"}) + )); + assert!(!unchanged( + ¤t, + &json!({"version": 2, "enabled": false, "name": "bot"}) + )); + // Grants are compared by `same_grants`, which needs the caller's member ID. + assert!(unchanged(¤t, &json!({"version": 2, "grants": []}))); + } + + #[test] + fn the_same_action_cannot_be_allowed_and_denied() { + let both = [permission("images:use").unwrap()]; + assert!(apply(&mut Map::new(), &both, &both).is_err()); + } + + #[test] + fn merge_keeps_current_fields_and_drops_response_only_ones() { + let current = json!({ + "id": "x", "version": 4, "name": "bot", "description": "d", "enabled": true, + "permissions": {"sandboxes": ["read"]}, "connections": [{"connectionId": "c"}], + "environmentVariableSetIds": ["s"], "maxSessionSeconds": 3600, + "grants": [{"memberId": "m", "name": "n"}], "canManage": true, + }); + let changes = Map::from_iter([("enabled".to_owned(), json!(false))]); + assert_eq!( + merged(¤t, changes).unwrap(), + json!({ + "name": "bot", "description": "d", "enabled": false, + "permissions": {"sandboxes": ["read"]}, "connections": [{"connectionId": "c"}], + "environmentVariableSetIds": ["s"], "maxSessionSeconds": 3600, "version": 4, + }) + ); + } + + #[test] + fn merge_refuses_a_stale_version_and_accepts_the_current_one() { + let current = json!({"version": 4, "name": "bot"}); + let stale = Map::from_iter([("version".to_owned(), json!(3))]); + assert!( + merged(¤t, stale) + .unwrap_err() + .to_string() + .contains("version 4, not 3") + ); + let fresh = Map::from_iter([ + ("version".to_owned(), json!(4)), + ("name".to_owned(), json!("new")), + ]); + assert_eq!( + merged(¤t, fresh).unwrap(), + json!({"name": "new", "version": 4}) + ); + } + + #[test] + fn grid_marks_actions_a_resource_does_not_have() { + let rows = grid(&json!({"execs": ["read"], "gateway": ["use"], "billing": ["read"]})); + assert_eq!( + rows[1], + json!({"resource": "commands", "read": "yes", "write": "no", "use": null}) + ); + assert_eq!( + rows[7], + json!({"resource": "mcp-tools", "read": "no", "write": null, "use": "yes"}) + ); + assert_eq!( + rows[9], + json!({"resource": "billing", "read": "yes", "write": null, "use": null}) + ); + } + + #[test] + fn rows_summarize_access_and_session_status() { + let identity = json!({"id": "i", "name": "bot", "enabled": false, "canAssume": false, "canManage": true}); + assert_eq!( + identity_row(&identity), + json!({"id": "i", "name": "bot", "enabled": "no", "access": "manage"}) + ); + let revoked = json!({"id": "s", "label": "ci", "userName": "Ana", "active": false, "revokedAt": "2026-11-17T00:00:00Z", "expiresAt": "e"}); + assert_eq!(session_row(&revoked)["status"], "revoked"); + let ended = json!({"active": false, "revokedAt": null}); + assert_eq!(session_row(&ended)["status"], "inactive"); + } + + #[test] + fn grants_compare_by_the_access_platform_would_keep() { + let me: Uuid = "00000000-0000-4000-8000-000000000000".parse().unwrap(); + let (m0, m1, m2) = ( + me.to_string(), + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + ); + let grant = |id: &str, assume: bool, manage: bool| json!({"memberId": id, "canAssume": assume, "canManage": manage}); + let current = json!({"grants": [ + {"memberId": m0, "canAssume": true, "canManage": true, "name": "Me", "email": "me@x"}, + {"memberId": m1, "canAssume": true, "canManage": false, "name": "Ana", "email": "ana@x"}, + ]}); + let same = |supplied: Value| same_grants(¤t, &supplied, me); + assert!(same(json!([grant(m1, true, false)])), "the caller left out"); + assert!( + same(json!([grant(&m0, true, true), grant(m1, true, false)])), + "the caller repeated" + ); + assert!( + same(json!([ + grant(&m1.to_uppercase(), true, false), + grant(m2, false, false) + ])), + "case and no-access entries" + ); + assert!( + !same(json!([grant(&m0, true, false), grant(m1, true, false)])), + "the caller's own access changed" + ); + assert!(!same(json!([])), "a member removed"); + assert!( + !same(json!([grant(m1, true, true)])), + "a member's access changed" + ); + assert!( + !same(json!([grant(m1, true, false), grant(m2, true, false)])), + "a member added" + ); + assert!( + !same(json!([grant(m1, true, false), grant(m1, true, false)])), + "a duplicate member" + ); + assert!( + !same(json!([grant(m2, false, false), grant(m2, true, false)])), + "a duplicate after a no-access entry" + ); + assert!(!same(json!({"memberId": m1})), "not a list"); + + // An admin managing an identity without a grant of their own. + let without_mine = + json!({"grants": [{"memberId": m1, "canAssume": true, "canManage": false}]}); + assert!(same_grants( + &without_mine, + &json!([grant(m1, true, false), grant(&m0, false, false)]), + me + )); + assert!(!same_grants( + &without_mine, + &json!([grant(&m0, true, false)]), + me + )); + } +} diff --git a/src/input.rs b/src/input.rs index 425dc6d..490733b 100644 --- a/src/input.rs +++ b/src/input.rs @@ -117,6 +117,39 @@ pub fn search_text(value: &str) -> Result { Ok(value.into()) } +/// An identity selector: a full UUID, or a name that Platform compares trimmed. +pub fn identity_ref(value: &str) -> Result { + let value = js_trim(value); + if value.is_empty() { + return Err("Use an identity name or ID".into()); + } + Ok(value.into()) +} + +/// Platform trims identity names and requires 1 to 100 characters. +pub fn identity_name(value: &str) -> Result { + let value = js_trim(value); + if value.is_empty() { + return Err("Identity name cannot be empty".into()); + } + if value.chars().count() > 100 { + return Err("Identity name must be at most 100 characters".into()); + } + Ok(value.into()) +} + +/// Platform trims session labels and requires 1 to 100 characters. +pub fn session_label(value: &str) -> Result { + let value = js_trim(value); + if value.is_empty() { + return Err("Session label cannot be empty".into()); + } + if value.chars().count() > 100 { + return Err("Session label must be at most 100 characters".into()); + } + Ok(value.into()) +} + /// Platform trims image names on import and when filtering, and rejects a blank one. pub fn image_name(value: &str) -> Result { let value = js_trim(value); diff --git a/src/main.rs b/src/main.rs index bb1b7b0..4eda65a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ mod auth; mod cli; mod commands; mod config; +mod identities; mod input; mod mcp; mod output; diff --git a/src/output.rs b/src/output.rs index fa3102f..8530119 100644 --- a/src/output.rs +++ b/src/output.rs @@ -69,6 +69,19 @@ pub fn print(value: &Value, json: bool) -> Result<()> { Ok(()) } +/// Prints one object: indented JSON in a terminal, compact JSON when piped. +/// Unlike `print`, it never shows a field such as `connections` as a table. +pub fn detail(value: &Value, json: bool) -> Result<()> { + let mut out = io::stdout().lock(); + if tables(json) { + serde_json::to_writer_pretty(&mut out, value)?; + } else { + serde_json::to_writer(&mut out, value)?; + } + writeln!(out)?; + Ok(()) +} + /// Writes `keys` of each row as left-aligned columns under uppercase headings. /// Cells are sanitized and cut at 80 characters; missing values show as —. pub fn table(out: &mut impl Write, keys: &[&str], rows: &[Value]) -> io::Result<()> { diff --git a/tests/cli.rs b/tests/cli.rs index 10ce12e..4af9333 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use std::time::Duration; use support::*; +mod identities; mod image_list; mod mcp_tools; mod resource_prefixes; diff --git a/tests/identities/mod.rs b/tests/identities/mod.rs new file mode 100644 index 0000000..1cb558f --- /dev/null +++ b/tests/identities/mod.rs @@ -0,0 +1,1093 @@ +use crate::support::*; +use serde_json::{Value, json}; + +// Platform's identity routes take full UUIDs only, so the CLI resolves names, and +// updates replace the whole configuration, so the CLI merges changes onto it. + +const OTHER: &str = "44444444-4444-4444-8444-444444444444"; +const MEMBER: &str = "55555555-5555-4555-8555-555555555555"; +const CONNECTION: &str = "66666666-6666-4666-8666-666666666666"; +const SESSION: &str = "77777777-7777-4777-8777-777777777777"; +const USER: &str = "88888888-8888-4888-8888-888888888888"; +const SELF: &str = "99999999-9999-4999-8999-999999999999"; +const TOKEN: &str = "adapt_identity_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + +/// Expects one authenticated request and answers with `status` and `reply`. +fn call( + method: &'static str, + target: String, + body: Option, + status: u16, + reply: Option, +) -> Handler { + Box::new(move |request| { + assert_eq!(request.method, method); + assert_eq!(request.target, target); + assert_eq!(request.headers["authorization"], "Bearer test-token"); + assert_eq!(request.headers["x-organization-id"], ORG); + if let Some(body) = body { + assert_eq!(request.json(), body); + } + match reply { + Some(reply) => Reply::json(status, reply), + None => Reply { + status, + content_type: "application/json", + headers: vec![], + body: vec![], + }, + } + }) +} + +fn detail() -> Value { + json!({ + "id": ID, "organizationId": ORG, "name": "deploy-bot", "description": "Deploys", + "enabled": true, "version": 3, + "permissions": {"sandboxes": ["read", "write"], "volumes": ["read", "write"], "execs": ["read"], "ingresses": []}, + "connections": [{"connectionId": CONNECTION, "account": "shared", "tools": ["search"]}], + "environmentVariableSetIds": [OTHER], "maxSessionSeconds": 3600, + "createdAt": "2026-11-01T00:00:00.000Z", "updatedAt": "2026-11-01T00:00:00.000Z", + "canAssume": true, "canManage": true, + "grants": [{"memberId": MEMBER, "canAssume": true, "canManage": true, "name": "Ana", "email": "ana@example.com"}], + "accounts": [], "connectionNames": {}, "environmentVariableSets": {}, + }) +} + +/// The update body the CLI should send: the current configuration without +/// response-only fields or grants, plus `changes`. +fn saved(changes: Value) -> Value { + let mut body = json!({ + "name": "deploy-bot", "description": "Deploys", "enabled": true, + "permissions": {"sandboxes": ["read", "write"], "volumes": ["read", "write"], "execs": ["read"], "ingresses": []}, + "connections": [{"connectionId": CONNECTION, "account": "shared", "tools": ["search"]}], + "environmentVariableSetIds": [OTHER], "maxSessionSeconds": 3600, "version": 3, + }); + for (key, value) in changes.as_object().unwrap() { + body[key] = value.clone(); + } + body +} + +fn listed(rows: Value, next: Option<&str>) -> Value { + json!({"identities": rows, "canCreate": true, "nextCursor": next}) +} + +fn failure(output: &std::process::Output) -> String { + assert!(!output.status.success(), "command unexpectedly succeeded"); + String::from_utf8_lossy(&output.stderr).into_owned() +} + +#[test] +fn list_follows_every_page_without_a_limit() { + let server = Server::start(vec![ + call( + "GET", + "/v1/identities".into(), + None, + 200, + Some(listed(json!([{"id": ID, "name": "a"}]), Some(OTHER))), + ), + call( + "GET", + format!("/v1/identities?cursor={OTHER}"), + None, + 200, + Some(listed(json!([{"id": OTHER, "name": "b"}]), None)), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let output = success(&run( + dir.path(), + &server.url, + &["identities", "list", "--all"], + )); + assert_eq!(output["identities"].as_array().unwrap().len(), 2); + server.finish(); +} + +#[test] +fn list_rejects_a_limit_platform_does_not_accept() { + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run( + dir.path(), + "http://127.0.0.1:9", + &["identities", "list", "--limit", "5"], + )); + assert!(stderr.contains("fixed page size"), "{stderr}"); +} + +#[test] +fn a_name_resolves_ignoring_case_and_surrounding_space() { + let server = Server::start(vec![ + call( + "GET", + "/v1/identities".into(), + None, + 200, + Some(listed( + json!([{"id": OTHER, "name": "other"}, {"id": ID, "name": "deploy-bot"}]), + None, + )), + ), + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let output = success(&run( + dir.path(), + &server.url, + &["identities", "get", " Deploy-Bot "], + )); + assert_eq!(output["id"], ID); + server.finish(); +} + +#[test] +fn a_full_uuid_is_used_without_a_lookup() { + let server = Server::start(vec![call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + )]); + let dir = tempfile::tempdir().unwrap(); + success(&run(dir.path(), &server.url, &["identities", "get", ID])); + assert_eq!(server.finish().len(), 1); +} + +#[test] +fn an_unknown_name_fails_before_any_detail_request() { + let server = Server::start(vec![call( + "GET", + "/v1/identities".into(), + None, + 200, + Some(listed(json!([{"id": ID, "name": "deploy-bot"}]), None)), + )]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run( + dir.path(), + &server.url, + &["identities", "get", "missing"], + )); + assert!( + stderr.contains("No identity named \"missing\" that you can assume or manage"), + "{stderr}" + ); + server.finish(); +} + +#[test] +fn an_ambiguous_name_lists_the_matching_ids() { + let server = Server::start(vec![call( + "GET", + "/v1/identities".into(), + None, + 200, + Some(listed( + json!([{"id": ID, "name": "Bot"}, {"id": OTHER, "name": "bot"}]), + None, + )), + )]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run(dir.path(), &server.url, &["identities", "get", "bot"])); + assert!( + stderr.contains(&format!("names 2 identities ({ID}, {OTHER}); use an ID")), + "{stderr}" + ); + server.finish(); +} + +#[test] +fn update_merges_changes_onto_the_current_configuration() { + let server = Server::start(vec![ + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + ), + call( + "PUT", + format!("/v1/identities/{ID}"), + Some(saved( + json!({"maxSessionSeconds": 7200, "description": "New"}), + )), + 200, + Some(detail()), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let output = run( + dir.path(), + &server.url, + &[ + "identities", + "update", + ID, + "--data", + r#"{"maxSessionSeconds":7200,"description":"New"}"#, + ], + ); + success(&output); + assert!(String::from_utf8_lossy(&output.stderr).contains("ends an identity's active sessions")); + server.finish(); +} + +#[test] +fn update_passes_grants_through_only_when_supplied() { + let grants = json!([{"memberId": MEMBER, "canAssume": true, "canManage": false}]); + let server = Server::start(vec![ + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + ), + whoami(), + own_membership(), + call( + "PUT", + format!("/v1/identities/{ID}"), + Some(saved(json!({ "grants": grants }))), + 200, + Some(detail()), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let data = json!({ "grants": grants }).to_string(); + success(&run( + dir.path(), + &server.url, + &["identities", "update", ID, "--data", &data], + )); + server.finish(); +} + +#[test] +fn update_refuses_a_stale_version_without_saving() { + let server = Server::start(vec![call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + )]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run( + dir.path(), + &server.url, + &[ + "identities", + "update", + ID, + "--data", + r#"{"version":2,"enabled":false}"#, + ], + )); + assert!(stderr.contains("version 3, not 2"), "{stderr}"); + assert_eq!(server.finish().len(), 1); +} + +#[test] +fn a_server_version_conflict_is_reported() { + let server = Server::start(vec![ + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + ), + call( + "PUT", + format!("/v1/identities/{ID}"), + None, + 409, + Some( + json!({"error": {"code": "CONFLICT", "message": "This identity changed. Reload it before saving."}}), + ), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run( + dir.path(), + &server.url, + &["identities", "disable", ID], + )); + assert!( + stderr.contains("409 CONFLICT: This identity changed"), + "{stderr}" + ); + server.finish(); +} + +#[test] +fn enable_and_disable_change_only_enabled() { + for (command, enabled) in [("disable", false), ("enable", true)] { + let mut current = detail(); + current["enabled"] = json!(!enabled); + let server = Server::start(vec![ + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(current), + ), + call( + "PUT", + format!("/v1/identities/{ID}"), + Some(saved(json!({ "enabled": enabled }))), + 200, + Some(detail()), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + success(&run(dir.path(), &server.url, &["identities", command, ID])); + server.finish(); + } +} + +#[test] +fn delete_confirms_the_deleted_id() { + let server = Server::start(vec![call( + "DELETE", + format!("/v1/identities/{ID}"), + None, + 204, + None, + )]); + let dir = tempfile::tempdir().unwrap(); + let output = success(&run(dir.path(), &server.url, &["identities", "delete", ID])); + assert_eq!(output, json!({ "deleted": ID })); + server.finish(); +} + +#[test] +fn permissions_without_changes_only_reads() { + let server = Server::start(vec![call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + )]); + let dir = tempfile::tempdir().unwrap(); + let output = success(&run( + dir.path(), + &server.url, + &["identities", "permissions", ID], + )); + assert_eq!(output["version"], 3); + assert_eq!(output["permissions"]["sandboxes"], json!(["read", "write"])); + assert_eq!(server.finish().len(), 1); +} + +#[test] +fn permissions_allow_and_deny_save_the_merged_permissions() { + let permissions = json!({ + "sandboxes": ["read", "write"], "volumes": ["read"], "execs": ["read", "write"], + "ingresses": [], "images": ["read", "use"], + }); + let mut updated = detail(); + updated["permissions"] = permissions.clone(); + let server = Server::start(vec![ + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + ), + call( + "PUT", + format!("/v1/identities/{ID}"), + Some(saved(json!({ "permissions": permissions }))), + 200, + Some(updated), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let output = success(&run( + dir.path(), + &server.url, + &[ + "identities", + "permissions", + ID, + "--allow", + "commands:write", + "--allow", + "images:use", + "--deny", + "volumes:write", + ], + )); + assert_eq!(output["permissions"]["images"], json!(["read", "use"])); + server.finish(); +} + +#[test] +fn permissions_reject_an_action_the_resource_does_not_have() { + let dir = tempfile::tempdir().unwrap(); + let output = run( + dir.path(), + "http://127.0.0.1:9", + &["identities", "permissions", ID, "--allow", "sandboxes:use"], + ); + assert_eq!(output.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&output.stderr).contains("sandboxes accepts read, write")); +} + +#[test] +fn access_finds_a_member_by_email_across_pages() { + let members = |offset: u64, email: &str, id: &str| { + call( + "GET", + format!( + "/v1/auth/organization/list-members?organizationId={ORG}&limit=50&offset={offset}" + ), + None, + 200, + Some( + json!({"members": [{"id": id, "userId": OTHER, "user": {"email": email, "name": "x"}}], "total": 2}), + ), + ) + }; + let server = Server::start(vec![ + members(0, "someone@example.com", OTHER), + members(1, "Ana@Example.com", MEMBER), + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + ), + call( + "PUT", + format!("/v1/identities/{ID}/grants"), + Some(json!({"memberId": MEMBER, "canAssume": true, "canManage": false})), + 204, + None, + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let output = success(&run( + dir.path(), + &server.url, + &["identities", "access", ID, "ana@example.com", "--assume"], + )); + assert_eq!(output["memberId"], MEMBER); + assert_eq!(output["canAssume"], true); + server.finish(); +} + +#[test] +fn access_without_flags_removes_a_member_by_id() { + let server = Server::start(vec![ + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + ), + call( + "PUT", + format!("/v1/identities/{ID}/grants"), + Some(json!({"memberId": MEMBER, "canAssume": false, "canManage": false})), + 204, + None, + ), + ]); + let dir = tempfile::tempdir().unwrap(); + success(&run( + dir.path(), + &server.url, + &["identities", "access", ID, MEMBER], + )); + server.finish(); +} + +#[test] +fn access_explains_that_grants_need_a_member_id() { + let server = Server::start(vec![ + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + ), + call( + "PUT", + format!("/v1/identities/{ID}/grants"), + None, + 400, + Some( + json!({"error": {"code": "INVALID_REQUEST", "message": "Choose a current member of this organization."}}), + ), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run( + dir.path(), + &server.url, + &["identities", "access", ID, OTHER, "--manage"], + )); + assert!(stderr.contains("not a user ID"), "{stderr}"); + server.finish(); +} + +#[test] +fn account_selects_and_clears_a_personal_connection() { + for (args, account) in [ + (vec!["--use", OTHER], json!(OTHER)), + (vec!["--clear"], Value::Null), + ] { + let server = Server::start(vec![call( + "PUT", + format!("/v1/identities/{ID}/accounts/{CONNECTION}"), + Some(json!({ "accountId": account })), + 204, + None, + )]); + let dir = tempfile::tempdir().unwrap(); + let mut command = vec!["identities", "account", ID, CONNECTION]; + command.extend(args); + assert_eq!( + success(&run(dir.path(), &server.url, &command))["accountId"], + account + ); + server.finish(); + } +} + +#[test] +fn account_requires_a_choice() { + let dir = tempfile::tempdir().unwrap(); + let output = run( + dir.path(), + "http://127.0.0.1:9", + &["identities", "account", ID, CONNECTION], + ); + assert_eq!(output.status.code(), Some(2)); +} + +#[test] +fn session_start_prints_the_token_once_on_stdout_only() { + let session = json!({"id": SESSION, "identityId": ID, "label": "ci", "expiresAt": "2026-11-18T00:15:00.000Z", "active": true}); + let server = Server::start(vec![call( + "POST", + format!("/v1/identities/{ID}/sessions"), + Some(json!({"label": "ci", "durationSeconds": 900})), + 201, + Some(json!({ "session": session, "token": TOKEN })), + )]); + let dir = tempfile::tempdir().unwrap(); + let output = run( + dir.path(), + &server.url, + &[ + "identities", + "sessions", + "start", + ID, + "--label", + " ci ", + "--duration", + "900", + ], + ); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + assert_eq!(success(&output)["token"], TOKEN); + assert!(stderr.contains("shown once"), "{stderr}"); + assert!(!stderr.contains(TOKEN)); + assert!( + !std::fs::read_to_string(dir.path().join("config.json")).is_ok_and(|c| c.contains(TOKEN)) + ); + server.finish(); +} + +#[test] +fn session_start_rejects_out_of_range_durations_and_blank_labels() { + let dir = tempfile::tempdir().unwrap(); + for args in [ + vec!["--label", "ci", "--duration", "60"], + vec!["--label", " "], + ] { + let mut command = vec!["identities", "sessions", "start", ID]; + command.extend(args); + assert_eq!( + run(dir.path(), "http://127.0.0.1:9", &command) + .status + .code(), + Some(2) + ); + } +} + +#[test] +fn session_revoke_confirms_the_session_was_revoked() { + let revoked = json!({"id": SESSION, "label": "ci", "active": false, "revokedAt": "2026-11-17T00:00:00.000Z"}); + let server = Server::start(vec![ + call( + "DELETE", + format!("/v1/identities/{ID}/sessions/{SESSION}"), + None, + 204, + None, + ), + call( + "GET", + format!("/v1/identities/{ID}/sessions"), + None, + 200, + Some(json!({"sessions": [revoked], "nextCursor": null})), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let output = success(&run( + dir.path(), + &server.url, + &["identities", "sessions", "revoke", ID, SESSION], + )); + assert_eq!(output["revokedAt"], "2026-11-17T00:00:00.000Z"); + server.finish(); +} + +#[test] +fn session_revoke_reports_a_session_platform_did_not_find() { + let server = Server::start(vec![ + call( + "DELETE", + format!("/v1/identities/{ID}/sessions/{SESSION}"), + None, + 204, + None, + ), + call( + "GET", + format!("/v1/identities/{ID}/sessions"), + None, + 200, + Some(json!({"sessions": [], "nextCursor": null})), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run( + dir.path(), + &server.url, + &["identities", "sessions", "revoke", ID, SESSION], + )); + assert!( + stderr.contains(&format!("no session {SESSION} that you can revoke")), + "{stderr}" + ); + server.finish(); +} + +#[test] +fn identity_commands_explain_that_they_need_a_browser_sign_in() { + let server = Server::start(vec![call( + "GET", + "/v1/identities".into(), + None, + 403, + Some( + json!({"error": {"code": "FORBIDDEN", "message": "Use your signed-in account to manage or assume identities."}}), + ), + )]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run(dir.path(), &server.url, &["identities", "list"])); + assert!( + stderr.contains("not an API key or identity token"), + "{stderr}" + ); + server.finish(); +} + +#[test] +fn an_expired_identity_token_points_to_a_new_session_not_a_login() { + let server = Server::start(vec![call( + "GET", + "/v1/sandboxes?limit=50".into(), + None, + 401, + Some( + json!({"error": {"code": "UNAUTHENTICATED", "message": "This identity session expired or its access changed. Start a new session."}}), + ), + )]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run(dir.path(), &server.url, &["sandbox", "list"])); + assert!( + stderr.contains("adapt identities sessions start"), + "{stderr}" + ); + assert!(!stderr.contains("adapt auth login"), "{stderr}"); + server.finish(); +} + +#[test] +fn a_change_to_current_values_is_not_saved_so_sessions_continue() { + let server = Server::start(vec![call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + )]); + let dir = tempfile::tempdir().unwrap(); + let output = run(dir.path(), &server.url, &["identities", "enable", ID]); + assert_eq!(success(&output)["id"], ID); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("Nothing was saved"), "{stderr}"); + assert!( + !stderr.contains("ends an identity's active sessions"), + "{stderr}" + ); + assert_eq!(server.finish().len(), 1); +} + +#[test] +fn allowing_a_held_permission_is_not_saved() { + let server = Server::start(vec![call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + )]); + let dir = tempfile::tempdir().unwrap(); + let output = run( + dir.path(), + &server.url, + &[ + "identities", + "permissions", + ID, + "--allow", + "sandboxes:write", + "--deny", + "images:use", + ], + ); + assert_eq!( + success(&output)["permissions"]["sandboxes"], + json!(["read", "write"]) + ); + assert_eq!(server.finish().len(), 1); +} + +#[test] +fn other_401_messages_that_mention_identity_sessions_keep_the_login_hint() { + let server = Server::start(vec![call( + "GET", + "/v1/sandboxes?limit=50".into(), + None, + 401, + Some( + json!({"error": "invalid_token", "error_description": "Connect using OAuth, an identity session, or an organization API key."}), + ), + )]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run(dir.path(), &server.url, &["sandbox", "list"])); + assert!(stderr.contains("adapt auth login"), "{stderr}"); + assert!(!stderr.contains("identities sessions start"), "{stderr}"); + server.finish(); +} + +#[test] +fn access_that_already_matches_is_not_saved() { + let server = Server::start(vec![call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + )]); + let dir = tempfile::tempdir().unwrap(); + let output = run( + dir.path(), + &server.url, + &["identities", "access", ID, MEMBER, "--assume", "--manage"], + ); + assert_eq!(success(&output)["canManage"], true); + assert!(String::from_utf8_lossy(&output.stderr).contains("Nothing was saved")); + assert_eq!(server.finish().len(), 1); +} + +#[test] +fn access_from_a_non_manager_is_left_to_platform() { + let mut current = detail(); + current["canManage"] = json!(false); + current["grants"] = json!([]); + let server = Server::start(vec![ + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(current), + ), + call( + "PUT", + format!("/v1/identities/{ID}/grants"), + Some(json!({"memberId": MEMBER, "canAssume": false, "canManage": false})), + 403, + Some( + json!({"error": {"code": "FORBIDDEN", "message": "Ask an identity manager to make this change."}}), + ), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run( + dir.path(), + &server.url, + &["identities", "access", ID, MEMBER], + )); + assert!(stderr.contains("Ask an identity manager"), "{stderr}"); + server.finish(); +} + +#[test] +fn create_from_flags_fills_the_required_permission_resources() { + let server = Server::start(vec![call( + "POST", + "/v1/identities".into(), + Some(json!({ + "name": "Deploy Bot", "description": "Deploys", "maxSessionSeconds": 1800, + "permissions": {"volumes": [], "sandboxes": ["read", "write"], "execs": [], "ingresses": [], "images": ["read", "use"]}, + })), + 201, + Some(detail()), + )]); + let dir = tempfile::tempdir().unwrap(); + success(&run( + dir.path(), + &server.url, + &[ + "identities", + "create", + "--name", + " Deploy Bot ", + "--description", + "Deploys", + "--allow", + "sandboxes:write", + "--allow", + "images:use", + "--max-session", + "1800", + ], + )); + server.finish(); +} + +#[test] +fn create_flags_override_fields_from_data() { + let connections = + json!([{"connectionId": CONNECTION, "account": "shared", "tools": ["search"]}]); + let server = Server::start(vec![call( + "POST", + "/v1/identities".into(), + Some(json!({ + "name": "new", "connections": connections, + "permissions": {"sandboxes": ["read"], "volumes": [], "execs": [], "ingresses": [], "gateway": ["read", "use"]}, + })), + 201, + Some(detail()), + )]); + let dir = tempfile::tempdir().unwrap(); + let data = + json!({"name": "old", "connections": connections, "permissions": {"sandboxes": ["read"]}}) + .to_string(); + success(&run( + dir.path(), + &server.url, + &[ + "identities", + "create", + "--data", + &data, + "--name", + "new", + "--allow", + "mcp-tools:use", + ], + )); + server.finish(); +} + +#[test] +fn create_needs_a_name_or_data() { + let dir = tempfile::tempdir().unwrap(); + for args in [ + vec![], + vec!["--name", " "], + vec!["--name", "x", "--max-session", "60"], + ] { + let mut command = vec!["identities", "create"]; + command.extend(args); + assert_eq!( + run(dir.path(), "http://127.0.0.1:9", &command) + .status + .code(), + Some(2) + ); + } +} + +#[cfg(unix)] +#[test] +fn a_terminal_shows_the_whole_identity_even_without_connections() { + let mut current = detail(); + current["connections"] = json!([]); + let mut disabled = current.clone(); + disabled["enabled"] = json!(false); + let mut saved_body = saved(json!({"enabled": false})); + saved_body["connections"] = json!([]); + for (args, steps) in [ + ( + vec!["identities", "get", ID], + vec![call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(current.clone()), + )], + ), + ( + vec!["identities", "disable", ID], + vec![ + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(current.clone()), + ), + call( + "PUT", + format!("/v1/identities/{ID}"), + Some(saved_body.clone()), + 200, + Some(disabled.clone()), + ), + ], + ), + ] { + let server = Server::start(steps); + let dir = tempfile::tempdir().unwrap(); + let mut command = command(dir.path(), &server.url); + command + .env("ADAPT_TOKEN", "test-token") + .env("ADAPT_ORG_ID", ORG) + .args(&args); + let (code, text) = in_terminal(command); + assert_eq!(code, 0, "{text}"); + assert!(!text.contains("No results."), "{text}"); + assert!(text.contains("\"name\": \"deploy-bot\""), "{text}"); + assert!(text.contains("\"connections\": []"), "{text}"); + server.finish(); + } +} + +fn whoami() -> Handler { + call( + "GET", + "/v1/whoami".into(), + None, + 200, + Some(json!({"type": "session", "userId": USER, "organizationId": ORG})), + ) +} + +fn own_membership() -> Handler { + call( + "GET", + format!( + "/v1/auth/organization/list-members?organizationId={ORG}&filterField=userId&filterValue={USER}" + ), + None, + 200, + Some(json!({"members": [{"id": SELF, "userId": USER}], "total": 1})), + ) +} + +#[test] +fn reapplying_the_same_grants_is_not_saved() { + // Responses add name and email, list in any order, and include the caller, + // whose own grant Platform keeps when the input leaves it out. + let mut current = detail(); + current["grants"] = json!([ + {"memberId": MEMBER, "canAssume": true, "canManage": false, "name": "Ana", "email": "ana@example.com"}, + {"memberId": SELF, "canAssume": true, "canManage": true, "name": "Me", "email": "me@example.com"}, + ]); + let server = Server::start(vec![ + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(current), + ), + whoami(), + own_membership(), + ]); + let dir = tempfile::tempdir().unwrap(); + let data = json!({"grants": [ + {"memberId": OTHER, "canAssume": false, "canManage": false}, + {"memberId": MEMBER.to_uppercase(), "canAssume": true, "canManage": false}, + ]}) + .to_string(); + let output = run( + dir.path(), + &server.url, + &["identities", "update", ID, "--data", &data], + ); + success(&output); + assert!(String::from_utf8_lossy(&output.stderr).contains("Nothing was saved")); + assert_eq!(server.finish().len(), 3); +} + +#[test] +fn grants_with_other_changes_save_without_looking_up_the_caller() { + let grants = json!([{"memberId": MEMBER, "canAssume": true, "canManage": true}]); + let server = Server::start(vec![ + call( + "GET", + format!("/v1/identities/{ID}"), + None, + 200, + Some(detail()), + ), + call( + "PUT", + format!("/v1/identities/{ID}"), + Some(saved(json!({"grants": grants, "description": "New"}))), + 200, + Some(detail()), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let data = json!({"grants": grants, "description": "New"}).to_string(); + success(&run( + dir.path(), + &server.url, + &["identities", "update", ID, "--data", &data], + )); + assert_eq!(server.finish().len(), 2); +} diff --git a/tests/support/mod.rs b/tests/support/mod.rs index 32f181d..f4d6ff3 100644 --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -331,3 +331,55 @@ pub fn save_profile(dir: &Path, url: &str) { .unwrap(); } } + +/// Runs `cmd` with stdout on a pseudo-terminal, as an interactive user sees it, +/// and returns its exit code and the terminal text with CRLF line endings normalized. +#[cfg(unix)] +pub fn in_terminal(mut cmd: Command) -> (i32, String) { + use std::{ + fs::File, + os::fd::{AsRawFd, FromRawFd}, + }; + let (mut master, mut slave) = (-1, -1); + // SAFETY: The out-pointers are valid, and the descriptors are owned by Files at once. + let (mut master, slave) = unsafe { + assert_eq!( + libc::openpty( + &mut master, + &mut slave, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut() + ), + 0 + ); + (File::from_raw_fd(master), File::from_raw_fd(slave)) + }; + // SAFETY: The descriptor is valid for the duration of the call. + unsafe { + assert_eq!( + libc::fcntl(master.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC), + 0 + ); + } + let mut child = cmd + .stdin(Stdio::null()) + .stdout(slave) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + // The Command holds the slave until dropped; the master reads EOF only once + // every slave descriptor is closed. + drop(cmd); + let mut text = Vec::new(); + let mut chunk = [0; 4096]; + // Linux reports EIO and macOS EOF once the child closes the terminal. + while let Ok(n @ 1..) = master.read(&mut chunk) { + text.extend_from_slice(&chunk[..n]); + } + let status = child.wait().unwrap(); + ( + status.code().unwrap_or(-1), + String::from_utf8_lossy(&text).replace("\r\n", "\n"), + ) +}