From 8bc9332a5f084820be76aff0e8671cc1dea08480 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Wed, 25 Nov 2026 23:07:25 +0000 Subject: [PATCH 01/11] feat(control): session policies for how long sign-ins last Instance admins set how long a browser stays signed in (from its sign-in, and unused), how long a CLI stays signed in, the longest an access token lasts and whether members make them. Every request checks its token against them, and saving one ends at once what it doesn't let last. `fctl admin sign-in policies` shows and changes them, with what a change ends before it saves. --- crates/fctl-client/src/api.rs | 10 + crates/fctl-control/src/api/admin.rs | 17 + crates/fctl-control/src/api/sign_in.rs | 41 ++ crates/fctl-control/src/api/tokens.rs | 65 ++- crates/fctl-control/src/auth.rs | 99 +++- crates/fctl-control/src/lib.rs | 3 + crates/fctl-control/src/sign_in.rs | 228 +++++++- crates/fctl-domain/src/lib.rs | 1 + crates/fctl-domain/src/session_policy.rs | 566 +++++++++++++++++++ crates/fctl-domain/src/verify.rs | 67 +++ crates/fctl-proto/src/api.rs | 114 ++++ crates/fctl-proto/src/ts_export.rs | 2 + crates/fctl/src/cmd/admin.rs | 6 +- crates/fctl/src/cmd/sign_in.rs | 214 ++++++- web/src/gen/InstanceSettings.ts | 36 +- web/src/gen/Me.ts | 9 +- web/src/gen/SessionPolicy.ts | 8 + web/src/gen/SessionPolicyPreview.ts | 30 + web/src/gen/SignInOverview.ts | 8 +- web/src/gen/UpdateInstanceSettingsRequest.ts | 20 +- web/src/gen/index.ts | 2 + 21 files changed, 1497 insertions(+), 49 deletions(-) create mode 100644 crates/fctl-domain/src/session_policy.rs create mode 100644 web/src/gen/SessionPolicy.ts create mode 100644 web/src/gen/SessionPolicyPreview.ts 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..593775f8 100644 --- a/crates/fctl-control/src/api/admin.rs +++ b/crates/fctl-control/src/api/admin.rs @@ -1162,6 +1162,18 @@ pub async fn update_settings(ctx: &mut Ctx, req: &mut Request) -> 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 +782,49 @@ 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, }) } +/// `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..3b880421 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,13 @@ 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 until its maker chose, which the policy checked. + let policy = match settings { + Some(s) => s.session_policy(), + None => crate::instance::settings(&ctx.db).await?.session_policy(), + }; + let expires_at = 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 +125,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(expires_at, ctx.now), ctx.cfg.secure_cookies(), )); } Ok((id.0, secret)) } +/// The seconds a browser keeps the session cookie of a sign-in that ends +/// at `expires_at`. +fn cookie_max_age(expires_at: Option, now: i64) -> u64 { + let ms = expires_at.map_or(30 * DAY_MS, |e| e - 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 +155,7 @@ 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?; let (token_id, _) = issue_token( ctx, &user.id, @@ -153,6 +163,7 @@ pub async fn start_web_session( NewToken { verified_at, how: how.clone(), + settings: Some(&settings), ..NewToken::default() }, ) @@ -164,7 +175,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 +238,29 @@ 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`). + fn ended( + &self, + kind: TokenKind, + settings: &InstanceSettings, + now: i64, + ) -> Option { + session_policy::ended( + &settings.session_policy(), + &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, + }, + 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)> { @@ -292,10 +325,11 @@ pub async fn by_token_id(db: &D1Database, token_id: &str, now: i64) -> AppResult .first() .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); + if f.ended(kind, &settings, now).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; @@ -362,14 +396,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) { 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 +416,6 @@ 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()); // 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 +427,21 @@ 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. - let stale = found - .last_used_at - .is_none_or(|t| ctx.now - t > 10 * 60 * 1000); + // 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 touch_after = match kind { + TokenKind::Web => session_policy::touch_after_ms(&policy), + TokenKind::Cli | TokenKind::Pat => session_policy::TOUCH_MS, + }; + let stale = found.last_used_at.is_none_or(|t| ctx.now - t > touch_after); 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 chosen = (kind == TokenKind::Pat) + .then_some(found.expires_at) + .flatten(); + let new_expiry = + session_policy::expires_at(&policy, kind, found.token_created_at, ctx.now, chosen); let db = crate::db::handle(&ctx.db); let id = found.token_id.clone(); let now = ctx.now; @@ -415,11 +456,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(new_expiry, ctx.now), ctx.cfg.secure_cookies(), )); } @@ -599,6 +639,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/sign_in.rs b/crates/fctl-control/src/sign_in.rs index 9e87be50..e86522e8 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; @@ -377,6 +377,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 +600,162 @@ 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. + let tokens: [(&str, TokenKind, &str, i64, Option, Option); 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..5f6736fe 100644 --- a/crates/fctl-domain/src/lib.rs +++ b/crates/fctl-domain/src/lib.rs @@ -60,6 +60,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/session_policy.rs b/crates/fctl-domain/src/session_policy.rs new file mode 100644 index 00000000..b562c94b --- /dev/null +++ b/crates/fctl-domain/src/session_policy.rs @@ -0,0 +1,566 @@ +//! 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() +} + +/// 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, +} + +/// 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) { + return Err(ApiError::validation( + "expires_in_days", + format!( + "This instance's access tokens last {} at most ({max} days): choose that or less", + days(max) + ), + )); + } + 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 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!(refused.is_some_and(|e| e.message.contains("90 days"))); + // 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..04e3f897 100644 --- a/crates/fctl-domain/src/verify.rs +++ b/crates/fctl-domain/src/verify.rs @@ -125,6 +125,9 @@ 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, or members make + /// access tokens again (`fctl_domain::session_policy::relaxes`). + RelaxSessions, } impl Sensitive { @@ -168,6 +171,7 @@ 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", } } } @@ -255,11 +259,37 @@ 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), + ) { + 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 +602,43 @@ 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); + } + #[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..7cbf5d24 100644 --- a/crates/fctl-proto/src/api.rs +++ b/crates/fctl-proto/src/api.rs @@ -328,6 +328,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 +1773,96 @@ 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, +} + +/// 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 +1919,10 @@ 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)] + pub sessions: SessionPolicy, } /// A provider as instance admins see it ([`SignInOverview::providers`]). @@ -1991,6 +2089,11 @@ 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, } } } @@ -2024,6 +2127,17 @@ 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, } // ───────────────────────────── 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..980e2503 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 set --self-sign-up off # accounts only from invitations and admin tokens" )] SignIn { #[command(subcommand)] @@ -761,6 +761,9 @@ 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)); + } println!( "Published screenshots {}", if s.publish_screenshots { @@ -1483,6 +1486,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..16fb3d6f 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,38 @@ 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, + /// Save it without asking. + #[arg(long)] + yes: bool, + }, } pub async fn run(api: &Api, cmd: Option, json: bool) -> Result<()> { @@ -81,10 +115,150 @@ 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, + yes, + } => { + let overview = api.sign_in_overview().await?; + let was = overview.sessions.clone(); + let mut next = was.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; + } + if next == was { + if json { + return style::print_json(&was); + } + print_policy(&was); + return Ok(()); + } + change_policy(api, 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"), + } +} + +/// Shows what saving `next` ends at once, asks unless `yes`, saves it and +/// shows the policy now. +async fn change_policy(api: &Api, next: SessionPolicy, yes: bool, json: bool) -> Result<()> { + let preview = api.session_policy_preview(&next).await?; + for line in policy_consequences(&preview) { + eprintln!("{line}"); + } + 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 saved = api + .update_instance_settings(&UpdateInstanceSettingsRequest { + browser_max_hours: Some(next.browser_max_hours), + browser_idle_minutes: Some(next.browser_idle_minutes), + cli_max_days: Some(next.cli_max_days), + access_token_max_days: Some(next.access_token_max_days), + member_access_tokens: Some(next.member_access_tokens), + ..UpdateInstanceSettingsRequest::default() + }) + .await?; + let now = saved.session_policy(); + if json { + return style::print_json(&now); + } + println!("{} Saved", style::accent("✓")); + print_policy(&now); + Ok(()) +} + +/// 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(), + 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: &SessionPolicy) { + for line in describe_policy(p) { + println!("{line}"); + } +} + /// 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 +505,10 @@ 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)); + } if let Some(owner) = &o.owner && !o.rules.is_empty() { @@ -413,4 +591,36 @@ 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.", + ] + ); + assert_eq!( + policy_consequences(&SessionPolicyPreview::default()), + ["Nobody is signed out now: sign-ins end as it says from here on."] + ); + } + + #[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/web/src/gen/InstanceSettings.ts b/web/src/gen/InstanceSettings.ts index d25b0604..520ba329 100644 --- a/web/src/gen/InstanceSettings.ts +++ b/web/src/gen/InstanceSettings.ts @@ -142,4 +142,38 @@ claude_instance_view: boolean, * trouble at Claude doesn't: [`DEFAULT_CLAUDE_REFUSALS`] by default, * 1 to [`MAX_CLAUDE_REFUSALS`]. */ -claude_refusals: number, }; +claude_refusals: number, +/** + * 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`]. + */ +browser_max_hours: number, +/** + * 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`]. + */ +browser_idle_minutes: number, +/** + * 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`]. + */ +cli_max_days: number, +/** + * 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`]. + */ +access_token_max_days: number, +/** + * 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. + */ +member_access_tokens: boolean, }; diff --git a/web/src/gen/Me.ts b/web/src/gen/Me.ts index a34d4394..41421bc5 100644 --- a/web/src/gen/Me.ts +++ b/web/src/gen/Me.ts @@ -5,6 +5,7 @@ import type { DataExport } from "./DataExport"; import type { EmailAddress } from "./EmailAddress"; import type { Identity } from "./Identity"; import type { Passkey } from "./Passkey"; +import type { SessionPolicy } from "./SessionPolicy"; import type { SignInRequirement } from "./SignInRequirement"; import type { TokenInfo } from "./TokenInfo"; import type { TwoFactor } from "./TwoFactor"; @@ -72,4 +73,10 @@ export?: DataExport, * of the people at a domain of one of your addresses * ([`InstanceSettings::sign_in`]). Absent where none does. */ -sign_in?: SignInRequirement, }; +sign_in?: SignInRequirement, +/** + * 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. + */ +sessions?: SessionPolicy, }; diff --git a/web/src/gen/SessionPolicy.ts b/web/src/gen/SessionPolicy.ts new file mode 100644 index 00000000..bda99f6c --- /dev/null +++ b/web/src/gen/SessionPolicy.ts @@ -0,0 +1,8 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * 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. + */ +export type SessionPolicy = { browser_max_hours: number, browser_idle_minutes: number, cli_max_days: number, access_token_max_days: number, member_access_tokens: boolean, }; diff --git a/web/src/gen/SessionPolicyPreview.ts b/web/src/gen/SessionPolicyPreview.ts new file mode 100644 index 00000000..66952fb0 --- /dev/null +++ b/web/src/gen/SessionPolicyPreview.ts @@ -0,0 +1,30 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * `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. + */ +export type SessionPolicyPreview = { +/** + * Browsers it signs out, which have been signed in longer than it lets + * them, or unused longer. + */ +browsers: number, +/** + * CLIs it signs out, signed in longer than it lets them. + */ +clis: number, +/** + * Access tokens it ends: older than it lets them be, or members' where + * members no longer make them. + */ +access_tokens: number, +/** + * Of `access_tokens`, those of members. + */ +member_tokens: number, +/** + * It signs out the browser or CLI this request comes from. + */ +you: boolean, }; diff --git a/web/src/gen/SignInOverview.ts b/web/src/gen/SignInOverview.ts index 6abe1ba4..770f70a2 100644 --- a/web/src/gen/SignInOverview.ts +++ b/web/src/gen/SignInOverview.ts @@ -1,4 +1,5 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { SessionPolicy } from "./SessionPolicy"; import type { SignInCoverage } from "./SignInCoverage"; import type { SignInPerson } from "./SignInPerson"; import type { SignInProviderStatus } from "./SignInProviderStatus"; @@ -58,4 +59,9 @@ method?: string, method_domain?: string, * The instance sends email: people hear when a rule changes how they * sign in. */ -email: boolean, }; +email: boolean, +/** + * How long sign-ins last and who makes access tokens. Its defaults + * from control planes before it. + */ +sessions: SessionPolicy, }; diff --git a/web/src/gen/UpdateInstanceSettingsRequest.ts b/web/src/gen/UpdateInstanceSettingsRequest.ts index 070fab1e..461d17f8 100644 --- a/web/src/gen/UpdateInstanceSettingsRequest.ts +++ b/web/src/gen/UpdateInstanceSettingsRequest.ts @@ -30,4 +30,22 @@ sign_in?: Array, self_sign_up?: boolean, claude_oversight?: ClaudeOv /** * 1 to [`MAX_CLAUDE_REFUSALS`]. */ -claude_refusals?: number, }; +claude_refusals?: number, +/** + * 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`]). + */ +browser_max_hours?: number, +/** + * [`MIN_BROWSER_IDLE_MINUTES`] to [`DEFAULT_BROWSER_IDLE_MINUTES`]. + */ +browser_idle_minutes?: number, +/** + * 0 to [`MAX_CLI_MAX_DAYS`]. + */ +cli_max_days?: number, +/** + * 0 to [`MAX_ACCESS_TOKEN_DAYS`]. + */ +access_token_max_days?: number, member_access_tokens?: boolean, }; diff --git a/web/src/gen/index.ts b/web/src/gen/index.ts index c89899bd..831ffcd6 100644 --- a/web/src/gen/index.ts +++ b/web/src/gen/index.ts @@ -383,6 +383,8 @@ export type { SessionFiles } from "./SessionFiles"; export type { SessionId } from "./SessionId"; export type { SessionList } from "./SessionList"; export type { SessionMatches } from "./SessionMatches"; +export type { SessionPolicy } from "./SessionPolicy"; +export type { SessionPolicyPreview } from "./SessionPolicyPreview"; export type { SessionQuestion } from "./SessionQuestion"; export type { SessionRef } from "./SessionRef"; export type { SessionRepo } from "./SessionRepo"; From cd7bb55fed4d78906dfedf6b26c98fa7196eeb5c Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Wed, 25 Nov 2026 23:11:38 +0000 Subject: [PATCH 02/11] =?UTF-8?q?feat(web):=20set=20how=20long=20sign-ins?= =?UTF-8?q?=20last=20in=20Admin=20=E2=86=92=20Sign-in?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A draft of a change shows what saving it ends at once before its Save button. Settings' access tokens last no longer than the instance lets them, members see who makes them where only admins do, and Devices says how long sign-ins last where the instance limits them. --- web/src/components/sign-in/admin.test.tsx | 2 + web/src/components/sign-in/sessions.test.tsx | 120 +++++++++++ web/src/components/sign-in/sessions.tsx | 204 +++++++++++++++++++ web/src/components/tokens.tsx | 50 +++-- web/src/lib/api.ts | 3 + web/src/lib/session-policy.test.ts | 80 ++++++++ web/src/lib/session-policy.ts | 137 +++++++++++++ web/src/lib/sign-in.test.ts | 2 + web/src/lib/tokens.test.ts | 25 ++- web/src/lib/tokens.ts | 25 ++- web/src/routes/admin.test.tsx | 2 + web/src/routes/admin.tsx | 5 + web/src/routes/settings.tsx | 5 +- 13 files changed, 643 insertions(+), 17 deletions(-) create mode 100644 web/src/components/sign-in/sessions.test.tsx create mode 100644 web/src/components/sign-in/sessions.tsx create mode 100644 web/src/lib/session-policy.test.ts create mode 100644 web/src/lib/session-policy.ts 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/sessions.test.tsx b/web/src/components/sign-in/sessions.test.tsx new file mode 100644 index 00000000..542efaf3 --- /dev/null +++ b/web/src/components/sign-in/sessions.test.tsx @@ -0,0 +1,120 @@ +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 { SessionPolicies } from "./sessions"; + +const sessionPolicyPreview = vi.fn(); +const updateInstanceSettings = vi.fn(); +vi.mock("@/lib/api", async (original) => ({ + ...(await original()), + api: { + sessionPolicyPreview: (p: G.SessionPolicy) => sessionPolicyPreview(p), + updateInstanceSettings: (b: G.UpdateInstanceSettingsRequest) => updateInstanceSettings(b), + }, +})); + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const roots: (() => void)[] = []; +beforeEach(() => { + sessionPolicyPreview.mockReset(); + updateInstanceSettings.mockReset(); + queryClient.clear(); +}); +afterEach(() => { + for (const unmount of roots.splice(0)) unmount(); +}); + +const settle = () => + act(async () => { + await new Promise((r) => setTimeout(r, 0)); + }); + +function open(policy: G.SessionPolicy) { + 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); + const choose = async (label: string, text: string) => { + const list = container.querySelector(`[aria-label="${label}"]`); + await act(async () => list?.click()); + const option = [...document.body.querySelectorAll('[role="option"]')].find((o) => + o.textContent?.startsWith(text), + ); + expect(option, text).toBeTruthy(); + await act(async () => option?.click()); + await settle(); + }; + return { container, button, choose }; +} + +describe("Admin → Sign-in: staying signed in", () => { + it("says what the policy is while nothing changes", () => { + const page = open(DEFAULT_POLICY); + expect(page.container.textContent).toContain( + "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.", + ); + expect(page.button("Save")).toBeUndefined(); + expect(sessionPolicyPreview).not.toHaveBeenCalled(); + }); + + it("shows what a change ends before it saves it", async () => { + sessionPolicyPreview.mockResolvedValue({ + browsers: 14, + clis: 0, + access_tokens: 2, + member_tokens: 0, + you: true, + } satisfies G.SessionPolicyPreview); + updateInstanceSettings.mockResolvedValue({}); + const page = open(DEFAULT_POLICY); + await page.choose("Browsers sign in again after", "12 hours"); + expect(sessionPolicyPreview).toHaveBeenLastCalledWith({ ...DEFAULT_POLICY, browser_max_hours: 12 }); + expect(page.container.textContent).toContain( + "Saving signs out 14 browsers at once, yours among them: their people sign in again.", + ); + expect(page.container.textContent).toContain( + "It ends 2 access tokens: scripts and CI that use them need new ones.", + ); + await act(async () => page.button("Save")?.click()); + expect(updateInstanceSettings).toHaveBeenCalledWith({ ...DEFAULT_POLICY, browser_max_hours: 12 }); + }); + + it("puts the saved policy back on cancel", async () => { + sessionPolicyPreview.mockResolvedValue({ + browsers: 0, + clis: 0, + access_tokens: 3, + member_tokens: 3, + you: false, + } satisfies G.SessionPolicyPreview); + const page = open(DEFAULT_POLICY); + const off = page.container.querySelector("[role=switch]"); + await act(async () => off?.click()); + await settle(); + expect(page.container.textContent).toContain( + "Only admins make them, and members' stop working: members use the CLI, signed in as themselves.", + ); + expect(page.container.textContent).toContain("It ends 3 access tokens, all of them members'"); + await act(async () => page.button("Cancel")?.click()); + expect(page.button("Save")).toBeUndefined(); + expect(page.container.textContent).toContain("Everyone makes access tokens"); + expect(updateInstanceSettings).not.toHaveBeenCalled(); + }); +}); diff --git a/web/src/components/sign-in/sessions.tsx b/web/src/components/sign-in/sessions.tsx new file mode 100644 index 00000000..eca7164b --- /dev/null +++ b/web/src/components/sign-in/sessions.tsx @@ -0,0 +1,204 @@ +// Admin → Sign-in's session policies: how long a browser and a CLI stay signed in, the longest an access token +// lasts, and whether members make them (G.SessionPolicy). A change is a draft until saved: what it ends at once +// shows first (POST /api/v1/admin/sign-in/sessions/preview), in the sentences `fctl admin sign-in policies` prints. + +import { keepPreviousData, useMutation, useQuery } from "@tanstack/react-query"; +import { type ReactNode, useEffect, useState } from "react"; +import { Banner, Button, Section, Select, Skeleton, Switch, toast } from "@/components/ui"; +import type * as G from "@/gen"; +import { api } from "@/lib/api"; +import { cn } from "@/lib/cn"; +import { keys, queryClient } from "@/lib/queries"; +import { + browserIdleChoices, + browserMaxChoices, + cliMaxChoices, + consequences, + describe, + samePolicy, + tokenMaxChoices, +} from "@/lib/session-policy"; + +/** A limit's row: what it is and what its value means, its control beside them. */ +function Row({ label, hint, children }: { label: string; hint: ReactNode; children: ReactNode }) { + return ( +
+ + {label} + {hint} + + {children} +
+ ); +} + +/** The section: the policy as saved, a draft of a change, and what saving it ends. */ +export function SessionPolicies({ policy }: { policy?: G.SessionPolicy }) { + const [draft, setDraft] = useState(policy); + // A policy saved here, or in another tab, replaces the draft. + useEffect(() => setDraft(policy), [policy]); + const changed = !!policy && !!draft && !samePolicy(policy, draft); + const preview = useQuery({ + queryKey: [...keys.signIn, "sessions", draft], + queryFn: () => api.sessionPolicyPreview(draft as G.SessionPolicy), + enabled: changed, + placeholderData: keepPreviousData, + retry: false, + }); + const save = useMutation({ + mutationFn: (p: G.SessionPolicy) => api.updateInstanceSettings({ ...p }), + onSuccess: (s) => { + queryClient.setQueryData(keys.instanceSettings, s); + void queryClient.invalidateQueries({ queryKey: keys.signIn }); + void queryClient.invalidateQueries({ queryKey: keys.me }); + void queryClient.invalidateQueries({ queryKey: keys.tokens }); + toast("Saved: sign-ins last as it says now"); + }, + }); + const set = (p: Partial) => setDraft((d) => (d ? { ...d, ...p } : d)); + return ( +
+ {!draft ? ( + + ) : ( +
{ + e.preventDefault(); + if (changed) save.mutate(draft); + }} + > + + set({ browser_idle_minutes: Number(v) })} + /> + + + set({ access_token_max_days: Number(v) })} + /> + + + set({ member_access_tokens: v })} + label="Members make access tokens" + /> + + {changed ? ( + { + setDraft(policy); + save.reset(); + }} + /> + ) : ( +

+ {describe(draft).join(" ")} +

+ )} + + )} +
+ ); +} + +/** What saving the draft ends at once, and its buttons. */ +function Change({ + preview, + loading, + error, + saving, + onCancel, +}: { + preview?: G.SessionPolicyPreview; + loading: boolean; + error?: string; + saving: boolean; + onCancel: () => void; +}) { + return ( +
+ {preview ? ( +
    + {consequences(preview).map((l) => ( +
  • {l}
  • + ))} +
+ ) : ( + loading && + )} + {error && {error}} +
+ + +
+
+ ); +} diff --git a/web/src/components/tokens.tsx b/web/src/components/tokens.tsx index 77262a4c..e9723fe5 100644 --- a/web/src/components/tokens.tsx +++ b/web/src/components/tokens.tsx @@ -14,11 +14,14 @@ import { cn } from "@/lib/cn"; import { ago } from "@/lib/format"; import { GITHUB_ACCESS } from "@/lib/github-access"; import { siteUrl } from "@/lib/install"; -import { keys, queryClient, useProjects, useWorkspaces } from "@/lib/queries"; +import { keys, queryClient, useMe, useProjects, useWorkspaces } from "@/lib/queries"; +import { days as expiryWords } from "@/lib/session-policy"; import { describeScope, - EXPIRIES, example, + expiries, + expiryDays, + fitExpiry, formScope, NEW_TOKEN, reach, @@ -33,23 +36,33 @@ const GUIDE = () => `${siteUrl()}/docs/automation/`; export function AccessTokens() { const list = useQuery({ queryKey: keys.tokens, queryFn: api.tokens }); + const { data: me } = useMe(); const [open, setOpen] = useState(false); const revoke = useMutation({ mutationFn: (id: string) => api.deleteToken(id), onSuccess: () => list.refetch(), }); const tokens = list.data?.tokens.filter((t) => t.kind === "pat") ?? []; + // Where only admins make them, a member's stopped working: the instance's admins say so in Admin → Sign-in. + const adminsOnly = me?.sessions?.member_access_tokens === false && me.user.role === "member"; + const max = me?.sessions?.access_token_max_days ?? 0; return (
0 ? ` This instance lets one last ${expiryWords(max)} at most.` : ""}` + } actions={ - + adminsOnly ? undefined : ( + + ) } > - {tokens.length ? ( + {adminsOnly && tokens.length === 0 ? null : tokens.length ? (
    {tokens.map((t) => (
  • @@ -87,14 +100,16 @@ export function AccessTokens() {

    )} - setOpen(false)} /> + {!adminsOnly && setOpen(false)} max={max} />}
); } /** Makes an access token: what it does, where, what its agents may do on GitHub, how long it works. */ -export function NewTokenDialog({ open, onClose }: { open: boolean; onClose: () => void }) { - const [form, setForm] = useState(NEW_TOKEN); +export function NewTokenDialog({ open, onClose, max }: { open: boolean; onClose: () => void; max: number }) { + const [typed, setForm] = useState(NEW_TOKEN); + // Within the longest the instance lets a token last. + const form = { ...typed, expires: fitExpiry(typed.expires, max) }; const [created, setCreated] = useState(null); const set = (f: Partial) => setForm((was) => ({ ...was, ...f })); const create = useMutation({ @@ -123,7 +138,7 @@ export function NewTokenDialog({ open, onClose }: { open: boolean; onClose: () = {created ? ( ) : ( - + )} ); @@ -133,10 +148,13 @@ function TokenFormView({ form, set, create, + max, }: { form: TokenForm; set: (f: Partial) => void; create: { mutate: () => void; isPending: boolean; error: Error | null }; + /** The longest the instance lets a token last, in days; 0: as long as its maker chooses. */ + max: number; }) { const workspaces = useWorkspaces().data?.workspaces ?? []; const projects = useProjects().data?.projects ?? []; @@ -148,7 +166,7 @@ function TokenFormView({ [workspaces, projects], ); const scope = formScope(form, names); - const expiry = EXPIRIES.find((e) => e.value === form.expires)?.days; + const expiry = expiryDays(form.expires); const field = (create.error as { field?: string } | null)?.field; const err = (f: string) => (field === f ? create.error?.message : undefined); const id = useId(); @@ -240,13 +258,17 @@ function TokenFormView({ )} )} - + 0 ? `This instance lets a token last ${expiryWords(max)} at most.` : undefined} + error={err("expires_in_days")} + > {(fid) => (