diff --git a/crates/fctl-control/migrations/0077_workspace_sign_in.sql b/crates/fctl-control/migrations/0077_workspace_sign_in.sql new file mode 100644 index 00000000..f9aa224c --- /dev/null +++ b/crates/fctl-control/migrations/0077_workspace_sign_in.sql @@ -0,0 +1,6 @@ +-- A workspace's own sign-in requirement (#618, ADR 0103): its members who +-- are in it as an address at one of the rule's domains open it only with a +-- sign-in made with its provider as such an address. JSON of a +-- fctl_proto::api::SignInRule ({"domains": [...], "provider": "google", +-- "passkeys": false}); NULL, the default: none. +ALTER TABLE workspaces ADD COLUMN sign_in TEXT; diff --git a/crates/fctl-control/src/api/account.rs b/crates/fctl-control/src/api/account.rs index 0ab2d98e..36ab99da 100644 --- a/crates/fctl-control/src/api/account.rs +++ b/crates/fctl-control/src/api/account.rs @@ -669,7 +669,7 @@ async fn start(ctx: &Ctx, user: &UserRow, slot: Slot) -> AppResult { let open: Vec = crate::workspaces::mine(&ctx.db, &user.id) .await? .into_iter() - .filter(|w| !user.blocked_by(&settings, w.require_two_factor)) + .filter(|w| !w.closed_to(user, &settings)) .map(|w| w.id) .collect(); let mine_open = diff --git a/crates/fctl-control/src/api/claude.rs b/crates/fctl-control/src/api/claude.rs index 5c2cf4ff..3dcf595c 100644 --- a/crates/fctl-control/src/api/claude.rs +++ b/crates/fctl-control/src/api/claude.rs @@ -627,7 +627,7 @@ async fn login_runners(ctx: &Ctx, user: &UserRow) -> AppResult> { let open: Vec = crate::workspaces::mine(&ctx.db, &user.id) .await? .into_iter() - .filter(|w| !crate::workspaces::blocked_for(ctx, user, w.require_two_factor)) + .filter(|w| !w.closed_to(user, &ctx.settings())) .map(|w| w.id) .collect(); let mine = |r: &R| r.owner.as_deref() == Some(user.id.as_str()); diff --git a/crates/fctl-control/src/api/projects.rs b/crates/fctl-control/src/api/projects.rs index 16ef6072..6ab71f27 100644 --- a/crates/fctl-control/src/api/projects.rs +++ b/crates/fctl-control/src/api/projects.rs @@ -1212,7 +1212,7 @@ pub async fn github_info(ctx: &Ctx) -> AppResult { let open: Vec = ws::mine(&ctx.db, &user.id) .await? .into_iter() - .filter(|w| !ws::blocked_for(ctx, user, w.require_two_factor)) + .filter(|w| !w.closed_to(user, &ctx.settings())) .filter(|w| reached.as_ref().is_none_or(|r| r.contains(&w.id))) .map(|w| w.id) .collect(); diff --git a/crates/fctl-control/src/api/runners.rs b/crates/fctl-control/src/api/runners.rs index 88467ebe..e0a18749 100644 --- a/crates/fctl-control/src/api/runners.rs +++ b/crates/fctl-control/src/api/runners.rs @@ -493,22 +493,34 @@ pub async fn rotate_token(ctx: &mut Ctx, id: &str) -> AppResult { name: String, #[serde(deserialize_with = "crate::db::int_bool")] require_two_factor: bool, + #[serde(default)] + sign_in: Option, } let served: Vec = q( &ctx.db, - "SELECT w.name AS name, w.require_two_factor AS require_two_factor FROM runner_workspaces rw \ + concat!( + "SELECT w.name AS name, w.require_two_factor AS require_two_factor, ", + crate::workspace_sign_in!("w", "m.email"), + " AS sign_in FROM runner_workspaces rw \ JOIN workspaces w ON w.id = rw.workspace_id \ JOIN workspace_members m ON m.workspace_id = rw.workspace_id AND m.user_id = ? \ - WHERE rw.runner_id = ?", + WHERE rw.runner_id = ?" + ), &[s(&user_id), s(id)], )? .all() .await?; let user = ctx.user()?; - if let Some(closed) = served - .iter() - .find(|w| crate::workspaces::blocked_for(ctx, user, w.require_two_factor)) - { + if let Some(closed) = served.iter().find(|w| { + crate::workspaces::blocked_for(ctx, user, w.require_two_factor, w.sign_in.as_deref()) + }) { + if user.sign_in_blocked(closed.sign_in.as_deref()) { + return Err(forbidden(&crate::workspaces::sign_in_refusal( + &closed.name, + closed.sign_in.as_deref(), + "replace the runner's token, as it runs its sessions", + ))); + } return Err(forbidden(&format!( "This runner runs the sessions of {}, which requires two-factor sign-in: set it up in Settings before you replace the runner's token.", closed.name diff --git a/crates/fctl-control/src/api/search.rs b/crates/fctl-control/src/api/search.rs index f3323d30..e8d676c8 100644 --- a/crates/fctl-control/src/api/search.rs +++ b/crates/fctl-control/src/api/search.rs @@ -60,11 +60,12 @@ pub async fn search(ctx: &Ctx, req: &Request) -> AppResult { let mut scopes: BTreeMap = BTreeMap::new(); let mut sql = format!( "SELECT p.id, m.role AS member_role, w.id AS workspace_id, w.base_role AS workspace_base_role, \ - w.require_two_factor AS workspace_two_factor, wm.role AS workspace_role \ + w.require_two_factor AS workspace_two_factor, {} AS workspace_sign_in, wm.role AS workspace_role \ FROM projects p JOIN workspaces w ON w.id = p.workspace_id \ LEFT JOIN workspace_members wm ON wm.workspace_id = p.workspace_id AND wm.user_id = ?1 \ LEFT JOIN project_members m ON m.project_id = p.id AND m.user_id = ?1 \ - WHERE {PROJECT_VISIBLE}" + WHERE {PROJECT_VISIBLE}", + crate::workspace_sign_in!() ); let mut params = vec![s(&user.id)]; if let Some(w) = &workspace { diff --git a/crates/fctl-control/src/api/workspaces.rs b/crates/fctl-control/src/api/workspaces.rs index 2d8f1154..fcab2988 100644 --- a/crates/fctl-control/src/api/workspaces.rs +++ b/crates/fctl-control/src/api/workspaces.rs @@ -37,7 +37,8 @@ async fn live(ctx: &Ctx) -> LiveRunners { async fn respond(ctx: &Ctx, id: &str) -> AppResult { let a = ws::load(ctx, id).await?; let live = live(ctx).await; - Ok(a.row.to_workspace(&ctx.settings(), a.blocked, &live.online)) + Ok(a.row + .to_workspace(&ctx.settings(), ctx.user()?, &live.online)) } /// `GET /api/v1/workspaces`. @@ -62,11 +63,7 @@ pub async fn list(ctx: &Ctx) -> AppResult { workspaces: rows .iter() .map(|r| { - let mut w = r.to_workspace( - &settings, - ws::blocked_for(ctx, user, r.require_two_factor), - &live.online, - ); + let mut w = r.to_workspace(&settings, user, &live.online); // A limited token reaches projects and sessions alone: not // the workspace's people, GitHub accounts or its person's // Claude connections (`fctl_domain::limits`). @@ -81,7 +78,10 @@ pub async fn list(ctx: &Ctx) -> AppResult { .collect(), invitations: invitations .iter() - .map(|i| i.to_invitation(ws::blocked_for(ctx, user, i.require_two_factor))) + // Its two-factor requirement alone, which the invitation names: + // accepting it refuses, saying so, where its sign-in requirement + // closes it to this sign-in. + .map(|i| i.to_invitation(ws::blocked_for(ctx, user, i.require_two_factor, None))) .collect(), limit: settings.max_workspaces, unlimited: policy::workspace_limit(user.role(), &settings).is_none(), @@ -218,7 +218,25 @@ pub async fn get(ctx: &Ctx, id: &str) -> AppResult { pub async fn update(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult { let body: UpdateWorkspaceRequest = http::body(req).await?; let a = ws::load(ctx, id).await?; - a.require_admin()?; + // Its primary admin may lift or change its sign-in requirement while it + // closes the workspace to them, and only that: where nobody can meet + // it any more (Google sign-in no longer set up, their Google accounts + // closed), the workspace would stay closed to everyone otherwise. + // Requiring less still takes confirming it's them, below. + let lifting = a.sign_in_blocked + && a.role == Some(WorkspaceRole::Owner) + && body.sign_in.is_some() + && body + == UpdateWorkspaceRequest { + sign_in: body.sign_in.clone(), + ..UpdateWorkspaceRequest::default() + } + && !ctx + .user()? + .blocked_by(&ctx.settings(), a.row.require_two_factor, None); + if !lifting { + a.require_admin()?; + } let user = ctx.user()?.clone(); let name = body.name.as_deref().map(policy::name).transpose()?; let slug = match body.slug.as_deref() { @@ -262,13 +280,51 @@ pub async fn update(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult Some( + fctl_domain::sign_in::check_workspace_rule(rule, &crate::sign_in::providers(&ctx.cfg)) + .map_err(AppError)?, + ), + None => None, + }; + if let Some(next) = &sign_in { + if fctl_domain::verify::workspace_sign_in_relaxed( + a.row.sign_in_rule().as_ref(), + next.as_ref(), + ) { + ctx.verified(Sensitive::RelaxWorkspaceSignIn)?; + } + if let Some(rule) = next { + let mine = fctl_domain::sign_in::domain_of(a.row.email.as_deref().unwrap_or_default()); + let covers = mine.is_some_and(|d| rule.domains.contains(&d)); + if covers + && user + .request_sign_in + .as_ref() + .is_some_and(|how| !fctl_domain::sign_in::meets(rule, how)) + { + return Err(AppError(ApiError::new( + ErrorCode::Conflict, + format!( + "This would close {} to you: you're in it as {}, and signed in another way. Sign in with {} as that address first, which shows it works for you, then require it.", + a.row.name, + a.row.email.as_deref().unwrap_or_default(), + crate::sign_in::provider_name(&rule.provider) + ), + ))); + } + } + } let updated = q( &ctx.db, "UPDATE workspaces SET name = COALESCE(?, name), slug = COALESCE(?, slug), color = COALESCE(?, color), \ @@ -301,6 +357,18 @@ pub async fn update(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult AppResult = ws::mine(&ctx.db, &user.id) .await? .into_iter() - .filter(|w| !ws::blocked_for(ctx, user, w.require_two_factor)) + .filter(|w| !w.closed_to(user, &ctx.settings())) .collect(); Ok(Self { user_id: user.id.clone(), diff --git a/crates/fctl-control/src/auth.rs b/crates/fctl-control/src/auth.rs index 9c5d5075..23baf55a 100644 --- a/crates/fctl-control/src/auth.rs +++ b/crates/fctl-control/src/auth.rs @@ -364,9 +364,13 @@ pub async fn by_token_id(db: &D1Database, token_id: &str, now: i64) -> AppResult f.user.has_password(), f.user.factors(), ); + // The token's own sign-in, which workspaces' own requirements + // check, as `authenticate` gives a request. + let mut user = f.user; + user.request_sign_in = Some(how); (!setup_required).then(|| Holder { limits: Limits::parse(f.scope.as_deref()), - user: f.user, + user, settings, }) })) @@ -558,8 +562,11 @@ pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> { ); // However it comes: in a cookie, a limited token stays limited. let limits = Limits::parse(found.scope.as_deref()); + // A person's own sign-in: what workspaces' own requirements check. + let mut user = found.user; + user.request_sign_in = Some(how.clone()); ctx.auth = Some(Authed { - user: found.user, + user, token_id: found.token_id, kind, via_cookie, diff --git a/crates/fctl-control/src/ctx.rs b/crates/fctl-control/src/ctx.rs index 6d68dc54..3a85acc1 100644 --- a/crates/fctl-control/src/ctx.rs +++ b/crates/fctl-control/src/ctx.rs @@ -101,8 +101,10 @@ impl Authed { verified_at: Option, how: SignedIn, ) -> Self { + let mut user = user.clone(); + user.request_sign_in = Some(how.clone()); Self { - user: user.clone(), + user, token_id, kind: TokenKind::Web, via_cookie: true, diff --git a/crates/fctl-control/src/do_fleet.rs b/crates/fctl-control/src/do_fleet.rs index f17ceb10..87374133 100644 --- a/crates/fctl-control/src/do_fleet.rs +++ b/crates/fctl-control/src/do_fleet.rs @@ -4031,22 +4031,42 @@ impl FleetObject { if sockets.is_empty() { continue; } - let Ok(Some(user)) = user_row(&db, user_id).await else { + let Ok(Some(person)) = user_row(&db, user_id).await else { continue; }; - let ident = match crate::workspaces::feed_identity(&db, &user, &settings).await { - Ok(i) => i, - Err(e) => { - worker::console_error!("feed identity: {}", e.0.message); - continue; - } - }; - let messages = self.view_changed(&ident).await; for ws in sockets { - // Each keeps the token it was opened with, checked as before. + // Each keeps the token it was opened with, checked as before, + // and sees what its sign-in opens: a workspace's own sign-in + // requirement may close it to one of their browsers and not + // another. let old = ws.deserialize_attachment::().ok().flatten(); - let mut ident = ident.clone(); - ident.token_id = old.as_ref().and_then(|o| o.token_id.clone()); + let token_id = old.as_ref().and_then(|o| o.token_id.clone()); + let mut user = person.clone(); + if let Some(t) = &token_id { + match crate::auth::by_token_id(&db, t, now_ms()).await { + Ok(Some(h)) if h.user.id == *user_id => { + user.request_sign_in = h.user.request_sign_in; + } + Ok(_) => { + let _ = ws.close(Some(CLOSE_NO_ACCESS), Some("signed out")); + continue; + } + Err(e) => { + worker::console_error!("checking a feed: {}", e.0.message); + continue; + } + } + } + let mut ident = match crate::workspaces::feed_identity(&db, &user, &settings).await + { + Ok(i) => i, + Err(e) => { + worker::console_error!("feed identity: {}", e.0.message); + continue; + } + }; + let messages = self.view_changed(&ident).await; + ident.token_id = token_id; ident.checked_at = old.and_then(|o| o.checked_at); let _ = ws.serialize_attachment(&ident); for text in &messages { diff --git a/crates/fctl-control/src/model.rs b/crates/fctl-control/src/model.rs index 9b84539d..ed392fef 100644 --- a/crates/fctl-control/src/model.rs +++ b/crates/fctl-control/src/model.rs @@ -21,6 +21,13 @@ use serde::Deserialize; #[derive(Clone, Debug, Deserialize)] pub struct UserRow { + /// How the sign-in of the request it came with was made, where it's a + /// person's own (a browser's, a CLI's or an access token's): what a + /// workspace's own sign-in requirement checks ([`Self::blocked_by`]). + /// `None` read from D1, and for service accounts' and autopilots' + /// requests, which no such requirement holds. + #[serde(skip)] + pub request_sign_in: Option, pub id: String, pub email: String, pub name: String, @@ -163,21 +170,36 @@ impl UserRow { fctl_domain::two_factor::with_workspaces(settings, self.two_factor_workspaces > 0) } - /// Whether a workspace that requires two-factor sign-in is closed to - /// them (they haven't set it up). `require_two_factor` is its admins' + /// Whether a workspace is closed to them: it requires two-factor + /// sign-in, which they haven't set up, or its own sign-in requirement + /// covers them and the sign-in of this request doesn't meet it + /// ([`Self::sign_in_blocked`]). `require_two_factor` is its admins' /// choice: the instance's requirement closes their whole account /// instead (`fctl_domain::two_factor::workspace_requires`). + /// `sign_in`: its requirement as [`workspace_sign_in!`] reads it, where + /// it covers them. pub fn blocked_by( &self, settings: &fctl_proto::api::InstanceSettings, require_two_factor: bool, + sign_in: Option<&str>, ) -> bool { - require_two_factor + (require_two_factor && fctl_domain::two_factor::workspace_blocked( settings, self.has_password(), self.factors(), - ) + )) + || self.sign_in_blocked(sign_in) + } + + /// Whether a workspace's own sign-in requirement, which covers them + /// (`sign_in`, as [`workspace_sign_in!`] reads it), closes it to the + /// request they come with. + pub fn sign_in_blocked(&self, sign_in: Option<&str>) -> bool { + let rule = + sign_in.and_then(|j| serde_json::from_str::(j).ok()); + fctl_domain::sign_in::workspace_closed(rule.as_ref(), self.request_sign_in.as_ref()) } /// Their other email addresses. @@ -387,6 +409,10 @@ pub struct WorkspaceCols { pub workspace_base_role: Option, #[serde(deserialize_with = "int_bool", default)] pub workspace_two_factor: bool, + /// Its own sign-in requirement, where it covers the caller + /// ([`workspace_sign_in!`]). + #[serde(default)] + pub workspace_sign_in: Option, /// The caller's role in it. #[serde(default)] pub workspace_role: Option, @@ -417,7 +443,11 @@ impl WorkspaceCols { .as_deref() .and_then(fctl_proto::api::BaseRole::parse) .unwrap_or_default(), - blocked: user.blocked_by(settings, self.workspace_two_factor), + blocked: user.blocked_by( + settings, + self.workspace_two_factor, + self.workspace_sign_in.as_deref(), + ), }) } } @@ -684,7 +714,8 @@ impl RepoRow { /// repositories. Bind: `?1` = caller user id. The counts leave out the /// sessions the lists do: review agents', and those of schedules that hide /// theirs. -pub const PROJECT_SELECT: &str = "SELECT p.id, p.slug, p.name, p.description, p.icon, p.repo_owner, p.repo_name, \ +pub const PROJECT_SELECT: &str = concat!( + "SELECT p.id, p.slug, p.name, p.description, p.icon, p.repo_owner, p.repo_name, \ p.default_branch, p.settings, p.session_counter, p.created_by, cu.name AS creator_name, \ cu.avatar_url AS creator_avatar, p.created_at, p.updated_at, p.archived_at, m.role AS member_role, \ (SELECT COUNT(*) FROM sessions s WHERE s.project_id = p.id AND s.status IN ('provisioning','preparing','running','idle','paused','stopping') \ @@ -703,7 +734,9 @@ pub const PROJECT_SELECT: &str = "SELECT p.id, p.slug, p.name, p.description, p. (SELECT r.owner FROM project_repos r WHERE r.project_id = p.id AND r.name = '*' LIMIT 1) AS all_repos_of, \ w.id AS workspace_id, w.slug AS workspace_slug, w.name AS workspace_name, w.color AS workspace_color, \ w.avatar_updated_at AS workspace_avatar_at, w.base_role AS workspace_base_role, \ - w.require_two_factor AS workspace_two_factor, wm.role AS workspace_role, \ + w.require_two_factor AS workspace_two_factor, ", + crate::workspace_sign_in!(), + " AS workspace_sign_in, wm.role AS workspace_role, \ c.model AS last_model, c.effort AS last_effort, \ w.autopilots AS workspace_autopilots, ap.state AS autopilot_state, ap.scope AS autopilot_scope, \ CASE WHEN ap.scope = 'workspace' AND COALESCE(wm.role, '') NOT IN ('owner', 'admin') THEN 0 \ @@ -721,7 +754,8 @@ pub const PROJECT_SELECT: &str = "SELECT p.id, p.slug, p.name, p.description, p. LEFT JOIN project_members m ON m.project_id = p.id AND m.user_id = ?1 \ LEFT JOIN project_choices c ON c.project_id = p.id AND c.user_id = ?1 \ LEFT JOIN autopilots ap ON ap.project_id = p.id \ - LEFT JOIN sessions aps ON aps.id = ap.session_id"; + LEFT JOIN sessions aps ON aps.id = ap.session_id" +); /// What lets the caller see a project, for `WHERE` clauses with /// [`PROJECT_SELECT`] (or [`SESSION_SELECT`]): they are in its workspace, @@ -739,6 +773,32 @@ macro_rules! workspace_order { }; } +/// A workspace's own sign-in requirement (`w.sign_in`, JSON) where it +/// covers its member whose address there is `$email` (`wm.email` unless +/// given): one of its domains is that address's. NULL elsewhere. For +/// [`UserRow::blocked_by`]. +#[macro_export] +macro_rules! workspace_sign_in { + () => { + $crate::workspace_sign_in!("w", "wm.email") + }; + ($w:literal, $email:literal) => { + concat!( + "CASE WHEN ", + $w, + ".sign_in IS NOT NULL AND EXISTS (SELECT 1 FROM json_each(", + $w, + ".sign_in, '$.domains') d WHERE d.value = lower(substr(", + $email, + ", instr(", + $email, + ", '@') + 1))) THEN ", + $w, + ".sign_in END" + ) + }; +} + /// [`workspace_order!`], for queries with [`crate::workspaces::WORKSPACE_SELECT`]. pub const WORKSPACE_ORDER: &str = workspace_order!(); @@ -1068,7 +1128,8 @@ impl SessionRow { /// project and share roles, and whether they follow it. Bind: `?1` = /// caller user id. A share someone gave themselves (as an owner, before /// they were demoted) counts for nothing. -pub const SESSION_SELECT: &str = "SELECT s.id, s.project_id, p.slug AS project_slug, s.number, s.title, s.description, s.prompt, s.prompt_attachments, \ +pub const SESSION_SELECT: &str = concat!( + "SELECT s.id, s.project_id, p.slug AS project_slug, s.number, s.title, s.description, s.prompt, s.prompt_attachments, \ s.status, s.status_reason, s.resume_at, s.created_by, cu.name AS creator_name, cu.avatar_url AS creator_avatar, \ s.credential_id, CASE WHEN cc.user_id = ?1 THEN s.credential_id END AS my_credential_id, cc.user_id AS claude_user_id, ccu.name AS claude_user_name, ccu.avatar_url AS claude_user_avatar, \ s.runner_id, r.name AS runner_name, s.branch, s.base_branch, s.model, s.effort, \ @@ -1083,7 +1144,9 @@ pub const SESSION_SELECT: &str = "SELECT s.id, s.project_id, p.slug AS project_s CASE WHEN s.autopilot_role = 'pilot' THEN (SELECT a.scope FROM autopilots a WHERE a.project_id = s.autopilot_id) END AS autopilot_scope, \ w.id AS workspace_id, w.slug AS workspace_slug, w.name AS workspace_name, w.color AS workspace_color, \ w.avatar_updated_at AS workspace_avatar_at, w.base_role AS workspace_base_role, \ - w.require_two_factor AS workspace_two_factor, wm.role AS workspace_role \ + w.require_two_factor AS workspace_two_factor, ", + crate::workspace_sign_in!(), + " AS workspace_sign_in, wm.role AS workspace_role \ FROM sessions s \ JOIN projects p ON p.id = s.project_id \ LEFT JOIN reviews rv ON rv.session_id = s.id \ @@ -1097,7 +1160,8 @@ pub const SESSION_SELECT: &str = "SELECT s.id, s.project_id, p.slug AS project_s LEFT JOIN project_members m ON m.project_id = s.project_id AND m.user_id = ?1 \ LEFT JOIN session_shares sh ON sh.session_id = s.id AND sh.user_id = ?1 \ AND (sh.created_by IS NULL OR sh.created_by != sh.user_id) \ - LEFT JOIN session_followers f ON f.session_id = s.id AND f.user_id = ?1"; + LEFT JOIN session_followers f ON f.session_id = s.id AND f.user_id = ?1" +); #[derive(Clone, Debug, Deserialize)] pub struct RunnerRow { diff --git a/crates/fctl-control/src/service_accounts.rs b/crates/fctl-control/src/service_accounts.rs index 2a6c54b6..f62f361e 100644 --- a/crates/fctl-control/src/service_accounts.rs +++ b/crates/fctl-control/src/service_accounts.rs @@ -446,7 +446,7 @@ async fn act_for(ctx: &Ctx, caller: &ServiceCaller, named: &Named) -> AppResult< let settings = ctx.settings(); let needs_two_factor = fctl_domain::two_factor::setup_required(&settings, person.has_password(), person.factors()) - || person.blocked_by(&settings, found.require_two_factor); + || person.blocked_by(&settings, found.require_two_factor, None); let state = Person { member: found.member, active: person.is_active(), @@ -503,7 +503,7 @@ pub async fn people( &settings, r.user.has_password(), r.user.factors(), - ) || r.user.blocked_by(&settings, require_two_factor); + ) || r.user.blocked_by(&settings, require_two_factor, None); let why = policy::may_act_for( consent, Person { diff --git a/crates/fctl-control/src/workspaces.rs b/crates/fctl-control/src/workspaces.rs index cddae97c..eda3aa5d 100644 --- a/crates/fctl-control/src/workspaces.rs +++ b/crates/fctl-control/src/workspaces.rs @@ -49,7 +49,9 @@ fn yes() -> bool { /// show of them. Bind: `?1` = caller user id. pub const WORKSPACE_SELECT: &str = concat!( "SELECT w.id, w.slug, w.name, w.color, w.avatar_updated_at, w.base_role, \ - w.require_two_factor, w.skip_invites, w.created_at, wm.role AS role, wm.email AS email, wm.credential_id AS credential_id, wm.own_runners AS own_runners, \ + w.require_two_factor, w.sign_in AS sign_in, ", + crate::workspace_sign_in!(), + " AS sign_in_covers, w.skip_invites, w.created_at, wm.role AS role, wm.email AS email, wm.credential_id AS credential_id, wm.own_runners AS own_runners, \ (SELECT COUNT(*) FROM workspace_members x WHERE x.workspace_id = w.id) AS members, \ (SELECT COUNT(*) FROM projects p WHERE p.workspace_id = w.id AND p.archived_at IS NULL) AS projects, \ (SELECT json_group_array(rw.runner_id) FROM runner_workspaces rw JOIN runners r ON r.id = rw.runner_id \ @@ -87,6 +89,12 @@ pub struct WorkspaceRow { pub base_role: String, #[serde(deserialize_with = "int_bool")] pub require_two_factor: bool, + /// Its own sign-in requirement (JSON, `fctl_proto::api::SignInRule`). + #[serde(default)] + pub sign_in: Option, + /// The same, where it covers the caller ([`crate::workspace_sign_in!`]). + #[serde(default)] + pub sign_in_covers: Option, #[serde(deserialize_with = "int_bool")] pub skip_invites: bool, #[serde(deserialize_with = "int")] @@ -195,14 +203,33 @@ impl WorkspaceRow { fctl_domain::two_factor::workspace_requires(settings, self.require_two_factor) } - /// The workspace as its member, the caller, sees it; `online`: the - /// runners online now. + /// Its own sign-in requirement. + pub fn sign_in_rule(&self) -> Option { + self.sign_in + .as_deref() + .and_then(|j| serde_json::from_str(j).ok()) + } + + /// Whether it's closed to `user`, the caller, as [`UserRow::blocked_by`] + /// says. + pub fn closed_to(&self, user: &UserRow, settings: &InstanceSettings) -> bool { + user.blocked_by( + settings, + self.require_two_factor, + self.sign_in_covers.as_deref(), + ) + } + + /// The workspace as its member, `user`, the caller, sees it; `online`: + /// the runners online now. pub fn to_workspace( &self, settings: &InstanceSettings, - blocked: bool, + user: &UserRow, online: &[String], ) -> Workspace { + let blocked = self.closed_to(user, settings); + let sign_in_blocked = user.sign_in_blocked(self.sign_in_covers.as_deref()); let runners = self.runner_ids(); let (color, hex) = fctl_domain::workspace::color(self.color.as_deref()); Workspace { @@ -218,6 +245,8 @@ impl WorkspaceRow { require_two_factor: self.requires_two_factor(settings), instance_requires_two_factor: settings.require_two_factor, blocked, + sign_in: self.sign_in_rule(), + sign_in_blocked, claude: self.credential_id.clone().map(CredentialId), primary: self.primary(), members: self.members.max(0) as u32, @@ -288,8 +317,12 @@ impl WorkspaceRow { pub struct WorkspaceAccess { pub row: WorkspaceRow, pub role: Option, - /// It requires two-factor sign-in, which the caller hasn't set up. + /// It's closed to the caller: it requires two-factor sign-in, which + /// they haven't set up, or its own sign-in requirement covers them and + /// this request's sign-in doesn't meet it. pub blocked: bool, + /// Its own sign-in requirement is what closes it. + pub sign_in_blocked: bool, } impl WorkspaceAccess { @@ -301,12 +334,17 @@ impl WorkspaceAccess { pub fn require_open(&self) -> AppResult { let role = self.role.ok_or_else(|| not_found("Workspace"))?; if self.blocked { + let sign_in = self.row.sign_in_covers.as_deref(); return Err(AppError(ApiError::new( ErrorCode::Forbidden, - format!( - "{} requires two-factor sign-in. Set it up in Settings → Security to open it.", - self.row.name - ), + if self.sign_in_blocked { + sign_in_refusal(&self.row.name, sign_in, "open it") + } else { + format!( + "{} requires two-factor sign-in. Set it up in Settings → Security to open it.", + self.row.name + ) + }, ))); } Ok(role) @@ -330,10 +368,17 @@ impl WorkspaceAccess { } } -/// Whether a workspace that requires two-factor sign-in is closed to the -/// caller. -pub fn blocked_for(ctx: &Ctx, user: &UserRow, require_two_factor: bool) -> bool { - user.blocked_by(&ctx.settings(), require_two_factor) +/// Whether a workspace is closed to the caller: it requires two-factor +/// sign-in they haven't set up, or its own sign-in requirement covers them +/// (`sign_in`, [`crate::workspace_sign_in!`]) and this request's sign-in +/// doesn't meet it. +pub fn blocked_for( + ctx: &Ctx, + user: &UserRow, + require_two_factor: bool, + sign_in: Option<&str>, +) -> bool { + user.blocked_by(&ctx.settings(), require_two_factor, sign_in) } /// A workspace by id or slug, with the caller's membership. People who @@ -353,8 +398,14 @@ pub async fn load(ctx: &Ctx, id_or_slug: &str) -> AppResult { { return Err(not_found("Workspace")); } - let blocked = blocked_for(ctx, user, row.require_two_factor); - Ok(WorkspaceAccess { row, role, blocked }) + let blocked = row.closed_to(user, &ctx.settings()); + let sign_in_blocked = user.sign_in_blocked(row.sign_in_covers.as_deref()); + Ok(WorkspaceAccess { + row, + role, + blocked, + sign_in_blocked, + }) } /// The workspaces a caller held to places reaches (a limited token, an @@ -487,6 +538,8 @@ pub const INVITATION_SELECT: &str = concat!( "SELECT i.id, i.workspace_id, i.email, i.role, i.invited_by, \ iu.name AS inviter_name, iu.avatar_url AS inviter_avatar, i.created_at, i.expires_at, \ w.slug, w.name, w.color, w.avatar_updated_at, w.require_two_factor, ", + crate::workspace_sign_in!("w", "i.email"), + " AS sign_in_covers, ", crate::service_account_refs!(), " AS service_accounts \ FROM workspace_invitations i JOIN workspaces w ON w.id = i.workspace_id \ @@ -522,6 +575,10 @@ pub struct InvitationRow { pub avatar_updated_at: Option, #[serde(deserialize_with = "int_bool")] pub require_two_factor: bool, + /// Its workspace's sign-in requirement where it covers the invited + /// address ([`crate::workspace_sign_in!`]). + #[serde(default)] + pub sign_in_covers: Option, /// Its workspace's service accounts (JSON, /// `crate::service_accounts::refs`). #[serde(default)] @@ -633,7 +690,17 @@ pub async fn join( } let limit = policy::workspace_limit(user.role(), settings); policy::check_limit(membership_count(db, &user.id).await?, limit)?; - if user.blocked_by(settings, invitation.require_two_factor) { + if user.sign_in_blocked(invitation.sign_in_covers.as_deref()) { + return Err(AppError(ApiError::new( + ErrorCode::Forbidden, + sign_in_refusal( + &invitation.name, + invitation.sign_in_covers.as_deref(), + "join", + ), + ))); + } + if user.blocked_by(settings, invitation.require_two_factor, None) { return Err(AppError(ApiError::new( ErrorCode::Forbidden, format!( @@ -923,7 +990,7 @@ pub async fn feed_identity( let workspaces = mine(db, &user.id).await?; let open: Vec<&WorkspaceRow> = workspaces .iter() - .filter(|w| !user.blocked_by(settings, w.require_two_factor)) + .filter(|w| !w.closed_to(user, settings)) .collect(); #[derive(Deserialize)] struct P { @@ -1003,3 +1070,126 @@ pub async fn member_ids(db: &D1Database, workspace_id: &str) -> AppResult, then: &str) -> String { + let rule: Option = rule.and_then(|j| serde_json::from_str(j).ok()); + let (provider, domains) = rule.map_or_else( + || ("its provider".to_owned(), String::new()), + |r| { + ( + crate::sign_in::provider_name(&r.provider).to_owned(), + fctl_domain::sign_in::domains_words(&r.domains).replace(" and ", " or "), + ) + }, + ); + format!( + "{name} requires its members to sign in with {provider} as their {domains} address: sign out, sign in again with {provider} as yours, then {then}." + ) +} + +#[cfg(all(test, target_arch = "wasm32"))] +mod d1_tests { + use super::*; + use crate::model::{PROJECT_SELECT, ProjectRow, user_columns}; + use crate::testing; + use fctl_domain::sign_in::SignedIn; + use wasm_bindgen_test::wasm_bindgen_test; + + async fn user(db: &D1Database, id: &str, how: Option) -> AppResult { + let row: Option = q( + db, + &format!("SELECT {} FROM users u WHERE u.id = ?", user_columns("u")), + &[s(id)], + )? + .first() + .await?; + let mut row = row.ok_or_else(|| crate::error::internal("no user"))?; + row.request_sign_in = how; + Ok(row) + } + + async fn sees_web(db: &D1Database, who: &UserRow) -> AppResult { + let row: Option = q( + db, + &format!("{PROJECT_SELECT} WHERE p.id = ?2"), + &[s(&who.id), s("prj_web")], + )? + .first() + .await?; + let settings = InstanceSettings::default(); + Ok(row + .and_then(|r| crate::access::project_role(who, &settings, None, &r)) + .is_some()) + } + + /// A workspace's own requirement closes it, its projects with it, to + /// the members it covers whose sign-in doesn't meet it, and only them. + #[wasm_bindgen_test] + async fn a_workspaces_requirement_closes_it_to_sign_ins_made_another_way() -> AppResult<()> { + let db = testing::database(); + for sql in [ + "INSERT INTO users (id, email, name, role, status, created_at, updated_at) VALUES \ + ('usr_ada', 'ada@acme.com', 'Ada', 'member', 'active', 0, 0), \ + ('usr_cy', 'cy@contractor.io', 'Cy', 'member', 'active', 0, 0)", + "INSERT INTO workspaces (id, slug, name, base_role, sign_in, created_at, updated_at) VALUES \ + ('wsp_acme', 'acme', 'Acme', 'editor', '{\"domains\":[\"acme.com\"],\"provider\":\"google\",\"passkeys\":false}', 0, 0)", + "INSERT INTO workspace_members (workspace_id, user_id, email, role, created_at) VALUES \ + ('wsp_acme', 'usr_ada', 'Ada@ACME.com', 'member', 0), ('wsp_acme', 'usr_cy', 'cy@contractor.io', 'member', 0)", + "INSERT INTO projects (id, slug, name, created_by, created_at, updated_at, workspace_id) VALUES \ + ('prj_web', 'web', 'Web', 'usr_ada', 0, 0, 'wsp_acme')", + ] { + q(&db, sql, &[])?.run().await?; + } + let google = |a: &str| Some(SignedIn::provider("google", Some(a))); + // Ada is in it as an acme.com address: only Google as one opens it. + let ada = user(&db, "usr_ada", Some(SignedIn::password())).await?; + assert!(!sees_web(&db, &ada).await?); + let ada_gmail = user(&db, "usr_ada", google("ada@gmail.com")).await?; + assert!(!sees_web(&db, &ada_gmail).await?); + let ada_google = user(&db, "usr_ada", google("ada@acme.com")).await?; + assert!(sees_web(&db, &ada_google).await?); + // Read without a sign-in of hers (a notification, a service + // account's request): no requirement holds. + let ada_nobody = user(&db, "usr_ada", None).await?; + assert!(sees_web(&db, &ada_nobody).await?); + // The workspace says so, and why. + let settings = InstanceSettings::default(); + let rows = mine(&db, "usr_ada").await?; + let acme = rows + .first() + .ok_or_else(|| crate::error::internal("no workspace"))?; + assert!(acme.closed_to(&ada, &settings)); + let seen = acme.to_workspace(&settings, &ada, &[]); + assert!(seen.blocked && seen.sign_in_blocked); + assert_eq!( + seen.sign_in.map(|r| r.domains), + Some(vec!["acme.com".to_owned()]) + ); + assert!(!acme.closed_to(&ada_google, &settings)); + // Cy, a contractor in it as his own address, signs in as he likes. + let cy = user(&db, "usr_cy", Some(SignedIn::password())).await?; + assert!(sees_web(&db, &cy).await?); + // An open socket's recheck reads its token's sign-in too. + q( + &db, + "INSERT INTO tokens (id, hash, kind, user_id, created_at, expires_at, auth_method, auth_domain) VALUES \ + ('tok_pw', 'h1', 'web', 'usr_ada', 0, 9000000000000, 'password', NULL), \ + ('tok_g', 'h2', 'web', 'usr_ada', 0, 9000000000000, 'google', 'acme.com')", + &[], + )? + .run() + .await?; + for (token, closed) in [("tok_pw", true), ("tok_g", false)] { + let holder = crate::auth::by_token_id(&db, token, 1) + .await? + .ok_or_else(|| crate::error::internal("no holder"))?; + assert_eq!(acme.closed_to(&holder.user, &settings), closed, "{token}"); + assert_eq!(sees_web(&db, &holder.user).await?, !closed, "{token}"); + } + Ok(()) + } +} diff --git a/crates/fctl-domain/src/sign_in.rs b/crates/fctl-domain/src/sign_in.rs index a16ab2dd..b77a5773 100644 --- a/crates/fctl-domain/src/sign_in.rs +++ b/crates/fctl-domain/src/sign_in.rs @@ -334,6 +334,35 @@ pub fn admits( } } +/// A workspace's own requirement as its admins save it +/// (`workspaces.sign_in`, ADR 0103): checked as the instance's rules are, +/// with a provider the instance has set up. No domains: none, the +/// workspace's members sign in as the instance lets them. +pub fn check_workspace_rule( + rule: &SignInRule, + providers: &[&str], +) -> Result, ApiError> { + if rule.domains.iter().all(|d| d.trim().is_empty()) { + return Ok(None); + } + Ok(check_rules(std::slice::from_ref(rule), providers)? + .into_iter() + .next()) +} + +/// Whether a workspace's own requirement closes it to a request made with +/// a sign-in `how`: the rule covers its member (`covering`, the rule where +/// the address the workspace knows them by is at one of its domains) and +/// `how` doesn't meet it. Without a sign-in of a person's (`None`: a +/// service account's request, or nobody's, as notifications go out), it +/// closes nothing: the rule is about how people sign in. +pub fn workspace_closed(covering: Option<&SignInRule>, how: Option<&SignedIn>) -> bool { + match (covering, how) { + (Some(rule), Some(how)) => !meets(rule, how), + _ => false, + } +} + /// Whether an instance admin whose role is `actor` may unlink the provider /// accounts of someone whose role is `target` (`own`: their own). Their own /// they unlink in Settings, where they keep another way in; nobody the @@ -657,6 +686,35 @@ mod tests { assert_eq!(check_rules(&[], &[]).ok(), Some(vec![])); } + #[test] + fn a_workspace_requires_its_provider_of_the_members_it_covers() { + // Saved as the instance's rules are; no domains is none. + assert_eq!( + check_workspace_rule(&rule(&["ACME.com", "*@acme.dev"], false), &[GOOGLE]) + .ok() + .flatten(), + Some(rule(&["acme.com", "acme.dev"], false)) + ); + assert_eq!( + check_workspace_rule(&rule(&[], false), &[GOOGLE]).ok(), + Some(None) + ); + assert!(check_workspace_rule(&rule(&["acme.com"], false), &[]).is_err()); + assert!(check_workspace_rule(&rule(&["acme"], false), &[GOOGLE]).is_err()); + // Closed to a covered member's sign-in made another way, open to + // one with Google as an address there, and to nobody's sign-in. + let r = rule(&["acme.com"], false); + assert!(workspace_closed(Some(&r), Some(&SignedIn::password()))); + assert!(workspace_closed(Some(&r), Some(&google("ada@gmail.com")))); + assert!(workspace_closed(Some(&r), Some(&SignedIn::default()))); + assert!(!workspace_closed(Some(&r), Some(&google("ada@acme.com")))); + assert!(!workspace_closed(Some(&r), None)); + assert!(!workspace_closed(None, Some(&SignedIn::password()))); + // Passkeys, where it lets them in. + let keys = rule(&["acme.com"], true); + assert!(!workspace_closed(Some(&keys), Some(&SignedIn::passkey()))); + } + #[test] fn a_rule_covers_every_account_with_an_address_at_its_domains() { let rules = [rule(&["acme.com", "acme.dev"], false)]; diff --git a/crates/fctl-domain/src/verify.rs b/crates/fctl-domain/src/verify.rs index 717f00ea..84ef88e8 100644 --- a/crates/fctl-domain/src/verify.rs +++ b/crates/fctl-domain/src/verify.rs @@ -47,6 +47,10 @@ pub enum Sensitive { StopVerifying, /// No longer requiring two-factor sign-in in a workspace. StopWorkspaceTwoFactor, + /// Letting a workspace's members open it with a sign-in its own + /// requirement didn't take: no longer requiring its provider at a + /// domain, letting passkeys in, or another provider. + RelaxWorkspaceSignIn, /// Adding a runner someone registered to a workspace, or letting it /// run everyone's sessions there. AddRunner, @@ -146,6 +150,9 @@ impl Sensitive { StopGoogleCodes => "stop asking for codes on Google sign-in", StopVerifying => "stop asking people to confirm sensitive actions", StopWorkspaceTwoFactor => "stop requiring two-factor sign-in in a workspace", + RelaxWorkspaceSignIn => { + "let a workspace's members open it without signing in with its provider" + } AddRunner => "add a runner to a workspace", NewEnrollmentToken => "make an enrollment token", ApproveRunner => "approve a runner", @@ -276,6 +283,17 @@ pub fn instance_settings_change( } } +/// Whether a workspace's requirement `next` lets its members open it with +/// a sign-in `current` didn't take: as [`relaxes`] reads the instance's +/// rules. +pub fn workspace_sign_in_relaxed( + current: Option<&fctl_proto::api::SignInRule>, + next: Option<&fctl_proto::api::SignInRule>, +) -> bool { + let list = |r: Option<&fctl_proto::api::SignInRule>| r.into_iter().cloned().collect::>(); + relaxes(&list(current), &list(next)) +} + /// The session policy `update` leaves the instance with, from `current`. pub fn session_policy( current: &InstanceSettings, @@ -609,6 +627,29 @@ mod tests { ); } + #[test] + fn letting_a_workspaces_members_past_its_provider_is_sensitive() { + use fctl_proto::api::SignInRule; + let rule = |domains: &[&str], passkeys: bool| SignInRule { + domains: domains.iter().map(|d| (*d).to_owned()).collect(), + provider: "google".to_owned(), + passkeys, + }; + let acme = rule(&["acme.com", "acme.dev"], false); + assert!(workspace_sign_in_relaxed(Some(&acme), None)); + assert!(workspace_sign_in_relaxed( + Some(&acme), + Some(&rule(&["acme.com"], false)) + )); + assert!(workspace_sign_in_relaxed( + Some(&acme), + Some(&rule(&["acme.com", "acme.dev"], true)) + )); + assert!(!workspace_sign_in_relaxed(Some(&acme), Some(&acme))); + assert!(!workspace_sign_in_relaxed(None, Some(&acme))); + assert!(!workspace_sign_in_relaxed(None, None)); + } + #[test] fn letting_sign_ins_last_longer_is_sensitive() { let current = InstanceSettings { diff --git a/crates/fctl-proto/src/api.rs b/crates/fctl-proto/src/api.rs index d3bbc425..e52bfeef 100644 --- a/crates/fctl-proto/src/api.rs +++ b/crates/fctl-proto/src/api.rs @@ -2248,9 +2248,24 @@ pub struct Workspace { /// ([`InstanceSettings::require_two_factor`]). #[serde(default)] pub instance_requires_two_factor: bool, - /// It requires two-factor sign-in, which you haven't set up: until you - /// do, its projects and sessions are closed to you. + /// It requires two-factor sign-in, which you haven't set up, or its + /// own sign-in requirement covers you and your sign-in doesn't meet it + /// (`sign_in_blocked`): until then, its projects and sessions are + /// closed to you. pub blocked: bool, + /// Its own sign-in requirement: its members who are in it as an + /// address at one of `domains` open it only with a sign-in made with + /// `provider` as such an address (a passkey alone too, where + /// `passkeys`). Members in it as other addresses sign in as the + /// instance lets them. Absent: none ([`UpdateWorkspaceRequest::sign_in`]). + pub sign_in: Option, + /// It's closed to you because of `sign_in`: you're in it as an address + /// it covers, and this sign-in of yours was made another way. Signing + /// in again with its provider opens it. Absent from control planes + /// before it. + #[serde(default)] + #[cfg_attr(feature = "ts", ts(as = "Option", optional))] + pub sign_in_blocked: bool, /// The Claude connection your sessions in it run on. Absent: your /// default one. pub claude: Option, @@ -2398,6 +2413,12 @@ pub struct UpdateWorkspaceRequest { /// Members need two-factor sign-in. Not `false` while the instance /// requires it: every workspace does then. pub require_two_factor: Option, + /// Its own sign-in requirement ([`Workspace::sign_in`]): no `domains` + /// stops requiring one. A provider the instance has set up (`google`). + /// Refused (`409`) where it would close the workspace to the admin who + /// saves it: they sign in with the provider first. Requiring less + /// takes confirming it's you, where the instance asks for that. + pub sign_in: Option, /// Leave inviting people out of the app's setup checklist, or (`false`) /// ask for it again. pub skip_invites: Option, diff --git a/crates/fctl/src/cmd/workspaces.rs b/crates/fctl/src/cmd/workspaces.rs index a3738305..3992346c 100644 --- a/crates/fctl/src/cmd/workspaces.rs +++ b/crates/fctl/src/cmd/workspaces.rs @@ -156,8 +156,8 @@ pub enum WorkspacesCmd { }, /// Change a workspace's name, address, avatar, rules or setup (admins). #[command( - group(ArgGroup::new("change").required(true).multiple(true).args(["name", "slug", "color", "avatar", "base_role", "require_two_factor", "skip_invites", "autopilots", "snapshots", "snapshot_days", "claude_oversight", "claude_limit_pauses", "claude_admin_email"])), - after_help = "Examples:\n fctl workspaces set --name hyperstructure --avatar logo.png\n fctl workspaces set --color '#2a9d8f' # a color of its own\n fctl workspaces set -w side-project --base-role editor\n fctl workspaces set --require-two-factor on\n fctl workspaces set -w side-project --skip-invites on\n fctl workspaces set -w acme --claude-oversight readiness # less for its admins\n fctl workspaces set -w acme --claude-admin-email each # an email for each, not weekly" + group(ArgGroup::new("change").required(true).multiple(true).args(["name", "slug", "color", "avatar", "base_role", "require_two_factor", "require_google", "skip_invites", "autopilots", "snapshots", "snapshot_days", "claude_oversight", "claude_limit_pauses", "claude_admin_email"])), + after_help = "Examples:\n fctl workspaces set --name hyperstructure --avatar logo.png\n fctl workspaces set --color '#2a9d8f' # a color of its own\n fctl workspaces set -w side-project --base-role editor\n fctl workspaces set --require-two-factor on\n fctl workspaces set -w acme --require-google acme.com,acme.dev # members there open it only signed in with Google as such an address\n fctl workspaces set -w acme --require-google off\n fctl workspaces set -w side-project --skip-invites on\n fctl workspaces set -w acme --claude-oversight readiness # less for its admins\n fctl workspaces set -w acme --claude-admin-email each # an email for each, not weekly" )] Set { /// The workspace (slug or id); default from `fctl workspaces use`, @@ -185,6 +185,16 @@ pub enum WorkspacesCmd { /// It stays on while the instance requires it. #[arg(long, value_name = "ON|OFF", value_parser = BoolishValueParser::new(), hide_possible_values = true)] require_two_factor: Option, + /// Its members who are in it as an address at these domains + /// (comma-separated, acme.com,acme.dev) open it only when they + /// signed in with Google as such an address; members in it as + /// other addresses sign in as before. `off` stops requiring it. + /// Sign in with Google as your own address there first. + #[arg(long, value_name = "DOMAINS|off")] + require_google: Option, + /// With --require-google: a passkey alone opens it too. + #[arg(long, requires = "require_google")] + google_passkeys: bool, /// Leave inviting people out of the app's setup checklist, as in a /// workspace for one; `off` asks for it again. #[arg(long, value_name = "ON|OFF", value_parser = BoolishValueParser::new(), hide_possible_values = true)] @@ -754,6 +764,26 @@ pub async fn run(server: Option<&str>, cmd: WorkspacesCmd, json: bool) -> Result w.github.join(", ") } ); + println!( + "sign-in: {}", + match &w.sign_in { + Some(r) => format!( + "members in it as an address at {} sign in with Google as one{}", + fctl_domain::sign_in::domains_words(&r.domains), + if r.passkeys { ", or a passkey" } else { "" } + ), + None => "as the instance lets each member".to_owned(), + } + ); + if w.sign_in_blocked { + println!( + " {}", + style::amber(&format!( + "closed to you: you're in it as {}, and signed in another way. Sign in again with Google as that address (fctl login, then continue with Google).", + w.email + )) + ); + } println!( "2fa: {}", if w.instance_requires_two_factor { @@ -782,7 +812,7 @@ pub async fn run(server: Option<&str>, cmd: WorkspacesCmd, json: bool) -> Result if let Some(c) = &w.claude_oversight { println!("claude: {}", super::claude_overview::settings_line(c)); } - if w.blocked { + if w.blocked && !w.sign_in_blocked { println!( "{}", style::amber( @@ -839,14 +869,21 @@ pub async fn run(server: Option<&str>, cmd: WorkspacesCmd, json: bool) -> Result claude_oversight, claude_limit_pauses, claude_admin_email, + require_google, + google_passkeys, } => { let w = resolve(&api, workspace).await?; let mut out = w.clone(); + let sign_in = require_google + .as_deref() + .map(|d| google_rule(d, google_passkeys)) + .transpose()?; if name.is_some() || slug.is_some() || color.is_some() || base_role.is_some() || require_two_factor.is_some() + || sign_in.is_some() || skip_invites.is_some() || autopilots.is_some() || snapshots.is_some() @@ -873,6 +910,7 @@ pub async fn run(server: Option<&str>, cmd: WorkspacesCmd, json: bool) -> Result claude_oversight: claude_oversight.map(Into::into), claude_limit_pauses, claude_admin_email: claude_admin_email.map(Into::into), + sign_in, }, ) .await?; @@ -1852,6 +1890,28 @@ fn review_app_state( } } +/// The requirement `--require-google` asks for: Google at `domains` +/// (comma-separated), or none, said as `off` or `none` alone: an empty +/// value (an unset variable in a script) is an error, not none. +fn google_rule(domains: &str, passkeys: bool) -> Result { + let off = matches!(domains.trim().to_ascii_lowercase().as_str(), "off" | "none"); + let list: Vec = domains + .split([',', ' ']) + .filter(|d| !d.trim().is_empty()) + .map(|d| d.trim().to_owned()) + .collect(); + if !off && list.is_empty() { + bail!( + "--require-google needs domains, like acme.com,acme.dev, or off to stop requiring it" + ); + } + Ok(fctl_proto::api::SignInRule { + domains: if off { Vec::new() } else { list }, + provider: fctl_domain::sign_in::GOOGLE.to_owned(), + passkeys, + }) +} + #[cfg(test)] mod tests { use super::*; @@ -1874,6 +1934,25 @@ mod tests { } } + #[test] + fn require_google_reads_domains_or_off() { + let r = google_rule("acme.com, acme.dev", true).ok(); + assert_eq!( + r.as_ref().map(|r| r.domains.clone()), + Some(vec!["acme.com".to_owned(), "acme.dev".to_owned()]) + ); + assert!(r.is_some_and(|r| r.passkeys && r.provider == "google")); + for off in ["off", "OFF", "none"] { + assert!( + google_rule(off, false).is_ok_and(|r| r.domains.is_empty()), + "{off}" + ); + } + // An unset variable isn't off. + assert!(google_rule("", false).is_err()); + assert!(google_rule(" , ", false).is_err()); + } + #[test] fn a_color_is_one_of_the_brand_or_one_of_its_own() { assert_eq!( diff --git a/docs/adr/0099-domains-require-signing-in-with-their-provider.md b/docs/adr/0099-domains-require-signing-in-with-their-provider.md index 1df12c2e..a42cde0d 100644 --- a/docs/adr/0099-domains-require-signing-in-with-their-provider.md +++ b/docs/adr/0099-domains-require-signing-in-with-their-provider.md @@ -70,7 +70,9 @@ none of the organization's business. `api::sign_in`, which links, signs in and signs up by the rules. Rules, tokens and identities name providers by id. - **Rules are the instance's**, as its admins own its allowlist: a - workspace of its own doesn't require a provider, and app.fctl.sh, where + workspace of its own doesn't require a provider (since [ADR + 0103](0103-workspaces-require-their-members-to-sign-in-with-google.md), + it requires one of its own members), and app.fctl.sh, where workspaces of many organizations share the instance, has none to set. ## Consequences diff --git a/docs/adr/0103-workspaces-require-their-members-to-sign-in-with-google.md b/docs/adr/0103-workspaces-require-their-members-to-sign-in-with-google.md new file mode 100644 index 00000000..099ccb5e --- /dev/null +++ b/docs/adr/0103-workspaces-require-their-members-to-sign-in-with-google.md @@ -0,0 +1,66 @@ +# 0103: Workspaces require their members to sign in with Google + +2026-11-26 · accepted + +## Context + +[ADR 0099](0099-domains-require-signing-in-with-their-provider.md) let an +instance's admins require a provider of everyone at some domains, and +left a workspace's own requirement for later (#618). On an instance that +people of several organizations share, app.fctl.sh above all, an +organization's workspace has no instance admin of its own: it can require +two-factor sign-in of its members, but not that they sign in through its +Google Workspace, under its two-step verification and device checks. + +A requirement that sends people to a provider from the sign-in page, or +holds them anywhere but the workspace, would let one customer claim +another's domain, so it would need the domain proved first. One that only +closes its own workspace needs nothing of the kind: its admins can +already remove anyone from it. + +## Decision + +- **A workspace's admins require Google of its members at some domains** + (`workspaces.sign_in`): members who are in it as an address at one of + them (the address it knows them by, `workspace_members.email`) open it + only with a sign-in made with Google as such an address, or with a + passkey alone where it says so. Their address there is the one its + people see, and they leave the workspace if they disconnect it, so no + member slips out by changing addresses. +- **It closes the workspace as its two-factor requirement does**: its + projects and sessions too, and its page says why and links Google's + sign-in. Members in it as other addresses (contractors) sign in as + before; their other workspaces stay open. +- **It holds people's own sign-ins only.** Each request's token keeps how + its sign-in was made (ADR 0099), and the account row the request + carries keeps it (`UserRow::request_sign_in`). Service accounts', + autopilots' and the control plane's own work for a member (their + notifications) aren't held to it: their admins chose those. +- **No admin closes it to themselves**, and letting anyone in another + way takes confirming it's you, as for the instance's rules. +- **No proof of the domains**: it closes only its own workspace. A + workspace's own provider, or a domain whose people the sign-in page + sends to it, needs proving the domain first, and waits for providers + other than Google (#650, #653). +- **Google only**, the one provider today; the rule names its provider, as + the instance's do. + +## Consequences + +- An organization on app.fctl.sh holds its people to its Google + Workspace in its own workspace. Google closing someone's account stops + their next sign-in there, not the sign-ins they have, which last as + the instance lets them: its admins remove them from the workspace too + (session policies, [ADR + 0102](0102-instances-limit-how-long-sign-ins-last.md), set how long + sign-ins last on an instance of one's own). +- Its primary admin can always stop requiring it, even while it closes + the workspace to them, so that a workspace nobody can meet the + requirement of (Google sign-in no longer set up, their Google accounts + closed) doesn't stay closed for good. They can change nothing else + until they sign in with Google. +- A member signed in with a password finds the workspace closed until + they sign in with Google, then finds it open in every tab. +- A member in it as a covered address who has no Google account there + can't open it: its admins invite them as another address, or don't + require it. diff --git a/docs/adr/README.md b/docs/adr/README.md index dc2e2f2f..441d8017 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -108,3 +108,4 @@ supersede an earlier one. Copy the newest record to start a new one. | [0100](0100-autopilots-keep-trying-after-their-sessions-fail.md) | Autopilots keep trying after their sessions fail (experimental) | | [0101](0101-runners-keep-snapshots-in-a-bucket-of-their-own.md) | Runners keep snapshots in a bucket of their own | | [0102](0102-instances-limit-how-long-sign-ins-last.md) | Instances limit how long sign-ins last | +| [0103](0103-workspaces-require-their-members-to-sign-in-with-google.md) | Workspaces require their members to sign in with Google | diff --git a/docs/api.md b/docs/api.md index 51ac7601..c3c7e5bb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -682,6 +682,15 @@ answers `409` (`conflict`), unless they're the primary instance owner. `GET `address`, and `GET /api/v1/instance` says whether the request comes from outside them (`sign_in.outside`). +A workspace's admins require Google of its members at some domains with +`PATCH /api/v1/workspaces/{id}` and `{"sign_in": {"domains": +["acme.com"], "provider": "google", "passkeys": false}}` (no domains to +stop), which answers `409` where it would close the workspace to the +caller's own sign-in, and asks them to confirm it's them where it lets +anyone in another way. Each workspace says its `sign_in`, and +`sign_in_blocked` where it's closed to the caller for that reason +(`blocked` too). + ## Runner pools What a pool (an enrollment token's runners) needs now, for whatever scales diff --git a/docs/architecture.md b/docs/architecture.md index 17c2d84b..eb19738f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -463,6 +463,23 @@ by its id, `google` ([ADR 0099](adr/0099-domains-require-signing-in-with-their-p The primary instance owner's browser and CLI are exempt (`sign_in::outside`); runners, webhooks and published links never reach these checks. +- **A workspace's own requirement** (`workspaces.sign_in`, a + `SignInRule`; the workspace's Settings → Access, `fctl workspaces set + --require-google acme.com`; + [ADR 0103](adr/0103-workspaces-require-their-members-to-sign-in-with-google.md)): + its members who are in it as an address at the rule's domains + (`workspace_members.email`) open it only with a sign-in that meets the + rule. `workspace_sign_in!` hands each query that reads a workspace with + its member the rule where it covers them, and `UserRow::blocked_by` + closes the workspace, as its two-factor requirement does, when the + request's own sign-in (`UserRow::request_sign_in`, which + `auth::authenticate` sets from the token) doesn't meet it + (`fctl_domain::sign_in::workspace_closed`). Requests without a person's + sign-in (service accounts, autopilots, notifications) aren't held to it. + An admin can't save a rule that would close the workspace to their own + sign-in, and letting anyone in another way is a sensitive action + (`Sensitive::RelaxWorkspaceSignIn`). It needs no proof of the domains: + it closes only its own workspace. - **Accounts only from the directory.** With `InstanceSettings::self_sign_up` off, a provider's sign-in makes an account only for an address with an allowlist entry of its own (an invitation's, or one an admin allowed): diff --git a/docs/cli.md b/docs/cli.md index 041a6f57..7f367fc6 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -315,6 +315,7 @@ fctl workspaces set --color '#2a9d8f' # its avatar's color, of its own (quot fctl workspaces set --slug side # its address in URLs (create takes --slug too); old links stop working fctl workspaces set --base-role editor # every member starts sessions in every project fctl workspaces set --require-two-factor on # closed to members without a second factor +fctl workspaces set --require-google acme.com,acme.dev # members there open it only signed in with Google as such an address (--google-passkeys: a passkey too; off to stop) fctl workspaces set --skip-invites on # a workspace for one: its setup stops asking for people fctl workspaces set --snapshot-days 7 # keep each session's snapshot a week after it stops (30 by default) fctl workspaces set --snapshots off # sessions keep no snapshots: one that resumes elsewhere starts its conversation again @@ -358,7 +359,11 @@ set --max-workspaces`), and the primary instance owner in any number and `"unlimited": true` to whoever it doesn't hold). While the instance requires two-factor sign-in (`fctl admin set --require-two-factor on`), every workspace does, and `fctl workspaces set --require-two-factor off` -fails. +fails. `--require-google` holds the members who are in the workspace as +an address at its domains to Google sign-ins as such an address; save it +once you've signed in with Google as yours, as it would close the +workspace to you otherwise ([A workspace of your +organization's](organizations.md#a-workspace-of-your-organizations)). `fctl workspaces members --claude` shows a workspace's admins what each member's sessions there run on, as much of it as they see, never a token, diff --git a/docs/llms.txt b/docs/llms.txt index 8e95e042..d4a4e3b8 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -73,7 +73,7 @@ web app · fctl CLI · HTTP API · Claude apps · Linear · GitHub webhooks - **Session**: `owner` (who started it, while they may still start sessions in the project, and the project's maintainers and owners: stop, resume, archive, share), `editor` (message and interrupt), `viewer` (read). Sessions can be shared with people in the same workspace, as viewers, editors or owners. - **Access token**: `read` (like a viewer), `run` (like an editor, and it stops and resumes the sessions it started), `full` (whatever its person may in its projects). A limited token never reaches the account, workspaces' people and settings, Claude connections, other tokens or administration. - **Admin token** (`fctl_adm_…`, id `adt_…`; self-hosted instances whose deployment sets `FCTL_ADMIN_TOKENS=1`, never app.fctl.sh): an instance admin's, for programs that provision people. It acts as that admin on the admin API's people endpoints alone: creates accounts (`POST /api/v1/admin/users`), reads one with their workspaces and projects (`GET /api/v1/admin/users/{id or address}`), changes names, primary address, commit email and status (`PATCH`), sets their picture and the Claude token their sessions run on (`PUT …/avatar`, `PUT …/claude`), adds them to any workspace and project or takes them out (`PUT`/`DELETE …/workspaces/{workspace}`, `…/projects/{project}`), and deletes them. A new account has no password (set one with `password`, or the link `fctl admin reset-link` makes, except where Google is required for its domain): where the instance has Google sign-in and Google hosts the address (Workspace or Gmail), the person's first Google sign-in links Google to it. It changes no roles and never the primary instance owner's account; only the primary owner's tokens change admins'. CLI: `fctl admin tokens create NAME`, then `FCTL_TOKEN=fctl_adm_… fctl admin users create|show|set|add|remove`. -- **Sign-in rules** (instance admins: Admin → Sign-in, `fctl admin sign-in require acme.com acme.dev`, `PATCH /api/v1/admin/settings` with `sign_in`): the people with an address at those domains sign in with Google alone, as that address (a Google Workspace account's): passwords, passkeys alone (unless `--passkeys`) and personal Google accounts stop working, and saving it deletes their browser sessions, CLI sign-ins, access tokens and admin tokens made another way, before the rule too; their next Google sign-in links Google and takes their password. Closing their Google account stops their next sign-in, not their sessions: disable their account too. The primary instance owner keeps every way in, for when Google is down; a rule that would sign out the admin who saves it waits until they sign in with Google. `fctl admin sign-in` shows whom each covers; `POST /api/v1/admin/sign-in/preview` says what a change would do; `fctl admin set --self-sign-up off` makes signing in make no accounts (only invitations, allowed addresses and admin tokens). Someone whose Workspace account was recreated at the same address: `fctl admin unlink ada@acme.com` signs them out everywhere, then their next Google sign-in links the new one; an address handed to someone else calls for `fctl admin disable` instead. A CLI refused by a rule signs in again with `fctl login`. **Session policies** (`fctl admin sign-in policies`, Admin → Sign-in → Staying signed in, `PATCH /api/v1/admin/settings` with `browser_max_hours`, `browser_idle_minutes`, `cli_max_days`, `access_token_max_days`, `member_access_tokens`): `--browser-max 12h --browser-idle 1h --cli-max 30d --token-max 90d --member-tokens off` makes browsers and CLIs sign in again (through Google where their domain requires it) and caps access tokens, those made before too; it prints what saving ends at once and asks unless `--yes` (`POST /api/v1/admin/sign-in/sessions/preview`). A CLI or token past it answers 401 saying why: `fctl login`, or a new token within the limit. `--networks 203.0.113.0/24,2001:db8::/32` (`any` to undo; `networks` in the settings) takes sign-ins and requests only from those ranges: elsewhere, CLIs, access tokens, admin tokens and service accounts answer 403 and browsers can't sign in; runners and webhooks aren't held to them, and the primary instance owner signs in from anywhere. +- **Sign-in rules** (instance admins: Admin → Sign-in, `fctl admin sign-in require acme.com acme.dev`, `PATCH /api/v1/admin/settings` with `sign_in`): the people with an address at those domains sign in with Google alone, as that address (a Google Workspace account's): passwords, passkeys alone (unless `--passkeys`) and personal Google accounts stop working, and saving it deletes their browser sessions, CLI sign-ins, access tokens and admin tokens made another way, before the rule too; their next Google sign-in links Google and takes their password. Closing their Google account stops their next sign-in, not their sessions: disable their account too. The primary instance owner keeps every way in, for when Google is down; a rule that would sign out the admin who saves it waits until they sign in with Google. `fctl admin sign-in` shows whom each covers; `POST /api/v1/admin/sign-in/preview` says what a change would do; `fctl admin set --self-sign-up off` makes signing in make no accounts (only invitations, allowed addresses and admin tokens). Someone whose Workspace account was recreated at the same address: `fctl admin unlink ada@acme.com` signs them out everywhere, then their next Google sign-in links the new one; an address handed to someone else calls for `fctl admin disable` instead. A CLI refused by a rule signs in again with `fctl login`. **Session policies** (`fctl admin sign-in policies`, Admin → Sign-in → Staying signed in, `PATCH /api/v1/admin/settings` with `browser_max_hours`, `browser_idle_minutes`, `cli_max_days`, `access_token_max_days`, `member_access_tokens`): `--browser-max 12h --browser-idle 1h --cli-max 30d --token-max 90d --member-tokens off` makes browsers and CLIs sign in again (through Google where their domain requires it) and caps access tokens, those made before too; it prints what saving ends at once and asks unless `--yes` (`POST /api/v1/admin/sign-in/sessions/preview`). A CLI or token past it answers 401 saying why: `fctl login`, or a new token within the limit. `--networks 203.0.113.0/24,2001:db8::/32` (`any` to undo; `networks` in the settings) takes sign-ins and requests only from those ranges: elsewhere, CLIs, access tokens, admin tokens and service accounts answer 403 and browsers can't sign in; runners and webhooks aren't held to them, and the primary instance owner signs in from anywhere. **A workspace's own requirement** (its admins: `fctl workspaces set -w acme --require-google acme.com,acme.dev`, Settings → Access, `PATCH /api/v1/workspaces/{id}` with `sign_in`): members in it as an address there open it only signed in with Google as that address (`sign_in_blocked` on the workspace otherwise); others sign in as before. - **Service account**: as the person a request names, what an access token that runs sessions does, in its workspace's projects (start sessions, message, interrupt, stop and resume theirs, run schedules, keep memory), within that person's roles; as nobody, it reads them. Never the account, people, settings, secrets, tokens or live connections (`/ws`): read events with `fctl logs` or `GET /api/v1/sessions/{id}/events`. ## Session lifecycle diff --git a/docs/organizations.md b/docs/organizations.md index 6a29d166..e29f8679 100644 --- a/docs/organizations.md +++ b/docs/organizations.md @@ -134,6 +134,30 @@ come only from those: `fctl admin sign-in policies --networks 203.0.113.0/24,2001:db8::/32` ([Signing in only from your networks](self-hosting.md#signing-in-only-from-your-networks)). +### A workspace of your organization's + +On an instance that people of several organizations share (app.fctl.sh, +or yours with contractors' workspaces), a workspace's own admins require +Google of its members at their domains, without an instance admin: in +the workspace's **Settings → Access → Members at your domains sign in +with Google**, or + +```sh +fctl workspaces set -w acme --require-google acme.com,acme.dev +``` + +Members who are in the workspace as an address at those domains open it, +its projects and sessions only once they've signed in with Google as +that address: a password's sign-in, or a personal Google account's, +finds it closed, and its page says how to open it. Their other +workspaces are as before, and members in it as other addresses +(contractors) sign in as they like. Closing someone's Google account +stops their next sign-in, not the sign-ins they have: remove them from +the workspace too. Its primary admin can stop requiring it whatever their +own sign-in, for when nobody can meet it. It closes only this workspace, so it +needs no proof that the domains are yours; requiring Google of everyone +at a domain, for the whole instance, is its admins' ([above](#signing-in-with-your-google-workspace)). + ## People from your directory On an instance of yours, your identity provider, your HR system or a diff --git a/docs/security.md b/docs/security.md index 278726f4..2bcffdf4 100644 --- a/docs/security.md +++ b/docs/security.md @@ -159,6 +159,18 @@ owner and purpose), so a value copied between rows does not decrypt. can't save ranges their own address is outside of; and letting people in from more places is a sensitive action. The address is the one Cloudflare, or a self-hosted server's trusted proxies, saw. +- **A workspace's own requirement.** A workspace's admins can require + Google of its members who are in it as an address at some domains + (`fctl workspaces set --require-google acme.com`): such a member's + request with a sign-in made another way, a password's or a personal + Google account's, finds the workspace, its projects and sessions + closed, as its two-factor requirement closes it, open sockets + included. It closes nothing else, so it needs no proof of the domains. + An admin can't save one that would close it to their own sign-in, its + primary admin can lift it whatever their sign-in, and requiring less + is a sensitive action. Closing someone's Google account stops their + next sign-in, not the sign-ins they have: remove them from the + workspace too. - **Sensitive actions take a passkey or a code**, where the primary instance owner turns that on (off by default): inviting and promoting admins, handing over the primary owner's and workspaces' primary admin diff --git a/web/src/components/shell/sidebar.tsx b/web/src/components/shell/sidebar.tsx index ca81b744..26f008d6 100644 --- a/web/src/components/shell/sidebar.tsx +++ b/web/src/components/shell/sidebar.tsx @@ -797,7 +797,11 @@ function WorkspaceGroup({ {workspace.blocked ? ( ) : ( folded && ( @@ -837,7 +841,17 @@ function WorkspaceGroup({ {!folded && (
- {workspace.blocked ? ( + {workspace.blocked && workspace.sign_in_blocked ? ( + // Its page says why, with the link that signs in with Google. + + Sign in with Google to open it + + ) : workspace.blocked ? ( ({ + ...(await original()), + api: { instance: () => new Promise(() => {}) }, + workspaces: { update: (id: string, b: G.UpdateWorkspaceRequest) => update(id, b) }, +})); + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const roots: (() => void)[] = []; +beforeEach(() => update.mockReset()); +afterEach(() => { + for (const unmount of roots.splice(0)) unmount(); +}); + +const acme: G.Workspace = { + id: "ws_acme", + slug: "acme", + name: "Acme", + color: "blue", + role: "admin", + email: "ada@acme.com", + base_role: "editor", + require_two_factor: false, + instance_requires_two_factor: false, + blocked: false, + members: 3, + projects: 1, + runners: 0, + runners_online: 0, + github: [], + skip_invites: false, + own_runners: false, + autopilots: false, + created_at: 0, +}; + +const member = (name: string, email: string): G.WorkspaceMember => ({ + user: { id: name.toLowerCase(), name }, + email, + role: "member", + joined_at: 0, +}); +const members = [ + member("Ada", "ada@acme.com"), + member("Bob", "bob@ACME.com"), + member("Cy", "cy@contractor.io"), +]; + +function render(el: ReactElement, google = true) { + const client = new QueryClient(); + client.setQueryData(keys.instance, { + name: "fctl", + version: "1.0.0", + setup_required: false, + features: { google, email: true, github: true, publish_screenshots: false, early_access: false }, + sign_in: { + providers: google ? [{ id: "google", name: "Google", start: "/api/v1/auth/google/start" }] : [], + rules: [], + self_sign_up: true, + }, + }); + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + act(() => root.render({el})); + roots.push(() => { + act(() => root.unmount()); + container.remove(); + }); + const button = (text: string) => + [...container.querySelectorAll("button")].find((b) => b.textContent?.trim() === text); + return { container, button }; +} + +describe("a workspace's own sign-in requirement", () => { + it("covers the members in it as an address at its domains", () => { + expect(covered(members, ["acme.com"]).map((m) => m.user.name)).toEqual(["Ada", "Bob"]); + expect(coverage("Acme", members, ["acme.com"])).toEqual([ + "2 people are in Acme as an address at acme.com: it opens to them only once they've signed in with Google as that address. Their other workspaces don't change.", + "1 person in it as other addresses signs in as before.", + ]); + expect(coverage("Acme", members, ["acme.dev"])[0]).toContain( + "No member is in Acme as an address at acme.dev yet", + ); + }); + + it("says whom it covers, then requires Google", async () => { + update.mockResolvedValue(acme); + const page = render( {}} />); + await act(async () => page.button("Require Google")?.click()); + // The admin's own domain comes first. + expect(page.container.querySelector("input")?.value).toBe("acme.com"); + expect(page.container.textContent).toContain("2 people are in Acme as an address at acme.com"); + const submit = [...page.container.querySelectorAll("button[type=submit]")][0] as HTMLButtonElement; + await act(async () => submit.click()); + expect(update).toHaveBeenCalledWith("ws_acme", { + sign_in: { domains: ["acme.com"], provider: "google", passkeys: false }, + }); + }); + + it("offers the way out when it would close the workspace to the admin", () => { + const google = { id: "google", name: "Google", start: "/api/v1/auth/google/start" }; + expect(wayOut({ code: "conflict" }, acme, google)).toBe( + "/api/v1/auth/google/start?intent=login&return_to=%2Fw%2Facme%3Ftab%3Dsettings&login_hint=ada%40acme.com", + ); + expect(wayOut({ code: "validation" }, acme, google)).toBeUndefined(); + expect(wayOut({ code: "conflict" }, acme, undefined)).toBeUndefined(); + expect(wayOut(null, acme, google)).toBeUndefined(); + }); + + it("stops requiring it", async () => { + update.mockResolvedValue(acme); + const required = { ...acme, sign_in: { domains: ["acme.com"], provider: "google", passkeys: false } }; + const page = render( {}} />); + expect(page.container.textContent).toContain("Members in Acme as an address at acme.com open it only"); + await act(async () => page.button("Stop requiring it")?.click()); + expect(update).toHaveBeenCalledWith("ws_acme", { + sign_in: { domains: [], provider: "google", passkeys: false }, + }); + }); + + it("waits for the instance to sign people in with Google", () => { + const page = render( {}} />, false); + expect(page.container.textContent).toContain("This instance doesn't sign people in with Google"); + expect(page.button("Require Google")).toBeUndefined(); + }); + + it("lets a rule be stopped where nobody signs in with Google any more", async () => { + update.mockResolvedValue(acme); + const required = { ...acme, sign_in: { domains: ["acme.com"], provider: "google", passkeys: false } }; + const page = render( {}} />, false); + expect(page.container.textContent).toContain("nobody it covers can open Acme"); + expect(page.button("Change domains")).toBeUndefined(); + await act(async () => page.button("Stop requiring it")?.click()); + expect(update).toHaveBeenCalledWith("ws_acme", { + sign_in: { domains: [], provider: "google", passkeys: false }, + }); + }); + + it("lets its primary admin stop requiring it while it closes it to them", async () => { + update.mockResolvedValue(acme); + const closed = { + ...acme, + role: "owner" as const, + blocked: true, + sign_in_blocked: true, + sign_in: { domains: ["acme.com"], provider: "google", passkeys: false }, + }; + const page = render(, false); + // Nobody signs in with Google here now: no link that goes nowhere. + expect(page.container.querySelector("a")).toBeNull(); + expect(page.container.textContent).toContain("doesn't sign people in with Google any more"); + await act(async () => page.button("Stop requiring Google")?.click()); + expect(update).toHaveBeenCalledWith("ws_acme", { + sign_in: { domains: [], provider: "google", passkeys: false }, + }); + // A member isn't offered it. + const member = render(); + expect(member.button("Stop requiring Google")).toBeUndefined(); + }); + + it("tells a member it closes to why, and the way in", () => { + const closed = { + ...acme, + blocked: true, + sign_in_blocked: true, + sign_in: { domains: ["acme.com"], provider: "google", passkeys: false }, + }; + const page = render(); + expect(page.container.textContent).toContain( + "Acme requires its members at acme.com to sign in with Google as that address, and you signed in another way.", + ); + expect(page.container.querySelector("a")?.getAttribute("href")).toBe( + "/api/v1/auth/google/start?intent=login&return_to=%2Fw%2Facme&login_hint=ada%40acme.com", + ); + }); +}); diff --git a/web/src/components/workspace/sign-in.tsx b/web/src/components/workspace/sign-in.tsx new file mode 100644 index 00000000..3c91a5cd --- /dev/null +++ b/web/src/components/workspace/sign-in.tsx @@ -0,0 +1,257 @@ +// A workspace's own sign-in requirement (G.Workspace.sign_in, ADR 0103): its members who are in it as an address at +// some domains open it only once they've signed in with Google as such an address. Its admins set it in the Access +// section, which says whom it covers before it saves; the workspace page says why it's closed, and how to open it. + +import { useMutation } from "@tanstack/react-query"; +import { Building2 } from "lucide-react"; +import { useState } from "react"; +import { ProviderMark } from "@/components/sign-in/provider"; +import { Banner, Button, Field, Input, Switch, toast } from "@/components/ui"; +import type * as G from "@/gen"; +import { workspaces } from "@/lib/api"; +import { useInstance } from "@/lib/queries"; +import { domainOf, domainsWords, GOOGLE, parseDomains, people, providers, startHref } from "@/lib/sign-in"; + +/** Which members a requirement at `domains` covers: those in the workspace as an address at one of them. */ +export function covered( + members: readonly G.WorkspaceMember[], + domains: readonly string[], +): G.WorkspaceMember[] { + return members.filter((m) => { + const d = domainOf(m.email); + return !!d && domains.includes(d); + }); +} + +/** + * Where saving the requirement was refused because it would close the workspace to the admin (`409`), the way out: + * signing in with Google as their address there, which shows it works for them, back to its settings. + */ +export function wayOut(error: unknown, w: G.Workspace, google?: G.SignInProvider): string | undefined { + if (!google || (error as { code?: string } | null)?.code !== "conflict") return undefined; + return startHref(google, { next: `/w/${w.slug}?tab=settings`, hint: w.email }); +} + +/** What requiring Google at `domains` does to the workspace's members, in sentences. */ +export function coverage( + name: string, + members: readonly G.WorkspaceMember[], + domains: readonly string[], +): string[] { + const them = covered(members, domains); + const others = members.length - them.length; + const lines = [ + them.length === 0 + ? `No member is in ${name} as an address at ${domainsWords(domains, "or")} yet: those who join as one open it once they've signed in with Google as that address.` + : `${people(them.length)} ${them.length === 1 ? "is" : "are"} in ${name} as an address at ${domainsWords(domains, "or")}: it opens to them only once they've signed in with Google as that address. Their other workspaces don't change.`, + ]; + if (others > 0) + lines.push(`${people(others)} in it as other addresses ${others === 1 ? "signs" : "sign"} in as before.`); + return lines; +} + +/** The setting, in a workspace's Access section (admins). */ +export function WorkspaceSignIn({ + w, + members, + onSaved, +}: { + w: G.Workspace; + members?: readonly G.WorkspaceMember[]; + onSaved: () => void; +}) { + const { data: instance } = useInstance(); + const google = providers(instance).find((p) => p.id === GOOGLE); + const rule = w.sign_in; + const [editing, setEditing] = useState(false); + const [text, setText] = useState(rule?.domains.join(", ") ?? domainOf(w.email) ?? ""); + const [passkeys, setPasskeys] = useState(rule?.passkeys ?? false); + const parsed = parseDomains(text); + const save = useMutation({ + mutationFn: (sign_in: G.SignInRule) => workspaces.update(w.id, { sign_in }), + onSuccess: (_, r) => { + onSaved(); + setEditing(false); + toast( + r.domains.length + ? `${w.name} requires Google at ${domainsWords(r.domains)}` + : `${w.name}'s members sign in as the instance lets them`, + ); + }, + }); + const ready = parsed.domains.length > 0 && parsed.invalid.length === 0; + return ( +
+
+ + Members at your domains sign in with Google + + {rule + ? `Members in ${w.name} as an address at ${domainsWords(rule.domains)} open it only once they've signed in with Google as that address${rule.passkeys ? ", or with a passkey" : ""}, under your Google Workspace's two-step verification and device checks. Closing someone's Google account stops their next sign-in, not the ones they have: remove them here too. Members in it as other addresses sign in as before.` + : `Members in ${w.name} as an address at your domains open it only once they've signed in with Google as that address. Members in it as other addresses, contractors say, sign in as before.`} + + + {rule && !editing && ( + + + {domainsWords(rule.domains)} + + )} +
+ {!google && !rule ? ( +

+ This instance doesn't sign people in with Google: its admins set that up first. +

+ ) : google && editing ? ( +
{ + e.preventDefault(); + if (ready) save.mutate({ domains: parsed.domains, provider: GOOGLE, passkeys }); + }} + > + 0 + ? `${parsed.invalid.join(", ")} isn't a domain: give one like acme.com` + : undefined + } + > + {(id) => ( + setText(e.target.value)} + spellCheck={false} + autoCapitalize="off" + /> + )} + +
+ + Passkeys open it too + + {passkeys + ? "Quick, but past Google's checks: a passkey still opens it to someone whose Google account you closed." + : "Off: a sign-in with a passkey alone doesn't open it."} + + + +
+ {ready && members && ( +
    + {coverage(w.name, members, parsed.domains).map((l) => ( +
  • {l}
  • + ))} +
+ )} + {save.error && ( + + {save.error.message}{" "} + {/* It would close the workspace to the admin: the way out, which shows Google works for them. */} + {wayOut(save.error, w, google) && ( + + Sign in with Google as {w.email} + + )} + + )} +
+ + +
+
+ ) : ( +
+ {google ? ( + + ) : ( + // Nobody signs in with Google here now: the requirement closes the workspace to everyone it covers. + + This instance doesn't sign people in with Google any more, so nobody it covers can open {w.name} + . + + )} + {rule && ( + + )} + {save.error && {save.error.message}} +
+ )} +
+ ); +} + +/** + * Why the workspace is closed to its member, the caller, by its own requirement, and the way in: signing in with + * Google, or, for its primary admin, stopping the requirement, as where nobody can meet it. + */ +export function SignInBlocked({ w, onChanged }: { w: G.Workspace; onChanged?: () => void }) { + const { data: instance } = useInstance(); + const google = providers(instance).find((p) => p.id === GOOGLE); + const domains = w.sign_in?.domains ?? []; + const lift = useMutation({ + mutationFn: () => + workspaces.update(w.id, { sign_in: { domains: [], provider: GOOGLE, passkeys: false } }), + onSuccess: () => { + onChanged?.(); + toast(`${w.name}'s members sign in as the instance lets them`); + }, + }); + return ( +
+ + {w.name} requires its members at {domainsWords(domains, "and")} to sign in with Google as that + address, and you signed in another way. Until you do, its projects and sessions are closed to you; + your other workspaces aren't.{" "} + {google ? ( + + Sign in with Google as {w.email} + + ) : ( + "This instance doesn't sign people in with Google any more: ask its admins, or the workspace's primary admin." + )} + + {w.role === "owner" && ( +
+ + As its primary admin, you can, for when nobody can sign in with Google. + {lift.error && {lift.error.message}} +
+ )} +
+ ); +} diff --git a/web/src/gen/UpdateWorkspaceRequest.ts b/web/src/gen/UpdateWorkspaceRequest.ts index 0a4dc6c5..ccabd986 100644 --- a/web/src/gen/UpdateWorkspaceRequest.ts +++ b/web/src/gen/UpdateWorkspaceRequest.ts @@ -2,6 +2,7 @@ import type { BaseRole } from "./BaseRole"; import type { ClaudeAdminEmail } from "./ClaudeAdminEmail"; import type { ClaudeOversight } from "./ClaudeOversight"; +import type { SignInRule } from "./SignInRule"; import type { WorkspaceColor } from "./WorkspaceColor"; /** @@ -23,6 +24,14 @@ hex?: string, base_role?: BaseRole, * requires it: every workspace does then. */ require_two_factor?: boolean, +/** + * Its own sign-in requirement ([`Workspace::sign_in`]): no `domains` + * stops requiring one. A provider the instance has set up (`google`). + * Refused (`409`) where it would close the workspace to the admin who + * saves it: they sign in with the provider first. Requiring less + * takes confirming it's you, where the instance asks for that. + */ +sign_in?: SignInRule, /** * Leave inviting people out of the app's setup checklist, or (`false`) * ask for it again. diff --git a/web/src/gen/Workspace.ts b/web/src/gen/Workspace.ts index d1bd0e54..4644d191 100644 --- a/web/src/gen/Workspace.ts +++ b/web/src/gen/Workspace.ts @@ -3,6 +3,7 @@ import type { BaseRole } from "./BaseRole"; import type { ClaudeOversightSettings } from "./ClaudeOversightSettings"; import type { CredentialId } from "./CredentialId"; import type { ServiceAccount } from "./ServiceAccount"; +import type { SignInRule } from "./SignInRule"; import type { UserRef } from "./UserRef"; import type { WorkspaceAutopilot } from "./WorkspaceAutopilot"; import type { WorkspaceColor } from "./WorkspaceColor"; @@ -58,10 +59,27 @@ require_two_factor: boolean, */ instance_requires_two_factor: boolean, /** - * It requires two-factor sign-in, which you haven't set up: until you - * do, its projects and sessions are closed to you. + * It requires two-factor sign-in, which you haven't set up, or its + * own sign-in requirement covers you and your sign-in doesn't meet it + * (`sign_in_blocked`): until then, its projects and sessions are + * closed to you. */ blocked: boolean, +/** + * Its own sign-in requirement: its members who are in it as an + * address at one of `domains` open it only with a sign-in made with + * `provider` as such an address (a passkey alone too, where + * `passkeys`). Members in it as other addresses sign in as the + * instance lets them. Absent: none ([`UpdateWorkspaceRequest::sign_in`]). + */ +sign_in?: SignInRule, +/** + * It's closed to you because of `sign_in`: you're in it as an address + * it covers, and this sign-in of yours was made another way. Signing + * in again with its provider opens it. Absent from control planes + * before it. + */ +sign_in_blocked?: boolean, /** * The Claude connection your sessions in it run on. Absent: your * default one. diff --git a/web/src/lib/sidebar.ts b/web/src/lib/sidebar.ts index bbcc602b..7a26c042 100644 --- a/web/src/lib/sidebar.ts +++ b/web/src/lib/sidebar.ts @@ -19,7 +19,7 @@ const VERSION = 1; /** A workspace as the sidebar shows it. */ export type SidebarWorkspace = Pick< G.Workspace, - "id" | "slug" | "name" | "color" | "hex" | "avatar_url" | "role" | "blocked" + "id" | "slug" | "name" | "color" | "hex" | "avatar_url" | "role" | "blocked" | "sign_in_blocked" >; /** A project as the sidebar shows it, under its workspace, with what picks its icon. */ export type SidebarProject = Pick< @@ -69,7 +69,12 @@ export function keepSidebar(user: string, workspaces: G.WorkspaceList, projects: version: VERSION, user, workspaces: { - workspaces: workspaces.workspaces.map((w) => ({ ...ref(w), role: w.role, blocked: w.blocked })), + workspaces: workspaces.workspaces.map((w) => ({ + ...ref(w), + role: w.role, + blocked: w.blocked, + ...(w.sign_in_blocked ? { sign_in_blocked: true } : {}), + })), invitations: workspaces.invitations.map((i) => ({ id: i.id, workspace: ref(i.workspace) })), limit: workspaces.limit, unlimited: workspaces.unlimited, @@ -126,7 +131,13 @@ function readRef(v: unknown): G.WorkspaceRef | undefined { function readWorkspace(v: unknown): SidebarWorkspace | undefined { const r = readRef(v); if (!r || !isObject(v) || !isText(v.role) || typeof v.blocked !== "boolean") return; - return { ...r, role: v.role as G.WorkspaceRole, blocked: v.blocked }; + // Kept before it said why it's closed: as closed by two-factor sign-in. + return { + ...r, + role: v.role as G.WorkspaceRole, + blocked: v.blocked, + ...(v.sign_in_blocked === true ? { sign_in_blocked: true } : {}), + }; } function readInvitation(v: unknown): SidebarInvitation | undefined { diff --git a/web/src/routes/home.tsx b/web/src/routes/home.tsx index 359ff68e..a3665301 100644 --- a/web/src/routes/home.tsx +++ b/web/src/routes/home.tsx @@ -32,6 +32,7 @@ import { } from "@/lib/queries"; import { asksOf } from "@/lib/service-accounts"; import { ACTIVE } from "@/lib/sessions"; +import { domainsWords } from "@/lib/sign-in"; import { waitsForYou } from "@/lib/status"; import { isUltra } from "@/lib/usage"; import { freshest, mayCreate, useWorkspaceIndex } from "@/lib/workspaces"; @@ -568,15 +569,29 @@ export function Home() { className="flex items-center gap-3 rounded-xl border border-amber/25 bg-amber-soft px-4 py-3 text-[13.5px] text-ink-2" > - - {w.name} requires two-factor sign-in. Until you set it up, its projects and sessions are - closed to you. - - - - + {w.sign_in_blocked ? ( + <> + + {w.name} requires its members at {domainsWords(w.sign_in?.domains ?? [])} to sign in with + Google as that address. Until you do, its projects and sessions are closed to you. + + + + + + ) : ( + <> + + {w.name} requires two-factor sign-in. Until you set it up, its projects and sessions are + closed to you. + + + + + + )}
))} {me && } diff --git a/web/src/routes/workspace.tsx b/web/src/routes/workspace.tsx index d8256aa5..6a0d693a 100644 --- a/web/src/routes/workspace.tsx +++ b/web/src/routes/workspace.tsx @@ -33,6 +33,7 @@ import { ExperimentalPill, TokenHungry } from "@/components/project/autopilot"; import { ProjectMark } from "@/components/project/project-icon"; import { ServiceAccountsPanel } from "@/components/service-accounts/panel"; import { SessionRow } from "@/components/session/row"; +import { ProviderMark } from "@/components/sign-in/provider"; import { AutopilotIcon, Avatar, @@ -71,6 +72,7 @@ import { LinearTab } from "@/components/workspace/linear"; import { ReviewAppReturned, ReviewAppSection } from "@/components/workspace/review-app"; import { RunnerRow } from "@/components/workspace/runner-row"; import { EnrollmentTokens, WaitingRunners } from "@/components/workspace/runners"; +import { SignInBlocked, WorkspaceSignIn } from "@/components/workspace/sign-in"; import { SnapshotSettings, SnapshotsSection } from "@/components/workspace/snapshots"; import type * as G from "@/gen"; import { ApiFailure, api, workspaces } from "@/lib/api"; @@ -94,6 +96,7 @@ import { useWorkspace, } from "@/lib/queries"; import { repoSummary } from "@/lib/repos"; +import { domainsWords } from "@/lib/sign-in"; import { BASE_ROLES, claudeOptions, createsProjects, roleLabel } from "@/lib/workspaces"; export type WorkspaceTab = @@ -231,6 +234,12 @@ export function WorkspacePage() { Two-factor required )} + {w.sign_in && ( + + Google at{" "} + {domainsWords(w.sign_in.domains)} + + )} {admin && !w.blocked && ( @@ -256,14 +265,18 @@ export function WorkspacePage() { )} {w?.blocked ? (
- - {w.name} requires two-factor sign-in of its members, and you haven't set it up. Until you do, its - projects and sessions are closed to you.{" "} - - Set it up in Settings - - . - + {w.sign_in_blocked ? ( + + ) : ( + + {w.name} requires two-factor sign-in of its members, and you haven't set it up. Until you do, + its projects and sessions are closed to you.{" "} + + Set it up in Settings + + . + + )}
) : ( @@ -2272,7 +2285,10 @@ function Autopilots({ w }: { w: G.Workspace }) { ); } -/** Who sees which projects, and two-factor sign-in, which stays on while the instance requires it. */ +/** + * Who sees which projects, two-factor sign-in, which stays on while the instance requires it, and whether the + * members at its domains sign in with Google. + */ function Access({ w }: { w: G.Workspace }) { const { data: me } = useMe(); const members = useQuery({ @@ -2359,6 +2375,7 @@ function Access({ w }: { w: G.Workspace }) { two-factor sign-in )} +