diff --git a/app/src/auth/invitations.rs b/app/src/auth/invitations.rs index 50339b58..45c284dc 100644 --- a/app/src/auth/invitations.rs +++ b/app/src/auth/invitations.rs @@ -135,14 +135,16 @@ pub async fn may_send(org_id: i64, address: Option<&str>) -> laravel::Result laravel::Result<(i64, String, Role)> { let user_id = user.id; let row = db::query!( "SELECT o.id, o.name, m.role FROM organizations o \ LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} WHERE o.id IN (SELECT id FROM organizations WHERE slug = {slug} UNION ALL \ - SELECT organization_id FROM previous_organization_slugs WHERE slug = {slug})" + SELECT organization_id FROM previous_organization_slugs WHERE slug = {slug}) \ + ORDER BY (o.slug = {slug}) DESC LIMIT 1" ) .select_one() .await? diff --git a/app/src/auth/orgs.rs b/app/src/auth/orgs.rs index 459f19a6..97585cc7 100644 --- a/app/src/auth/orgs.rs +++ b/app/src/auth/orgs.rs @@ -305,17 +305,37 @@ pub async fn rename(org_id: i64, slug: &str) -> laravel::Result { Ok(renamed) } -/// `PATCH /api/ui/orgs/{org}` (admins): its slug, its name and the settings new projects start with; fields left out stay as -/// they are. Existing projects keep their own settings. -pub async fn update( - Authenticated(user): Authenticated, - Params(slug): Params, - Valid(p): Valid, -) -> laravel::Result> { - let (org_id, _, role) = super::invitations::org_role(&user, &slug).await?; +/// What an update changes; fields left out stay as they are. +#[derive(Debug, Default)] +pub struct Change { + /// The display name. + pub name: Option, + /// A new slug: the old one keeps working ([`rename`]). + pub slug: Option, + /// The diff threshold a new project starts with, 0 to 1. + pub project_threshold: Option, + /// Whether a new project comments on pull requests whose builds are unchanged. + pub project_comment_when_unchanged: Option, +} + +/// Refuse anyone but an organization's admins: what the settings page, the API and MCP all say. +/// +/// # Errors +/// A 403 for anyone else. +pub fn need_admin(role: Role) -> laravel::Result<()> { if role < Role::Admin { return Err(laravel::abort_with(403, "only admins can change the organization's settings")); } + Ok(()) +} + +/// Change an organization's name, slug or the settings new projects start with, for its settings page, the API and +/// MCP (the caller checks it's an admin, [`need_admin`]). 422 for a name, threshold or slug it refuses, 409 for a +/// slug that's taken. +/// +/// # Errors +/// Those, and database errors. +pub async fn change(org_id: i64, p: Change) -> laravel::Result { let name = p.name.as_deref().map(str::trim).map(str::to_string); if let Some(name) = &name && (name.is_empty() || name.chars().count() > MAX_NAME) @@ -338,7 +358,25 @@ pub async fn update( ) .update() .await?; - let org = Organization::find_or_fail(org_id).await?; + Organization::find_or_fail(org_id).await +} + +/// `PATCH /api/ui/orgs/{org}` (admins): its slug, its name and the settings new projects start with; fields left out stay as +/// they are. Existing projects keep their own settings. +pub async fn update( + Authenticated(user): Authenticated, + Params(slug): Params, + Valid(p): Valid, +) -> laravel::Result> { + let (org_id, _, role) = super::invitations::org_role(&user, &slug).await?; + need_admin(role)?; + let change = Change { + name: p.name, + slug: p.slug, + project_threshold: p.project_threshold, + project_comment_when_unchanged: p.project_comment_when_unchanged, + }; + let org = self::change(org_id, change).await?; Ok(Json(json!({ "slug": org.slug, "name": org.name, "project_defaults": { diff --git a/app/src/http/api/mod.rs b/app/src/http/api/mod.rs index 382984c4..f53c39fc 100644 --- a/app/src/http/api/mod.rs +++ b/app/src/http/api/mod.rs @@ -4,6 +4,7 @@ pub mod builds; pub mod downloads; +pub mod organizations; pub mod support; pub mod versions; @@ -23,6 +24,7 @@ pub fn routes(route: &mut Router) { route.get("/v1/whoami", crate::auth::whoami); builds::routes(route); route.post("/v1/support/feedback", support::feedback); + organizations::routes(route); downloads::routes(route); versions::routes(route); crate::auth::device::api_routes(route); @@ -72,6 +74,26 @@ impl ApiError { } } + #[must_use] + pub fn forbidden(message: impl Into) -> Self { + Self { status: StatusCode::FORBIDDEN, body: json!({ "error": "forbidden", "description": message.into() }) } + } + + /// A handler's refusal (`laravel::abort_with`) with its status and message; a server error as one. + #[must_use] + pub fn refused(e: laravel::Error) -> Self { + let status = e.status(); + let kind = match status { + StatusCode::FORBIDDEN => "forbidden", + StatusCode::NOT_FOUND => return Self::not_found(), + StatusCode::CONFLICT => "conflict", + StatusCode::UNPROCESSABLE_ENTITY => "unprocessable", + s if s.is_client_error() => "Bad Request", + _ => return Self::server(&e), + }; + Self { status, body: json!({ "error": kind, "description": e.to_string() }) } + } + #[must_use] pub fn not_found() -> Self { Self { diff --git a/app/src/http/api/organizations.rs b/app/src/http/api/organizations.rs new file mode 100644 index 00000000..9e3d75d9 --- /dev/null +++ b/app/src/http/api/organizations.rs @@ -0,0 +1,106 @@ +//! `GET` and `PATCH /api/v1/organizations/{org}`: an organization as MCP's `get_organization` answers it, and its name +//! and slug changed by an admin with the settings page's rules ([`crate::auth::orgs::change`]). `{org}` may be a slug +//! the organization had before a rename. + +use axum::response::{IntoResponse, Response}; +use serde::Deserialize; +use serde_json::Value; + +use super::ApiError; +use crate::auth::{Principal, Role}; +use crate::mcp::VisualCi; +use crate::models::{Organization, Project}; + +pub fn routes(route: &mut laravel::prelude::Router) { + route.get("/v1/organizations/{org}", show); + route.patch("/v1/organizations/{org}", update); +} + +/// The fields `PATCH` takes; any other is refused (422, as [`super::Body`] does). +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct UpdateBody { + #[serde(default)] + name: Option, + #[serde(default)] + slug: Option, +} + +fn unauthorized() -> ApiError { + ApiError::unauthorized("a personal access token or a project token is required") +} + +/// The organization and the caller's role there (`project` for a project token of one of its projects); a 404 for +/// anyone who can't see it. +async fn find(principal: &Principal, slug: &str) -> Result<(Organization, String), ApiError> { + match principal { + Principal::User { user, .. } => { + let (id, _, role) = crate::auth::invitations::org_role(user, slug).await.map_err(ApiError::refused)?; + Ok((Organization::find_or_fail(id).await?, role.as_str().to_string())) + } + Principal::Project { project_id, .. } => { + let org = Organization::by_slug(slug).await?.ok_or_else(ApiError::not_found)?; + let project = Project::find_live(*project_id).await?.ok_or_else(ApiError::not_found)?; + if project.organization_id != org.id { + return Err(ApiError::not_found()); + } + Ok((org, "project".to_string())) + } + } +} + +async fn answer(org: &Organization, role: &str, principal: &Principal) -> Result, ApiError> { + VisualCi::organization_json(org, role, principal) + .await + .map(axum::Json) + .map_err(|e| ApiError::server(&laravel::Error::msg(e.message.to_string()))) +} + +/// `GET /api/v1/organizations/{org}`: the organization, as MCP's `get_organization` answers it. +pub async fn show( + principal: Result, + laravel::prelude::Params(slug): laravel::prelude::Params, +) -> Response { + respond(show_org(principal, &slug).await) +} + +async fn show_org(principal: Result, slug: &str) -> Result, ApiError> { + let principal = principal.map_err(|_| unauthorized())?; + let (org, role) = find(&principal, slug).await?; + answer(&org, &role, &principal).await +} + +fn respond(r: Result, ApiError>) -> Response { + match r { + Ok(json) => json.into_response(), + Err(e) => e.into_response(), + } +} + +/// `PATCH /api/v1/organizations/{org}` (admins, with a personal token): its name and slug; fields left out stay as +/// they are. A new slug renames it, and the old one keeps working. +pub async fn update( + principal: Result, + laravel::prelude::Params(slug): laravel::prelude::Params, + body: axum::body::Bytes, +) -> Response { + respond(update_org(principal, &slug, &body).await) +} + +async fn update_org( + principal: Result, + slug: &str, + body: &[u8], +) -> Result, ApiError> { + let principal = principal.map_err(|_| unauthorized())?; + // Read after the token: a request without one is a 401, whatever its body. + let body: UpdateBody = serde_json::from_slice(body).map_err(|e| ApiError::unreadable(&e))?; + if !matches!(principal, Principal::User { .. }) { + return Err(ApiError::forbidden("changing an organization needs a personal access token, not a project token")); + } + let (org, role) = find(&principal, slug).await?; + crate::auth::orgs::need_admin(Role::parse(&role).unwrap_or(Role::Read)).map_err(ApiError::refused)?; + let change = crate::auth::orgs::Change { name: body.name, slug: body.slug, ..Default::default() }; + let org = crate::auth::orgs::change(org.id, change).await.map_err(ApiError::refused)?; + answer(&org, &role, &principal).await +} diff --git a/app/src/mcp/args.rs b/app/src/mcp/args.rs index 79637e57..f0220247 100644 --- a/app/src/mcp/args.rs +++ b/app/src/mcp/args.rs @@ -60,6 +60,18 @@ pub struct CreateOrgArgs { pub name: String, } +#[derive(Debug, Deserialize, JsonSchema)] +pub struct UpdateOrgArgs { + /// The organization's slug (its current one, or one it had before). + pub org: String, + /// A new display name. Leave it out to keep it. + #[serde(default)] + pub name: Option, + /// A new slug: lowercase letters, digits and dashes, not a reserved word. Leave it out to keep it. + #[serde(default)] + pub slug: Option, +} + #[derive(Debug, Deserialize, JsonSchema)] pub struct CreateProjectArgs { pub org: String, diff --git a/app/src/mcp/mod.rs b/app/src/mcp/mod.rs index ee4ab6b1..6bb390cd 100644 --- a/app/src/mcp/mod.rs +++ b/app/src/mcp/mod.rs @@ -312,6 +312,75 @@ impl VisualCi { Ok(out) } + /// An organization as `get_organization` (and the API's `GET /api/v1/organizations/{org}`) answers it, for a caller + /// with `role` there. A project token sees its own project and the organization's plan and usage: not the members + /// (their emails) or the other projects. + /// + /// # Errors + /// On a database error. + pub async fn organization_json( + org: &Organization, + role: &str, + principal: &Principal, + ) -> Result { + let only = match principal { + Principal::Project { project_id, .. } => Some(*project_id), + _ => None, + }; + let mut list = Vec::new(); + for p in Self::projects_of(org.id).await? { + if only.is_some_and(|id| id != p.id) { + continue; + } + let last = match domain::builds::recent(p.id, None, false, 1).await.map_err(internal)?.first() { + Some(b) => Some(Self::build_json(&p, b, true).await?), + None => None, + }; + list.push(json!({ "project": format!("{}/{}", org.slug, p.slug), "name": p.name, "last_build": last })); + } + let usage = domain::credits::usage(org).await.map_err(internal)?; + // The usage history names other projects' builds. + let history: Vec = if only.is_some() { + Vec::new() + } else { + let org_id = org.id; + db::query!( + "SELECT amount, kind, reference, \ + to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"+00:00\"') AS created_at \ + FROM credit_transactions \ + WHERE organization_id = {org_id} AND kind IN ('build', 'render', 'gallery') ORDER BY id DESC LIMIT 50" + ) + .select() + .await + .map_err(internal)? + .iter() + .map(|t| { + json!({ + "credits": -t.try_get::("amount").unwrap_or_default(), + "kind": t.try_get::("kind").ok(), + "reference": t.try_get::>("reference").ok().flatten(), + "created_at": t.try_get::("created_at").ok(), + }) + }) + .collect() + }; + let user_pid = principal.user().map(|u| u.pid); + let setup = crate::auth::setup::state(org.id, user_pid).await.map_err(internal)?; + let admin = role == "admin"; + let members = if only.is_some() { + Vec::new() + } else { + crate::auth::invitations::members_json(org.id, admin).await.map_err(internal)? + }; + let pending = + if admin { crate::auth::invitations::pending(org.id).await.map_err(internal)? } else { Vec::new() }; + Ok(json!({ + "slug": org.slug, "name": org.name, "role": role, "usage": usage, "members": members, + "invitations": pending, "billing_url": format!("{}/{}/billing", app_url(), org.slug), "projects": list, + "usage_history": history, "setup": setup, + })) + } + /// An organization the caller may see, with the caller's role as text: `admin`, `member` or `read`, or `project` /// for a project token's own organization. async fn org( @@ -741,64 +810,38 @@ impl VisualCi { rc: RequestContext, ) -> Result { let (org, role) = need!(Self::org(&rc, &args.org)); - // A project token sees its own project and the organization's plan and usage: not the members (their emails) - // or the other projects. - let only = match principal_of(&rc) { - Some(Principal::Project { project_id, .. }) => Some(project_id), - _ => None, + let Some(principal) = principal_of(&rc) else { return Ok(tool_error("missing token")) }; + Ok(structured(Self::organization_json(&org, &role, &principal).await?)) + } + + #[tool( + description = "Change an organization's name or slug (admins, with a personal access token or an MCP client signed in as one; project tokens can't). Fields left out stay as they are. A new slug renames the organization: the old slug keeps working, so links to its pages and galleries redirect to the new one, and the API, MCP and project tokens accept project names with either. Returns the organization as get_organization does.", + annotations( + title = "Update organization", + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true, + open_world_hint = false + ) + )] + async fn update_organization( + &self, + Parameters(args): Parameters, + rc: RequestContext, + ) -> Result { + let Some(principal @ Principal::User { .. }) = principal_of(&rc) else { + return Ok(tool_error("changing an organization needs a personal access token, not a project token")); }; - let mut list = Vec::new(); - for p in Self::projects_of(org.id).await? { - if only.is_some_and(|id| id != p.id) { - continue; - } - let last = match domain::builds::recent(p.id, None, false, 1).await.map_err(internal)?.first() { - Some(b) => Some(Self::build_json(&p, b, true).await?), - None => None, - }; - list.push(json!({ "project": format!("{}/{}", org.slug, p.slug), "name": p.name, "last_build": last })); + let (org, role) = need!(Self::org(&rc, &args.org)); + if let Err(e) = crate::auth::orgs::need_admin(Role::parse(&role).unwrap_or(Role::Read)) { + return Ok(tool_error(refusal(e)?)); } - let usage = domain::credits::usage(&org).await.map_err(internal)?; - // The usage history names other projects' builds. - let history: Vec = if only.is_some() { - Vec::new() - } else { - let org_id = org.id; - db::query!( - "SELECT amount, kind, reference, \ - to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"+00:00\"') AS created_at \ - FROM credit_transactions \ - WHERE organization_id = {org_id} AND kind IN ('build', 'render', 'gallery') ORDER BY id DESC LIMIT 50" - ) - .select() - .await - .map_err(internal)? - .iter() - .map(|t| { - json!({ - "credits": -t.try_get::("amount").unwrap_or_default(), - "kind": t.try_get::("kind").ok(), - "reference": t.try_get::>("reference").ok().flatten(), - "created_at": t.try_get::("created_at").ok(), - }) - }) - .collect() - }; - let user_pid = principal_of(&rc).and_then(|p| p.user().map(|u| u.pid)); - let setup = crate::auth::setup::state(org.id, user_pid).await.map_err(internal)?; - let admin = role == "admin"; - let members = if only.is_some() { - Vec::new() - } else { - crate::auth::invitations::members_json(org.id, admin).await.map_err(internal)? + let change = crate::auth::orgs::Change { name: args.name, slug: args.slug, ..Default::default() }; + let org = match crate::auth::orgs::change(org.id, change).await { + Ok(org) => org, + Err(e) => return Ok(tool_error(refusal(e)?)), }; - let pending = - if admin { crate::auth::invitations::pending(org.id).await.map_err(internal)? } else { Vec::new() }; - Ok(structured(json!({ - "slug": org.slug, "name": org.name, "role": role, "usage": usage, "members": members, - "invitations": pending, "billing_url": format!("{}/{}/billing", app_url(), org.slug), "projects": list, - "usage_history": history, "setup": setup, - }))) + Ok(structured(Self::organization_json(&org, &role, &principal).await?)) } #[tool( diff --git a/app/tests/golden/mcp/admins_update_the_organization/get_organization.json b/app/tests/golden/mcp/admins_update_the_organization/get_organization.json new file mode 100644 index 00000000..5f53f72c --- /dev/null +++ b/app/tests/golden/mcp/admins_update_the_organization/get_organization.json @@ -0,0 +1,123 @@ +{ + "arguments": { + "org": "" + }, + "result": { + "content": [ + { + "text": "{\"billing_url\":\"https://app.visualci.test/-hq/billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null},{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"bob\",\"role\":\"member\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Renamed\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"-hq/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"-hq/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"-hq\",\"usage\":{\"auto_reload_packs\":0,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "billing_url": "https://app.visualci.test/-hq/billing", + "invitations": [], + "members": [ + { + "avatar_url": null, + "email": "@example.com", + "id": "", + "identities": [], + "login": null, + "name": "owner", + "role": "admin", + "since": "", + "source": "created", + "synced_at": null + }, + { + "avatar_url": null, + "email": "@example.com", + "id": "", + "identities": [], + "login": null, + "name": "bob", + "role": "member", + "since": "", + "source": "created", + "synced_at": null + } + ], + "name": "Renamed", + "projects": [ + { + "last_build": null, + "name": "PDFs", + "project": "-hq/pdfs" + }, + { + "last_build": null, + "name": "Screenshots", + "project": "-hq/shots" + } + ], + "role": "admin", + "setup": { + "complete": false, + "github": [], + "github_sync": "done", + "install_url": "/github/install", + "installations": [], + "next": "install_github_app", + "shown": true, + "steps": [ + { + "done": false, + "key": "install_github_app" + }, + { + "done": true, + "key": "connect_agent" + }, + { + "done": false, + "key": "add_to_ci" + }, + { + "done": false, + "key": "review_changes" + } + ] + }, + "slug": "-hq", + "usage": { + "auto_reload_packs": 0, + "billing_problem": null, + "credit_pack": { + "credits": 500000, + "price_cents": 1500, + "reload_below": 100000 + }, + "credits_this_month": 0, + "included_credits": 25000, + "open_source": { + "pool": 1000000, + "projects": 0, + "used": 0 + }, + "out_of_credits": false, + "pack_credits": 0, + "plan": { + "credit_packs": false, + "id": "free", + "included_credits": 25000, + "name": "Free", + "price_cents": 0, + "unlimited": false + }, + "rates": { + "image_diff": 10, + "rendered_page": 20, + "snapshot_check": 1, + "text_diff": 5 + }, + "reloads_paused": false, + "reloads_this_month": 0, + "renews_at": "", + "unlimited": false + }, + "usage_history": [] + } + } +} diff --git a/app/tests/golden/mcp/admins_update_the_organization/get_project.json b/app/tests/golden/mcp/admins_update_the_organization/get_project.json new file mode 100644 index 00000000..c384bbf4 --- /dev/null +++ b/app/tests/golden/mcp/admins_update_the_organization/get_project.json @@ -0,0 +1,58 @@ +{ + "arguments": { + "project": "/pdfs" + }, + "result": { + "content": [ + { + "text": "{\"gallery\":{\"enabled\":true,\"items\":[],\"manifest_url\":null},\"project\":\"-hq/pdfs\",\"repository_seen_in_ci\":null,\"settings\":{\"ci_mode\":\"review\",\"comment_when_unchanged\":false,\"default_branch\":\"main\",\"dpi\":140,\"forge\":null,\"forge_app_installed\":false,\"forge_webhook_at\":null,\"gallery_enabled\":true,\"ignore_anti_aliasing\":false,\"ignore_rules\":[],\"name\":\"PDFs\",\"notice\":null,\"open_source\":false,\"open_source_note\":null,\"open_source_pool\":false,\"open_source_withdrawn\":false,\"public\":false,\"renderer\":\"pdfbox\",\"repository_public\":false,\"repository_url\":null,\"slug\":\"pdfs\",\"threshold\":0.0,\"tokens_can_approve\":true},\"tokens\":[{\"created_at\":\"\",\"id\":1,\"last_used_at\":\"\",\"name\":\"ci\",\"prefix\":\"\"}],\"url\":\"https://app.visualci.test/-hq/pdfs\"}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "gallery": { + "enabled": true, + "items": [], + "manifest_url": null + }, + "project": "-hq/pdfs", + "repository_seen_in_ci": null, + "settings": { + "ci_mode": "review", + "comment_when_unchanged": false, + "default_branch": "main", + "dpi": 140, + "forge": null, + "forge_app_installed": false, + "forge_webhook_at": null, + "gallery_enabled": true, + "ignore_anti_aliasing": false, + "ignore_rules": [], + "name": "PDFs", + "notice": null, + "open_source": false, + "open_source_note": null, + "open_source_pool": false, + "open_source_withdrawn": false, + "public": false, + "renderer": "pdfbox", + "repository_public": false, + "repository_url": null, + "slug": "pdfs", + "threshold": 0.0, + "tokens_can_approve": true + }, + "tokens": [ + { + "created_at": "", + "id": 1, + "last_used_at": "", + "name": "ci", + "prefix": "" + } + ], + "url": "https://app.visualci.test/-hq/pdfs" + } + } +} diff --git a/app/tests/golden/mcp/admins_update_the_organization/update_organization-2.json b/app/tests/golden/mcp/admins_update_the_organization/update_organization-2.json new file mode 100644 index 00000000..8100ae18 --- /dev/null +++ b/app/tests/golden/mcp/admins_update_the_organization/update_organization-2.json @@ -0,0 +1,15 @@ +{ + "arguments": { + "name": "CI", + "org": "" + }, + "result": { + "content": [ + { + "text": "changing an organization needs a personal access token, not a project token", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/admins_update_the_organization/update_organization-3.json b/app/tests/golden/mcp/admins_update_the_organization/update_organization-3.json new file mode 100644 index 00000000..1c5e5a6c --- /dev/null +++ b/app/tests/golden/mcp/admins_update_the_organization/update_organization-3.json @@ -0,0 +1,15 @@ +{ + "arguments": { + "org": "", + "slug": "Bad Slug" + }, + "result": { + "content": [ + { + "text": "slugs use lowercase letters, digits and dashes, and can't be a reserved word such as account or api", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/admins_update_the_organization/update_organization-4.json b/app/tests/golden/mcp/admins_update_the_organization/update_organization-4.json new file mode 100644 index 00000000..82dc768c --- /dev/null +++ b/app/tests/golden/mcp/admins_update_the_organization/update_organization-4.json @@ -0,0 +1,15 @@ +{ + "arguments": { + "org": "", + "slug": "-other" + }, + "result": { + "content": [ + { + "text": "that slug is taken", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/admins_update_the_organization/update_organization-5.json b/app/tests/golden/mcp/admins_update_the_organization/update_organization-5.json new file mode 100644 index 00000000..82dc768c --- /dev/null +++ b/app/tests/golden/mcp/admins_update_the_organization/update_organization-5.json @@ -0,0 +1,15 @@ +{ + "arguments": { + "org": "", + "slug": "-other" + }, + "result": { + "content": [ + { + "text": "that slug is taken", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/admins_update_the_organization/update_organization-6.json b/app/tests/golden/mcp/admins_update_the_organization/update_organization-6.json new file mode 100644 index 00000000..4e2a7125 --- /dev/null +++ b/app/tests/golden/mcp/admins_update_the_organization/update_organization-6.json @@ -0,0 +1,15 @@ +{ + "arguments": { + "name": "Eve's", + "org": "" + }, + "result": { + "content": [ + { + "text": "no organization that this token can see", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/admins_update_the_organization/update_organization-7.json b/app/tests/golden/mcp/admins_update_the_organization/update_organization-7.json new file mode 100644 index 00000000..6f89e31d --- /dev/null +++ b/app/tests/golden/mcp/admins_update_the_organization/update_organization-7.json @@ -0,0 +1,124 @@ +{ + "arguments": { + "name": "Renamed", + "org": "" + }, + "result": { + "content": [ + { + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null},{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"bob\",\"role\":\"member\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Renamed\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":0,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "billing_url": "https://app.visualci.test//billing", + "invitations": [], + "members": [ + { + "avatar_url": null, + "email": "@example.com", + "id": "", + "identities": [], + "login": null, + "name": "owner", + "role": "admin", + "since": "", + "source": "created", + "synced_at": null + }, + { + "avatar_url": null, + "email": "@example.com", + "id": "", + "identities": [], + "login": null, + "name": "bob", + "role": "member", + "since": "", + "source": "created", + "synced_at": null + } + ], + "name": "Renamed", + "projects": [ + { + "last_build": null, + "name": "PDFs", + "project": "/pdfs" + }, + { + "last_build": null, + "name": "Screenshots", + "project": "/shots" + } + ], + "role": "admin", + "setup": { + "complete": false, + "github": [], + "github_sync": "done", + "install_url": "/github/install", + "installations": [], + "next": "install_github_app", + "shown": true, + "steps": [ + { + "done": false, + "key": "install_github_app" + }, + { + "done": true, + "key": "connect_agent" + }, + { + "done": false, + "key": "add_to_ci" + }, + { + "done": false, + "key": "review_changes" + } + ] + }, + "slug": "", + "usage": { + "auto_reload_packs": 0, + "billing_problem": null, + "credit_pack": { + "credits": 500000, + "price_cents": 1500, + "reload_below": 100000 + }, + "credits_this_month": 0, + "included_credits": 25000, + "open_source": { + "pool": 1000000, + "projects": 0, + "used": 0 + }, + "out_of_credits": false, + "pack_credits": 0, + "plan": { + "credit_packs": false, + "id": "free", + "included_credits": 25000, + "name": "Free", + "price_cents": 0, + "unlimited": false + }, + "rates": { + "image_diff": 10, + "rendered_page": 20, + "snapshot_check": 1, + "text_diff": 5 + }, + "reloads_paused": false, + "reloads_this_month": 0, + "renews_at": "", + "unlimited": false + }, + "usage_history": [] + } + } +} diff --git a/app/tests/golden/mcp/admins_update_the_organization/update_organization-8.json b/app/tests/golden/mcp/admins_update_the_organization/update_organization-8.json new file mode 100644 index 00000000..82e629f0 --- /dev/null +++ b/app/tests/golden/mcp/admins_update_the_organization/update_organization-8.json @@ -0,0 +1,124 @@ +{ + "arguments": { + "org": "", + "slug": "-hq" + }, + "result": { + "content": [ + { + "text": "{\"billing_url\":\"https://app.visualci.test/-hq/billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null},{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"bob\",\"role\":\"member\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Renamed\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"-hq/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"-hq/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"-hq\",\"usage\":{\"auto_reload_packs\":0,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "type": "text" + } + ], + "isError": false, + "structuredContent": { + "billing_url": "https://app.visualci.test/-hq/billing", + "invitations": [], + "members": [ + { + "avatar_url": null, + "email": "@example.com", + "id": "", + "identities": [], + "login": null, + "name": "owner", + "role": "admin", + "since": "", + "source": "created", + "synced_at": null + }, + { + "avatar_url": null, + "email": "@example.com", + "id": "", + "identities": [], + "login": null, + "name": "bob", + "role": "member", + "since": "", + "source": "created", + "synced_at": null + } + ], + "name": "Renamed", + "projects": [ + { + "last_build": null, + "name": "PDFs", + "project": "-hq/pdfs" + }, + { + "last_build": null, + "name": "Screenshots", + "project": "-hq/shots" + } + ], + "role": "admin", + "setup": { + "complete": false, + "github": [], + "github_sync": "done", + "install_url": "/github/install", + "installations": [], + "next": "install_github_app", + "shown": true, + "steps": [ + { + "done": false, + "key": "install_github_app" + }, + { + "done": true, + "key": "connect_agent" + }, + { + "done": false, + "key": "add_to_ci" + }, + { + "done": false, + "key": "review_changes" + } + ] + }, + "slug": "-hq", + "usage": { + "auto_reload_packs": 0, + "billing_problem": null, + "credit_pack": { + "credits": 500000, + "price_cents": 1500, + "reload_below": 100000 + }, + "credits_this_month": 0, + "included_credits": 25000, + "open_source": { + "pool": 1000000, + "projects": 0, + "used": 0 + }, + "out_of_credits": false, + "pack_credits": 0, + "plan": { + "credit_packs": false, + "id": "free", + "included_credits": 25000, + "name": "Free", + "price_cents": 0, + "unlimited": false + }, + "rates": { + "image_diff": 10, + "rendered_page": 20, + "snapshot_check": 1, + "text_diff": 5 + }, + "reloads_paused": false, + "reloads_this_month": 0, + "renews_at": "", + "unlimited": false + }, + "usage_history": [] + } + } +} diff --git a/app/tests/golden/mcp/admins_update_the_organization/update_organization.json b/app/tests/golden/mcp/admins_update_the_organization/update_organization.json new file mode 100644 index 00000000..2323c1c3 --- /dev/null +++ b/app/tests/golden/mcp/admins_update_the_organization/update_organization.json @@ -0,0 +1,15 @@ +{ + "arguments": { + "org": "", + "slug": "-hq" + }, + "result": { + "content": [ + { + "text": "only admins can change the organization's settings", + "type": "text" + } + ], + "isError": true + } +} diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json index e3dcdbc6..3e6e38c8 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-project-token.json @@ -1380,6 +1380,47 @@ }, "name": "update_comment" }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": false, + "title": "Update organization" + }, + "description": "Change an organization's name or slug (admins, with a personal access token or an MCP client signed in as one; project tokens can't). Fields left out stay as they are. A new slug renames the organization: the old slug keeps working, so links to its pages and galleries redirect to the new one, and the API, MCP and project tokens accept project names with either. Returns the organization as get_organization does.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "name": { + "default": null, + "description": "A new display name. Leave it out to keep it.", + "type": [ + "string", + "null" + ] + }, + "org": { + "description": "The organization's slug (its current one, or one it had before).", + "type": "string" + }, + "slug": { + "default": null, + "description": "A new slug: lowercase letters, digits and dashes, not a reserved word. Leave it out to keep it.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "org" + ], + "type": "object" + }, + "name": "update_organization" + }, { "annotations": { "destructiveHint": true, diff --git a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json index e3dcdbc6..3e6e38c8 100644 --- a/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json +++ b/app/tests/golden/mcp/lists_the_tools_each_kind_of_token_can_use/tools-list-user-token.json @@ -1380,6 +1380,47 @@ }, "name": "update_comment" }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false, + "readOnlyHint": false, + "title": "Update organization" + }, + "description": "Change an organization's name or slug (admins, with a personal access token or an MCP client signed in as one; project tokens can't). Fields left out stay as they are. A new slug renames the organization: the old slug keeps working, so links to its pages and galleries redirect to the new one, and the API, MCP and project tokens accept project names with either. Returns the organization as get_organization does.", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "name": { + "default": null, + "description": "A new display name. Leave it out to keep it.", + "type": [ + "string", + "null" + ] + }, + "org": { + "description": "The organization's slug (its current one, or one it had before).", + "type": "string" + }, + "slug": { + "default": null, + "description": "A new slug: lowercase letters, digits and dashes, not a reserved word. Leave it out to keep it.", + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "org" + ], + "type": "object" + }, + "name": "update_organization" + }, { "annotations": { "destructiveHint": true, diff --git a/app/tests/mcp.rs b/app/tests/mcp.rs index 8be00a3b..f5f26ab2 100644 --- a/app/tests/mcp.rs +++ b/app/tests/mcp.rs @@ -1221,6 +1221,67 @@ async fn create_organization_refuses_a_taken_slug(app: Application) -> laravel:: Ok(()) } +/// `update_organization` renames an organization with the settings page's rules: admins with a person's token, and the +/// old slug keeps working. (New: today's server has no such tool.) +#[laravel::test] +async fn admins_update_the_organization(app: Application) -> laravel::Result<()> { + const TEST: &str = "admins_update_the_organization"; + let f = fixture().await?; + let org = Organization::find_or_fail(f.organization_id).await?; + let email = format!("{}@example.com", laravel::str::uuid7()); + let bob = create!(User { pid: laravel::str::uuid7(), name: "bob", email: email, staff: false }).await?; + app::testing::fixtures::member(&org, &bob, "member").await?; + let bob_token = token("user_tokens", bob.id, "bob", "vcu").await?; + let (t, new) = (&f.user_token, format!("{}-hq", f.org)); + + let (err, r) = call(&app, TEST, &bob_token, "update_organization", json!({ "org": f.org, "slug": new })).await; + assert!(err, "{r}"); + assert_eq!(r, json!("only admins can change the organization's settings")); + let (err, r) = + call(&app, TEST, &f.project_token, "update_organization", json!({ "org": f.org, "name": "CI" })).await; + assert!(err, "{r}"); + assert!(r.as_str().unwrap_or("").contains("personal access token"), "{r}"); + let (err, r) = call(&app, TEST, t, "update_organization", json!({ "org": f.org, "slug": "Bad Slug" })).await; + assert!(err, "{r}"); + assert!(r.as_str().unwrap_or("").starts_with("slugs use lowercase letters"), "{r}"); + let other = format!("{}-other", f.org); + create!(Organization { pid: laravel::str::uuid7(), slug: other.clone(), name: "Other" }).await?; + let (err, r) = call(&app, TEST, t, "update_organization", json!({ "org": f.org, "slug": other })).await; + assert!(err, "{r}"); + assert_eq!(r, json!("that slug is taken")); + + // Another organization's old slug stays its own + let other_org = Organization::by_slug(&other).await?.expect("the other organization"); + let renamed = format!("{other}-2"); + other_org.rename_slug(&renamed).await?.expect("renamed"); + let (err, r) = call(&app, TEST, t, "update_organization", json!({ "org": f.org, "slug": other })).await; + assert!(err, "{r}"); + assert_eq!(r, json!("that slug is taken")); + // Someone outside isn't told it exists + let email = format!("{}@example.com", laravel::str::uuid7()); + let eve = create!(User { pid: laravel::str::uuid7(), name: "eve", email: email, staff: false }).await?; + let eve_token = token("user_tokens", eve.id, "eve", "vcu").await?; + let (err, r) = call(&app, TEST, &eve_token, "update_organization", json!({ "org": f.org, "name": "Eve's" })).await; + assert!(err, "{r}"); + assert_eq!(r, json!(format!("no organization {} that this token can see", f.org))); + + let (err, r) = call(&app, TEST, t, "update_organization", json!({ "org": f.org, "name": "Renamed" })).await; + assert!(!err, "{r}"); + assert_eq!((r["name"].as_str(), r["slug"].as_str()), (Some("Renamed"), Some(f.org.as_str()))); + let (err, r) = call(&app, TEST, t, "update_organization", json!({ "org": f.org, "slug": new })).await; + assert!(!err, "{r}"); + assert_eq!(r["slug"], json!(new)); + assert_eq!(r["projects"][0]["project"], json!(format!("{new}/pdfs"))); + // The old slug still names it, and its project + let (err, r) = call(&app, TEST, t, "get_organization", json!({ "org": f.org })).await; + assert!(!err, "{r}"); + assert_eq!(r["slug"], json!(new)); + let (err, r) = call(&app, TEST, t, "get_project", json!({ "project": format!("{}/pdfs", f.org) })).await; + assert!(!err, "{r}"); + assert_eq!(r["project"], json!(format!("{new}/pdfs"))); + Ok(()) +} + /// A GitHub App key made once per run (base64 of its PEM). fn app_key() -> &'static str { static KEY: std::sync::OnceLock = std::sync::OnceLock::new(); diff --git a/app/tests/org_settings.rs b/app/tests/org_settings.rs index f46154a4..7dc9275a 100644 --- a/app/tests/org_settings.rs +++ b/app/tests/org_settings.rs @@ -243,3 +243,148 @@ async fn app_paths_stay_the_apps_and_renames_are_capped(app: Application) -> lar .assert_ok(); Ok(()) } + +/// A token for `owner` in `table` (`user_tokens` or `project_tokens`). +async fn token(table: &str, owner: i64) -> laravel::Result { + let prefix = if table == "user_tokens" { "vcu" } else { "vci" }; + let token = format!("{prefix}_{}", laravel::str::uuid7().simple()); + let (hash, short) = (app::models::token_hash(&token), token[..6].to_string()); + if table == "user_tokens" { + db::query!( + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({owner}, 'agent', {hash}, {short}, now(), now())" + ) + .insert() + .await?; + } else { + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({owner}, 'ci', {hash}, {short}, now(), now())" + ) + .insert() + .await?; + } + Ok(token) +} + +/// The API changes an organization's name and slug with the settings page's rules and words: admins with a personal +/// token only, and the old slug keeps working. +#[laravel::test] +async fn admins_rename_the_organization_over_the_api(app: Application) -> laravel::Result<()> { + let ada = person("Ada", "ada@example.com").await?; + let bob = person("Bob", "bob@example.com").await?; + let eve = person("Eve", "eve@example.com").await?; + let org = fixtures::organization("acme").await?; + let other = fixtures::organization("other").await?; + fixtures::member(&org, &ada, "admin").await?; + fixtures::member(&org, &bob, "member").await?; + let web = fixtures::project(&org, "web").await?; + let (ada_t, bob_t, eve_t) = + (token("user_tokens", ada.id).await?, token("user_tokens", bob.id).await?, token("user_tokens", eve.id).await?); + let ci = token("project_tokens", web.id).await?; + let patch = |path: &str, token: &str, body: serde_json::Value| { + app.patch(path).header("authorization", format!("Bearer {token}")).json(body) + }; + let description = |r: &laravel::testing::TestResponse| r.json()["description"].as_str().unwrap_or("").to_string(); + + // A member who isn't an admin, a project token and someone outside are refused + let r = patch("/api/v1/organizations/acme", &bob_t, json!({ "slug": "acme-hq" })).await; + r.assert_status(403); + assert_eq!(description(&r), "only admins can change the organization's settings"); + let r = patch("/api/v1/organizations/acme", &ci, json!({ "name": "CI's" })).await; + r.assert_status(403); + assert!(description(&r).contains("personal access token"), "{}", description(&r)); + patch("/api/v1/organizations/acme", &eve_t, json!({ "name": "Evil" })).await.assert_status(404); + app.patch("/api/v1/organizations/acme").json(json!({ "name": "Anon" })).await.assert_status(401); + + // The settings page's errors + let r = patch("/api/v1/organizations/acme", &ada_t, json!({ "slug": "Not A Slug" })).await; + r.assert_status(422); + assert!(description(&r).starts_with("slugs use lowercase letters"), "{}", description(&r)); + patch("/api/v1/organizations/acme", &ada_t, json!({ "slug": "api" })).await.assert_status(422); + let r = patch("/api/v1/organizations/acme", &ada_t, json!({ "slug": "other" })).await; + r.assert_status(409); + assert_eq!(description(&r), "that slug is taken"); + patch("/api/v1/organizations/acme", &ada_t, json!({ "name": "" })).await.assert_status(422); + patch("/api/v1/organizations/acme", &ada_t, json!({ "project_threshold": 0.5 })).await.assert_status(422); + + // A name alone + patch("/api/v1/organizations/acme", &ada_t, json!({ "name": " Acme Ltd " })) + .await + .assert_ok() + .assert_json_path("name", "Acme Ltd") + .assert_json_path("slug", "acme") + .assert_json_path("role", "admin") + .assert_json_path("projects.0.project", "acme/web"); + + // A slug: the old one keeps working everywhere + patch("/api/v1/organizations/acme", &ada_t, json!({ "slug": "acme-hq" })) + .await + .assert_ok() + .assert_json_path("slug", "acme-hq") + .assert_json_path("name", "Acme Ltd") + .assert_json_path("projects.0.project", "acme-hq/web"); + for t in [&bob_t, &ci] { + app.get("/api/v1/organizations/acme") + .header("authorization", format!("Bearer {t}")) + .await + .assert_ok() + .assert_json_path("slug", "acme-hq"); + } + let page = app.get("/acme/web").acting_as(&bob).await; + page.assert_status(302); + assert_eq!(page.header("location").unwrap_or_default(), "/acme-hq/web"); + app.get("/api/v1/organizations/other").header("authorization", format!("Bearer {ci}")).await.assert_status(404); + app.get("/api/v1/organizations/acme-hq") + .header("authorization", format!("Bearer {eve_t}")) + .await + .assert_status(404); + assert_eq!(app::models::Organization::by_slug("acme").await?.map(|o| o.id), Some(org.id)); + + // A project token reads the plan and its own project: no members, invitations, usage history or emails + app.post("/api/ui/orgs/acme-hq/invitations") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .json(json!({ "invitee": "zed@example.com", "role": "member" })) + .await + .assert_ok(); + let r = app.get("/api/v1/organizations/acme-hq").header("authorization", format!("Bearer {ci}")).await; + r.assert_ok(); + let body = r.json().clone(); + assert_eq!((&body["members"], &body["invitations"], &body["usage_history"]), (&json!([]), &json!([]), &json!([]))); + assert!(!body.to_string().contains("@example.com"), "{body}"); + let r = app.get("/api/v1/organizations/acme-hq").header("authorization", format!("Bearer {ada_t}")).await; + assert_eq!(r.json()["invitations"][0]["email"], "zed@example.com", "{}", r.json()); + + // `{}` and the slug it has change nothing + let slugs = || async { + let id = org.id; + db::query!("SELECT count(*) FROM previous_organization_slugs WHERE organization_id = {id}") + .scalar::() + .await + }; + let before = slugs().await?; + for body in [json!({}), json!({ "slug": "acme-hq" })] { + patch("/api/v1/organizations/acme-hq", &ada_t, body) + .await + .assert_ok() + .assert_json_path("slug", "acme-hq") + .assert_json_path("name", "Acme Ltd"); + } + assert_eq!(slugs().await?, before); + + // Another organization's old slug stays its own + fixtures::member(&other, &ada, "admin").await?; + patch("/api/v1/organizations/other", &ada_t, json!({ "slug": "other-new" })).await.assert_ok(); + let r = patch("/api/v1/organizations/acme-hq", &ada_t, json!({ "slug": "other" })).await; + r.assert_status(409); + assert_eq!(description(&r), "that slug is taken"); + + // No token is a 401 whatever the body + app.patch("/api/v1/organizations/acme-hq") + .header("content-type", "application/json") + .body("{not json") + .await + .assert_status(401); + Ok(()) +} diff --git a/frontend/content/changelog/2026-12-06-0434-organization-updates-api.md b/frontend/content/changelog/2026-12-06-0434-organization-updates-api.md new file mode 100644 index 00000000..e7d32dfd --- /dev/null +++ b/frontend/content/changelog/2026-12-06-0434-organization-updates-api.md @@ -0,0 +1 @@ +Rename an organization or change its name over the API (`PATCH /api/v1/organizations/{org}`) and MCP (`update_organization`), for its admins. The old slug keeps working: its links redirect, and project names with it are still accepted. diff --git a/frontend/content/docs/agents.md b/frontend/content/docs/agents.md index 41c83513..2bd910cb 100644 --- a/frontend/content/docs/agents.md +++ b/frontend/content/docs/agents.md @@ -229,7 +229,7 @@ failing in the repository instead of sending them. - `whoami` (who the token belongs to, and the newest builds waiting for a review), `list_organizations`, `get_organization` (projects, plan, credits used this month and pack credits). - Out of credits: `whoami` (for each organization) and `get_build` return `blocked`, with what fixes it and a `message` to pass on to your person as it is. Buying credits stays with them. -- `create_organization`, `create_project`, `get_project`, `update_project` (settings and [ignore rules](/docs/reference/api/#project-settings)), `create_project_token`, `delete_project_token`, `delete_project` (admins, with the full `org/project` name to confirm; support can restore it for 7 days). +- `create_organization`, `update_organization` (its name or slug, admins with a person's token: the old slug keeps working, and links to it redirect), `create_project`, `get_project`, `update_project` (settings and [ignore rules](/docs/reference/api/#project-settings)), `create_project_token`, `delete_project_token`, `delete_project` (admins, with the full `org/project` name to confirm; support can restore it for 7 days). **Without the MCP server** diff --git a/frontend/content/docs/reference/api.md b/frontend/content/docs/reference/api.md index b75d7276..48254fb4 100644 --- a/frontend/content/docs/reference/api.md +++ b/frontend/content/docs/reference/api.md @@ -5,7 +5,7 @@ description: VisualCI's CI API (builds, snapshots, finalize), its project settin The CLI uses this API. Most integrations should use the CLI, which hashes files and uploads the new ones for you. Coding agents use the [MCP server](/docs/agents/), which covers everything the web app does. -All requests go to `https://api.visualci.com/api/v1` with `Authorization: Bearer ` (`vci_...`). Bodies and responses are JSON. A body with a field the endpoint doesn't take is refused (422, naming the field and the ones it takes), so a misspelt field never passes unnoticed. The MCP server's tools do the same. Numbers may be sent as JSON numbers or as strings holding them (`"2"`). +All requests go to `https://api.visualci.com/api/v1` with `Authorization: Bearer ` (`vci_...`), or a personal access token (`vcu_...`) where it says so. Bodies and responses are JSON. A body with a field the endpoint doesn't take is refused (422, naming the field and the ones it takes), so a misspelt field never passes unnoticed. The MCP server's tools do the same. Numbers may be sent as JSON numbers or as strings holding them (`"2"`). ## Create a build @@ -132,6 +132,18 @@ snapshot's name, platform, state, path and pages (changed fraction, regions and `POST /api/v1/versions` with `{"version": "v2.0.0", "commit": "", "parent_commits": ["", …]}` records what the project's [gallery](/docs/gallery/versions/) published at that commit as a version: the answer is `{"key", "label", "commit", "released_at", "manifest"}`, 201 when it's recorded, 200 when the same version was recorded at that commit before. A version that isn't up to 64 letters, digits and `._+-` (or is `latest`) is a 400, the same version recorded at another commit a 409, and a commit the gallery published nothing at a 422, as is a new version once the project has 500. `GET /api/v1/versions` lists the project's versions, newest first, as `{"versions": [...]}`. +## Organizations + +`GET /api/v1/organizations/{org}` returns the organization as MCP's `get_organization` does: its projects with each one's latest build, its plan and credits used this month, and (for a personal token) its members. A project token sees its own project and the plan and usage, not the members or the other projects. + +`PATCH /api/v1/organizations/{org}` changes its name or slug, with a personal access token (`vcu_...`) of one of its admins; a project token is refused (403). + +```json +{ "name": "Acme Ltd", "slug": "acme-hq" } +``` + +Both fields are optional, and one left out stays as it is. The answer is the organization, as the `GET` returns it. A new slug renames the organization, as its settings page does: the old slug keeps working, so links to its pages and galleries redirect to the new one, and the API, MCP and tokens accept project names with either. `{org}` may be the old slug too. Errors are the settings page's: 403 for a member who isn't an admin, 422 for a slug that isn't lowercase letters, digits and dashes or is a reserved word (such as `api`), or a name that isn't 1 to 100 characters, and 409 for a slug another organization has or had. MCP's `update_organization` does the same. + ## Feedback `POST /api/v1/support/feedback`: see [Support](/docs/support/). diff --git a/frontend/content/llms-header.md b/frontend/content/llms-header.md index 046c974e..628460c5 100644 --- a/frontend/content/llms-header.md +++ b/frontend/content/llms-header.md @@ -25,7 +25,7 @@ The tools cover everything the web app and the CI API do, except choosing a plan - Builds: `list_builds`, `get_build`, `get_snapshot` (base, head and diff images of each changed page, scaled with `max_width` or cropped to the changes with `crop: changed`, the changed regions and the page's text diff; for text, JSON and HTML snapshots the changes by JSON path and a unified diff), `contact_sheet` (a grid of thumbnails for many snapshots), `snapshot_history` - Reviews: `review` (approve or reject a build or some of its snapshots), `review_page` (accept one page as a variant, or ignore one change) - Running a comparison: `create_build`, `upload_snapshots` (PDFs, PNG/JPEG/WebP images, or text, JSON and HTML with an optional `format`, base64), `finalize_build` -- Organizations and projects: `whoami`, `list_organizations`, `get_organization` (projects, plan, credits used this month and pack credits), `create_organization`, `create_project`, `get_project`, `update_project` (including `ignore_rules` for text snapshots, each scoped to a snapshot glob), `create_project_token`, `delete_project_token`, `delete_project` (admins, with the full `org/project` name to confirm; restorable through support for 7 days) +- Organizations and projects: `whoami`, `list_organizations`, `get_organization` (projects, plan, credits used this month and pack credits), `create_organization`, `update_organization` (name or slug, admins; the old slug keeps working and redirects), `create_project`, `get_project`, `update_project` (including `ignore_rules` for text snapshots, each scoped to a snapshot glob), `create_project_token`, `delete_project_token`, `delete_project` (admins, with the full `org/project` name to confirm; restorable through support for 7 days) ## Snapshot tests: text, JSON and HTML diff --git a/plugin/skills/visualci-review/SKILL.md b/plugin/skills/visualci-review/SKILL.md index 7379c1fb..54b9ff28 100644 --- a/plugin/skills/visualci-review/SKILL.md +++ b/plugin/skills/visualci-review/SKILL.md @@ -234,7 +234,7 @@ failing in the repository instead of sending them. - `whoami` (who the token belongs to, and the newest builds waiting for a review), `list_organizations`, `get_organization` (projects, plan, credits used this month and pack credits). - Out of credits: `whoami` (for each organization) and `get_build` return `blocked`, with what fixes it and a `message` to pass on to your person as it is. Buying credits stays with them. -- `create_organization`, `create_project`, `get_project`, `update_project` (settings and [ignore rules](https://visualci.com/docs/reference/api.md#project-settings)), `create_project_token`, `delete_project_token`, `delete_project` (admins, with the full `org/project` name to confirm; support can restore it for 7 days). +- `create_organization`, `update_organization` (its name or slug, admins with a person's token: the old slug keeps working, and links to it redirect), `create_project`, `get_project`, `update_project` (settings and [ignore rules](https://visualci.com/docs/reference/api.md#project-settings)), `create_project_token`, `delete_project_token`, `delete_project` (admins, with the full `org/project` name to confirm; support can restore it for 7 days). **Without the MCP server**