From dced199132ce0d6bc1c3683a7ddf01b073db0549 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 20:28:12 +0100 Subject: [PATCH] [control] Team sign-in without Authelia: a one-time setup link for the first admin, invite links, per-browser sessions in an HttpOnly cookie, admin and member roles, Tessera roots with their match code; the admin host kept by control ([ui] admin_tls) --- crates/control/src/api/handlers.rs | 12 +- crates/control/src/api/mod.rs | 80 +++++ crates/control/src/api/team.rs | 351 +++++++++++++++++++++ crates/control/src/api/ui.rs | 16 + crates/control/src/config.rs | 6 + crates/control/src/dev.rs | 1 + crates/control/src/engine.rs | 3 + crates/control/src/lib.rs | 5 + crates/control/src/main.rs | 32 ++ crates/control/src/messages.rs | 14 + crates/control/src/previews.rs | 56 ++++ crates/control/src/team.rs | 470 +++++++++++++++++++++++++++++ crates/control/tests/team.rs | 257 ++++++++++++++++ 13 files changed, 1300 insertions(+), 3 deletions(-) create mode 100644 crates/control/src/api/team.rs create mode 100644 crates/control/src/team.rs create mode 100644 crates/control/tests/team.rs diff --git a/crates/control/src/api/handlers.rs b/crates/control/src/api/handlers.rs index ff52aba..e8b410b 100644 --- a/crates/control/src/api/handlers.rs +++ b/crates/control/src/api/handlers.rs @@ -300,6 +300,8 @@ pub async fn overview( viewer: Some(Viewer { via: if actor.token_id.starts_with("user:") { "authelia".into() + } else if actor.member.is_some() { + "session".into() } else { "token".into() }, @@ -1401,7 +1403,9 @@ impl Modify for Bearer { super::pki::get_csr, super::pki::get_ext, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device, super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine, super::previews::list_previews, super::previews::open_preview, super::previews::get_preview, - super::previews::kill_preview, super::previews::close_preview + super::previews::kill_preview, super::previews::close_preview, + super::team::sign_out, super::team::get_team, super::team::invite, super::team::cancel_invite, + super::team::remove_member, super::team::set_root ), components(schemas( HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate, @@ -1413,13 +1417,15 @@ impl Modify for Bearer { super::pki::BundleBody, super::pki::BundleView, super::pki::EngineSwitchView, super::pki::EngineBody, FallbackReady, crate::hostspec::PreviewSpec, super::previews::PreviewOpen, super::previews::PreviewClose, super::previews::PreviewView, super::previews::PreviewOpened, super::previews::PreviewOne, - super::previews::PreviewList, super::previews::PreviewClosed + super::previews::PreviewList, super::previews::PreviewClosed, + super::team::SignIn, super::team::SignedIn, super::team::MemberView, super::team::TeamView, + super::team::InviteBody, super::team::InviteMade, super::team::InviteView, super::team::RootBody )), modifiers(&Bearer), tags( (name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"), (name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links"), - (name = "certs"), (name = "engine"), (name = "previews") + (name = "certs"), (name = "engine"), (name = "previews"), (name = "team") ) )] pub struct ApiDoc; diff --git a/crates/control/src/api/mod.rs b/crates/control/src/api/mod.rs index 16710cf..b532bc6 100644 --- a/crates/control/src/api/mod.rs +++ b/crates/control/src/api/mod.rs @@ -18,6 +18,7 @@ pub mod handlers; pub mod pki; pub mod previews; +pub mod team; pub mod ui; pub mod views; @@ -52,6 +53,22 @@ pub struct Actor { pub token_id: String, pub name: String, pub scope: crate::tokens::Scope, + /// A team member signed in with a session (`crate::team`): their id, session and role. + /// `None` for API tokens and Authelia sign-ins, which may do everything. + pub member: Option, + pub session: Option, + pub role: Option, +} + +/// What only an admin may do (a `member` session gets 403 `team.admin_only`): API tokens, +/// the team, the engine and the CA. +fn admin_only(method: &str, path: &str) -> bool { + let write = !matches!(method, "GET" | "HEAD" | "OPTIONS"); + path.starts_with("/api/v1/tokens") + || (path.starts_with("/api/v1/team/") && !path.starts_with("/api/v1/team/me/")) + || (write && path == "/api/v1/engine") + || (write && path.starts_with("/api/v1/certs/intermediate")) + || path.starts_with("/api/v1/pki-requests") } /// The only routes a `previews` token may call (T4: it can never touch another host). @@ -472,10 +489,64 @@ async fn guard(State(st): State>, mut req: Request, next: Next) -> token_id: format!("user:{user}"), name: display, scope: crate::tokens::Scope::Full, + member: None, + session: None, + role: None, }); return Ok(next.run(req).await); } } + // A team session (crate::team): the cookie, when no API token is given. + if !req.headers().contains_key(header::AUTHORIZATION) + && let Some(value) = team::session_cookie(req.headers()) + { + let ctl = st.ctl.clone(); + let found = tokio::task::spawn_blocking(move || ctl.team.check(&value)) + .await + .ok() + .flatten(); + let Some((member, session)) = found else { + return Err(ApiError::new( + StatusCode::UNAUTHORIZED, + "session.unknown", + Params::new(), + )); + }; + let same_site = req + .headers() + .get("sec-fetch-site") + .is_none_or(|v| matches!(v.as_bytes(), b"same-origin" | b"none")); + if write && (!ui || !same_site) { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "request.csrf", + Params::new(), + )); + } + if member.role != crate::team::Role::Admin + && admin_only(method.as_str(), req.uri().path()) + { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "team.admin_only", + Params::new(), + )); + } + st.limit(&format!("member:{}", member.id), RATE_PER_MINUTE, 60) + .map_err(|s| { + ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()) + .retry(s) + })?; + req.extensions_mut().insert(Actor { + token_id: format!("member:{}", member.id), + name: member.name.clone(), + scope: crate::tokens::Scope::Full, + member: Some(member.id), + session: Some(session.id), + role: Some(member.role), + }); + return Ok(next.run(req).await); + } let auth = req .headers() .get(header::AUTHORIZATION) @@ -516,6 +587,9 @@ async fn guard(State(st): State>, mut req: Request, next: Next) -> token_id: tok.id, name: tok.name, scope: tok.scope, + member: None, + session: None, + role: None, }); Ok(next.run(req).await) } @@ -648,6 +722,12 @@ pub fn router(st: Arc) -> Router { "/api/v1/previews/{hostname}", get(previews::get_preview).delete(previews::kill_preview), ) + .route("/api/v1/team", get(team::get_team)) + .route("/api/v1/team/invites", post(team::invite)) + .route("/api/v1/team/invites/{id}", delete(team::cancel_invite)) + .route("/api/v1/team/members/{id}", delete(team::remove_member)) + .route("/api/v1/team/me/root", axum::routing::put(team::set_root)) + .route("/api/v1/session/end", post(team::sign_out)) .route("/api/v1/health", get(h::health)) .route("/api/v1/openapi.json", get(h::openapi)) .method_not_allowed_fallback(method_not_allowed) diff --git a/crates/control/src/api/team.rs b/crates/control/src/api/team.rs new file mode 100644 index 0000000..9cf45c6 --- /dev/null +++ b/crates/control/src/api/team.rs @@ -0,0 +1,351 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Team sign-in and the team list (`crate::team`). `POST /api/v1/session` is the one call +//! without a token or session: it redeems a setup or invite link. Everything else here goes +//! through the guard; inviting and removing people needs the admin role. + +// An error answer is built once per failed request; boxing it buys nothing. +#![allow(clippy::result_large_err)] + +use std::sync::Arc; + +use axum::Extension; +use axum::extract::{Path, Request, State}; +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +use super::{Actor, ApiError, AppState, Body}; +use crate::messages::Params; +use crate::team::{COOKIE, Member, Role, SESSION_SECS, match_code}; +use crate::util::rfc3339; + +type Shared = State>; + +fn json(status: StatusCode, v: &T) -> Response { + (status, axum::Json(v)).into_response() +} + +fn refused(code: &'static str) -> ApiError { + let status = match code { + "internal" => StatusCode::INTERNAL_SERVER_ERROR, + "session.code" => StatusCode::UNAUTHORIZED, + "team.not_found" => StatusCode::NOT_FOUND, + "team.last_admin" | "team.full" => StatusCode::CONFLICT, + _ => StatusCode::UNPROCESSABLE_ENTITY, + }; + ApiError::new(status, code, Params::new()) +} + +/// The session cookie's value from a request, if any. +pub fn session_cookie(headers: &HeaderMap) -> Option { + headers + .get_all(header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .filter_map(|kv| kv.trim().split_once('=')) + .find(|(k, _)| *k == COOKIE) + .map(|(_, v)| v.to_owned()) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct SignIn { + /// The code from a setup or invite link (`#signin=`). + pub code: String, + /// Your name (setup links only; an invite already names you). + pub name: Option, + /// What to call this browser in the sessions list. + pub device: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct MemberView { + pub id: String, + pub name: String, + /// `admin` or `member`. + pub role: String, + pub added_at: String, + /// The member's Tessera root and its match code, when they recorded it. + pub tessera_root: Option, + pub match_code: Option, +} + +impl From<&Member> for MemberView { + fn from(m: &Member) -> Self { + MemberView { + id: m.id.clone(), + name: m.name.clone(), + role: m.role.as_str().into(), + added_at: rfc3339(m.added_at), + tessera_root: m.tessera_root.clone(), + match_code: m.tessera_root.as_deref().and_then(match_code), + } + } +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct SignedIn { + pub member: MemberView, +} + +/// Redeem a setup or invite link: sets the session cookie. No token needed (this is the +/// door). At most 20 tries a minute for the whole server. +pub async fn sign_in(st: Arc, req: Request) -> Response { + async { + if st.limit("signin", 20, 60).is_err() { + return Err(ApiError::new( + StatusCode::TOO_MANY_REQUESTS, + "rate.limited", + Params::new(), + ) + .retry(60)); + } + // Only the UI's own page signs in (the custom header needs a CORS preflight that + // control never answers), and never a cross-site page. + let h = req.headers(); + let ui = h.get("x-ianitor-ui").is_some_and(|v| v.as_bytes() == b"1"); + let site_ok = h + .get("sec-fetch-site") + .is_none_or(|v| matches!(v.as_bytes(), b"same-origin" | b"none")); + if !ui || !site_ok { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "request.csrf", + Params::new(), + )); + } + let body = as axum::extract::FromRequest<()>>::from_request(req, &()).await?; + let b = body.value; + let team = st.ctl.team.clone(); + let device = b.device.unwrap_or_else(|| "Browser".into()); + let (member, value) = + tokio::task::spawn_blocking(move || team.redeem(&b.code, b.name.as_deref(), &device)) + .await + .map_err(|_| ApiError::internal("sign-in"))? + .map_err(|r| refused(r.0))?; + log::info!(target: "ianitor::team", "{} ({}) signed in", member.name, member.role.as_str()); + let mut resp = json( + StatusCode::OK, + &SignedIn { + member: MemberView::from(&member), + }, + ); + let cookie = format!( + "{COOKIE}={value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age={SESSION_SECS}" + ); + if let Ok(v) = HeaderValue::from_str(&cookie) { + resp.headers_mut().insert(header::SET_COOKIE, v); + } + resp.headers_mut() + .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + Ok(resp) + } + .await + .unwrap_or_else(IntoResponse::into_response) +} + +/// Sign this browser out. +#[utoipa::path(post, path = "/api/v1/session/end", tag = "team", + responses((status = 200, body = super::views::Done)), security(("bearer" = [])))] +pub async fn sign_out( + State(st): Shared, + Extension(actor): Extension, +) -> Result { + if let Some(id) = &actor.session { + st.ctl.team.end_session(id).map_err(ApiError::internal)?; + } + let mut resp = json( + StatusCode::OK, + &super::views::Done { + message: "Done.".into(), + }, + ); + if let Ok(v) = HeaderValue::from_str(&format!( + "{COOKIE}=; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=0" + )) { + resp.headers_mut().insert(header::SET_COOKIE, v); + } + Ok(resp) +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct InviteView { + pub id: String, + pub name: Option, + pub role: String, + pub expires_at: String, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct TeamView { + /// Who is asking; absent for an API token. + pub me: Option, + pub members: Vec, + pub invites: Vec, + /// Whether Authelia signs people in on this server instead. + pub authelia: bool, +} + +/// The team: members, open invites, and who you are. +#[utoipa::path(get, path = "/api/v1/team", tag = "team", + responses((status = 200, body = TeamView)), security(("bearer" = [])))] +pub async fn get_team( + State(st): Shared, + Extension(actor): Extension, +) -> Result { + let members = st.ctl.team.members().map_err(ApiError::internal)?; + let invites = st + .ctl + .team + .codes() + .map_err(ApiError::internal)? + .into_iter() + .filter(|c| c.kind == "invite") + .map(|c| InviteView { + id: c.id, + name: c.name, + role: c.role.as_str().into(), + expires_at: rfc3339(c.expires_at), + }) + .collect(); + let me = actor + .member + .as_ref() + .and_then(|id| members.iter().find(|m| &m.id == id)) + .map(MemberView::from); + Ok(json( + StatusCode::OK, + &TeamView { + me, + members: members.iter().map(MemberView::from).collect(), + invites, + authelia: st.ctl.ui_proof.is_some(), + }, + )) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct InviteBody { + pub name: String, + /// `admin` or `member` (default). + pub role: Option, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct InviteMade { + pub invite: InviteView, + /// Send this to the person: `/#signin=`. Shown once. + pub link_fragment: String, +} + +/// Invite someone (admin). The link is shown once. +#[utoipa::path(post, path = "/api/v1/team/invites", tag = "team", request_body = InviteBody, + responses((status = 201, body = InviteMade), (status = 403, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn invite( + State(st): Shared, + Extension(actor): Extension, + body: Body, +) -> Result { + let role = match body.value.role.as_deref() { + None => Role::Member, + Some(r) => Role::parse(r).ok_or_else(|| refused("team.role"))?, + }; + let (code, value) = st + .ctl + .team + .invite(&body.value.name, role, &actor.name) + .map_err(|r| refused(r.0))?; + log::info!(target: "ianitor::team", "{} invited {} as {}", actor.name, code.name.clone().unwrap_or_default(), role.as_str()); + Ok(json( + StatusCode::CREATED, + &InviteMade { + invite: InviteView { + id: code.id, + name: code.name, + role: role.as_str().into(), + expires_at: rfc3339(code.expires_at), + }, + link_fragment: format!("#signin={value}"), + }, + )) +} + +/// Cancel an invite that was not used (admin). +#[utoipa::path(delete, path = "/api/v1/team/invites/{id}", tag = "team", params(("id" = String, Path)), + responses((status = 200, body = super::views::Done)), security(("bearer" = [])))] +pub async fn cancel_invite( + State(st): Shared, + Path(id): Path, +) -> Result { + if !st.ctl.team.cancel_invite(&id).map_err(ApiError::internal)? { + return Err(refused("team.not_found")); + } + Ok(json( + StatusCode::OK, + &super::views::Done { + message: "Done.".into(), + }, + )) +} + +/// Remove a member and sign them out everywhere (admin). The last admin stays. +#[utoipa::path(delete, path = "/api/v1/team/members/{id}", tag = "team", params(("id" = String, Path)), + responses((status = 200, body = super::views::Done), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn remove_member( + State(st): Shared, + Extension(actor): Extension, + Path(id): Path, +) -> Result { + match st.ctl.team.remove(&id).map_err(|r| refused(r.0))? { + Some(m) => { + log::info!(target: "ianitor::team", "{} removed {}", actor.name, m.name); + Ok(json( + StatusCode::OK, + &super::views::Done { + message: "Done.".into(), + }, + )) + } + None => Err(refused("team.not_found")), + } +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct RootBody { + /// Your Tessera root (base64url, as Custos shows it under Domi identity), or null. + pub tessera_root: Option, +} + +/// Record your own Tessera root, so the team list shows its match code. +#[utoipa::path(put, path = "/api/v1/team/me/root", tag = "team", request_body = RootBody, + responses((status = 200, body = super::views::Done)), security(("bearer" = [])))] +pub async fn set_root( + State(st): Shared, + Extension(actor): Extension, + body: Body, +) -> Result { + let Some(me) = &actor.member else { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "team.session_only", + Params::new(), + )); + }; + st.ctl + .team + .set_root(me, body.value.tessera_root.as_deref()) + .map_err(|r| refused(r.0))?; + Ok(json( + StatusCode::OK, + &super::views::Done { + message: "Done.".into(), + }, + )) +} diff --git a/crates/control/src/api/ui.rs b/crates/control/src/api/ui.rs index 8b878c8..5608695 100644 --- a/crates/control/src/api/ui.rs +++ b/crates/control/src/api/ui.rs @@ -43,6 +43,22 @@ pub async fn front(State(st): State>, req: Request, next: Next) -> .into_response(), }; } + // The door: redeeming a setup or invite link needs no token (crate::team). + if path == "/api/v1/session" { + if !host_allowed(&st.ctl, req.headers()) { + return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new()) + .into_response(); + } + if req.method() != "POST" { + return ApiError::new( + StatusCode::METHOD_NOT_ALLOWED, + "request.method", + Params::new(), + ) + .into_response(); + } + return super::team::sign_in(st, req).await; + } if path.starts_with("/api/") || path == "/api" { return next.run(req).await; } diff --git a/crates/control/src/config.rs b/crates/control/src/config.rs index 9977bad..f8dd774 100644 --- a/crates/control/src/config.rs +++ b/crates/control/src/config.rs @@ -403,6 +403,12 @@ pub struct UiConfig { /// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out". #[serde(default)] pub logout_url: Option, + /// Without Authelia (T4): control keeps the admin host in the routes repository itself, + /// as a plain host to this API with this certificate (`letsencrypt` or `domi`); people + /// sign in with team links (crate::team). Unset: the admin host is managed by hand + /// (the NixOS module's Authelia setup). + #[serde(default)] + pub admin_tls: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs index 7f644cb..4eddf0e 100644 --- a/crates/control/src/dev.rs +++ b/crates/control/src/dev.rs @@ -168,6 +168,7 @@ pub async fn run(args: &[String]) -> Result<(), String> { proof_credential: None, static_dir: Some(PathBuf::from(d)), logout_url: None, + admin_tls: None, }), engine: None, // Branch previews on a name nobody can own (RFC 2606), from loopback test upstreams. diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs index 8d4ef85..44f4ef3 100644 --- a/crates/control/src/engine.rs +++ b/crates/control/src/engine.rs @@ -143,6 +143,8 @@ pub struct Control { pub repo: Repo, pub edge: EdgeLink, pub tokens: Tokens, + /// Team members and their sessions (sign-in without Authelia). + pub team: Arc, pub shares: Shares, pub share_key: Option, /// The Domi CA, when `[pki]` is configured. @@ -247,6 +249,7 @@ impl Control { let paused: Option = read_json(&cfg.state_dir.join("paused.json"))?; let c = Arc::new(Control { tokens: Tokens::new(&cfg.state_dir), + team: Arc::new(crate::team::Team::new(&cfg.state_dir)), shares: Shares::new(&cfg.state_dir, &cfg.edge.share_revocations), repo, edge, diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index 2118447..3435f2e 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -23,6 +23,7 @@ pub mod records; pub mod repo; pub mod shares; pub mod switch; +pub mod team; pub mod tokens; pub mod util; @@ -44,6 +45,10 @@ pub async fn serve( tokio::spawn(ctl.clone().pusher()); tokio::spawn(ctl.clone().pki_poller()); tokio::spawn(ctl.clone().preview_sweeper()); + ctl.ensure_admin_host(); + if ctl.cfg.ui.is_some() && !ctl.team.has_members() && ctl.ui_proof.is_none() { + log::warn!(target: "ianitor::team", "nobody is in the team yet: run `ianitor-control team setup-link --config ` and open the link it prints"); + } let app = api::router(api::AppState::new(ctl.clone())); if !listen.ip().is_loopback() { return Err("ianitor-control only listens on loopback".into()); diff --git a/crates/control/src/main.rs b/crates/control/src/main.rs index 46bfb66..c94eab4 100644 --- a/crates/control/src/main.rs +++ b/crates/control/src/main.rs @@ -15,6 +15,7 @@ //! ianitor-control ca init --out [--passphrase-file ] the offline root (never on the server) //! ianitor-control ca sign --root --csr --out [--yes] sign an intermediate offline //! ianitor-control check --config check the config and exit +//! ianitor-control team setup-link|list --config the first admin's sign-in link //! ianitor-control service control|caddy-guard --config [--log-file ] Windows service //! ``` //! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`), @@ -386,6 +387,36 @@ fn pki_cli(args: &[String]) -> Result<(), String> { } } +/// `team setup-link | list` on the server, as the user control runs as. +fn team_cli(args: &[String]) -> Result<(), String> { + let path = arg_after(args, "--config").ok_or("team setup-link|list --config ")?; + let cfg = Config::load(&PathBuf::from(path)).map_err(|e| e.to_string())?; + same_owner(&cfg.state_dir)?; + let team = ianitor_control::team::Team::new(&cfg.state_dir); + match args.first().map(String::as_str) { + Some("setup-link") => { + let (code, until) = team.setup_code()?; + let base = match cfg.ui.as_ref().and_then(|u| u.hostname.as_ref()) { + Some(h) => format!("https://{h}/"), + None => format!("http://{}/", cfg.listen), + }; + eprintln!( + "Open this link to sign in as the team's first admin. It works once, until {}:", + ianitor_control::util::rfc3339(until) + ); + println!("{base}#signin={code}"); + Ok(()) + } + Some("list") => { + for m in team.members()? { + println!("{} {} {}", m.id, m.role.as_str(), m.name); + } + Ok(()) + } + _ => Err("team setup-link|list --config ".into()), + } +} + fn main() -> ExitCode { if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") { return askpass(); @@ -429,6 +460,7 @@ fn main() -> ExitCode { let result = match args.first().map(String::as_str) { Some("token") => token(&args[1..]), Some("pki") => pki_cli(&args[1..]), + Some("team") => team_cli(&args[1..]), Some("ca") => ca(&args[1..]), Some("openapi") => { println!("{}", ianitor_control::api::openapi_json()); diff --git a/crates/control/src/messages.rs b/crates/control/src/messages.rs index bd2e09b..99b7627 100644 --- a/crates/control/src/messages.rs +++ b/crates/control/src/messages.rs @@ -209,6 +209,20 @@ fn template(code: &str) -> &'static str { "This API token may only open and close branch previews (/api/v1/previews)." } "token.scope_value" => "A token's scope is full or previews.", + "session.code" => { + "This sign-in link does not work: it was used, it expired, or it was mistyped. Ask an admin for a new one." + } + "session.unknown" => { + "You are signed out. Open your sign-in link again, or ask an admin for one." + } + "team.admin_only" => "Only an admin of this team can do that.", + "team.last_admin" => "The team needs at least one admin. Make someone else an admin first.", + "team.full" => "The team is full (64 people, 100 open invites).", + "team.name" => "Enter a name of 1 to 64 characters.", + "team.role" => "A role is admin or member.", + "team.root" => "That is not a Tessera root. Copy it from Custos, Domi identity.", + "team.not_found" => "There is no such member or invite.", + "team.session_only" => "Only a signed-in person can do that, not an API token.", "preview.off" => { "Previews are off on this server: set a preview domain under [previews] in control.toml." } diff --git a/crates/control/src/previews.rs b/crates/control/src/previews.rs index 17a5652..24e2d5f 100644 --- a/crates/control/src/previews.rs +++ b/crates/control/src/previews.rs @@ -313,6 +313,62 @@ pub struct Listed { } impl Control { + /// With `[ui] hostname` and `admin_tls`: make sure the admin host (the web UI and this + /// API, through the engine) is in the routes repository; queue it at start if not. + pub fn ensure_admin_host(&self) { + let Some(ui) = &self.cfg.ui else { return }; + let (Some(host), Some(tls)) = (&ui.hostname, &ui.admin_tls) else { + return; + }; + let Ok((_, tree, _)) = self.head_model() else { + return; + }; + if tree.host(host).is_some() { + return; + } + let spec = HostSpec { + hostname: host.clone(), + upstreams: vec![format!("http://{}", self.cfg.listen)], + tls: tls.clone(), + auth: "none".into(), + websockets: false, + share_links: false, + device_certs: false, + access_log: "off".into(), + health_check: Some(crate::hostspec::HealthCheckSpec { + path: "/api/v1/health".into(), + interval_secs: 10, + }), + request_headers: Vec::new(), + response_headers: vec![ + HeaderRuleSpec { + action: "set".into(), + name: "X-Robots-Tag".into(), + value: Some("noindex, nofollow".into()), + secret: None, + }, + HeaderRuleSpec { + action: "set".into(), + name: "Strict-Transport-Security".into(), + value: Some("max-age=31536000".into()), + secret: None, + }, + ], + preview: None, + }; + match self.submit_as( + Change::Put { spec, create: true }, + None, + "Setup", + Some(format!("Added the admin host {host} (the web UI)")), + ) { + Ok(_) => log::info!(target: "ianitor::control", "adding the admin host {host}"), + Err(f) => { + log::error!(target: "ianitor::control", "cannot add the admin host {host}: {}", f.reason.message) + } + } + } + pub fn previews_cfg(&self) -> Result<&PreviewsConfig, Fail> { self.cfg .previews diff --git a/crates/control/src/team.rs b/crates/control/src/team.rs new file mode 100644 index 0000000..96cbb75 --- /dev/null +++ b/crates/control/src/team.rs @@ -0,0 +1,470 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Team sign-in without Authelia (T4: Ianitor on any server, for a small team). Authelia stays +//! an option (`[ui] proof_credential`, docs/api.md "Sign-in"); this is the default elsewhere. +//! +//! - **The founding admin** signs in with a one-time **setup link** (`#signin=isc_…`): made at +//! the first start of a server with no member, printed by the installer +//! (`ianitor-control team setup-link`), valid 7 days, one use. +//! - **Teammates** get an **invite link** from an admin (Settings → Team → Invite), for a role: +//! `admin` (everything) or `member` (hosts, previews, history; not tokens, the team, the +//! engine or the CA). One use, 7 days. +//! - Redeeming a link makes a **session**: `ise_` + 32 random bytes in an `HttpOnly`, +//! `Secure`, `SameSite=Strict`, `__Host-` cookie, 30 days, no sliding. Control stores only +//! SHA-256 of codes and sessions (in `team.json`, 0600), so a copy of the state directory +//! signs no one in. Signing out ends the session; removing a member ends all of theirs. +//! - A member may record their **Tessera root** (the Domi identity's public key, as Custos +//! shows it) so the team list shows its match code. Signing in *with* the Tessera key (a +//! browser Domi key) and Custos approval of admin changes need operations Custos does not +//! have yet (docs/custos-ticket.md, T4 part); until then admin changes need the admin role. + +use std::path::{Path, PathBuf}; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use serde::{Deserialize, Serialize}; + +use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json}; + +pub const COOKIE: &str = "__Host-ianitor"; +pub const SESSION_SECS: u64 = 30 * 86_400; +pub const CODE_SECS: u64 = 7 * 86_400; +const MAX_MEMBERS: usize = 64; +const MAX_SESSIONS: usize = 400; +const MAX_CODES: usize = 100; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Role { + Admin, + Member, +} + +impl Role { + pub fn as_str(self) -> &'static str { + match self { + Role::Admin => "admin", + Role::Member => "member", + } + } + pub fn parse(s: &str) -> Option { + match s { + "admin" => Some(Role::Admin), + "member" => Some(Role::Member), + _ => None, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Member { + pub id: String, + pub name: String, + pub role: Role, + /// The member's Tessera root public key (base64url, 32 bytes), when they gave it. + #[serde(default)] + pub tessera_root: Option, + pub added_at: u64, + pub added_by: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Session { + pub id: String, + pub sha256: String, + pub member: String, + /// What the browser was called at sign-in (`Laptop`, `Phone`). + pub device: String, + pub created_at: u64, + pub expires_at: u64, + pub last_used_at: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Code { + pub id: String, + pub sha256: String, + /// `setup` (the founding admin) or `invite`. + pub kind: String, + pub role: Role, + /// The invitee's name, as the admin typed it. + pub name: Option, + pub expires_at: u64, + pub created_by: String, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct TeamFile { + members: Vec, + sessions: Vec, + codes: Vec, +} + +/// Why a sign-in or a team change was refused (an API error code). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Refused(pub &'static str); + +pub struct Team { + path: PathBuf, + lock: std::sync::Mutex<()>, +} + +struct Guard<'a> { + _m: std::sync::MutexGuard<'a, ()>, + _f: std::fs::File, +} + +pub fn valid_name(n: &str) -> bool { + let n = n.trim(); + !n.is_empty() && n.chars().count() <= 64 && !n.chars().any(char::is_control) +} + +/// A Tessera root as Custos shows it: base64url of 32 bytes. +pub fn valid_root(r: &str) -> bool { + URL_SAFE_NO_PAD + .decode(r.trim()) + .is_ok_and(|b| b.len() == 32) +} + +/// The 6-digit match code of a Tessera key, exactly as Fundamentum's `tessera::match_code` +/// (docs/TESSERA.md §5): SHA-256 of `"tessera match v1"` and the key, first 4 bytes +/// big-endian, mod 10^6; shown as `474 719`. +pub fn match_code(root: &str) -> Option { + let b = URL_SAFE_NO_PAD.decode(root.trim()).ok()?; + let mut ctx = ring::digest::Context::new(&ring::digest::SHA256); + ctx.update(b"tessera match v1"); + ctx.update(&b); + let d = ctx.finish(); + let n = u32::from_be_bytes([d.as_ref()[0], d.as_ref()[1], d.as_ref()[2], d.as_ref()[3]]); + let c = n % 1_000_000; + Some(format!("{:03} {:03}", c / 1000, c % 1000)) +} + +fn secret(prefix: &str) -> Result { + Ok(format!( + "{prefix}_{}", + URL_SAFE_NO_PAD.encode(random::<32>().map_err(|e| e.to_string())?) + )) +} + +fn new_id() -> Result { + Ok(hex(&random::<8>().map_err(|e| e.to_string())?)) +} + +impl Team { + pub fn new(state_dir: &Path) -> Team { + Team { + path: state_dir.join("team.json"), + lock: std::sync::Mutex::new(()), + } + } + + fn guard(&self) -> Result, String> { + let m = self + .lock + .lock() + .map_err(|_| "team store unavailable".to_owned())?; + let path = self.path.with_file_name("team.lock"); + if let Some(d) = path.parent() { + std::fs::create_dir_all(d) + .map_err(|e| format!("cannot create {}: {e}", d.display()))?; + } + let f = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&path) + .map_err(|e| format!("cannot open {}: {e}", path.display()))?; + f.lock() + .map_err(|e| format!("cannot lock {}: {e}", path.display()))?; + Ok(Guard { _m: m, _f: f }) + } + + fn load(&self) -> Result { + let mut f: TeamFile = read_json(&self.path)?.unwrap_or_default(); + let t = now(); + f.sessions.retain(|s| s.expires_at > t); + f.codes.retain(|c| c.expires_at > t); + Ok(f) + } + + fn save(&self, f: &TeamFile) -> Result<(), String> { + write_json(&self.path, f) + } + + pub fn members(&self) -> Result, String> { + let _g = self.guard()?; + Ok(self.load()?.members) + } + + /// Open invites (never their values). + pub fn codes(&self) -> Result, String> { + let _g = self.guard()?; + Ok(self.load()?.codes) + } + + pub fn has_members(&self) -> bool { + self.members().is_ok_and(|m| !m.is_empty()) + } + + /// A new setup code for the founding admin, while the team has no member. Older setup + /// codes stop working. + pub fn setup_code(&self) -> Result<(String, u64), String> { + let _g = self.guard()?; + let mut f = self.load()?; + if !f.members.is_empty() { + return Err( + "the team already has members; an admin invites people from Settings → Team".into(), + ); + } + f.codes.retain(|c| c.kind != "setup"); + let value = secret("isc")?; + let expires_at = now() + CODE_SECS; + f.codes.push(Code { + id: new_id()?, + sha256: sha256_hex(value.as_bytes()), + kind: "setup".into(), + role: Role::Admin, + name: None, + expires_at, + created_by: "setup".into(), + }); + self.save(&f)?; + Ok((value, expires_at)) + } + + /// An invite for one person (admin only, checked by the caller). + pub fn invite(&self, name: &str, role: Role, by: &str) -> Result<(Code, String), Refused> { + let _g = self.guard().map_err(|_| Refused("internal"))?; + let mut f = self.load().map_err(|_| Refused("internal"))?; + if !valid_name(name) { + return Err(Refused("team.name")); + } + if f.codes.len() >= MAX_CODES || f.members.len() >= MAX_MEMBERS { + return Err(Refused("team.full")); + } + let value = secret("iin").map_err(|_| Refused("internal"))?; + let code = Code { + id: new_id().map_err(|_| Refused("internal"))?, + sha256: sha256_hex(value.as_bytes()), + kind: "invite".into(), + role, + name: Some(name.trim().to_owned()), + expires_at: now() + CODE_SECS, + created_by: by.to_owned(), + }; + f.codes.push(code.clone()); + self.save(&f).map_err(|_| Refused("internal"))?; + Ok((code, value)) + } + + pub fn cancel_invite(&self, id: &str) -> Result { + let _g = self.guard()?; + let mut f = self.load()?; + let before = f.codes.len(); + f.codes.retain(|c| !(c.id == id && c.kind == "invite")); + let gone = f.codes.len() != before; + self.save(&f)?; + Ok(gone) + } + + /// Redeem a setup or invite code: the member (made now) and a new session's value. + pub fn redeem( + &self, + code: &str, + name: Option<&str>, + device: &str, + ) -> Result<(Member, String), Refused> { + let _g = self.guard().map_err(|_| Refused("internal"))?; + let mut f = self.load().map_err(|_| Refused("internal"))?; + let presented = sha256_hex(code.trim().as_bytes()); + let Some(pos) = f + .codes + .iter() + .position(|c| ct_eq(c.sha256.as_bytes(), presented.as_bytes())) + else { + return Err(Refused("session.code")); + }; + let c = f.codes.remove(pos); + if c.kind == "setup" && !f.members.is_empty() { + return Err(Refused("session.code")); + } + let name = match (c.name.as_deref(), name) { + (Some(n), _) => n.to_owned(), + (None, Some(n)) if valid_name(n) => n.trim().to_owned(), + (None, _) => "Admin".to_owned(), + }; + if f.members.len() >= MAX_MEMBERS { + return Err(Refused("team.full")); + } + let member = Member { + id: new_id().map_err(|_| Refused("internal"))?, + name, + role: c.role, + tessera_root: None, + added_at: now(), + added_by: c.created_by.clone(), + }; + f.members.push(member.clone()); + let value = self.push_session(&mut f, &member.id, device)?; + self.save(&f).map_err(|_| Refused("internal"))?; + Ok((member, value)) + } + + fn push_session( + &self, + f: &mut TeamFile, + member: &str, + device: &str, + ) -> Result { + let value = secret("ise").map_err(|_| Refused("internal"))?; + let t = now(); + if f.sessions.len() >= MAX_SESSIONS { + // The oldest one goes. + f.sessions.sort_by_key(|s| s.created_at); + f.sessions.remove(0); + } + let device = if valid_name(device) { + device.trim().to_owned() + } else { + "Browser".to_owned() + }; + f.sessions.push(Session { + id: new_id().map_err(|_| Refused("internal"))?, + sha256: sha256_hex(value.as_bytes()), + member: member.to_owned(), + device, + created_at: t, + expires_at: t + SESSION_SECS, + last_used_at: Some(t), + }); + Ok(value) + } + + /// The member and session behind a cookie value. + pub fn check(&self, value: &str) -> Option<(Member, Session)> { + if !value.starts_with("ise_") || value.len() > 100 { + return None; + } + let _g = self.guard().ok()?; + let mut f = self.load().ok()?; + let presented = sha256_hex(value.as_bytes()); + let s = f + .sessions + .iter_mut() + .find(|s| ct_eq(s.sha256.as_bytes(), presented.as_bytes()))?; + let t = now(); + let touch = s.last_used_at.is_none_or(|l| t.saturating_sub(l) >= 60); + if touch { + s.last_used_at = Some(t); + } + let s = s.clone(); + let m = f.members.iter().find(|m| m.id == s.member)?.clone(); + if touch { + let _ = self.save(&f); + } + Some((m, s)) + } + + pub fn end_session(&self, id: &str) -> Result<(), String> { + let _g = self.guard()?; + let mut f = self.load()?; + f.sessions.retain(|s| s.id != id); + self.save(&f) + } + + /// Remove a member and every session of theirs. The last admin stays. + pub fn remove(&self, id: &str) -> Result, Refused> { + let _g = self.guard().map_err(|_| Refused("internal"))?; + let mut f = self.load().map_err(|_| Refused("internal"))?; + let Some(m) = f.members.iter().find(|m| m.id == id).cloned() else { + return Ok(None); + }; + let admins = f.members.iter().filter(|m| m.role == Role::Admin).count(); + if m.role == Role::Admin && admins <= 1 { + return Err(Refused("team.last_admin")); + } + f.members.retain(|x| x.id != id); + f.sessions.retain(|s| s.member != id); + self.save(&f).map_err(|_| Refused("internal"))?; + Ok(Some(m)) + } + + /// Record (or clear) a member's own Tessera root. + pub fn set_root(&self, member: &str, root: Option<&str>) -> Result<(), Refused> { + if root.is_some_and(|r| !valid_root(r)) { + return Err(Refused("team.root")); + } + let _g = self.guard().map_err(|_| Refused("internal"))?; + let mut f = self.load().map_err(|_| Refused("internal"))?; + let m = f + .members + .iter_mut() + .find(|m| m.id == member) + .ok_or(Refused("team.not_found"))?; + m.tessera_root = root.map(|r| r.trim().to_owned()); + self.save(&f).map_err(|_| Refused("internal")) + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + fn dir(n: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("ianitor-team-{n}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d + } + + #[test] + fn setup_then_invite_then_sessions() { + let d = dir("flow"); + let t = Team::new(&d); + let (setup, _) = t.setup_code().unwrap(); + assert!(t.redeem("isc_wrong", Some("Mark"), "Laptop").is_err()); + let (mark, s1) = t.redeem(&setup, Some("Mark"), "Laptop").unwrap(); + assert_eq!(mark.role, Role::Admin); + // One use only, and no second setup once there is a member. + assert_eq!( + t.redeem(&setup, Some("Eve"), "x").unwrap_err(), + Refused("session.code") + ); + assert!(t.setup_code().is_err()); + let (who, _) = t.check(&s1).unwrap(); + assert_eq!(who.name, "Mark"); + // Only hashes on disk. + let stored = std::fs::read_to_string(d.join("team.json")).unwrap(); + assert!(!stored.contains(&s1) && !stored.contains(&setup)); + let (_, inv) = t.invite("Petra", Role::Member, &mark.id).unwrap(); + let (petra, s2) = t.redeem(&inv, Some("Someone else"), "Phone").unwrap(); + assert_eq!((petra.name.as_str(), petra.role), ("Petra", Role::Member)); + // The last admin cannot go; a member can, with their sessions. + assert_eq!(t.remove(&mark.id).unwrap_err(), Refused("team.last_admin")); + t.remove(&petra.id).unwrap(); + assert!(t.check(&s2).is_none()); + let (_, s) = t.check(&s1).unwrap(); + t.end_session(&s.id).unwrap(); + assert!(t.check(&s1).is_none()); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn tessera_roots_are_checked() { + assert!(valid_root(&URL_SAFE_NO_PAD.encode([7u8; 32]))); + assert!(!valid_root("not base64!")); + assert!(!valid_root(&URL_SAFE_NO_PAD.encode([7u8; 31]))); + // Fundamentum's vector (crates/tessera/tests/mandatory.rs, MATCH_SEVENS = "016810"). + assert_eq!( + match_code(&URL_SAFE_NO_PAD.encode([7u8; 32])).unwrap(), + "016 810" + ); + } +} diff --git a/crates/control/tests/team.rs b/crates/control/tests/team.rs new file mode 100644 index 0000000..a81e2ec --- /dev/null +++ b/crates/control/tests/team.rs @@ -0,0 +1,257 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Team sign-in without Authelia (T4): the setup link makes the founding admin, invites make +//! members, a session cookie identifies them, members cannot do admin things, and browser +//! writes need the UI header. Runs on Windows and Linux (control in this process, no edge). + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::net::SocketAddr; +use std::time::Duration; + +use ianitor_control::Config; +use ianitor_control::team::Team; +use ianitor_testkit::more::{JsonResp, tcp_json}; +use ianitor_testkit::proc::{TempDir, free_port, local, wait_for_port}; +use serde_json::{Value, json}; + +fn s(p: &std::path::Path) -> String { + p.to_string_lossy().replace('\\', "/") +} + +async fn start() -> (TempDir, SocketAddr, tokio::sync::oneshot::Sender<()>) { + let dir = TempDir::new("team"); + std::fs::create_dir_all(dir.join("state")).unwrap(); + let api = local(free_port()); + let text = format!( + "listen = \"{api}\"\nstate_dir = \"{st}\"\n\n[routes]\nrepo = \"{repo}\"\n\n[edge]\nconfig = \"{d}/edge.json\"\nshare_revocations = \"{d}/rev.json\"\n\n[caddy]\nconfig = \"{d}/caddy.json\"\n\n[compile]\nhttp_listen = \"127.0.0.1:{h}\"\nhttps_listen = \"127.0.0.1:{hs}\"\ncert_dir = \"{d}\"\nstate_dir = \"{d}\"\naccess_log = \"{d}/a.log\"\ncaddy_credentials_dir = \"{d}\"\n", + st = s(&dir.join("state")), + repo = s(&dir.join("routes.git")), + d = s(dir.path()), + h = free_port(), + hs = free_port(), + ); + std::fs::write(dir.join("control.toml"), text).unwrap(); + let cfg = Config::load(&dir.join("control.toml")).unwrap(); + let (tx, rx) = tokio::sync::oneshot::channel::<()>(); + tokio::spawn(ianitor_control::serve(cfg, async { + let _ = rx.await; + })); + assert!(wait_for_port(api, Duration::from_secs(20))); + (dir, api, tx) +} + +async fn req(api: SocketAddr, m: &str, p: &str, h: &[(&str, &str)], b: Option) -> JsonResp { + tcp_json(api, m, p, h, b.as_ref()).await.unwrap() +} + +fn cookie_of(r: &JsonResp) -> String { + let set = r + .headers + .iter() + .find(|(n, _)| n == "set-cookie") + .map(|(_, v)| v.clone()) + .expect("a Set-Cookie"); + for part in ["HttpOnly", "Secure", "SameSite=Strict", "Path=/"] { + assert!(set.contains(part), "{set}"); + } + assert!(set.starts_with("__Host-ianitor=ise_"), "{set}"); + set.split(';').next().unwrap().to_owned() +} + +async fn sign_in(api: SocketAddr, code: &str, name: &str) -> (JsonResp, String) { + let r = req( + api, + "POST", + "/api/v1/session", + &[("X-Ianitor-UI", "1"), ("Sec-Fetch-Site", "same-origin")], + Some(json!({"code": code, "name": name, "device": "Laptop"})), + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + let c = cookie_of(&r); + (r, c) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_setup_link_then_invites_sign_a_team_in() { + let (dir, api, _stop) = start().await; + let (setup, _) = Team::new(&dir.join("state")).setup_code().unwrap(); + + // The door refuses bad codes, other sites and pages that are not the UI. + for (headers, code) in [ + (vec![("X-Ianitor-UI", "1")], "isc_wrong"), + (vec![], setup.as_str()), + ( + vec![("X-Ianitor-UI", "1"), ("Sec-Fetch-Site", "cross-site")], + setup.as_str(), + ), + ] { + let r = req( + api, + "POST", + "/api/v1/session", + &headers, + Some(json!({"code": code})), + ) + .await; + assert!( + r.status == 401 || r.status == 403, + "{headers:?}: {}", + r.text + ); + assert!(!r.headers.iter().any(|(n, _)| n == "set-cookie")); + } + + let (r, mark) = sign_in(api, &setup, "Mark").await; + assert_eq!(r.json["member"]["role"], "admin"); + let ov = req(api, "GET", "/api/v1/overview", &[("Cookie", &mark)], None).await; + assert_eq!(ov.status, 200, "{}", ov.text); + assert_eq!(ov.json["viewer"]["via"], "session"); + assert_eq!(ov.json["viewer"]["name"], "Mark"); + // The setup link worked once. + let r = req( + api, + "POST", + "/api/v1/session", + &[("X-Ianitor-UI", "1")], + Some(json!({"code": setup})), + ) + .await; + assert_eq!(r.status, 401, "{}", r.text); + + // A browser write without the UI header is refused (CSRF), with it it works. + let r = req( + api, + "POST", + "/api/v1/team/invites", + &[("Cookie", &mark)], + Some(json!({"name": "Petra"})), + ) + .await; + assert_eq!(r.status, 403, "{}", r.text); + assert_eq!(r.json["error"]["code"], "request.csrf"); + let r = req( + api, + "POST", + "/api/v1/team/invites", + &[("Cookie", &mark), ("X-Ianitor-UI", "1")], + Some(json!({"name": "Petra", "role": "member"})), + ) + .await; + assert_eq!(r.status, 201, "{}", r.text); + let code = r.json["link_fragment"] + .as_str() + .unwrap() + .strip_prefix("#signin=") + .unwrap() + .to_owned(); + + // Petra is a member: hosts yes, tokens, the team and the engine no. + let (_, petra) = sign_in(api, &code, "Not Petra").await; + let team = req(api, "GET", "/api/v1/team", &[("Cookie", &petra)], None).await; + assert_eq!(team.json["me"]["name"], "Petra", "{}", team.text); + for (m, p, b) in [ + ("GET", "/api/v1/tokens", None), + ("POST", "/api/v1/tokens", Some(json!({"name": "x"}))), + ( + "POST", + "/api/v1/team/invites", + Some(json!({"name": "Eve", "role": "admin"})), + ), + ("POST", "/api/v1/engine", Some(json!({"target": "caddy"}))), + ] { + let r = req(api, m, p, &[("Cookie", &petra), ("X-Ianitor-UI", "1")], b).await; + assert_eq!(r.status, 403, "{m} {p}: {}", r.text); + assert_eq!(r.json["error"]["code"], "team.admin_only", "{m} {p}"); + } + let r = req( + api, + "POST", + "/api/v1/hosts", + &[("Cookie", &petra), ("X-Ianitor-UI", "1")], + Some( + json!({"host": {"hostname": "wiki.example.test", "upstreams": ["http://10.0.0.2:80"]}}), + ), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + + // A member records their Tessera root; the list shows its match code. + let root = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc"; + let r = req( + api, + "PUT", + "/api/v1/team/me/root", + &[("Cookie", &petra), ("X-Ianitor-UI", "1")], + Some(json!({"tessera_root": root})), + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + let team = req(api, "GET", "/api/v1/team", &[("Cookie", &mark)], None).await; + let p = team.json["members"] + .as_array() + .unwrap() + .iter() + .find(|m| m["name"] == "Petra") + .unwrap() + .clone(); + assert_eq!(p["match_code"], "016 810"); + + // Removing Petra signs her out; a forged cookie gets nothing; the last admin stays. + let id = p["id"].as_str().unwrap(); + let r = req( + api, + "DELETE", + &format!("/api/v1/team/members/{id}"), + &[("Cookie", &mark), ("X-Ianitor-UI", "1")], + None, + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + let r = req(api, "GET", "/api/v1/overview", &[("Cookie", &petra)], None).await; + assert_eq!(r.status, 401, "{}", r.text); + let r = req( + api, + "GET", + "/api/v1/overview", + &[("Cookie", "__Host-ianitor=ise_forged")], + None, + ) + .await; + assert_eq!(r.status, 401); + let me = team.json["members"] + .as_array() + .unwrap() + .iter() + .find(|m| m["name"] == "Mark") + .unwrap()["id"] + .as_str() + .unwrap() + .to_owned(); + let r = req( + api, + "DELETE", + &format!("/api/v1/team/members/{me}"), + &[("Cookie", &mark), ("X-Ianitor-UI", "1")], + None, + ) + .await; + assert_eq!(r.status, 409, "{}", r.text); + assert_eq!(r.json["error"]["code"], "team.last_admin"); + + // Signing out ends this browser's session. + let r = req( + api, + "POST", + "/api/v1/session/end", + &[("Cookie", &mark), ("X-Ianitor-UI", "1")], + None, + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + let r = req(api, "GET", "/api/v1/overview", &[("Cookie", &mark)], None).await; + assert_eq!(r.status, 401); +}