diff --git a/crates/fctl-client/src/api.rs b/crates/fctl-client/src/api.rs index 660bdabc..fcb804b1 100644 --- a/crates/fctl-client/src/api.rs +++ b/crates/fctl-client/src/api.rs @@ -2300,6 +2300,16 @@ impl Api { .await } + /// What saving `policy` in place of the instance's session policy + /// would end at once, before anything changes (admins). Saving it is + /// [`Self::update_instance_settings`] with its fields. + pub async fn session_policy_preview( + &self, + policy: &SessionPolicy, + ) -> Result { + self.post("/admin/sign-in/sessions/preview", policy).await + } + /// Invites an address to the instance, and to workspaces you are an /// admin of. pub async fn invite(&self, req: &CreateInviteRequest) -> Result { diff --git a/crates/fctl-control/src/api/admin.rs b/crates/fctl-control/src/api/admin.rs index d3bb637b..f5f0dea3 100644 --- a/crates/fctl-control/src/api/admin.rs +++ b/crates/fctl-control/src/api/admin.rs @@ -1162,6 +1162,33 @@ pub async fn update_settings(ctx: &mut Ctx, req: &mut Request) -> AppResult AppResult AppResult { admin_tokens: ctx.cfg.admin_tokens, service_account_consent: settings.service_account_consent, }, - sign_in: Some(crate::sign_in::info(&ctx.cfg, &settings)), + sign_in: Some(crate::sign_in::info(&ctx.cfg, &settings, ctx.ip.as_deref())), }) } @@ -237,6 +237,12 @@ pub async fn signup(ctx: &mut Ctx, req: &mut Request) -> AppResult { "An account with this email already exists. Sign in instead.", )); } + // From outside the instance's networks, before the account and the + // invitation's use are written: nobody new signs in from there. + let networks = crate::instance::settings(&ctx.db).await?.networks; + if !fctl_domain::networks::admits(&networks, ctx.ip.as_deref()) { + return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref()))); + } // Where its domain signs in with a provider, the invitation is taken // with that provider's sign-in, which makes the account (`api::sign_in`). let settings = crate::instance::settings(&ctx.db).await?; @@ -326,6 +332,11 @@ pub async fn login(ctx: &mut Ctx, req: &mut Request) -> AppResult { if let Err(required) = user.admits(&instance, &SignedIn::password()) { return Err(AppError(crate::sign_in::password_refused(&required))); } + // Before a code is asked for: from outside the instance's networks it + // would sign nobody in. + if crate::sign_in::outside(&instance, ctx.ip.as_deref(), &user, true) { + return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref()))); + } let settings = user.two_factor_settings(&instance); if two_factor::asks( &settings, @@ -749,6 +760,11 @@ pub async fn reset_password(ctx: &mut Ctx, req: &mut Request) -> AppResult AppResult AppResult AppResult AppResult { let people = crate::sign_in::people(&ctx.db).await?; let how = signed_in_with(ctx); let count = |f: fn(&rules::Person) -> bool| people.iter().filter(|p| f(p)).count() as u32; + let sessions = settings.session_policy(); http::ok(&SignInOverview { providers: crate::sign_in::statuses(&ctx.cfg, &people), coverage: settings @@ -781,9 +793,51 @@ pub async fn overview(ctx: &Ctx) -> AppResult { method: how.method_str().map(str::to_owned), method_domain: how.domain, email: ctx.cfg.email.is_some(), + sessions, + networks: settings.networks.clone(), + address: ctx.ip.clone(), }) } +/// `POST /api/v1/admin/sign-in/sessions/preview`: what saving the +/// request's session policy would end at once, before anything changes. +pub async fn sessions_preview(ctx: &Ctx, req: &mut Request) -> AppResult { + let actor = ctx.admin()?.clone(); + let policy: SessionPolicy = http::body(req).await?; + fctl_domain::session_policy::check(&policy).map_err(AppError)?; + let mut p = SessionPolicyPreview::default(); + for (kind, member, n) in crate::sign_in::ended_by_policy(&ctx.db, &policy, ctx.now).await? { + match kind { + TokenKind::Web => p.browsers += n, + TokenKind::Cli => p.clis += n, + TokenKind::Pat => { + p.access_tokens += n; + if member { + p.member_tokens += n; + } + } + } + } + // The sign-in this request comes with, used just now: one of those, if + // it's too old. An admin token isn't one. + p.you = ctx.auth.as_ref().is_some_and(|a| { + !a.admin_token + && fctl_domain::session_policy::ended( + &policy, + &fctl_domain::session_policy::Token { + kind: a.kind, + created_at: a.signed_in_at, + last_used_at: Some(ctx.now), + expires_at: None, + member: actor.role() == fctl_proto::session::InstanceRole::Member, + }, + ctx.now, + ) + .is_some() + }); + http::ok(&p) +} + /// How the caller's sign-in was made. fn signed_in_with(ctx: &Ctx) -> SignedIn { ctx.auth diff --git a/crates/fctl-control/src/api/tokens.rs b/crates/fctl-control/src/api/tokens.rs index eb0fa255..139e012b 100644 --- a/crates/fctl-control/src/api/tokens.rs +++ b/crates/fctl-control/src/api/tokens.rs @@ -10,10 +10,11 @@ use crate::error::{AppError, AppResult, not_found, validation}; use crate::http; use crate::model::PROJECT_VISIBLE; use fctl_domain::limits::{Limits, MAX_PLACES, Places}; +use fctl_domain::session_policy; use fctl_domain::validate; use fctl_domain::verify::Sensitive; -use fctl_proto::TokenId; use fctl_proto::api::*; +use fctl_proto::{ApiError, TokenId}; use serde::Deserialize; use std::collections::HashMap; use worker::{Request, Response}; @@ -134,8 +135,27 @@ impl TokenRow { Limits::parse(self.scope.as_deref()) } - fn info(self, current: &str, named: &Named) -> TokenInfo { + /// It as the instance's session policy reads it (`member`: its person + /// is a member of the instance, not an admin). + fn token(&self, member: bool) -> session_policy::Token { + session_policy::Token { + kind: TokenKind::parse(&self.kind).unwrap_or(TokenKind::Pat), + created_at: self.created_at, + last_used_at: self.last_used_at, + expires_at: self.expires_at, + member, + } + } + + /// Whether `policy` still lets it sign its person in at `now`. + fn live(&self, policy: &SessionPolicy, member: bool, now: i64) -> bool { + session_policy::ended(policy, &self.token(member), now).is_none() + } + + /// What people see of it, as `policy` lets it last. + fn info(self, current: &str, named: &Named, policy: &SessionPolicy) -> TokenInfo { let scope = self.limits().map(|l| named.scope(&l)); + let expires_at = session_policy::ends_at(policy, &self.token(false)); TokenInfo { current: self.id == current, id: TokenId(self.id), @@ -143,7 +163,7 @@ impl TokenRow { name: self.name, created_at: self.created_at, last_used_at: self.last_used_at, - expires_at: self.expires_at, + expires_at, user_agent: self.user_agent, scope, method: self.auth_method, @@ -170,10 +190,20 @@ pub async fn list(ctx: &Ctx) -> AppResult { )? .all() .await?; + // Those the instance's session policy ended are gone. + let policy = ctx.settings().session_policy(); + let member = user.role() == fctl_proto::session::InstanceRole::Member; + let rows: Vec = rows + .into_iter() + .filter(|r| r.live(&policy, member, ctx.now)) + .collect(); let limits: Vec = rows.iter().filter_map(TokenRow::limits).collect(); let named = Named::of(ctx, &user.id, &limits.iter().collect::>()).await?; http::ok(&TokenList { - tokens: rows.into_iter().map(|r| r.info(¤t, &named)).collect(), + tokens: rows + .into_iter() + .map(|r| r.info(¤t, &named, &policy)) + .collect(), }) } @@ -195,7 +225,11 @@ pub async fn current(ctx: &Ctx) -> AppResult> { }; let limits = row.limits(); let named = Named::of(ctx, &a.user.id, &limits.iter().collect::>()).await?; - Ok(Some(row.info(&a.token_id, &named))) + Ok(Some(row.info( + &a.token_id, + &named, + &a.settings.session_policy(), + ))) } /// The places a new token names: workspaces the caller is a member of and @@ -266,12 +300,21 @@ async fn places( pub async fn create(ctx: &mut Ctx, req: &mut Request) -> AppResult { let body: CreateTokenRequest = http::body(req).await?; let user = ctx.user()?.clone(); + let settings = ctx.settings(); + let policy = settings.session_policy(); + // Where members make none, they use the CLI signed in as themselves. + if !policy.member_access_tokens && user.role() == fctl_proto::session::InstanceRole::Member { + return Err(AppError(ApiError::forbidden( + "Only this instance's admins make access tokens: use the CLI signed in as you (fctl login), or ask an admin.", + ))); + } let name = validate::name("name", &body.name)?; - let expires_at = match body.expires_in_days { - Some(0) | None => None, - Some(d) if d <= 3650 => Some(ctx.now + d as i64 * DAY_MS), - Some(_) => return Err(validation("expires_in_days", "Use at most 3650 days")), - }; + let days = body.expires_in_days.filter(|d| *d > 0); + if days.is_some_and(|d| d > fctl_proto::api::MAX_ACCESS_TOKEN_DAYS) { + return Err(validation("expires_in_days", "Use at most 3650 days")); + } + session_policy::check_token_days(&policy, days).map_err(AppError)?; + let expires_at = days.map(|d| ctx.now + i64::from(d) * DAY_MS); let access = body.access.unwrap_or_default(); fctl_domain::limits::check(access, body.github_access).map_err(AppError)?; let places = places(ctx, &body.workspaces, &body.projects).await?; @@ -295,6 +338,7 @@ pub async fn create(ctx: &mut Ctx, req: &mut Request) -> AppResult { limits: limits.as_ref(), verified_at: None, how, + settings: Some(&settings), }, ) .await?; @@ -375,5 +419,6 @@ pub fn limited_me(user: &crate::model::UserRow, token: Option) -> Me claude_stand_in: false, export: None, sign_in: None, + sessions: None, } } diff --git a/crates/fctl-control/src/auth.rs b/crates/fctl-control/src/auth.rs index f24e01e1..9c5d5075 100644 --- a/crates/fctl-control/src/auth.rs +++ b/crates/fctl-control/src/auth.rs @@ -9,6 +9,7 @@ use argon2::Argon2; use argon2::password_hash::{PasswordHasher, PasswordVerifier, phc::PasswordHash}; use fctl_domain::cookies::Cookie; use fctl_domain::limits::Limits; +use fctl_domain::session_policy; use fctl_domain::sign_in::SignedIn; use fctl_domain::tokens::{SecretKind, hash_secret, new_secret}; use fctl_proto::ApiError; @@ -16,10 +17,6 @@ use fctl_proto::api::{InstanceSettings, Me, TokenKind}; use worker::{D1Database, Request}; pub const DAY_MS: i64 = 24 * 60 * 60 * 1000; -/// Web sessions expire this long after their last use. -pub const WEB_SESSION_TTL_MS: i64 = 30 * DAY_MS; -/// CLI tokens expire this long after their last use. -pub const CLI_TOKEN_TTL_MS: i64 = 180 * DAY_MS; // ───────────────────────────── passwords ───────────────────────────── @@ -65,6 +62,9 @@ pub struct NewToken<'a> { pub verified_at: Option, /// How the sign-in it comes from was made (`fctl_domain::sign_in`). pub how: SignedIn, + /// The instance's settings, where the caller has them: their session + /// policy says when it ends. Read from D1 otherwise. + pub settings: Option<&'a InstanceSettings>, } /// Creates a web session, CLI token or PAT and returns its id and secret. @@ -81,6 +81,7 @@ pub async fn issue_token( limits, verified_at, how, + settings, } = new; let secret_kind = match kind { TokenKind::Web => SecretKind::WebSession, @@ -89,11 +90,20 @@ pub async fn issue_token( }; let secret = new_secret(secret_kind); let id = fctl_domain::ids::token_id(ctx.now); - let expires_at = expires_at.or(match kind { - TokenKind::Web => Some(ctx.now + WEB_SESSION_TTL_MS), - TokenKind::Cli => Some(ctx.now + CLI_TOKEN_TTL_MS), - TokenKind::Pat => None, - }); + // A browser's or a CLI's lasts as the instance's session policy says. + // An access token keeps the end its maker chose, which the policy + // checked: every request applies the policy's longest from when it was + // made, so that relaxing the policy gives the maker's choice back. + let policy = match settings { + Some(s) => s.session_policy(), + None => crate::instance::settings(&ctx.db).await?.session_policy(), + }; + let expires_at = match kind { + TokenKind::Pat => expires_at, + TokenKind::Web | TokenKind::Cli => { + session_policy::expires_at(&policy, kind, ctx.now, ctx.now, expires_at) + } + }; let scope = limits .filter(|_| kind == TokenKind::Pat) .map(Limits::to_json); @@ -122,17 +132,23 @@ pub async fn issue_token( .run() .await?; if kind == TokenKind::Web { - let max_age = (WEB_SESSION_TTL_MS / 1000) as u64; ctx.cookies.push(http::set_cookie( Cookie::Session, &secret, - max_age, + cookie_max_age(&policy, ctx.now, ctx.now), ctx.cfg.secure_cookies(), )); } Ok((id.0, secret)) } +/// The seconds a browser keeps the session cookie of a sign-in made at +/// `created_at`, as it's used at `now` (`session_policy::cookie_until`). +fn cookie_max_age(policy: &fctl_proto::api::SessionPolicy, created_at: i64, now: i64) -> u64 { + let ms = (session_policy::cookie_until(policy, created_at, now) - now).max(0); + (ms / 1000) as u64 +} + /// Signs in `user` in the browser: a new web session, and `last_login_at` /// and `last_active_at`. The request then counts as theirs (for the audit /// log). `confirmed`: the sign-in took a passkey or a second factor, so the @@ -146,6 +162,12 @@ pub async fn start_web_session( how: SignedIn, ) -> AppResult<()> { let verified_at = confirmed.then_some(ctx.now); + let settings = crate::instance::settings(&ctx.db).await?; + // Every way into a browser comes here: none from outside the + // instance's networks, but the primary instance owner's. + if crate::sign_in::outside(&settings, ctx.ip.as_deref(), user, true) { + return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref()))); + } let (token_id, _) = issue_token( ctx, &user.id, @@ -153,6 +175,7 @@ pub async fn start_web_session( NewToken { verified_at, how: how.clone(), + settings: Some(&settings), ..NewToken::default() }, ) @@ -164,7 +187,6 @@ pub async fn start_web_session( )? .run() .await?; - let settings = crate::instance::settings(&ctx.db).await?; ctx.auth = Some(Authed::signed_in( user, token_id, @@ -228,6 +250,30 @@ struct TokenLookup { user: UserRow, } +impl TokenLookup { + /// Whether, and why, the token no longer signs its person in at `now` + /// under `settings`' session policy (`fctl_domain::session_policy`). + /// `in_use`: a socket opened with it is open, which counts as use, + /// though nothing records it ([`session_policy::Token::in_use`]). + fn ended( + &self, + kind: TokenKind, + settings: &InstanceSettings, + now: i64, + in_use: bool, + ) -> Option { + let token = session_policy::Token { + kind, + created_at: self.token_created_at, + last_used_at: self.last_used_at, + expires_at: self.expires_at, + member: self.user.role() == fctl_proto::session::InstanceRole::Member, + }; + let token = if in_use { token.in_use(now) } else { token }; + session_policy::ended(&settings.session_policy(), &token, now) + } +} + /// The bearer token or session cookie of a request, if any (`secure`: /// `Config::secure_cookies`). pub fn presented_secret(req: &Request, secure: bool) -> Option<(String, bool)> { @@ -291,11 +337,24 @@ pub async fn by_token_id(db: &D1Database, token_id: &str, now: i64) -> AppResult let found: Option = q(db, &token_lookup_sql("id"), &[s(token_id)])? .first() .await?; + // An open socket is in use: it records that as a request does + // ([`authenticate`]), so that its sign-in's end slides, and the hourly + // job, which deletes ended sign-ins, leaves it. + if let Some(f) = &found { + let settings = crate::instance::parse(f.instance_settings.as_deref()); + let kind = TokenKind::parse(&f.kind).unwrap_or(TokenKind::Pat); + if f.ended(kind, &settings, now, true).is_none() { + touch(db, f, kind, &settings.session_policy(), now).await?; + } + } Ok(found.and_then(|f| { - if f.expires_at.is_some_and(|e| e <= now) || !f.user.is_active() { + let settings = crate::instance::parse(f.instance_settings.as_deref()); + let kind = TokenKind::parse(&f.kind).unwrap_or(TokenKind::Pat); + // Only its sign-in's age, its end as its maker chose and who makes + // access tokens close it. + if f.ended(kind, &settings, now, true).is_some() || !f.user.is_active() { return None; } - let settings = crate::instance::parse(f.instance_settings.as_deref()); let how = SignedIn::read(f.auth_method.as_deref(), f.auth_domain.as_deref()); if f.user.admits(&settings, &how).is_err() { return None; @@ -313,6 +372,61 @@ pub async fn by_token_id(db: &D1Database, token_id: &str, now: i64) -> AppResult })) } +/// When a token's use is recorded again after its last record: often +/// enough, for a browser, that one in use isn't taken for unused. +fn touch_after(kind: TokenKind, policy: &fctl_proto::api::SessionPolicy) -> i64 { + match kind { + TokenKind::Web => session_policy::touch_after_ms(policy), + TokenKind::Cli | TokenKind::Pat => session_policy::TOUCH_MS, + } +} + +/// The end a token of `kind` slides to as it's used at `now`: a browser's +/// or a CLI's as the session policy says; an access token's stays its +/// maker's ([`issue_token`]). +fn slid( + found: &TokenLookup, + kind: TokenKind, + policy: &fctl_proto::api::SessionPolicy, + now: i64, +) -> Option { + match kind { + TokenKind::Pat => found.expires_at, + TokenKind::Web | TokenKind::Cli => { + session_policy::expires_at(policy, kind, found.token_created_at, now, None) + } + } +} + +/// Records a socket's use of its token, at most as often as +/// [`touch_after`] says. +async fn touch( + db: &D1Database, + found: &TokenLookup, + kind: TokenKind, + policy: &fctl_proto::api::SessionPolicy, + now: i64, +) -> AppResult<()> { + if found + .last_used_at + .is_some_and(|t| now - t <= touch_after(kind, policy)) + { + return Ok(()); + } + q( + db, + "UPDATE tokens SET last_used_at = ?, expires_at = ? WHERE id = ?", + &[ + n(now), + on(slid(found, kind, policy, now)), + s(&found.token_id), + ], + )? + .run() + .await?; + Ok(()) +} + /// Resolves the caller from the bearer token or the session cookie. Invalid /// or expired credentials are treated as signed out (and the cookie cleared). pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> { @@ -362,14 +476,18 @@ pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> { } return Err(AppError(ApiError::unauthorized())); }; - if found.expires_at.is_some_and(|e| e <= ctx.now) { + let kind = TokenKind::parse(&found.kind).unwrap_or(TokenKind::Pat); + let settings = crate::instance::parse(found.instance_settings.as_deref()); + // Expired, or past what the instance's session policy lets it last: a + // browser's is signed out, and signs in again. + if let Some(why) = found.ended(kind, &settings, ctx.now, false) { if via_cookie { clear_session_cookie(ctx); return Ok(()); } return Err(AppError(ApiError::new( fctl_proto::ErrorCode::Unauthorized, - "Your token has expired. Sign in again.", + session_policy::refusal(&settings.session_policy(), kind, why), ))); } if !found.user.is_active() { @@ -378,8 +496,19 @@ pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> { "Your account is disabled. Ask an admin for access.", ))); } - let kind = TokenKind::parse(&found.kind).unwrap_or(TokenKind::Pat); - let settings = crate::instance::parse(found.instance_settings.as_deref()); + // From outside the instance's networks: a browser is as signed out, + // and keeps its sign-in for when it's back inside one. + if crate::sign_in::outside( + &settings, + ctx.ip.as_deref(), + &found.user, + kind != TokenKind::Pat, + ) { + if via_cookie { + return Ok(()); + } + return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref()))); + } // A domain of theirs signs in with a provider only: a sign-in made // another way, or before fctl kept how, no longer lets them in. A // browser's is signed out, and the sign-in page shows the way in. @@ -391,16 +520,15 @@ pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> { } return Err(AppError(crate::sign_in::token_refused(&required, kind))); } - // Touch the token at most every 10 minutes; slide web and CLI expiry. + // Touch the token at most every 10 minutes, or more often where + // browsers sign out after a short while unused; slide web and CLI + // expiry, never past what the session policy lets them last. + let policy = settings.session_policy(); let stale = found .last_used_at - .is_none_or(|t| ctx.now - t > 10 * 60 * 1000); + .is_none_or(|t| ctx.now - t > touch_after(kind, &policy)); if stale { - let new_expiry = match kind { - TokenKind::Web => Some(ctx.now + WEB_SESSION_TTL_MS), - TokenKind::Cli => Some(ctx.now + CLI_TOKEN_TTL_MS), - TokenKind::Pat => found.expires_at, - }; + let new_expiry = slid(&found, kind, &policy, ctx.now); let db = crate::db::handle(&ctx.db); let id = found.token_id.clone(); let now = ctx.now; @@ -415,11 +543,10 @@ pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> { Ok(()) }); if kind == TokenKind::Web && via_cookie { - let max_age = (WEB_SESSION_TTL_MS / 1000) as u64; ctx.cookies.push(http::set_cookie( Cookie::Session, &secret, - max_age, + cookie_max_age(&policy, found.token_created_at, ctx.now), ctx.cfg.secure_cookies(), )); } @@ -478,6 +605,9 @@ async fn admin_token(ctx: &mut Ctx, secret: &str) -> AppResult<()> { ))); } let settings = crate::instance::parse(found.instance_settings.as_deref()); + if crate::sign_in::outside(&settings, ctx.ip.as_deref(), &found.user, false) { + return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref()))); + } // Held to the rules as its admin's own sign-ins are: one their domain's // rule doesn't meet stops. let how = SignedIn::read(found.auth_method.as_deref(), found.auth_domain.as_deref()); @@ -599,6 +729,7 @@ pub async fn me(ctx: &Ctx, user: &UserRow) -> AppResult { claude_stand_in: user.claude_stand_in, export: Some(data_export(ctx, user)), sign_in: crate::sign_in::requirement(user, &ctx.settings()), + sessions: Some(ctx.settings().session_policy()), }) } diff --git a/crates/fctl-control/src/lib.rs b/crates/fctl-control/src/lib.rs index 6f501fcd..baacf1cc 100644 --- a/crates/fctl-control/src/lib.rs +++ b/crates/fctl-control/src/lib.rs @@ -338,6 +338,9 @@ async fn dispatch( (Get, ["admin", "settings"]) => api::admin::settings(ctx).await, (Get, ["admin", "sign-in"]) => api::sign_in::overview(ctx).await, (Post, ["admin", "sign-in", "preview"]) => api::sign_in::preview(ctx, req).await, + (Post, ["admin", "sign-in", "sessions", "preview"]) => { + api::sign_in::sessions_preview(ctx, req).await + } (Patch, ["admin", "settings"]) => api::admin::update_settings(ctx, req).await, (Post, ["admin", "transfer"]) => api::admin::transfer(ctx, req).await, (Get, ["admin", "workspaces"]) => api::admin::workspaces(ctx).await, diff --git a/crates/fctl-control/src/service_accounts.rs b/crates/fctl-control/src/service_accounts.rs index e4e34f82..2a6c54b6 100644 --- a/crates/fctl-control/src/service_accounts.rs +++ b/crates/fctl-control/src/service_accounts.rs @@ -274,6 +274,9 @@ pub async fn authenticate(ctx: &mut Ctx, secret: &str) -> AppResult<()> { ))); }; let settings = crate::instance::settings(&ctx.db).await?; + if !fctl_domain::networks::admits(&settings.networks, ctx.ip.as_deref()) { + return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref()))); + } // Its keeper left or lost the role, or, as it acts with their // authority, has to set up two-factor sign-in first, as their own // tokens wait too. diff --git a/crates/fctl-control/src/sign_in.rs b/crates/fctl-control/src/sign_in.rs index 9e87be50..8d301699 100644 --- a/crates/fctl-control/src/sign_in.rs +++ b/crates/fctl-control/src/sign_in.rs @@ -4,13 +4,13 @@ //! accounts a change to the rules concerns. use crate::config::Config; -use crate::db::{q, s}; +use crate::db::{b, n, q, s}; use crate::error::AppResult; use crate::model::UserRow; use fctl_domain::sign_in::{GOOGLE, Person, Required, SignedIn, domains_words}; use fctl_proto::api::{ - InstanceSettings, SignInInfo, SignInProvider, SignInProviderStatus, SignInRequirement, - SignInRule, TokenKind, + InstanceSettings, SessionPolicy, SignInInfo, SignInProvider, SignInProviderStatus, + SignInRequirement, SignInRule, TokenKind, }; use fctl_proto::{ApiError, ErrorCode}; use serde::Deserialize; @@ -70,8 +70,9 @@ pub fn statuses(cfg: &Config, people: &[Person]) -> Vec { .collect() } -/// What the sign-in page needs ([`fctl_proto::api::InstanceInfo::sign_in`]). -pub fn info(cfg: &Config, settings: &InstanceSettings) -> SignInInfo { +/// What the sign-in page needs ([`fctl_proto::api::InstanceInfo::sign_in`]), +/// for a request from `ip`. +pub fn info(cfg: &Config, settings: &InstanceSettings, ip: Option<&str>) -> SignInInfo { SignInInfo { providers: PROVIDERS .iter() @@ -84,9 +85,28 @@ pub fn info(cfg: &Config, settings: &InstanceSettings) -> SignInInfo { .collect(), rules: settings.sign_in.clone(), self_sign_up: settings.self_sign_up, + outside: !fctl_domain::networks::admits(&settings.networks, ip), } } +/// Whether the instance's networks refuse `user`'s request from `ip` +/// (`fctl_domain::networks`). `signing_in`: it's a browser's or a CLI's +/// sign-in, or a request with one, which the primary instance owner makes +/// from anywhere; their access tokens and admin tokens are held to them. +pub fn outside( + settings: &InstanceSettings, + ip: Option<&str>, + user: &UserRow, + signing_in: bool, +) -> bool { + !fctl_domain::networks::admits(&settings.networks, ip) && !(signing_in && user.is_owner()) +} + +/// The refusal of a request from outside the instance's networks. +pub fn outside_refused(ip: Option<&str>) -> ApiError { + ApiError::forbidden(fctl_domain::networks::refusal(ip)) +} + /// What a rule requires, as refusals begin: "acme.com signs in with /// Google". pub fn says(required: &Required) -> String { @@ -377,6 +397,70 @@ pub fn revoke_unmet(db: &D1Database, rules: &[SignInRule]) -> AppResult (&'static str, Vec) { + use fctl_domain::session_policy::{idle_ms, max_age_ms}; + let max = |kind| n(max_age_ms(policy, kind).unwrap_or(0)); + ( + "(expires_at IS NULL OR expires_at > ?1) AND ( (kind = 'web' AND ((?2 > 0 AND created_at + ?2 <= ?1) OR COALESCE(last_used_at, created_at) + ?3 <= ?1)) OR (kind = 'cli' AND ?4 > 0 AND created_at + ?4 <= ?1) OR (kind = 'pat' AND ((?5 > 0 AND created_at + ?5 <= ?1) OR (?6 AND user_id IN (SELECT id FROM users WHERE role = 'member')))))", + vec![ + n(now), + max(TokenKind::Web), + n(idle_ms(policy, TokenKind::Web).unwrap_or(i64::MAX / 2)), + max(TokenKind::Cli), + max(TokenKind::Pat), + b(!policy.member_access_tokens), + ], + ) +} + +/// What saving `policy` ends at once: browser and CLI sign-ins older than +/// it lets them be, browsers unused longer, and access tokens older than +/// it lets them be, or members' where members make none. Counted by kind +/// and by whether a member of the instance holds it. +pub async fn ended_by_policy( + db: &D1Database, + policy: &SessionPolicy, + now: i64, +) -> AppResult> { + #[derive(Deserialize)] + struct Row { + kind: String, + #[serde(deserialize_with = "crate::db::int")] + member: i64, + #[serde(deserialize_with = "crate::db::int")] + n: i64, + } + let (ended, params) = ended_by(policy, now); + let rows: Vec = q( + db, + &format!( + "SELECT kind, (user_id IN (SELECT id FROM users WHERE role = 'member')) AS member, COUNT(*) AS n FROM tokens WHERE {ended} GROUP BY kind, member" + ), + ¶ms, + )? + .all() + .await?; + Ok(rows + .into_iter() + .filter_map(|r| Some((TokenKind::parse(&r.kind)?, r.member != 0, r.n as u32))) + .collect()) +} + +/// What deletes, once `policy` is saved, the sign-ins and access tokens it +/// ends ([`ended_by_policy`]): they no longer let anyone in, and none +/// comes back when the policy is relaxed. +pub fn revoke_ended( + db: &D1Database, + policy: &SessionPolicy, + now: i64, +) -> AppResult { + let (ended, params) = ended_by(policy, now); + q(db, &format!("DELETE FROM tokens WHERE {ended}"), ¶ms) +} + #[cfg(test)] mod tests { use super::*; @@ -536,4 +620,163 @@ mod d1_tests { assert_eq!(left(&db, "tokens").await?.len(), 3); Ok(()) } + + /// What saving a session policy ends is what every request refuses + /// under it (`fctl_domain::session_policy::ended`). + #[wasm_bindgen_test] + async fn saving_a_session_policy_ends_what_it_doesnt_let_last() -> AppResult<()> { + use fctl_domain::session_policy::{self as sp, DAY_MS, HOUR_MS}; + let db = testing::database(); + let now = 100 * DAY_MS; + q( + &db, + "INSERT INTO users (id, email, name, role, status, created_at, updated_at) VALUES ('usr_ada', 'ada@acme.dev', 'Ada', 'owner', 'active', 0, 0), ('usr_bob', 'bob@acme.dev', 'Bob', 'member', 'active', 0, 0)", + &[], + )? + .run() + .await?; + // id, kind, user, created, last used, expires. + type Row<'a> = (&'a str, TokenKind, &'a str, i64, Option, Option); + let tokens: [Row; 9] = [ + // A browser signed in 13 hours ago, used a minute ago. + ( + "tok_web_old", + TokenKind::Web, + "usr_ada", + now - 13 * HOUR_MS, + Some(now - 60_000), + Some(now + DAY_MS), + ), + // One signed in an hour ago, unused for 50 minutes. + ( + "tok_web_idle", + TokenKind::Web, + "usr_bob", + now - HOUR_MS, + Some(now - 50 * 60_000), + Some(now + DAY_MS), + ), + ( + "tok_web_new", + TokenKind::Web, + "usr_bob", + now - HOUR_MS, + Some(now - 60_000), + Some(now + DAY_MS), + ), + ( + "tok_cli_old", + TokenKind::Cli, + "usr_ada", + now - 40 * DAY_MS, + Some(now), + Some(now + DAY_MS), + ), + ( + "tok_cli_new", + TokenKind::Cli, + "usr_bob", + now - 20 * DAY_MS, + Some(now), + Some(now + DAY_MS), + ), + // Access tokens: an admin's for ever, 100 days old; a member's. + ("tok_pat_ada", TokenKind::Pat, "usr_ada", 0, None, None), + ( + "tok_pat_ada_new", + TokenKind::Pat, + "usr_ada", + now - DAY_MS, + None, + None, + ), + ( + "tok_pat_bob", + TokenKind::Pat, + "usr_bob", + now - DAY_MS, + None, + None, + ), + // Expired already: no change counts it. + ( + "tok_gone", + TokenKind::Web, + "usr_bob", + 0, + Some(0), + Some(now - 1), + ), + ]; + for (id, kind, user, created, used, expires) in tokens { + q( + &db, + "INSERT INTO tokens (id, hash, kind, user_id, created_at, last_used_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)", + &[s(id), s(id), s(kind.as_str()), s(user), n(created), crate::db::on(used), crate::db::on(expires)], + )? + .run() + .await?; + } + let policy = SessionPolicy { + browser_max_hours: 12, + browser_idle_minutes: 30, + cli_max_days: 30, + access_token_max_days: 90, + member_access_tokens: false, + }; + // As each request would read them. + let refused: Vec<&str> = tokens + .iter() + .filter(|(_, kind, user, created, used, expires)| { + expires.is_none_or(|e| e > now) + && sp::ended( + &policy, + &sp::Token { + kind: *kind, + created_at: *created, + last_used_at: *used, + expires_at: *expires, + member: *user == "usr_bob", + }, + now, + ) + .is_some() + }) + .map(|t| t.0) + .collect(); + assert_eq!( + refused, + [ + "tok_web_old", + "tok_web_idle", + "tok_cli_old", + "tok_pat_ada", + "tok_pat_bob" + ] + ); + let mut counted = ended_by_policy(&db, &policy, now).await?; + counted.sort_by_key(|(kind, member, _)| (kind.as_str(), *member)); + assert_eq!( + counted, + [ + (TokenKind::Cli, false, 1), + (TokenKind::Pat, false, 1), + (TokenKind::Pat, true, 1), + (TokenKind::Web, false, 1), + (TokenKind::Web, true, 1), + ] + ); + revoke_ended(&db, &policy, now)?.run().await?; + assert_eq!( + left(&db, "tokens").await?, + ["tok_cli_new", "tok_gone", "tok_pat_ada_new", "tok_web_new"] + ); + // The defaults end nothing more. + assert!( + ended_by_policy(&db, &SessionPolicy::default(), now) + .await? + .is_empty() + ); + Ok(()) + } } diff --git a/crates/fctl-domain/src/lib.rs b/crates/fctl-domain/src/lib.rs index e1e580f6..39729d62 100644 --- a/crates/fctl-domain/src/lib.rs +++ b/crates/fctl-domain/src/lib.rs @@ -41,6 +41,7 @@ pub mod merge_checks; pub mod metadata; pub mod models; pub mod naming; +pub mod networks; pub mod notify; pub mod order; pub mod perm; @@ -60,6 +61,7 @@ pub mod schedule; pub mod schedules; pub mod search; pub mod service_accounts; +pub mod session_policy; pub mod settings; pub mod sign_in; pub mod sigv4; diff --git a/crates/fctl-domain/src/networks.rs b/crates/fctl-domain/src/networks.rs new file mode 100644 index 00000000..7e7b638d --- /dev/null +++ b/crates/fctl-domain/src/networks.rs @@ -0,0 +1,220 @@ +//! The networks an instance takes sign-ins and requests from +//! (`InstanceSettings::networks`, #618): IP ranges such as an office's or +//! a VPN's, in CIDR notation. None, the default, takes them from +//! anywhere. +//! +//! People's browsers, CLIs and access tokens, admin tokens and service +//! accounts' secrets are held to them; runners' connections, webhooks +//! (GitHub's, Linear's), published links and the identity tokens' keys +//! aren't, as they never sign anyone in. The primary instance owner signs +//! in from anywhere, in a browser or with the CLI: the instance's way in +//! when its network changes. Their access tokens and admin tokens are held +//! to them as everyone's are. + +use fctl_proto::ApiError; +use std::net::IpAddr; + +/// The most ranges an instance names. +pub const MAX_NETWORKS: usize = 100; + +/// A range of addresses: an address and how many of its leading bits a +/// member shares with it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Network { + addr: IpAddr, + prefix: u8, +} + +impl Network { + /// A range as an admin types it: `10.0.0.0/8`, `2001:db8::/32`, or an + /// address alone, which is a range of one. Its host bits must be zero, + /// so that what's saved says what it takes. + pub fn parse(input: &str) -> Result { + let s = input.trim(); + let bad = || format!("{s} isn't a network: give one like 203.0.113.0/24 or 2001:db8::/32"); + let (addr, prefix) = match s.split_once('/') { + Some((a, p)) => (a, Some(p)), + None => (s, None), + }; + let addr: IpAddr = addr.trim().parse().map_err(|_| bad())?; + let max = if addr.is_ipv4() { 32 } else { 128 }; + let prefix = match prefix { + Some(p) => p.trim().parse::().map_err(|_| bad())?, + None => max, + }; + if prefix > max { + return Err(bad()); + } + let net = Self { addr, prefix }; + if net.masked(addr) != addr { + return Err(format!( + "{s} has bits past its prefix: did you mean {}?", + Self { + addr: net.masked(addr), + prefix + } + )); + } + Ok(net) + } + + /// `ip` with the bits past this range's prefix cleared. + fn masked(&self, ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V4(v4) => { + let bits = u32::from(v4); + let mask = u32::MAX + .checked_shl(32 - u32::from(self.prefix)) + .unwrap_or(0); + IpAddr::V4((bits & mask).into()) + } + IpAddr::V6(v6) => { + let bits = u128::from(v6); + let mask = u128::MAX + .checked_shl(128 - u32::from(self.prefix)) + .unwrap_or(0); + IpAddr::V6((bits & mask).into()) + } + } + } + + /// Whether `ip` is in it. An IPv4 address mapped into IPv6 + /// (`::ffff:203.0.113.7`) counts as the IPv4 one. + pub fn contains(&self, ip: IpAddr) -> bool { + let ip = match ip { + IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4), + v4 => v4, + }; + ip.is_ipv4() == self.addr.is_ipv4() && self.masked(ip) == self.addr + } +} + +impl std::fmt::Display for Network { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}/{}", self.addr, self.prefix) + } +} + +/// `networks` as the instance keeps them, from what an admin saves: each +/// checked and written as `address/prefix`, once each, [`MAX_NETWORKS`] +/// at most. +pub fn check(networks: &[String]) -> Result, ApiError> { + let mut out: Vec = Vec::new(); + for typed in networks.iter().filter(|n| !n.trim().is_empty()) { + let net = Network::parse(typed).map_err(|m| ApiError::validation("networks", m))?; + let s = net.to_string(); + if !out.contains(&s) { + out.push(s); + } + } + if out.len() > MAX_NETWORKS { + return Err(ApiError::validation( + "networks", + format!("Name {MAX_NETWORKS} networks at most: a wider one takes in several"), + )); + } + Ok(out) +} + +/// Whether `networks` (as kept) take a request from `ip`: they name none, +/// or one holds it. An address that isn't one, or none at all, is in none +/// of them. +pub fn admits(networks: &[String], ip: Option<&str>) -> bool { + if networks.is_empty() { + return true; + } + let Some(ip) = ip.and_then(|i| i.trim().parse::().ok()) else { + return false; + }; + networks + .iter() + .filter_map(|n| Network::parse(n).ok()) + .any(|n| n.contains(ip)) +} + +/// Whether saving `next` in place of `current` takes requests from +/// anywhere `current` didn't: from anywhere at all, or from a network it +/// didn't name. Such a change takes confirming it's you. +pub fn widens(current: &[String], next: &[String]) -> bool { + if current.is_empty() { + return false; + } + let read = |n: &String| Network::parse(n).map_or_else(|_| n.clone(), |n| n.to_string()); + let was: Vec = current.iter().map(read).collect(); + let next: Vec = next + .iter() + .filter(|n| !n.trim().is_empty()) + .map(read) + .collect(); + next.is_empty() || next.iter().any(|n| !was.contains(n)) +} + +/// What a request from outside `networks` answers. +pub fn refusal(ip: Option<&str>) -> String { + format!( + "This instance takes sign-ins and requests only from its organization's networks, and {} isn't in one: connect to one (a VPN, say), then try again.", + ip.map_or_else(|| "this request's address".to_owned(), |i| i.to_owned()) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn nets(list: &[&str]) -> Vec { + list.iter().map(|s| (*s).to_owned()).collect() + } + + #[test] + fn ranges_read_as_admins_type_them() { + assert_eq!( + check(&nets(&[ + " 10.0.0.0/8", + "203.0.113.7", + "2001:DB8::/32", + "10.0.0.0/8", + "" + ])) + .ok(), + Some(nets(&["10.0.0.0/8", "203.0.113.7/32", "2001:db8::/32"])) + ); + for bad in [ + "10.0.0/8", + "10.0.0.0/33", + "acme.com", + "2001:db8::/129", + "10.0.0.1/8", + ] { + assert!(check(&nets(&[bad])).is_err(), "{bad}"); + } + // What a mistyped one meant. + assert!( + check(&nets(&["10.1.2.3/8"])) + .err() + .is_some_and(|e| e.message.contains("did you mean 10.0.0.0/8")) + ); + let many: Vec = (0..=MAX_NETWORKS) + .map(|i| format!("10.0.{i}.0/24")) + .collect(); + assert!(check(&many).is_err()); + assert_eq!(check(&[]).ok(), Some(vec![])); + } + + #[test] + fn requests_from_inside_a_range_are_taken() { + let ranges = nets(&["10.0.0.0/8", "203.0.113.7/32", "2001:db8::/32"]); + for inside in ["10.1.2.3", "203.0.113.7", "2001:db8::1", "::ffff:10.9.9.9"] { + assert!(admits(&ranges, Some(inside)), "{inside}"); + } + for outside in ["11.0.0.1", "203.0.113.8", "2001:db9::1", "not an address"] { + assert!(!admits(&ranges, Some(outside)), "{outside}"); + } + // Without an address, only an instance that names none takes it. + assert!(!admits(&ranges, None)); + assert!(admits(&[], None)); + assert!(admits(&[], Some("198.51.100.1"))); + // Everything, as wide as ranges go. + assert!(admits(&nets(&["0.0.0.0/0"]), Some("198.51.100.1"))); + assert!(!admits(&nets(&["0.0.0.0/0"]), Some("2001:db8::1"))); + } +} diff --git a/crates/fctl-domain/src/session_policy.rs b/crates/fctl-domain/src/session_policy.rs new file mode 100644 index 00000000..5ce94952 --- /dev/null +++ b/crates/fctl-domain/src/session_policy.rs @@ -0,0 +1,672 @@ +//! How long sign-ins last, and who makes access tokens: the instance's +//! session policies (#618; `InstanceSettings::browser_max_hours` and the +//! rest, [`SessionPolicy`]). +//! +//! - A browser's sign-in ends a set number of hours after it was made, +//! however much it's used, and after a set time unused (30 days unless +//! the instance says less). +//! - A CLI's ends a set number of days after it was made, and after 180 +//! days unused as before. +//! - An access token can't be made to last longer than the instance lets +//! one, and one made before that ends when it gets that old. +//! - Members may be kept from making access tokens: theirs stop working. +//! +//! Every request checks its token against them ([`ended`]), so that a +//! policy holds the sign-ins made before it too; saving one also ends +//! those it doesn't let last, and sets the others' end to the policy's, so +//! that what people see of them says so. Where a domain requires its +//! provider, signing in again goes through it, which checks that its +//! person may still sign in: how short a policy makes sign-ins is how soon +//! someone the provider closed out is out of fctl too. + +use crate::enrollment::minutes; +use fctl_proto::ApiError; +use fctl_proto::api::{ + DEFAULT_BROWSER_IDLE_MINUTES, MAX_ACCESS_TOKEN_DAYS, MAX_BROWSER_MAX_HOURS, MAX_CLI_MAX_DAYS, + MIN_BROWSER_IDLE_MINUTES, SessionPolicy, TokenKind, +}; + +pub const MINUTE_MS: i64 = 60 * 1000; +pub const HOUR_MS: i64 = 60 * MINUTE_MS; +pub const DAY_MS: i64 = 24 * HOUR_MS; + +/// A CLI's sign-in ends this long after it was last used. +pub const CLI_IDLE_MS: i64 = 180 * DAY_MS; + +/// How often, at most, a token's use is recorded (`tokens.last_used_at`), +/// where the instance lets browsers sit unused for long. +pub const TOUCH_MS: i64 = 10 * MINUTE_MS; + +/// The longest a token of `kind` lasts from its sign-in, where the policy +/// limits it. +pub fn max_age_ms(p: &SessionPolicy, kind: TokenKind) -> Option { + let (n, unit) = match kind { + TokenKind::Web => (p.browser_max_hours, HOUR_MS), + TokenKind::Cli => (p.cli_max_days, DAY_MS), + TokenKind::Pat => (p.access_token_max_days, DAY_MS), + }; + (n > 0).then(|| i64::from(n) * unit) +} + +/// How long a token of `kind` lasts unused. An access token lasts until +/// the end its maker chose, used or not. +pub fn idle_ms(p: &SessionPolicy, kind: TokenKind) -> Option { + match kind { + TokenKind::Web => Some(browser_idle_ms(p)), + TokenKind::Cli => Some(CLI_IDLE_MS), + TokenKind::Pat => None, + } +} + +/// How long a browser lasts unused, within the bounds a policy may set, +/// whatever was saved. +fn browser_idle_ms(p: &SessionPolicy) -> i64 { + let m = p + .browser_idle_minutes + .clamp(MIN_BROWSER_IDLE_MINUTES, DEFAULT_BROWSER_IDLE_MINUTES); + i64::from(m) * MINUTE_MS +} + +/// When a token of `kind` whose sign-in was at `created_at` ends, as it's +/// used at `now`: unused long enough, at its policy's longest, or at +/// `chosen`, the end its maker chose, whichever comes first. `None`: never. +pub fn expires_at( + p: &SessionPolicy, + kind: TokenKind, + created_at: i64, + now: i64, + chosen: Option, +) -> Option { + let idle = idle_ms(p, kind).map(|i| now.saturating_add(i)); + let max = max_age_ms(p, kind).map(|m| created_at.saturating_add(m)); + [chosen, idle, max].into_iter().flatten().min() +} + +/// Until when a browser keeps the cookie of a sign-in made at +/// `created_at`, as it's used at `now`: its policy's longest, and 30 days +/// from now at most, as before policies. Not its time unused: only +/// requests renew a cookie, and a tab that holds a socket open stays in +/// use without them ([`Token::in_use`]); the server ends a sign-in unused +/// too long whatever its cookie says. +pub fn cookie_until(p: &SessionPolicy, created_at: i64, now: i64) -> i64 { + let longest = now.saturating_add(i64::from(DEFAULT_BROWSER_IDLE_MINUTES) * MINUTE_MS); + max_age_ms(p, TokenKind::Web).map_or(longest, |m| created_at.saturating_add(m).min(longest)) +} + +/// How often a browser's use is recorded: often enough, where browsers +/// sign out after a short while unused, that one in use isn't taken for +/// unused between two records. +pub fn touch_after_ms(p: &SessionPolicy) -> i64 { + TOUCH_MS.min(browser_idle_ms(p) / 4) +} + +/// A browser's or CLI's sign-in, or an access token, as [`ended`] reads +/// it. +#[derive(Clone, Copy, Debug)] +pub struct Token { + pub kind: TokenKind, + /// When its sign-in was, or the access token was made. + pub created_at: i64, + /// When its use was last recorded. + pub last_used_at: Option, + /// When it ends, as kept. + pub expires_at: Option, + /// Its person is a member of the instance, not an admin. + pub member: bool, +} + +impl Token { + /// It as a socket opened with it reads it while it stays open: used at + /// `now`, as an open socket is in use though nothing records it. A + /// browser's or a CLI's stored end is its last recorded use plus the + /// time it may go unused, capped by the policy's longest, so it goes + /// too: [`ended`] applies that longest from its sign-in. An access + /// token keeps the end its maker chose. + pub fn in_use(self, now: i64) -> Self { + Self { + last_used_at: Some(now), + expires_at: match self.kind { + TokenKind::Pat => self.expires_at, + TokenKind::Web | TokenKind::Cli => None, + }, + ..self + } + } +} + +/// Why a token no longer signs its person in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ended { + /// It ended as kept: unused too long, or when its maker chose. + Expired, + /// Its sign-in is older than the policy lets one of its kind be. + TooOld, + /// A browser unused longer than the policy lets one be. + Unused, + /// A member's access token, where members make none. + MembersMakeNone, +} + +/// Whether, and why, `t` no longer signs its person in at `now` under +/// `p`. +pub fn ended(p: &SessionPolicy, t: &Token, now: i64) -> Option { + if t.expires_at.is_some_and(|e| e <= now) { + return Some(Ended::Expired); + } + if max_age_ms(p, t.kind).is_some_and(|m| t.created_at.saturating_add(m) <= now) { + return Some(Ended::TooOld); + } + if t.kind == TokenKind::Web + && t.last_used_at + .unwrap_or(t.created_at) + .saturating_add(browser_idle_ms(p)) + <= now + { + return Some(Ended::Unused); + } + if t.kind == TokenKind::Pat && t.member && !p.member_access_tokens { + return Some(Ended::MembersMakeNone); + } + None +} + +/// When `t` ends under `p`, unless it's used again first: as kept, or +/// sooner where the policy says less. What people see of it says this. +pub fn ends_at(p: &SessionPolicy, t: &Token) -> Option { + let max = max_age_ms(p, t.kind).map(|m| t.created_at.saturating_add(m)); + let unused = (t.kind == TokenKind::Web).then(|| { + t.last_used_at + .unwrap_or(t.created_at) + .saturating_add(browser_idle_ms(p)) + }); + [t.expires_at, max, unused].into_iter().flatten().min() +} + +/// What a CLI's or an access token's request that `why` refuses answers. +/// A browser's is signed out, and signs in again. +pub fn refusal(p: &SessionPolicy, kind: TokenKind, why: Ended) -> String { + match (kind, why) { + (TokenKind::Pat, Ended::MembersMakeNone) => { + "Only this instance's admins make access tokens now, so yours stopped working: use the CLI signed in as you (fctl login), or ask an admin.".to_owned() + } + (TokenKind::Pat, Ended::TooOld) => format!( + "This access token is older than this instance lets one last ({}): make another in Settings → Access tokens.", + days(p.access_token_max_days) + ), + (TokenKind::Cli, Ended::TooOld) => format!( + "This instance signs CLIs out {} after they sign in. Sign in again: fctl login", + days(p.cli_max_days) + ), + (TokenKind::Pat, _) => "This access token has expired: make another in Settings → Access tokens.".to_owned(), + _ => "Your sign-in has expired. Sign in again: fctl login".to_owned(), + } +} + +/// `a day`, `30 days`, `a year`. +pub fn days(n: u32) -> String { + match n { + 365 => "a year".to_owned(), + n => minutes(n.saturating_mul(1440)), + } +} + +/// `an hour`, `12 hours`, `a day`, `a week`. +pub fn hours(n: u32) -> String { + match n { + 8760 => "a year".to_owned(), + n => minutes(n.saturating_mul(60)), + } +} + +/// Checks `p` as an admin saves it: each limit within its bounds. +pub fn check(p: &SessionPolicy) -> Result<(), ApiError> { + if p.browser_max_hours > MAX_BROWSER_MAX_HOURS { + return Err(ApiError::validation( + "browser_max_hours", + format!( + "A browser can be kept signed in {MAX_BROWSER_MAX_HOURS} hours (a year) at most: 0 lets it stay as long as it's used" + ), + )); + } + if !(MIN_BROWSER_IDLE_MINUTES..=DEFAULT_BROWSER_IDLE_MINUTES).contains(&p.browser_idle_minutes) + { + return Err(ApiError::validation( + "browser_idle_minutes", + format!( + "A browser unused for {MIN_BROWSER_IDLE_MINUTES} minutes to 30 days ({DEFAULT_BROWSER_IDLE_MINUTES} minutes) can be signed out" + ), + )); + } + if p.cli_max_days > MAX_CLI_MAX_DAYS { + return Err(ApiError::validation( + "cli_max_days", + format!( + "A CLI can be kept signed in {MAX_CLI_MAX_DAYS} days at most: 0 lets it stay as long as it's used" + ), + )); + } + if p.access_token_max_days > MAX_ACCESS_TOKEN_DAYS { + return Err(ApiError::validation( + "access_token_max_days", + format!( + "Access tokens can be made to last {MAX_ACCESS_TOKEN_DAYS} days at most: 0 lets their makers choose" + ), + )); + } + Ok(()) +} + +/// Checks the days a new access token is to last (`None`: for ever) +/// against the longest `p` lets one. +pub fn check_token_days(p: &SessionPolicy, days_asked: Option) -> Result<(), ApiError> { + let max = p.access_token_max_days; + if max > 0 && days_asked.is_none_or(|d| d > max) { + // In days, as people choose a token's: "1 day", "90 days". + let longest = if max == 1 { + "1 day".to_owned() + } else { + format!("{max} days") + }; + return Err(ApiError::validation( + "expires_in_days", + format!("This instance's access tokens last {longest} at most: choose that or less"), + )); + } + Ok(()) +} + +/// Whether `next` lets sign-ins last longer than `current`, or lets +/// members make access tokens again: such a change takes confirming it's +/// you. +pub fn relaxes(current: &SessionPolicy, next: &SessionPolicy) -> bool { + // 0 is no limit: longer than any. + let longer = |was: u32, now: u32| was > 0 && (now == 0 || now > was); + longer(current.browser_max_hours, next.browser_max_hours) + || next.browser_idle_minutes > current.browser_idle_minutes + || longer(current.cli_max_days, next.cli_max_days) + || longer(current.access_token_max_days, next.access_token_max_days) + || (!current.member_access_tokens && next.member_access_tokens) +} + +/// What `p` says, a sentence for browsers, CLIs and access tokens each. +pub fn describe(p: &SessionPolicy) -> Vec { + let idle = minutes(p.browser_idle_minutes); + let browsers = if p.browser_max_hours > 0 { + format!( + "Browsers sign in again after {}, and after {idle} unused.", + hours(p.browser_max_hours) + ) + } else { + format!("Browsers stay signed in while they're used, until {idle} unused.") + }; + let clis = if p.cli_max_days > 0 { + format!( + "CLIs sign in again after {}, and after 180 days unused.", + days(p.cli_max_days) + ) + } else { + "CLIs stay signed in while they're used, until 180 days unused.".to_owned() + }; + let who = if p.member_access_tokens { + "Everyone makes access tokens" + } else { + "Only admins make access tokens" + }; + let tokens = if p.access_token_max_days > 0 { + format!( + "{who}, each lasting {} at most.", + days(p.access_token_max_days) + ) + } else { + format!("{who}, each lasting as long as its maker chooses.") + }; + vec![browsers, clis, tokens] +} + +#[cfg(test)] +mod tests { + use super::*; + + fn policy() -> SessionPolicy { + SessionPolicy::default() + } + + fn token(kind: TokenKind, created_at: i64, last_used_at: Option) -> Token { + Token { + kind, + created_at, + last_used_at, + expires_at: None, + member: true, + } + } + + #[test] + fn by_default_sign_ins_last_as_they_did() { + let p = policy(); + // A browser: 30 days after its last use; a CLI: 180. + assert_eq!( + expires_at(&p, TokenKind::Web, 0, 5 * DAY_MS, None), + Some(35 * DAY_MS) + ); + assert_eq!( + expires_at(&p, TokenKind::Cli, 0, DAY_MS, None), + Some(181 * DAY_MS) + ); + // An access token: when its maker chose, or never. + assert_eq!(expires_at(&p, TokenKind::Pat, 0, DAY_MS, None), None); + assert_eq!( + expires_at(&p, TokenKind::Pat, 0, DAY_MS, Some(90 * DAY_MS)), + Some(90 * DAY_MS) + ); + // Used often, nothing ends. + let used = token(TokenKind::Web, 0, Some(400 * DAY_MS)); + assert_eq!(ended(&p, &used, 401 * DAY_MS), None); + assert_eq!(touch_after_ms(&p), TOUCH_MS); + } + + #[test] + fn a_policy_caps_each_kind_from_its_sign_in() { + let p = SessionPolicy { + browser_max_hours: 12, + cli_max_days: 30, + access_token_max_days: 90, + ..policy() + }; + // However recently it's used, a browser ends 12 hours in. + assert_eq!( + expires_at(&p, TokenKind::Web, 0, 11 * HOUR_MS, None), + Some(12 * HOUR_MS) + ); + assert_eq!( + ended( + &p, + &token(TokenKind::Web, 0, Some(11 * HOUR_MS)), + 12 * HOUR_MS + ), + Some(Ended::TooOld) + ); + assert_eq!( + expires_at(&p, TokenKind::Cli, 0, DAY_MS, None), + Some(30 * DAY_MS) + ); + // An access token made to last for ever lasts 90 days; one that + // ends sooner, then. + assert_eq!( + expires_at(&p, TokenKind::Pat, 0, 0, None), + Some(90 * DAY_MS) + ); + assert_eq!( + expires_at(&p, TokenKind::Pat, 0, 0, Some(7 * DAY_MS)), + Some(7 * DAY_MS) + ); + // Made before the policy, it ends once it's that old, and says so. + assert_eq!( + ended(&p, &token(TokenKind::Pat, 0, None), 90 * DAY_MS), + Some(Ended::TooOld) + ); + assert_eq!( + ends_at(&p, &token(TokenKind::Pat, 0, None)), + Some(90 * DAY_MS) + ); + let soon = Token { + expires_at: Some(DAY_MS), + ..token(TokenKind::Pat, 0, None) + }; + assert_eq!(ends_at(&p, &soon), Some(DAY_MS)); + assert_eq!(ends_at(&policy(), &token(TokenKind::Pat, 0, None)), None); + // A browser: at the first of its policy's longest and its time + // unused. + assert_eq!( + ends_at(&p, &token(TokenKind::Web, 0, Some(HOUR_MS))), + Some(12 * HOUR_MS) + ); + assert_eq!( + ended(&p, &token(TokenKind::Pat, 0, None), 89 * DAY_MS), + None + ); + } + + #[test] + fn browsers_unused_too_long_sign_out() { + let p = SessionPolicy { + browser_idle_minutes: 15, + ..policy() + }; + let t = token(TokenKind::Web, 0, Some(HOUR_MS)); + assert_eq!(ended(&p, &t, HOUR_MS + 14 * MINUTE_MS), None); + assert_eq!(ended(&p, &t, HOUR_MS + 15 * MINUTE_MS), Some(Ended::Unused)); + // Never used since its sign-in: from then. + let fresh = token(TokenKind::Web, 0, None); + assert_eq!(ended(&p, &fresh, 15 * MINUTE_MS), Some(Ended::Unused)); + // CLIs and access tokens aren't browsers. + assert_eq!( + ended(&p, &token(TokenKind::Cli, 0, None), 15 * MINUTE_MS), + None + ); + // Its use is recorded often enough not to be taken for unused. + assert!(touch_after_ms(&p) * 4 <= 15 * MINUTE_MS); + // Out of bounds as saved, it reads within them. + let short = SessionPolicy { + browser_idle_minutes: 0, + ..policy() + }; + assert_eq!( + expires_at(&short, TokenKind::Web, 0, 0, None), + Some(5 * MINUTE_MS) + ); + } + + #[test] + fn a_cookie_lasts_as_long_as_its_sign_in_may() { + // Not just the time a browser may sit unused: a socket keeps it in + // use without requests that renew its cookie. + let idle = SessionPolicy { + browser_idle_minutes: 15, + ..policy() + }; + assert_eq!(cookie_until(&idle, 0, HOUR_MS), HOUR_MS + 30 * DAY_MS); + // Its longest, from its sign-in. + let short = SessionPolicy { + browser_max_hours: 12, + ..idle + }; + assert_eq!(cookie_until(&short, 0, HOUR_MS), 12 * HOUR_MS); + assert_eq!(cookie_until(&policy(), 0, 0), 30 * DAY_MS); + } + + #[test] + fn an_open_socket_is_in_use() { + let p = SessionPolicy { + browser_max_hours: 12, + browser_idle_minutes: 15, + ..policy() + }; + // A browser last recorded in use an hour ago, its stored end the + // 15 minutes after: a request ends it, its open socket doesn't. + let watching = Token { + expires_at: Some(15 * MINUTE_MS), + ..token(TokenKind::Web, 0, Some(0)) + }; + assert_eq!(ended(&p, &watching, HOUR_MS), Some(Ended::Expired)); + assert_eq!(ended(&p, &watching.in_use(HOUR_MS), HOUR_MS), None); + // Past the policy's longest from its sign-in, it ends either way. + assert_eq!( + ended(&p, &watching.in_use(12 * HOUR_MS), 12 * HOUR_MS), + Some(Ended::TooOld) + ); + // An access token keeps its maker's end. + let pat = Token { + expires_at: Some(HOUR_MS), + ..token(TokenKind::Pat, 0, None) + }; + assert_eq!( + ended(&p, &pat.in_use(HOUR_MS), HOUR_MS), + Some(Ended::Expired) + ); + } + + #[test] + fn members_tokens_stop_where_members_make_none() { + let p = SessionPolicy { + member_access_tokens: false, + ..policy() + }; + let member = token(TokenKind::Pat, 0, None); + assert_eq!(ended(&p, &member, 1), Some(Ended::MembersMakeNone)); + let admin = Token { + member: false, + ..member + }; + assert_eq!(ended(&p, &admin, 1), None); + // Their CLIs stay signed in. + assert_eq!(ended(&p, &token(TokenKind::Cli, 0, None), 1), None); + assert!(refusal(&p, TokenKind::Pat, Ended::MembersMakeNone).contains("fctl login")); + } + + #[test] + fn ended_as_kept_comes_first() { + let t = Token { + expires_at: Some(10), + ..token(TokenKind::Pat, 0, None) + }; + assert_eq!(ended(&policy(), &t, 10), Some(Ended::Expired)); + assert_eq!(ended(&policy(), &t, 9), None); + } + + #[test] + fn policies_are_checked_as_they_are_saved() { + assert!(check(&policy()).is_ok()); + for bad in [ + SessionPolicy { + browser_max_hours: MAX_BROWSER_MAX_HOURS + 1, + ..policy() + }, + SessionPolicy { + browser_idle_minutes: MIN_BROWSER_IDLE_MINUTES - 1, + ..policy() + }, + SessionPolicy { + browser_idle_minutes: DEFAULT_BROWSER_IDLE_MINUTES + 1, + ..policy() + }, + SessionPolicy { + cli_max_days: MAX_CLI_MAX_DAYS + 1, + ..policy() + }, + SessionPolicy { + access_token_max_days: MAX_ACCESS_TOKEN_DAYS + 1, + ..policy() + }, + ] { + assert!(check(&bad).is_err(), "{bad:?}"); + } + } + + #[test] + fn new_tokens_last_no_longer_than_the_policy_lets_them() { + let p = SessionPolicy { + access_token_max_days: 90, + ..policy() + }; + assert!(check_token_days(&p, Some(90)).is_ok()); + assert!(check_token_days(&p, Some(7)).is_ok()); + let refused = check_token_days(&p, Some(365)).err(); + assert_eq!( + refused.map(|e| e.message), + Some( + "This instance's access tokens last 90 days at most: choose that or less" + .to_owned() + ) + ); + let year = SessionPolicy { + access_token_max_days: 365, + ..policy() + }; + assert!( + check_token_days(&year, None) + .err() + .is_some_and(|e| e.message.contains("last 365 days at most")) + ); + let day = SessionPolicy { + access_token_max_days: 1, + ..policy() + }; + assert!( + check_token_days(&day, Some(7)) + .err() + .is_some_and(|e| e.message.contains("last 1 day at most")) + ); + // For ever is longer than any. + assert!(check_token_days(&p, None).is_err()); + assert!(check_token_days(&policy(), None).is_ok()); + } + + #[test] + fn longer_sign_ins_and_members_tokens_relax_a_policy() { + let strict = SessionPolicy { + browser_max_hours: 12, + browser_idle_minutes: 60, + cli_max_days: 30, + access_token_max_days: 90, + member_access_tokens: false, + }; + assert!(!relaxes(&strict, &strict)); + assert!(!relaxes(&policy(), &strict)); + for looser in [ + SessionPolicy { + browser_max_hours: 0, + ..strict.clone() + }, + SessionPolicy { + browser_max_hours: 24, + ..strict.clone() + }, + SessionPolicy { + browser_idle_minutes: 120, + ..strict.clone() + }, + SessionPolicy { + cli_max_days: 0, + ..strict.clone() + }, + SessionPolicy { + access_token_max_days: 365, + ..strict.clone() + }, + SessionPolicy { + member_access_tokens: true, + ..strict.clone() + }, + ] { + assert!(relaxes(&strict, &looser), "{looser:?}"); + } + } + + #[test] + fn a_policy_reads_as_sentences() { + assert_eq!( + describe(&policy()), + [ + "Browsers stay signed in while they're used, until 30 days unused.", + "CLIs stay signed in while they're used, until 180 days unused.", + "Everyone makes access tokens, each lasting as long as its maker chooses.", + ] + ); + let strict = SessionPolicy { + browser_max_hours: 12, + browser_idle_minutes: 60, + cli_max_days: 30, + access_token_max_days: 365, + member_access_tokens: false, + }; + assert_eq!( + describe(&strict), + [ + "Browsers sign in again after 12 hours, and after an hour unused.", + "CLIs sign in again after 30 days, and after 180 days unused.", + "Only admins make access tokens, each lasting a year at most.", + ] + ); + } +} diff --git a/crates/fctl-domain/src/verify.rs b/crates/fctl-domain/src/verify.rs index c2d9aedb..717f00ea 100644 --- a/crates/fctl-domain/src/verify.rs +++ b/crates/fctl-domain/src/verify.rs @@ -125,6 +125,10 @@ pub enum Sensitive { /// domain requires the provider, whoever next signs in with its address /// there links to their account. UnlinkSignIn, + /// Letting sign-ins and access tokens last longer, members make access + /// tokens again (`fctl_domain::session_policy::relaxes`), or people sign + /// in from more networks (`fctl_domain::networks::widens`). + RelaxSessions, } impl Sensitive { @@ -168,6 +172,9 @@ impl Sensitive { } RelaxSignIn => "let people sign in another way than their domain's provider", UnlinkSignIn => "unlink someone's sign-in account", + RelaxSessions => { + "let sign-ins or access tokens last longer, or come from more networks" + } } } } @@ -255,11 +262,41 @@ pub fn instance_settings_change( .is_some_and(|next| relaxes(¤t.sign_in, next)) { Some(Sensitive::RelaxSignIn) + } else if crate::session_policy::relaxes( + ¤t.session_policy(), + &session_policy(current, update), + ) || update + .networks + .as_ref() + .is_some_and(|next| crate::networks::widens(¤t.networks, next)) + { + Some(Sensitive::RelaxSessions) } else { None } } +/// The session policy `update` leaves the instance with, from `current`. +pub fn session_policy( + current: &InstanceSettings, + update: &UpdateInstanceSettingsRequest, +) -> fctl_proto::api::SessionPolicy { + let was = current.session_policy(); + fctl_proto::api::SessionPolicy { + browser_max_hours: update.browser_max_hours.unwrap_or(was.browser_max_hours), + browser_idle_minutes: update + .browser_idle_minutes + .unwrap_or(was.browser_idle_minutes), + cli_max_days: update.cli_max_days.unwrap_or(was.cli_max_days), + access_token_max_days: update + .access_token_max_days + .unwrap_or(was.access_token_max_days), + member_access_tokens: update + .member_access_tokens + .unwrap_or(was.member_access_tokens), + } +} + /// Whether `next` lets anyone sign in a way `current` doesn't: a domain /// that no longer requires its provider, or requires another, or whose /// people's passkeys alone sign them in now. @@ -572,6 +609,70 @@ mod tests { ); } + #[test] + fn letting_sign_ins_last_longer_is_sensitive() { + let current = InstanceSettings { + browser_max_hours: 12, + member_access_tokens: false, + ..Default::default() + }; + let change = + |update: UpdateInstanceSettingsRequest| instance_settings_change(¤t, &update); + let relaxes = Some(Sensitive::RelaxSessions); + assert_eq!( + change(UpdateInstanceSettingsRequest { + browser_max_hours: Some(0), + ..Default::default() + }), + relaxes + ); + assert_eq!( + change(UpdateInstanceSettingsRequest { + member_access_tokens: Some(true), + ..Default::default() + }), + relaxes + ); + // Shorter, or the same, isn't; nor is a first limit. + assert_eq!( + change(UpdateInstanceSettingsRequest { + browser_max_hours: Some(8), + member_access_tokens: Some(false), + cli_max_days: Some(30), + ..Default::default() + }), + None + ); + assert_eq!(change(UpdateInstanceSettingsRequest::default()), None); + // Networks: anywhere again, or one more; not fewer. + let inside = InstanceSettings { + networks: vec!["10.0.0.0/8".to_owned()], + ..Default::default() + }; + let networks = |next: &[&str]| { + instance_settings_change( + &inside, + &UpdateInstanceSettingsRequest { + networks: Some(next.iter().map(|n| (*n).to_owned()).collect()), + ..Default::default() + }, + ) + }; + assert_eq!(networks(&[]), relaxes); + assert_eq!(networks(&["10.0.0.0/8", "192.0.2.0/24"]), relaxes); + assert_eq!(networks(&["10.0.0.0/8"]), None); + assert_eq!( + instance_settings_change( + &InstanceSettings::default(), + &UpdateInstanceSettingsRequest { + networks: Some(vec!["10.0.0.0/8".to_owned()]), + ..Default::default() + } + ), + None + ); + } + #[test] fn only_the_primary_instance_owner_turns_it_on_or_off() { for (current, next) in [(false, true), (true, false)] { diff --git a/crates/fctl-proto/src/api.rs b/crates/fctl-proto/src/api.rs index c2d53696..d3bbc425 100644 --- a/crates/fctl-proto/src/api.rs +++ b/crates/fctl-proto/src/api.rs @@ -56,6 +56,13 @@ pub struct SignInInfo { /// ([`InstanceSettings::self_sign_up`]). Off, the page tells people /// without an account to ask an admin. pub self_sign_up: bool, + /// This request comes from outside the networks the instance takes + /// sign-ins from ([`InstanceSettings::networks`]): the page says so, + /// as only the primary instance owner signs in from here. Absent from + /// control planes before it. + #[serde(default)] + #[cfg_attr(feature = "ts", ts(as = "Option", optional))] + pub outside: bool, } /// A provider people sign in with: Google, or (later) another OpenID @@ -328,6 +335,10 @@ pub struct Me { /// of the people at a domain of one of your addresses /// ([`InstanceSettings::sign_in`]). Absent where none does. pub sign_in: Option, + /// How long your sign-ins last and whether you make access tokens, as + /// the instance's admins set them. Absent for limited tokens, and from + /// control planes before it. + pub sessions: Option, } /// How someone signs in, as a domain of one of their addresses requires @@ -1769,6 +1780,104 @@ pub struct InstanceSettings { /// trouble at Claude doesn't: [`DEFAULT_CLAUDE_REFUSALS`] by default, /// 1 to [`MAX_CLAUDE_REFUSALS`]. pub claude_refusals: u32, + /// A browser stays signed in at most this many hours after its sign-in, + /// however much it's used; then its person signs in again, through + /// their domain's provider where one is required, which checks they + /// may. 0 (the default): as long as it's used. At most + /// [`MAX_BROWSER_MAX_HOURS`]. + pub browser_max_hours: u32, + /// A browser unused this many minutes is signed out: no request with + /// its sign-in, a tab that shows something live keeping it in use. + /// [`DEFAULT_BROWSER_IDLE_MINUTES`] (30 days) by default, at least + /// [`MIN_BROWSER_IDLE_MINUTES`]. + pub browser_idle_minutes: u32, + /// A CLI stays signed in at most this many days after its sign-in; + /// then it signs in again with `fctl login`. 0 (the default): as long + /// as it's used, until 180 days unused. At most [`MAX_CLI_MAX_DAYS`]. + pub cli_max_days: u32, + /// An access token lasts at most this many days after it's made: new + /// ones can't be made to last longer, and older ones end then. 0 (the + /// default): as long as their maker chose, for ever included. At most + /// [`MAX_ACCESS_TOKEN_DAYS`]. + pub access_token_max_days: u32, + /// Members make access tokens. Off, only instance admins and the + /// primary instance owner make them, and members' stop working: they + /// use the CLI, signed in as themselves. On by default. + pub member_access_tokens: bool, + /// The networks people sign in and send requests from, as CIDR ranges + /// (`203.0.113.0/24`, `2001:db8::/32`): an office's, a VPN's. Browsers, + /// CLIs, access tokens, admin tokens and service accounts outside them + /// are refused; runners, webhooks and published links aren't held to + /// them, and the primary instance owner signs in from anywhere, in a + /// browser or the CLI. None (the default): anywhere. At most + /// `fctl_domain::networks::MAX_NETWORKS`. + pub networks: Vec, +} + +/// How long sign-ins last and who makes access tokens: the instance's +/// session policies, as [`InstanceSettings`] keeps them +/// (`browser_max_hours` and the rest), each in the same unit. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(default)] +pub struct SessionPolicy { + pub browser_max_hours: u32, + pub browser_idle_minutes: u32, + pub cli_max_days: u32, + pub access_token_max_days: u32, + pub member_access_tokens: bool, +} + +impl Default for SessionPolicy { + fn default() -> Self { + InstanceSettings::default().session_policy() + } +} + +impl InstanceSettings { + /// Its session policies. + pub fn session_policy(&self) -> SessionPolicy { + SessionPolicy { + browser_max_hours: self.browser_max_hours, + browser_idle_minutes: self.browser_idle_minutes, + cli_max_days: self.cli_max_days, + access_token_max_days: self.access_token_max_days, + member_access_tokens: self.member_access_tokens, + } + } +} + +/// [`InstanceSettings::browser_idle_minutes`] by default: 30 days, the +/// longest it may be. +pub const DEFAULT_BROWSER_IDLE_MINUTES: u32 = 30 * 24 * 60; +/// The shortest [`InstanceSettings::browser_idle_minutes`]. +pub const MIN_BROWSER_IDLE_MINUTES: u32 = 5; +/// The longest [`InstanceSettings::browser_max_hours`]: a year. +pub const MAX_BROWSER_MAX_HOURS: u32 = 8760; +/// The longest [`InstanceSettings::cli_max_days`]: a year. +pub const MAX_CLI_MAX_DAYS: u32 = 365; +/// The longest [`InstanceSettings::access_token_max_days`], as long as an +/// access token may be made to last: ten years. +pub const MAX_ACCESS_TOKEN_DAYS: u32 = 3650; + +/// `POST /api/v1/admin/sign-in/sessions/preview`'s answer: what saving a +/// [`SessionPolicy`] in place of the instance's would end at once, before +/// anything changes. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct SessionPolicyPreview { + /// Browsers it signs out, which have been signed in longer than it lets + /// them, or unused longer. + pub browsers: u32, + /// CLIs it signs out, signed in longer than it lets them. + pub clis: u32, + /// Access tokens it ends: older than it lets them be, or members' where + /// members no longer make them. + pub access_tokens: u32, + /// Of `access_tokens`, those of members. + pub member_tokens: u32, + /// It signs out the browser or CLI this request comes from. + pub you: bool, } /// How the people at some domains sign in ([`InstanceSettings::sign_in`]): @@ -1825,6 +1934,18 @@ pub struct SignInOverview { /// The instance sends email: people hear when a rule changes how they /// sign in. pub email: bool, + /// How long sign-ins last and who makes access tokens. Its defaults + /// from control planes before it. + #[serde(default)] + #[cfg_attr(feature = "ts", ts(as = "Option", optional))] + pub sessions: SessionPolicy, + /// [`InstanceSettings::networks`]. None from control planes before it. + #[serde(default)] + #[cfg_attr(feature = "ts", ts(as = "Option>", optional))] + pub networks: Vec, + /// The address this request comes from, as the instance sees it: what a + /// network has to hold for the admin to stay in. + pub address: Option, } /// A provider as instance admins see it ([`SignInOverview::providers`]). @@ -1991,6 +2112,12 @@ impl Default for InstanceSettings { claude_limit_pauses: true, claude_instance_view: false, claude_refusals: DEFAULT_CLAUDE_REFUSALS, + browser_max_hours: 0, + browser_idle_minutes: DEFAULT_BROWSER_IDLE_MINUTES, + cli_max_days: 0, + access_token_max_days: 0, + member_access_tokens: true, + networks: Vec::new(), } } } @@ -2024,6 +2151,21 @@ pub struct UpdateInstanceSettingsRequest { pub claude_instance_view: Option, /// 1 to [`MAX_CLAUDE_REFUSALS`]. pub claude_refusals: Option, + /// 0 to [`MAX_BROWSER_MAX_HOURS`]. Saving a session policy ends at once + /// the sign-ins and access tokens it doesn't let last + /// ([`SessionPolicyPreview`]). + pub browser_max_hours: Option, + /// [`MIN_BROWSER_IDLE_MINUTES`] to [`DEFAULT_BROWSER_IDLE_MINUTES`]. + pub browser_idle_minutes: Option, + /// 0 to [`MAX_CLI_MAX_DAYS`]. + pub cli_max_days: Option, + /// 0 to [`MAX_ACCESS_TOKEN_DAYS`]. + pub access_token_max_days: Option, + pub member_access_tokens: Option, + /// Replaces the networks: `[]` for anywhere. Refused (`409`) where the + /// caller's own address would be outside them, unless they're the + /// primary instance owner. + pub networks: Option>, } // ───────────────────────────── workspaces ───────────────────────────── diff --git a/crates/fctl-proto/src/ts_export.rs b/crates/fctl-proto/src/ts_export.rs index 1ff0c969..1211b6e4 100644 --- a/crates/fctl-proto/src/ts_export.rs +++ b/crates/fctl-proto/src/ts_export.rs @@ -151,6 +151,8 @@ pub fn export_typescript(dir: &Path) -> Result<(), ExportError> { api::SignInOverview, api::SignInPreviewRequest, api::SignInPreview, + api::SessionPolicy, + api::SessionPolicyPreview, api::BaseRole, api::Workspace, api::WorkspaceList, diff --git a/crates/fctl/src/cmd/admin.rs b/crates/fctl/src/cmd/admin.rs index 253b8aee..f571e71c 100644 --- a/crates/fctl/src/cmd/admin.rs +++ b/crates/fctl/src/cmd/admin.rs @@ -145,7 +145,7 @@ pub enum AdminCmd { /// change those domains. #[command( name = "sign-in", - after_help = "Examples:\n fctl admin sign-in\n fctl admin sign-in require acme.com acme.dev # people at acme.com and acme.dev sign in with Google only\n fctl admin sign-in require acme.com --passkeys # passkeys alone sign them in too\n fctl admin sign-in unrequire acme.dev\n fctl admin set --self-sign-up off # accounts only from invitations and admin tokens" + after_help = "Examples:\n fctl admin sign-in\n fctl admin sign-in require acme.com acme.dev # people at acme.com and acme.dev sign in with Google only\n fctl admin sign-in require acme.com --passkeys # passkeys alone sign them in too\n fctl admin sign-in unrequire acme.dev\n fctl admin sign-in policies --browser-max 12h --browser-idle 1h # browsers sign in again twice a day\n fctl admin sign-in policies --token-max 90d --member-tokens off\n fctl admin sign-in policies --networks 203.0.113.0/24,2001:db8::/32 # sign-ins only from your office and VPN\n fctl admin set --self-sign-up off # accounts only from invitations and admin tokens" )] SignIn { #[command(subcommand)] @@ -761,6 +761,18 @@ fn print_settings(s: &InstanceSettings) { "Only invitations, addresses allowed one by one and admin tokens make accounts. `fctl admin sign-in` says more." }) ); + for line in fctl_domain::session_policy::describe(&s.session_policy()) { + println!(" {}", style::dim(&line)); + } + if !s.networks.is_empty() { + println!( + " {}", + style::dim(&format!( + "People sign in only from {}, the primary instance owner aside.", + fctl_domain::sign_in::domains_words(&s.networks) + )) + ); + } println!( "Published screenshots {}", if s.publish_screenshots { @@ -1483,6 +1495,7 @@ pub async fn run(server: Option<&str>, cmd: AdminCmd, json: bool) -> Result<()> claude_limit_pauses, claude_instance_view, claude_refusals, + ..UpdateInstanceSettingsRequest::default() }) .await?; if json { diff --git a/crates/fctl/src/cmd/sign_in.rs b/crates/fctl/src/cmd/sign_in.rs index 26e70b07..8853bb3c 100644 --- a/crates/fctl/src/cmd/sign_in.rs +++ b/crates/fctl/src/cmd/sign_in.rs @@ -5,10 +5,12 @@ use crate::style; use anyhow::{Result, bail}; use clap::Subcommand; use fctl_client::Api; +use fctl_domain::enrollment::parse_minutes; +use fctl_domain::session_policy::describe as describe_policy; use fctl_domain::sign_in::{GOOGLE, domains_words, with_required, without}; use fctl_proto::api::{ - SignInOverview, SignInPerson, SignInPreview, SignInRule, SignInYou, - UpdateInstanceSettingsRequest, + SessionPolicy, SessionPolicyPreview, SignInOverview, SignInPerson, SignInPreview, SignInRule, + SignInYou, UpdateInstanceSettingsRequest, }; use std::io::{BufRead, IsTerminal, Write}; @@ -49,6 +51,45 @@ pub enum SignInCmd { #[arg(long)] yes: bool, }, + /// Show or change how long sign-ins last and who makes access tokens. + /// A change shows what it ends at once (browsers and CLIs signed in + /// longer than it lets them, access tokens older) and asks first, + /// unless --yes. Letting them last longer takes confirming it's you, + /// where the instance asks for that. + Policies { + /// How long a browser stays signed in after its sign-in, however + /// much it's used, in whole hours (12h, 1d, 7d), or `none`: as + /// long as it's used. + #[arg(long, value_name = "DURATION|none")] + browser_max: Option, + /// How long a browser may go unused before it's signed out: 5m to + /// 30d (the default). + #[arg(long, value_name = "DURATION")] + browser_idle: Option, + /// How long a CLI stays signed in after `fctl login`, in whole days + /// (30d), or `none`: as long as it's used, until 180 days unused. + #[arg(long, value_name = "DURATION|none")] + cli_max: Option, + /// The longest an access token may last, in whole days (90d), or + /// `none`: as long as its maker chooses. Older ones end. + #[arg(long, value_name = "DURATION|none")] + token_max: Option, + /// Whether members make access tokens. Off, only admins do, and + /// members' stop working: they use the CLI signed in as + /// themselves. + #[arg(long, value_name = "ON|OFF", value_parser = clap::builder::BoolishValueParser::new(), hide_possible_values = true)] + member_tokens: Option, + /// The networks people sign in and send requests from, as CIDR + /// ranges separated by commas (203.0.113.0/24,2001:db8::/32), or + /// `any`. Runners and webhooks connect from anywhere, and the + /// primary instance owner signs in from anywhere. Your own address + /// has to be in them. + #[arg(long, value_name = "RANGES|any")] + networks: Option, + /// Save it without asking. + #[arg(long)] + yes: bool, + }, } pub async fn run(api: &Api, cmd: Option, json: bool) -> Result<()> { @@ -81,10 +122,236 @@ pub async fn run(api: &Api, cmd: Option, json: bool) -> Result<()> { } change(api, &overview, next, yes, json).await?; } + SignInCmd::Policies { + browser_max, + browser_idle, + cli_max, + token_max, + member_tokens, + networks, + yes, + } => { + let overview = api.sign_in_overview().await?; + let was = Policies { + sessions: overview.sessions.clone(), + networks: overview.networks.clone(), + }; + let mut next = was.sessions.clone(); + if let Some(d) = browser_max { + next.browser_max_hours = whole(&d, 60, "hours", "12h or 1d")?; + } + if let Some(d) = browser_idle { + next.browser_idle_minutes = parse_minutes(&d) + .map_err(anyhow::Error::msg)? + .ok_or_else(|| { + anyhow::anyhow!( + "Browsers are signed out after 30 days unused at most: give 5m to 30d" + ) + })?; + } + if let Some(d) = cli_max { + next.cli_max_days = whole(&d, 1440, "days", "30d")?; + } + if let Some(d) = token_max { + next.access_token_max_days = whole(&d, 1440, "days", "90d")?; + } + if let Some(on) = member_tokens { + next.member_access_tokens = on; + } + let next = Policies { + sessions: next, + networks: match networks.as_deref().map(str::trim) { + Some("any" | "anywhere" | "none" | "") => Vec::new(), + Some(list) => network_list(list)?, + None => was.networks.clone(), + }, + }; + if next == was { + if json { + return style::print_json(&was); + } + print_policy(&was); + return Ok(()); + } + change_policy(api, &overview, &was, next, yes, json).await?; + } } Ok(()) } +/// A duration as people type it (`12h`, `7d`), in whole `unit`s of `per` +/// minutes; `none` is 0, no limit. +fn whole(input: &str, per: u32, unit: &str, example: &str) -> Result { + match parse_minutes(input).map_err(anyhow::Error::msg)? { + None => Ok(0), + Some(m) if m % per == 0 => Ok(m / per), + Some(_) => bail!("{input:?} isn't whole {unit}: give one like {example}, or none"), + } +} + +/// How long sign-ins last, who makes access tokens and where people sign +/// in from: what `fctl admin sign-in policies` shows and changes. +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +struct Policies { + #[serde(flatten)] + sessions: SessionPolicy, + networks: Vec, +} + +/// Ranges as typed: by commas or spaces, each checked as the instance +/// checks them. +fn network_list(list: &str) -> Result> { + let typed: Vec = list + .split([',', ' ']) + .filter(|n| !n.trim().is_empty()) + .map(str::to_owned) + .collect(); + fctl_domain::networks::check(&typed).map_err(|e| anyhow::anyhow!(e.message)) +} + +/// Shows what saving `next` ends at once, asks unless `yes`, saves it and +/// shows the policies now. +async fn change_policy( + api: &Api, + overview: &SignInOverview, + was: &Policies, + next: Policies, + yes: bool, + json: bool, +) -> Result<()> { + if next.sessions != was.sessions { + let preview = api.session_policy_preview(&next.sessions).await?; + for line in policy_consequences(&preview) { + eprintln!("{line}"); + } + } + if next.networks != was.networks { + eprintln!( + "{}", + networks_consequence(&next.networks, overview.address.as_deref()) + ); + } + if !yes { + if !std::io::stdin().is_terminal() { + bail!("Not saved: pass --yes to save it without being asked"); + } + eprint!("Save it? [y/N] "); + std::io::stderr().flush()?; + let mut line = String::new(); + std::io::stdin().lock().read_line(&mut line)?; + if !matches!(line.trim(), "y" | "Y" | "yes" | "Yes") { + bail!("Not saved"); + } + } + let p = &next.sessions; + let saved = api + .update_instance_settings(&UpdateInstanceSettingsRequest { + browser_max_hours: Some(p.browser_max_hours), + browser_idle_minutes: Some(p.browser_idle_minutes), + cli_max_days: Some(p.cli_max_days), + access_token_max_days: Some(p.access_token_max_days), + member_access_tokens: Some(p.member_access_tokens), + networks: (next.networks != was.networks).then(|| next.networks.clone()), + ..UpdateInstanceSettingsRequest::default() + }) + .await?; + let now = Policies { + sessions: saved.session_policy(), + networks: saved.networks, + }; + if json { + return style::print_json(&now); + } + println!("{} Saved", style::accent("✓")); + print_policy(&now); + Ok(()) +} + +/// What saving `networks` does, for a request from `address`. +fn networks_consequence(networks: &[String], address: Option<&str>) -> String { + if networks.is_empty() { + return "People sign in and send requests from anywhere again.".to_owned(); + } + let you = match address { + Some(a) if fctl_domain::networks::admits(networks, Some(a)) => { + format!("your address, {a}, is in them") + } + Some(a) => format!( + "your address, {a}, isn't in them: only the primary instance owner saves them from outside" + ), + None => "fctl can't tell your address".to_owned(), + }; + format!( + "People sign in and send requests only from {}, the primary instance owner's browser and CLI aside; {you}. Runners and webhooks connect from anywhere.", + domains_words(networks) + ) +} + +/// What saving a session policy ends, in the sentences the web app shows +/// too. +pub fn policy_consequences(p: &SessionPolicyPreview) -> Vec { + let count = |n: u32, one: &str, many: &str| { + if n == 1 { + format!("1 {one}") + } else { + format!("{n} {many}") + } + }; + let mut signed_out = Vec::new(); + if p.browsers > 0 { + signed_out.push(count(p.browsers, "browser", "browsers")); + } + if p.clis > 0 { + signed_out.push(count(p.clis, "CLI", "CLIs")); + } + let mut lines = Vec::new(); + if !signed_out.is_empty() { + lines.push(format!( + "Saving signs out {} at once{}: their people sign in again.", + domains_words(&signed_out), + if p.you { ", yours among them" } else { "" } + )); + } else if p.you { + lines.push("Saving signs you out at once: you sign in again.".to_owned()); + } + if p.access_tokens > 0 { + let members = match p.member_tokens { + 0 => String::new(), + 1 if p.access_tokens == 1 => ", a member's".to_owned(), + n if n == p.access_tokens => ", all of them members'".to_owned(), + n => format!(", {n} of them members'"), + }; + lines.push(format!( + "It ends {}{members}: scripts and CI that use {} need new ones.", + count(p.access_tokens, "access token", "access tokens"), + if p.access_tokens == 1 { "it" } else { "them" } + )); + } + if lines.is_empty() { + lines.push("Nobody is signed out now: sign-ins end as it says from here on.".to_owned()); + } + lines +} + +fn print_policy(p: &Policies) { + for line in describe_policy(&p.sessions) { + println!("{line}"); + } + println!("{}", networks_line(&p.networks)); +} + +/// Where people sign in from, in a sentence. +fn networks_line(networks: &[String]) -> String { + if networks.is_empty() { + "People sign in from anywhere.".to_owned() + } else { + format!( + "People sign in only from {}, the primary instance owner aside.", + domains_words(networks) + ) + } +} + /// Shows what saving `next` would do, asks unless `yes`, saves it and /// shows how people sign in now. What it shows before it asks goes to /// stderr, so that `--json` leaves stdout to the result. @@ -331,6 +598,11 @@ fn print_overview(o: &SignInOverview) { o.no_way_in )) ); + println!("{}", style::bold("Staying signed in")); + for line in describe_policy(&o.sessions) { + println!(" {}", style::dim(&line)); + } + println!(" {}", style::dim(&networks_line(&o.networks))); if let Some(owner) = &o.owner && !o.rules.is_empty() { @@ -413,4 +685,61 @@ mod tests { }; assert_eq!(consequences(&quiet, "Google"), ["Nobody's way in changes."]); } + + #[test] + fn a_session_policy_says_what_it_ends() { + let p = SessionPolicyPreview { + browsers: 14, + clis: 1, + access_tokens: 5, + member_tokens: 3, + you: true, + }; + assert_eq!( + policy_consequences(&p), + [ + "Saving signs out 14 browsers and 1 CLI at once, yours among them: their people sign in again.", + "It ends 5 access tokens, 3 of them members': scripts and CI that use them need new ones.", + ] + ); + let one = SessionPolicyPreview { + access_tokens: 1, + member_tokens: 1, + ..SessionPolicyPreview::default() + }; + assert_eq!( + policy_consequences(&one), + ["It ends 1 access token, a member's: scripts and CI that use it need new ones."] + ); + assert_eq!( + policy_consequences(&SessionPolicyPreview::default()), + ["Nobody is signed out now: sign-ins end as it says from here on."] + ); + } + + #[test] + fn networks_say_whether_you_stay_in() { + let nets = network_list("203.0.113.0/24, 10.0.0.0/8").unwrap_or_default(); + assert_eq!(nets, ["203.0.113.0/24", "10.0.0.0/8"]); + assert!(network_list("acme.com").is_err()); + assert!( + networks_consequence(&nets, Some("203.0.113.9")) + .contains("your address, 203.0.113.9, is in them") + ); + assert!(networks_consequence(&nets, Some("198.51.100.1")).contains("isn't in them")); + assert_eq!( + networks_consequence(&[], None), + "People sign in and send requests from anywhere again." + ); + } + + #[test] + fn policy_durations_read_in_whole_units() { + assert_eq!(whole("12h", 60, "hours", "12h").ok(), Some(12)); + assert_eq!(whole("1d", 60, "hours", "12h").ok(), Some(24)); + assert_eq!(whole("none", 60, "hours", "12h").ok(), Some(0)); + assert_eq!(whole("90d", 1440, "days", "90d").ok(), Some(90)); + assert!(whole("36h", 1440, "days", "30d").is_err()); + assert!(whole("90m", 60, "hours", "12h").is_err()); + } } diff --git a/docs/adr/0102-instances-limit-how-long-sign-ins-last.md b/docs/adr/0102-instances-limit-how-long-sign-ins-last.md new file mode 100644 index 00000000..55282fdb --- /dev/null +++ b/docs/adr/0102-instances-limit-how-long-sign-ins-last.md @@ -0,0 +1,72 @@ +# 0102: Instances limit how long sign-ins last + +2026-11-25 · accepted + +## Context + +A browser signed in to fctl stayed signed in while it was used, until 30 +days unused; a CLI until 180 days unused; an access token as long as its +maker chose, for ever included. Once an organization requires its +provider of its domains ([ADR 0099](0099-domains-require-signing-in-with-their-provider.md)), +closing someone's account at the provider stops their next sign-in, but +not the sign-ins they have: someone who left kept fctl for as long as +their laptop's browser or CLI stayed in use. Google offers OpenID +Connect apps no back-channel logout, and its Cross-Account Protection +events, which could tell fctl of some closed accounts, take a service +account of each organization's to receive. Security +teams also ask for limits of their own: a browser that signs in again +every working day, a CLI every month, no access token older than 90 +days, and no tokens made by people outside a few admins (#618). + +## Decision + +- **Instance admins set session policies**, beside the rules: how long a + browser stays signed in from its sign-in however much it's used, how + long one may sit unused (30 days, the default, at most), how long a + CLI stays signed in from `fctl login`, the oldest an access token may + be, and whether members make access tokens. Each limit is off by + default but the browser's unused one, which keeps its 30 days: nothing + changes until an admin says so. +- **A policy holds every sign-in, those made before it too.** Every + request checks its token against it, as it checks the rules, and saving + one deletes at once what it ends, so that nothing it ended comes back + when it's relaxed. Admin → Sign-in and `fctl admin sign-in policies` + say what saving ends before it saves, and letting anything last longer + is a sensitive action. +- **Signing in again goes through the provider.** That is how a closed + account ends: the shorter the policy, the sooner. Access tokens don't + sign in again, so their limit and who makes them are part of the + policy. +- **Unused means no request.** The control plane sees requests, not + people: a tab left open on a page that updates itself counts as use, + and the pages say so. +- **Admin tokens and service accounts' secrets aren't held to it.** They + are machines' credentials, made by admins for a directory sync or a bot + with an end of their own, and ending them with people's would stop the + sync that offboards people. +- **The primary instance owner is held to it like everyone else.** A + policy ends sign-ins and nothing more: whoever it signs out signs in + again, the owner with their password while the provider is down. +- **Networks keep sign-ins and requests to some IP ranges**, with the + same exemptions as the rest: runners, webhooks and published links + connect from anywhere. The primary instance owner signs in from + anywhere with a browser or the CLI, the instance's way in when its + network's addresses change, while their access tokens and admin tokens + are held to them; an admin can't save ranges they're outside of. A + browser outside them is as signed out and keeps its sign-in, so that + stepping off the VPN signs nobody out for good. + +## Consequences + +- An organization that requires Google and signs browsers out after 12 + hours has someone it closed out of Google out of fctl within 12 hours, + and out of their CLI within its limit; their access tokens last until + their own limit unless an admin disables the account. +- A policy that shortens sign-ins signs people out the moment it's saved, + the admin who saves it among them if theirs is older: the preview says + so. +- Members' access tokens that go when members may no longer make them + don't come back when they may again: their people make new ones. +- Signals from a provider that someone signed out or left (Okta's + Universal Logout, OpenID back-channel logout, Google's Cross-Account + Protection), which would end sign-ins at once, remain later work. diff --git a/docs/adr/README.md b/docs/adr/README.md index 6334f9f8..dc2e2f2f 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -107,3 +107,4 @@ supersede an earlier one. Copy the newest record to start a new one. | [0099](0099-domains-require-signing-in-with-their-provider.md) | Domains require signing in with their provider | | [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 | diff --git a/docs/api.md b/docs/api.md index afcd5795..51ac7601 100644 --- a/docs/api.md +++ b/docs/api.md @@ -652,6 +652,36 @@ out everywhere, as a password reset does. Each token in `GET `passkey` or `google`), and `GET /api/v1/auth/me` the rule that covers you (`sign_in`). +How long sign-ins last ([How long people stay signed +in](self-hosting.md#how-long-people-stay-signed-in)) is five fields of the +same settings: `browser_max_hours` (0: while it's used), +`browser_idle_minutes` (5 to 43200, 30 days by default), `cli_max_days` +(0: while it's used), `access_token_max_days` (0: as its maker chooses) +and `member_access_tokens`. `GET /api/v1/admin/sign-in` has them as +`sessions`, and `POST /api/v1/admin/sign-in/sessions/preview` with them +says what saving them would end at once, changing nothing: `{"browsers", +"clis", "access_tokens", "member_tokens", "you"}`. Saving them with `PATCH +/api/v1/admin/settings` ends those, and asks the caller to confirm it's +them (`verification_required`) where it lets anything last longer. A CLI's +or an access token's request past what they let it last answers `401` +(`unauthorized`), saying why; `POST /api/v1/auth/tokens` refuses an access +token that would last longer (`validation`, `expires_in_days`), and +a member's where only admins make them (`403`, `forbidden`). `GET /api/v1/auth/me` has +them as `sessions`, and each token's `expires_at` in `GET +/api/v1/auth/tokens` says when it ends under them. + +`networks` in the same settings, a list of CIDR ranges (`[]` for +anywhere), keeps sign-ins and requests to them ([Signing in only from your +networks](self-hosting.md#signing-in-only-from-your-networks)): a request +from elsewhere with a CLI's sign-in, an access token, an admin token or a +service account's secret answers `403` (`forbidden`), and a sign-in from +elsewhere is refused the same way, but the primary instance owner's in a +browser or the CLI. Saving ranges the caller's own address is outside of +answers `409` (`conflict`), unless they're the primary instance owner. `GET +/api/v1/admin/sign-in` has them as `networks`, with the caller's +`address`, and `GET /api/v1/instance` says whether the request comes from +outside them (`sign_in.outside`). + ## 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 430f4553..61d96c84 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -436,8 +436,33 @@ by its id, `google` ([ADR 0099](adr/0099-domains-require-signing-in-with-their-p token, removes one. Saving rules that let anyone sign in another way (a domain let go, passkeys let in, another provider) is a sensitive action (`Sensitive::RelaxSignIn`). Closing someone's account at the - provider stops their next sign-in, not the sessions they have: - disabling their account here does that. + provider stops their next sign-in, not the sign-ins they have: + disabling their account here does that, and session policies keep them + short. +- **Session policies** (`InstanceSettings::browser_max_hours`, + `browser_idle_minutes`, `cli_max_days`, `access_token_max_days`, + `member_access_tokens`; Admin → Sign-in → Staying signed in, `fctl admin + sign-in policies`): how long a browser's and a CLI's sign-ins last from + when they were made, how long a browser lasts unused (30 days unless + less), the oldest an access token may be, and whether members make them + ([ADR 0102](adr/0102-instances-limit-how-long-sign-ins-last.md)). Every + request checks its token against them as `auth::authenticate` reads it + (`fctl_domain::session_policy::ended`), those made before them too; a + token's sliding end never passes them, and its use is recorded at least + every quarter of the time a browser may sit unused. Saving one deletes + what it ends at once, in one statement (`sign_in::revoke_ended`, whose + count `POST /admin/sign-in/sessions/preview` shows first). Admin tokens + and service accounts' secrets aren't held to them. +- **Networks** (`InstanceSettings::networks`, `fctl_domain::networks`): + the CIDR ranges sign-ins and requests come from, by `CF-Connecting-IP`. + `auth::authenticate` refuses a CLI's, access token's or admin token's + request from elsewhere and treats a browser as signed out without + clearing its cookie; `service_accounts::authenticate` refuses theirs; + `auth::start_web_session`, the password and reset handlers, the Google + sign-in (`?error=network`) and the CLI's device code refuse a sign-in. + The primary instance owner's browser and CLI are exempt + (`sign_in::outside`); runners, webhooks and published links never reach + these checks. - **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 5a966d59..303b3c11 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1709,6 +1709,10 @@ fctl admin sign-in # the providers, the domains that req fctl admin sign-in require acme.com acme.dev # their people sign in with Google alone: says whom it concerns, then asks fctl admin sign-in require acme.com --passkeys --yes # passkeys alone sign them in too; without asking fctl admin sign-in unrequire acme.dev # its people sign in as they like again +fctl admin sign-in policies # how long sign-ins last, and who makes access tokens +fctl admin sign-in policies --browser-max 12h --browser-idle 1h # browsers sign in again after 12 hours, and out after an hour unused +fctl admin sign-in policies --cli-max 30d --token-max 90d --member-tokens off --yes # says what it ends at once; without asking +fctl admin sign-in policies --networks 203.0.113.0/24,2001:db8::/32 # sign-ins and requests only from these ranges (`any` for anywhere) fctl admin unlink grace@example.com # her Google account was recreated: signs her out, and her next Google sign-in links the new one fctl admin reset-two-factor grace@example.com # they lost their phone and recovery codes fctl admin reset-link grace@example.com # a link that sets their password (emailed to them where the instance sends email) @@ -1727,6 +1731,19 @@ your address there). A CLI whose sign-in a domain's rule doesn't meet says so, and signs in again with `fctl login` ([Requiring Google for your domains](self-hosting.md#requiring-google-for-your-domains)). +`fctl admin sign-in policies` takes durations as `12h`, `30d` or `none` +(no limit): whole hours for browsers' `--browser-max`, whole days for +`--cli-max` and `--token-max`, and 5 minutes to 30 days for +`--browser-idle`. Like `require`, it prints what saving ends at once +before it asks ("Saving signs out 14 browsers and 3 CLIs at once…"), and +`--json` prints the policy once it's saved +([How long people stay signed in](self-hosting.md#how-long-people-stay-signed-in)). +A CLI signed in longer than the policy lets one says so, and signs in +again with `fctl login`. `--networks` takes CIDR ranges separated by +commas, or `any`; it says whether your own address is in them before it +asks ([Signing in only from your +networks](self-hosting.md#signing-in-only-from-your-networks)). + ### Provisioning people with an admin token Where a self-hosted instance's deployment turns them on diff --git a/docs/llms.txt b/docs/llms.txt index 55b3c084..6485c3a8 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`. +- **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. - **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 78c725d6..6a29d166 100644 --- a/docs/organizations.md +++ b/docs/organizations.md @@ -119,6 +119,21 @@ two-factor requirement. [Requiring Google for your domains](self-hosting.md#requiring-google-for-your-domains) has the details. +How long sign-ins last is yours to say too, so that someone whose Google +account you closed is out of fctl soon after, as their sign-ins end: a +browser's after 12 hours, say, a CLI's after 30 days, and access tokens' +after 90, which only admins make +([How long people stay signed in](self-hosting.md#how-long-people-stay-signed-in)): + +```sh +fctl admin sign-in policies --browser-max 12h --cli-max 30d --token-max 90d --member-tokens off +``` + +And where your people work from known networks, sign-ins and requests can +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)). + ## 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 49f59d01..5c947b28 100644 --- a/docs/security.md +++ b/docs/security.md @@ -140,8 +140,25 @@ owner and purpose), so a value copied between rows does not decrypt. while the provider is down; an admin can't save a rule their own sign-in doesn't meet, and letting a domain go, or passkeys in, is a sensitive action. Closing someone's account at the provider stops their - next sign-in, not the sessions they have: disable their account here - too. + next sign-in, not the sign-ins they have: disable their account here + too, or keep sign-ins short. +- **How long sign-ins last.** A browser's sign-in ends after 30 days + unused, a CLI's after 180, and an access token when its maker chose. + Instance admins can say less (Admin → Sign-in → Staying signed in, + `fctl admin sign-in policies`): browsers signed in at most so many + hours, however much they're used, and signed out after as little as 5 + minutes unused; CLIs at most so many days; access tokens no older than + so many days, and made by admins alone. Every request checks its token + against them, those made before too, and saving one ends the sign-ins + it doesn't let last. Letting them last longer is a sensitive action. +- **Networks.** Instance admins can take sign-ins and requests only from + some IP ranges (Admin → Sign-in → Networks): browsers, CLIs, access + tokens, admin tokens and service accounts elsewhere are refused, while + runners, webhooks and published links aren't held to them. The primary + instance owner signs in from anywhere with a browser or the CLI; an admin + 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. - **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/docs/self-hosting.md b/docs/self-hosting.md index a730e8ab..75b0aff2 100644 --- a/docs/self-hosting.md +++ b/docs/self-hosting.md @@ -1170,9 +1170,10 @@ Where your people's addresses are your Google Workspace's, they can sign in with it alone: under its two-step verification and device checks, unable to sign in again once you close their Google account, and with no password of fctl's to forget or leave behind. Closing a Google account -doesn't end the sessions its person has already: disable their account +doesn't end the sign-ins its person has already: disable their account here too as they leave (or with your [admin -token](#provision-people-with-admin-tokens)'s sync). Under **Admin → Sign-in → Domains that sign in +token](#provision-people-with-admin-tokens)'s sync), or keep sign-ins +short ([How long people stay signed in](#how-long-people-stay-signed-in)). Under **Admin → Sign-in → Domains that sign in with a provider**, choose **Require a provider** and give your domains (`acme.com, acme.dev`), or: @@ -1243,6 +1244,69 @@ and the sign-in page tells people without one to ask an admin. fctl signs people in through Google alone today. SAML, Okta, Microsoft Entra ID and other OpenID Connect providers aren't supported yet. +### How long people stay signed in + +By default a browser stays signed in while it's used, until 30 days +unused; a CLI until 180 days unused; and an access token as long as its +maker chose, for ever included. Under **Admin → Sign-in → Staying signed +in**, or with `fctl admin sign-in policies`, an instance admin sets: + +- **Browsers sign in again after** a set time, however much they're used + (`--browser-max 12h`), and **sign out unused for** less than 30 days + (`--browser-idle 1h`, at least 5 minutes). A tab left open on a page + that updates itself counts as use. +- **CLIs sign in again after** a set number of days (`--cli-max 30d`), with + `fctl login`. +- **Access tokens last at most** a set number of days (`--token-max 90d`): + new ones can't be made to last longer, and older ones end once they're + that old. +- **Members make access tokens**, or only admins (`--member-tokens off`): + members' tokens stop working, and they use the CLI, signed in as + themselves. + +```sh +fctl admin sign-in policies --browser-max 12h --browser-idle 1h --cli-max 30d --token-max 90d +``` + +Before it saves, it shows what it ends at once ("Saving signs out 14 +browsers and 3 CLIs at once: their people sign in again. It ends 5 access +tokens: scripts and CI that use them need new ones."), and the CLI asks +unless `--yes`. Every request checks its sign-in against the policy, +those made before it too, and **Settings** tells people how long theirs +last. Where your domains require Google, signing in again goes through +Google, which checks they still may: someone whose Google account you +closed is out of fctl once their browser's and CLI's sign-ins end. Their +access tokens don't go through Google, so limit those, or keep members +from making them, too. Letting sign-ins or tokens last longer again asks +you to confirm it's you, where the instance asks for that. Admin tokens +and service accounts' secrets last as long as their makers chose. + +### Signing in only from your networks + +Under **Admin → Sign-in → Networks**, or with `fctl admin sign-in policies +--networks`, an instance admin names the IP ranges people sign in and send +requests from (your office's, your VPN's), as CIDR: + +```sh +fctl admin sign-in policies --networks 203.0.113.0/24,2001:db8::/32 +fctl admin sign-in policies --networks any # from anywhere again +``` + +Browsers, CLIs, access tokens, admin tokens and service accounts elsewhere +are refused: a browser outside them shows the sign-in page, which says +why, and keeps its sign-in for when it's back inside. Runners' connections, +GitHub's and Linear's webhooks and published screenshots' links come from +anywhere, so runners in your cloud need no range of their own, but a +script that calls the API from CI does. The primary instance owner signs +in from anywhere with a browser or the CLI, the way in when your network's +addresses change; their access tokens and admin tokens are held to the +ranges. An admin can't save ranges their own address is outside of +(**Admin → Sign-in** shows it, with **Add it**), and letting people in from +more places asks you to confirm it's you, where the instance asks for +that. The control plane sees each request's address as `CF-Connecting-IP` +says, which your own server sets from the proxies in front of it +([`FCTL_TRUST_PROXY`](#https-and-reverse-proxies)). + ## Email (optional) Without email, admins copy invite and password-reset links from the app. To diff --git a/web/src/components/sign-in/admin.test.tsx b/web/src/components/sign-in/admin.test.tsx index 7f0094a7..498cd9cb 100644 --- a/web/src/components/sign-in/admin.test.tsx +++ b/web/src/components/sign-in/admin.test.tsx @@ -4,6 +4,7 @@ import { createRoot } from "react-dom/client"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type * as G from "@/gen"; import { keys, queryClient } from "@/lib/queries"; +import { DEFAULT_POLICY } from "@/lib/session-policy"; import { SignInAdmin } from "./admin"; const signInPreview = vi.fn(); @@ -51,6 +52,7 @@ const overview = (fields: Partial = {}): G.SignInOverview => ( owner: person("Ada"), method: "password", email: true, + sessions: DEFAULT_POLICY, ...fields, }); diff --git a/web/src/components/sign-in/networks.test.tsx b/web/src/components/sign-in/networks.test.tsx new file mode 100644 index 00000000..6b69060d --- /dev/null +++ b/web/src/components/sign-in/networks.test.tsx @@ -0,0 +1,108 @@ +import { QueryClientProvider } from "@tanstack/react-query"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type * as G from "@/gen"; +import { queryClient } from "@/lib/queries"; +import { DEFAULT_POLICY } from "@/lib/session-policy"; +import { Networks, networksLead, parseNetworks } from "./networks"; + +const updateInstanceSettings = vi.fn(); +vi.mock("@/lib/api", async (original) => ({ + ...(await original()), + api: { updateInstanceSettings: (b: G.UpdateInstanceSettingsRequest) => updateInstanceSettings(b) }, +})); + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const roots: (() => void)[] = []; +beforeEach(() => { + updateInstanceSettings.mockReset(); + queryClient.clear(); +}); +afterEach(() => { + for (const unmount of roots.splice(0)) unmount(); +}); + +const overview = (networks: string[]): G.SignInOverview => ({ + providers: [], + rules: [], + coverage: [], + self_sign_up: true, + active: 3, + passwords: 3, + passkeys: 0, + no_way_in: 0, + email: false, + sessions: DEFAULT_POLICY, + networks, + address: "203.0.113.9", +}); + +function open(o: G.SignInOverview) { + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + act(() => + root.render( + + + , + ), + ); + roots.push(() => { + act(() => root.unmount()); + container.remove(); + }); + const button = (text: string) => + [...container.querySelectorAll("button")].find((b) => b.textContent?.trim() === text); + return { container, button }; +} + +describe("Admin → Sign-in: networks", () => { + it("reads ranges as typed, and says where people sign in from", () => { + expect(parseNetworks("203.0.113.0/24\n 2001:db8::/32, 10.0.0.1")).toEqual([ + "203.0.113.0/24", + "2001:db8::/32", + "10.0.0.1", + ]); + expect(networksLead([])).toBe("People sign in and send requests from anywhere."); + expect(networksLead(["203.0.113.0/24", "2001:db8::/32"])).toBe( + "People sign in and send requests only from 203.0.113.0/24 and 2001:db8::/32. The primary instance owner signs in from anywhere, in a browser or the CLI.", + ); + }); + + it("adds the admin's own address, and saves the ranges", async () => { + updateInstanceSettings.mockResolvedValue({ networks: ["203.0.113.9/32"] }); + const page = open(overview([])); + expect(page.container.textContent).toContain("Your address: 203.0.113.9"); + expect(page.button("Save")).toBeUndefined(); + await act(async () => page.button("Add it")?.click()); + expect(page.container.querySelector("textarea")?.value).toBe("203.0.113.9"); + await act(async () => page.button("Save")?.click()); + expect(updateInstanceSettings).toHaveBeenCalledWith({ networks: ["203.0.113.9"] }); + }); + + it("shows why the instance refused them", async () => { + updateInstanceSettings.mockRejectedValue( + Object.assign(new Error("Your own address, 203.0.113.9, isn't in these networks"), { + field: undefined, + }), + ); + const page = open(overview(["10.0.0.0/8"])); + const area = page.container.querySelector("textarea"); + expect(area?.value).toBe("10.0.0.0/8"); + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set?.call( + area, + "192.0.2.0/24", + ); + area?.dispatchEvent(new Event("input", { bubbles: true })); + }); + await act(async () => page.button("Save")?.click()); + await act(async () => { + await new Promise((r) => setTimeout(r, 0)); + }); + expect(page.container.textContent).toContain("Your own address, 203.0.113.9, isn't in these networks"); + }); +}); diff --git a/web/src/components/sign-in/networks.tsx b/web/src/components/sign-in/networks.tsx new file mode 100644 index 00000000..f618b440 --- /dev/null +++ b/web/src/components/sign-in/networks.tsx @@ -0,0 +1,123 @@ +// Admin → Sign-in's networks (InstanceSettings.networks): the IP ranges people sign in and send requests from, +// an office's or a VPN's. The admin's own address shows beside them, and the control plane refuses to save ranges +// that would shut them out, unless they are the primary instance owner, who signs in from anywhere. + +import { useMutation } from "@tanstack/react-query"; +import { useEffect, useState } from "react"; +import { Banner, Button, Field, Section, Skeleton, Textarea, toast } from "@/components/ui"; +import type * as G from "@/gen"; +import { api } from "@/lib/api"; +import { keys, queryClient } from "@/lib/queries"; +import { domainsWords } from "@/lib/sign-in"; + +/** Ranges as typed: by lines, commas or spaces. */ +export const parseNetworks = (text: string): string[] => + text + .split(/[\s,]+/) + .map((n) => n.trim()) + .filter(Boolean); + +/** What the section says of the networks saved. */ +export function networksLead(networks: readonly string[]): string { + return networks.length === 0 + ? "People sign in and send requests from anywhere." + : `People sign in and send requests only from ${domainsWords(networks)}. The primary instance owner signs in from anywhere, in a browser or the CLI.`; +} + +export function Networks({ overview }: { overview?: G.SignInOverview }) { + const saved = overview?.networks; + const [text, setText] = useState(""); + // What's saved, here or in another tab, replaces what's typed. + useEffect(() => setText((saved ?? []).join("\n")), [saved]); + const typed = parseNetworks(text); + const changed = !!saved && typed.join(",") !== saved.join(","); + const save = useMutation({ + mutationFn: (networks: string[]) => api.updateInstanceSettings({ networks }), + onSuccess: (s) => { + queryClient.setQueryData(keys.instanceSettings, s); + void queryClient.invalidateQueries({ queryKey: keys.signIn }); + void queryClient.invalidateQueries({ queryKey: keys.instance }); + toast( + s.networks.length + ? "Saved: sign-ins come only from these networks" + : "Saved: people sign in from anywhere", + ); + }, + }); + const address = overview?.address; + const field = (save.error as { field?: string } | null)?.field; + return ( +
+ {!overview ? ( + + ) : ( +
{ + e.preventDefault(); + if (changed) save.mutate(typed); + }} + > +

+ {networksLead(overview.networks ?? [])} +

+ + {(id) => ( +