diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ca3726176..66c0e36d8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -192,6 +192,9 @@ jobs: AUTH_PUBLIC_BASE_URL: https://localhost:3443 AUTH_PUBLIC_LISTENER: 127.0.0.1:3000 AUTH_INVITE_REQUIRED: 'false' + # The suite runs serially from one address, and spends in a minute what a + # person would in an hour. + AUTH_REQUESTS_PER_MINUTE: '1000' # The dashboard on its own host, as admin.piquel.fr is: browsers resolve # `*.localhost` to the loopback address. AUTH_ADMIN_LISTENER: 127.0.0.1:3001 diff --git a/README.md b/README.md index 4921b9223..5c46a834a 100644 --- a/README.md +++ b/README.md @@ -23,9 +23,10 @@ just build ``` The executables are `target/release/auth-service` and `target/release/piquel-web`. -Auth embeds the stylesheet (`crates/ui/assets/style.css`) and the passkey script -(`apps/auth-service/assets/passkey.js`) as they are, and piquel-web the stylesheet -and the policies (`apps/web/assets/policies/`); rebuild Rust after changing them. +Both embed the stylesheet (`crates/ui/assets/style.css`) and its typefaces +(`crates/ui/assets/fonts`, under the SIL Open Font License); auth also embeds the +passkey script (`apps/auth-service/assets/passkey.js`), and piquel-web the +policies (`apps/web/assets/policies/`). Rebuild Rust after changing them. ## Development @@ -50,6 +51,7 @@ work from devices on the tailnet. Run the same command after changing code. | `AUTH_DATABASE_OWNER_URL`, `AUTH_DATABASE_OWNER_PASSWORD` | Optional schema owner `migrate` connects as instead, in the same formats. It then creates or resets the role `AUTH_DATABASE_URL` names, with the `AUTH_DATABASE_PASSWORD` password and only row access to the app tables. The owner must be a superuser | | `AUTH_PUBLIC_BASE_URL` | Exact auth origin, normally `https://auth.piquel.fr` | | `AUTH_TRUSTED_PROXIES` | Optional comma-separated proxy peer IPs or CIDRs; these peers must overwrite `X-Forwarded-For` with one client IP. Defaults to piqueld's `PIQUELD_INGRESS_PROXIES` | +| `AUTH_REQUESTS_PER_MINUTE` | Optional requests a client may make a minute in each rate category (pages, sign-in, tokens, …); defaults to `120` | | `AUTH_PUBLIC_LISTENER` | Listener address; defaults to `127.0.0.1:8080` | | `AUTH_ADMIN_LISTENER`, `AUTH_ADMIN_ORIGIN` | Optional address of the admin dashboard's listener, e.g. `0.0.0.0:8081`, and the dashboard's origin, e.g. `https://admin.piquel.fr`, set together. Only a private route may reach the listener. Without them, auth serves no dashboard | | `AUTH_WEB_ORIGIN` | piquel.fr's origin, whose privacy policy and terms every page links and discovery advertises; defaults to `https://piquel.fr` | diff --git a/apps/auth-service/src/admin/mod.rs b/apps/auth-service/src/admin/mod.rs index 3f4216ef6..13ab1cae6 100644 --- a/apps/auth-service/src/admin/mod.rs +++ b/apps/auth-service/src/admin/mod.rs @@ -11,6 +11,8 @@ mod error; mod operation; /// Who runs an administrative operation. mod operator; +/// The dashboard's overview. +mod overview; /// The service shared by the dashboard and the CLI. mod service; /// Signing administrators in to the dashboard. @@ -22,6 +24,7 @@ pub use error::AdminError; pub(crate) use operation::AdminOperation; use operator::AdminSession; pub use operator::Operator; +pub(crate) use overview::{Kinds, Overview, Problem}; pub use service::AdminService; pub(crate) use sign_in::{DashboardSignIn, SignedInAdmin}; pub use types::{GracePeriod, HandleProblem, InvalidLifetime, InviteExpiry, Reason, UserRef}; diff --git a/apps/auth-service/src/admin/overview.rs b/apps/auth-service/src/admin/overview.rs new file mode 100644 index 000000000..852420b94 --- /dev/null +++ b/apps/auth-service/src/admin/overview.rs @@ -0,0 +1,197 @@ +//! The dashboard's overview: what the service is doing now, against what it +//! usually does, and what needs an administrator's attention. + +use super::{AdminError, AdminService, Operator}; +use chrono::{DateTime, Duration, Utc}; +use piquel_common::admin::{Event, EventSearch, User}; +use piquel_repository::{DeliveryBacklog, Email}; + +/// How many of the newest events the overview shows. +const EVENTS_SHOWN: usize = 8; +/// How many of the newest accounts the overview shows. +const NEWEST_SHOWN: u16 = 6; +/// The hours of the week a rate is averaged over. +const HOURS_PER_WEEK: u64 = 7 * 24; +/// How long a message may wait before its backlog needs attention. +const DELIVERY_PATIENCE: Duration = Duration::minutes(15); + +/// The kinds of event the overview counts, by the serde tags +/// [`DomainEvent`](piquel_common::events::DomainEvent) stores them under. +pub(crate) struct Kinds; + +impl Kinds { + /// A rejected passkey or provider authentication. + pub(crate) const FAILED: &'static str = "sign_in_failed"; + /// A browser signed in. + const SIGNED_IN: &'static str = "signed_in"; + /// A client exchanged a code for tokens. + const GRANT: &'static str = "grant_issued"; +} + +/// How often something happened in the last hour, against an hour's usual +/// count over the last week. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Rate { + /// In the last hour. + pub last_hour: u64, + /// Per hour, averaged over the week before, rounded up. + pub usual: u64, +} + +impl Rate { + /// The rate of `last_hour` against `week`, a week's total that includes the + /// last hour: the usual hour is the week before it, so a spike never raises + /// its own baseline. + const fn new(last_hour: u64, week: u64) -> Self { + Self { + last_hour, + usual: week.saturating_sub(last_hour).div_ceil(HOURS_PER_WEEK - 1), + } + } + + /// Whether the last hour is a spike: at least ten, and more than three times + /// usual, so a quiet service's first failures raise nothing. + const fn spikes(self) -> bool { + self.last_hour >= 10 && self.last_hour > self.usual.saturating_mul(3) + } +} + +/// What needs an administrator's attention. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Problem { + /// Far more sign-ins failed in the last hour than usually do. + FailedSignIns(Rate), + /// Messages wait to be delivered, the oldest for longer than they should. + DeliveriesWaiting { + /// How many wait. + pending: u64, + /// Since when the oldest waits. + oldest: DateTime, + }, +} + +/// What the overview shows. +#[derive(Clone, Debug)] +pub struct Overview { + /// Rejected passkey and provider authentications. + pub failed_sign_ins: Rate, + /// Browsers signing in. + pub sign_ins: Rate, + /// Clients exchanging codes for tokens. + pub app_sign_ins: Rate, + /// Sessions signed in now. + pub active_sessions: u64, + /// Every account. + pub accounts: u64, + /// The accounts administering Piquel. + pub administrators: u64, + /// The newest events. + pub events: Vec, + /// The newest accounts. + pub newest: Vec, + /// The emails waiting to be sent. + pub email_backlog: DeliveryBacklog, + /// When it was read. + pub now: DateTime, +} + +impl Overview { + /// What needs attention, most pressing first. + #[must_use] + pub fn problems(&self) -> Vec { + let mut problems = Vec::new(); + if self.failed_sign_ins.spikes() { + problems.push(Problem::FailedSignIns(self.failed_sign_ins)); + } + if let Some(oldest) = self.email_backlog.oldest + && self.now - oldest > DELIVERY_PATIENCE + { + problems.push(Problem::DeliveriesWaiting { + pending: self.email_backlog.pending, + oldest, + }); + } + problems + } +} + +impl AdminService { + /// Reads the overview: the last hour's rates against the week's, what is + /// signed in now, the newest events and accounts, and the email backlog. + /// + /// # Errors + /// Fails when the operator may not read, or a query fails. + pub(crate) async fn overview(&self, operator: &Operator) -> Result { + operator.authorize_read(&self.database).await?; + let now = Utc::now(); + let (hour, week) = (now - Duration::hours(1), now - Duration::days(7)); + let mut events = self.database.events(); + let mut rate = async |kind: &str| -> Result { + let kinds = [kind.to_owned()]; + let last_hour = events.count_since(None, &kinds, hour).await?; + let weekly = events.count_since(None, &kinds, week).await?; + Ok(Rate::new(last_hour, weekly)) + }; + let failed_sign_ins = rate(Kinds::FAILED).await?; + let sign_ins = rate(Kinds::SIGNED_IN).await?; + let app_sign_ins = rate(Kinds::GRANT).await?; + let mut newest_events = self.events(operator, EventSearch::default()).await?.events; + newest_events.truncate(EVENTS_SHOWN); + Ok(Overview { + failed_sign_ins, + sign_ins, + app_sign_ins, + active_sessions: self.database.sessions().count_active().await?, + accounts: self.database.users().count().await?, + administrators: u64::try_from(self.database.administrators().list().await?.len()) + .unwrap_or(u64::MAX), + events: newest_events, + newest: self.database.users().newest(NEWEST_SHOWN).await?, + email_backlog: self.database.deliveries().backlog::().await?, + now, + }) + } +} + +#[cfg(test)] +mod tests { + //! The overview's arithmetic. + use super::*; + use piquel_common::{ + AuthenticationMethod, SessionId, + events::{DomainEvent, SignInFailure}, + }; + + /// The kinds counted are the tags the events are stored under. + #[test] + fn the_counted_kinds_are_the_stored_tags() { + let failed = DomainEvent::SignInFailed { + method: AuthenticationMethod::Passkey, + reason: SignInFailure::InvalidCredential, + }; + assert_eq!(failed.kind(), Kinds::FAILED); + let signed_in = DomainEvent::SignedIn { + session_id: SessionId::new(), + method: AuthenticationMethod::Passkey, + inline: None, + }; + assert_eq!(signed_in.kind(), Kinds::SIGNED_IN); + let grant = DomainEvent::GrantIssued { + client_id: "notes".parse().expect("client ID"), + family_id: None, + scopes: Vec::new(), + }; + assert_eq!(grant.kind(), Kinds::GRANT); + } + + /// A spike needs both a floor and a multiple of usual: a quiet week's first + /// failures are no alarm, and a busy service's usual failures are none either. + #[test] + fn a_spike_is_at_least_ten_and_over_three_times_usual() { + assert!(!Rate::new(9, 0).spikes()); + assert!(Rate::new(10, 0).spikes()); + assert!(!Rate::new(30, HOURS_PER_WEEK * 10).spikes()); + assert!(Rate::new(31, HOURS_PER_WEEK * 10).spikes()); + assert_eq!(Rate::new(0, 1).usual, 1, "a week's one failure rounds up"); + } +} diff --git a/apps/auth-service/src/admin/service.rs b/apps/auth-service/src/admin/service.rs index 36f87f1a5..f9ac96f3a 100644 --- a/apps/auth-service/src/admin/service.rs +++ b/apps/auth-service/src/admin/service.rs @@ -17,7 +17,7 @@ use piquel_common::{ AccountStatus, ClientId, DeliveryId, Handle, Personal, RecoveryId, SessionId, TokenId, UserId, admin::{ Administrator, ApprovedOrigin, Client, CreatedInvitation, Email, Event, EventPage, - EventSearch, Invitation, ScheduledDeletion, UserDetail, UserPage, + EventSearch, Invitation, Paging, ScheduledDeletion, UserDetail, UserPage, }, clients::{ClientField, ClientOwner, ClientRegistration, RelatedOrigin}, config::Origin, @@ -35,7 +35,7 @@ use url::Url; /// Accounts per search page. const USER_PAGE_SIZE: u16 = 50; /// Events per page. -const EVENT_PAGE_SIZE: u16 = 100; +const EVENT_PAGE_SIZE: u16 = 50; /// Owns each administrative operation. Dashboard pages and CLI commands are thin /// adapters that say which [`Operator`] acts. Every mutation, and viewing an @@ -56,7 +56,7 @@ const EVENT_PAGE_SIZE: u16 = 100; #[derive(Clone)] pub struct AdminService { /// Accounts, sessions, invitations, clients, events, deliveries and administrators. - database: Database, + pub(super) database: Database, /// Whether email is enabled, so a recovery link can be mailed. mails: bool, } @@ -125,23 +125,21 @@ impl AdminService { found.ok_or(AdminError::UserNotFound) } - /// Lists accounts matching `query`, by ID, after the `cursor` of a previous page. + /// Lists `page` of the accounts matching `query`, by handle: the first page + /// when `None`. pub(crate) async fn search_users( &self, operator: &Operator, query: &str, - cursor: Option, + page: Option, ) -> Result { operator.authorize_read(&self.database).await?; - let users = self - .database - .users() - .search(query.trim(), cursor, USER_PAGE_SIZE) - .await?; - let next = (users.len() == usize::from(USER_PAGE_SIZE)) - .then(|| users.last().map(|user| user.id)) - .flatten(); - Ok(UserPage { users, next }) + let query = query.trim(); + let mut users = self.database.users(); + let total = users.count_matching(query).await?; + let paging = Paging::new(page, total, u32::from(USER_PAGE_SIZE)); + let users = users.search(query, paging.offset(), USER_PAGE_SIZE).await?; + Ok(UserPage { users, paging }) } /// Returns an account's profile, emails, status, passkey labels, identities, @@ -802,27 +800,23 @@ impl AdminService { .await } - /// Returns a page of the events matching `search`, newest first. + /// Returns the page of the events matching `search`, newest first. pub(crate) async fn events( &self, operator: &Operator, search: EventSearch, ) -> Result { operator.authorize_read(&self.database).await?; - let filter = EventFilter { + let mut filter = EventFilter { subject: search.user, kind: search.kind, - before: search.before, - id: None, + ..EventFilter::default() }; - let stored = self - .database - .events() - .list(&filter, u32::from(EVENT_PAGE_SIZE)) - .await?; - let next = (stored.len() == usize::from(EVENT_PAGE_SIZE)) - .then(|| stored.last().map(|event| event.id)) - .flatten(); + let mut events = self.database.events(); + let total = events.count(&filter).await?; + let paging = Paging::new(search.page, total, u32::from(EVENT_PAGE_SIZE)); + filter.offset = u32::try_from(paging.offset()).unwrap_or(u32::MAX); + let stored = events.list(&filter, u32::from(EVENT_PAGE_SIZE)).await?; let events = stored .into_iter() .map(|stored| { @@ -836,7 +830,7 @@ impl AdminService { }) }) .collect::>()?; - Ok(EventPage { events, next }) + Ok(EventPage { events, paging }) } /// Lists the accounts whose current handle is reserved, by handle: ones an diff --git a/apps/auth-service/src/admin/tests.rs b/apps/auth-service/src/admin/tests.rs index 9a56059bf..c193dbc8d 100644 --- a/apps/auth-service/src/admin/tests.rs +++ b/apps/auth-service/src/admin/tests.rs @@ -253,7 +253,7 @@ async fn disabling_ends_sessions_and_is_recorded() { EventSearch { user: Some(user.user_id), kind: Some("account_disabled".into()), - before: None, + page: None, }, ) .await diff --git a/apps/auth-service/src/assets.rs b/apps/auth-service/src/assets.rs index 7d629d8c3..c0e09df6d 100644 --- a/apps/auth-service/src/assets.rs +++ b/apps/auth-service/src/assets.rs @@ -1,5 +1,6 @@ -//! The stylesheet and passkey script of auth's pages, embedded under paths naming -//! their content, so browsers and shared caches keep them forever. +//! The stylesheet, typefaces and passkey script of auth's pages, embedded under +//! paths that never serve other content, so browsers and shared caches keep them +//! forever. use crate::security::{ApiError, CacheClass, Cached}; use axum::{ @@ -32,12 +33,21 @@ impl EmbeddedAssets { /// The passkey script, the one script of auth's pages. pub(crate) const SCRIPT: Asset = Asset::script("passkey", include_bytes!("../assets/passkey.js")); + /// The files the admin dashboard serves too: the stylesheet and the + /// typefaces it links. + pub(crate) const SHARED: [Asset; 4] = [ + Self::STYLESHEET, + piquel_ui::FONTS[0], + piquel_ui::FONTS[1], + piquel_ui::FONTS[2], + ]; /// Serves the embedded file at exactly `path`. A file's path changes with its - /// content, so nothing needs revalidating. + /// content, or its version, so nothing needs revalidating. pub(crate) fn serve(path: &str) -> Result { - let asset = [Self::STYLESHEET, Self::SCRIPT] + let asset = Self::SHARED .into_iter() + .chain([Self::SCRIPT]) .find(|asset| asset.path() == path) .ok_or(AssetError::NotFound)?; let headers = [(header::CONTENT_TYPE, asset.content_type())]; @@ -50,13 +60,15 @@ mod tests { //! Focused coverage of embedded file serving. use super::*; - /// The pages' stylesheet and passkey script are served at the paths naming their - /// content, as their own type, so they are cached forever. + /// The pages' stylesheet, typefaces and passkey script are served at the paths + /// naming their content or version, as their own type, so they are cached + /// forever. #[test] fn the_pages_files_are_immutable() { for (asset, content_type) in [ (EmbeddedAssets::STYLESHEET, "text/css; charset=utf-8"), (EmbeddedAssets::SCRIPT, "text/javascript; charset=utf-8"), + (piquel_ui::FONTS[0], "font/woff2"), ] { let response = EmbeddedAssets::serve(&asset.path()).expect("found"); assert_eq!(response.headers()[header::CONTENT_TYPE], content_type); diff --git a/apps/auth-service/src/cli/audit.rs b/apps/auth-service/src/cli/audit.rs index 3a570b4d4..32e9ec260 100644 --- a/apps/auth-service/src/cli/audit.rs +++ b/apps/auth-service/src/cli/audit.rs @@ -8,7 +8,6 @@ use crate::{ }; use clap::{Args, Subcommand}; use piquel_common::{ - EventId, admin::{EventPage, EventSearch}, events::Actor, }; @@ -17,7 +16,7 @@ use std::path::PathBuf; /// Paging through, verifying and pruning the audit history. #[derive(Subcommand)] pub(super) enum AuditCommand { - /// Page through recorded events, newest first, 100 at a time. + /// Page through recorded events, newest first. List(ListEvents), /// Recompute the chain and check every checkpoint against it. Exits non-zero, /// naming the first position that does not match, when the chain is broken. @@ -131,7 +130,7 @@ impl AuditCommand { } } -/// Page through recorded events, newest first, 100 at a time. +/// Page through recorded events, newest first. #[derive(Args)] pub(super) struct ListEvents { /// Only events concerning this account: its handle, ID or verified email. @@ -140,9 +139,9 @@ pub(super) struct ListEvents { /// Only events of this kind, e.g. `session_revoked`. #[arg(long)] kind: Option, - /// Continue with events older than this one, the last one listed. + /// The page to list, counting from 1 at the newest events. #[arg(long)] - before: Option, + page: Option, /// Output format. #[command(flatten)] output: Output, @@ -158,7 +157,7 @@ impl ListEvents { let search = EventSearch { user, kind: self.kind, - before: self.before, + page: self.page, }; self.output.print( &console.service.events(&console.operator, search).await?, @@ -181,9 +180,7 @@ impl ListEvents { event.event["kind"].as_str().unwrap_or("-"), ); } - if let Some(next) = page.next { - eprintln!("More may follow: --before {next}"); - } + Output::paging(page.paging, "events"); } /// Names who acted in a few words, or as the stored JSON when this release diff --git a/apps/auth-service/src/cli/console.rs b/apps/auth-service/src/cli/console.rs index c42882462..4baf47540 100644 --- a/apps/auth-service/src/cli/console.rs +++ b/apps/auth-service/src/cli/console.rs @@ -5,7 +5,7 @@ use super::CliError; use crate::{AdminService, AuthConfig, Operator, UserRef, account::AccountService}; use clap::{Args, ValueEnum}; -use piquel_common::UserId; +use piquel_common::{UserId, admin::Paging}; use piquel_repository::Database; use serde::Serialize; use std::io::{BufRead, IsTerminal}; @@ -74,6 +74,20 @@ impl Output { } Ok(()) } + + /// Says where a page of `what` stands, and how to go on, after a table. + pub(super) fn paging(paging: Paging, what: &str) { + eprintln!( + "Page {} of {}: {} {what} in all.{}", + paging.page, + paging.pages, + paging.total, + paging + .next() + .map(|next| format!(" Next: --page {next}")) + .unwrap_or_default() + ); + } } /// The `--yes` option of commands that cut off a whole account, administrator or diff --git a/apps/auth-service/src/cli/user.rs b/apps/auth-service/src/cli/user.rs index 6e922c728..22bcfa45d 100644 --- a/apps/auth-service/src/cli/user.rs +++ b/apps/auth-service/src/cli/user.rs @@ -6,7 +6,7 @@ use crate::{AdminError, AuthConfig, Reason, UserRef, recovery::Revoke}; use chrono::{DateTime, Utc}; use clap::Subcommand; use piquel_common::{ - PasskeyId, UserId, + PasskeyId, admin::{UserDetail, UserPage}, }; use piquel_repository::{RecentRecovery, RecoveryState}; @@ -15,14 +15,14 @@ use piquel_repository::{RecentRecovery, RecoveryState}; #[derive(Subcommand)] pub(super) enum UserCommand { /// Search accounts by ID, or by part of a handle, display name or email, - /// ignoring case. Lists 50 at a time, by ID. + /// ignoring case. Lists 50 at a time, by handle. Search { /// What to look for. Lists every account when empty. #[arg(default_value = "")] query: String, - /// Continue after this account ID, the last one listed. + /// The page to list, counting from 1. #[arg(long)] - cursor: Option, + page: Option, /// Output format. #[command(flatten)] output: Output, @@ -141,10 +141,10 @@ impl UserCommand { match self { Self::Search { query, - cursor, + page, output, } => output.print( - &service.search_users(operator, &query, cursor).await?, + &service.search_users(operator, &query, page).await?, Self::print_page, )?, Self::Show { user, output } => { @@ -327,9 +327,7 @@ impl UserCommand { user.display_name ); } - if let Some(next) = page.next { - eprintln!("More may follow: --cursor {next}"); - } + Output::paging(page.paging, "accounts"); } /// Prints an account's facts, then one section per kind of record. diff --git a/apps/auth-service/src/config.rs b/apps/auth-service/src/config.rs index 4c2374212..ff064fd7a 100644 --- a/apps/auth-service/src/config.rs +++ b/apps/auth-service/src/config.rs @@ -98,6 +98,11 @@ const INVITE_REQUIRED: Variable = Variable::new("AUTH_INVITE_REQUIRED"); const CLIENTS_FILE: Variable = Variable::new("AUTH_CLIENTS_FILE"); /// Operator-specified trusted ingress peers. const TRUSTED_PROXIES: Variable = Variable::new("AUTH_TRUSTED_PROXIES"); +/// How many requests a client may make a minute, in each rate category. +const REQUESTS_PER_MINUTE: Variable = Variable::new("AUTH_REQUESTS_PER_MINUTE"); +/// [`REQUESTS_PER_MINUTE`] when none is configured: enough for a person, not +/// for a browser suite or a scraper. +const DEFAULT_REQUESTS_PER_MINUTE: &str = "120"; /// Default ingress peers provided by piqueld. const INGRESS_PROXIES: Variable = Variable::new("PIQUELD_INGRESS_PROXIES"); @@ -747,6 +752,8 @@ pub struct AuthConfig { pub(crate) audit: AuditConfig, /// Trusted reverse-proxy peers. pub(crate) trusted_proxies: Vec, + /// How many requests a client may make a minute, in each rate category. + pub(crate) requests_per_minute: i32, } impl AuthConfig { @@ -830,9 +837,18 @@ impl AuthConfig { }, key_encryption_key: Arc::new(Self::key_encryption_key_from_environment()?), trusted_proxies: Self::trusted_proxies()?, + requests_per_minute: Self::requests_per_minute()?, }) } + /// `AUTH_REQUESTS_PER_MINUTE`, a positive count the counters can hold. + fn requests_per_minute() -> Result { + let budget: std::num::NonZeroU32 = + REQUESTS_PER_MINUTE.parse_or(DEFAULT_REQUESTS_PER_MINUTE)?; + i32::try_from(budget.get()) + .map_err(|source| REQUESTS_PER_MINUTE.error("is too large", source)) + } + /// Loads what the `user recover` command needs to print a recovery link: the /// public origin and the current token digest key, which every other setting /// can do without. diff --git a/apps/auth-service/src/history/mod.rs b/apps/auth-service/src/history/mod.rs index a19ca61a1..f7d6acd72 100644 --- a/apps/auth-service/src/history/mod.rs +++ b/apps/auth-service/src/history/mod.rs @@ -178,6 +178,93 @@ impl HistoryItem { } } +/// What happened to the account over a period, as its overview counts it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Activity { + /// How many times apps exchanged a code for tokens: sign-ins through apps. + pub(crate) app_sign_ins: u64, + /// How many security events were recorded: sign-ins, failures and changes. + pub(crate) security_events: u64, +} + +impl Activity { + /// The kind of event counted as a sign-in through an app, by the tag + /// [`DomainEvent`] stores it under. + const APP_SIGN_INS: [&'static str; 1] = ["grant_issued"]; + /// The kinds counted as security events: every kind the security history + /// shows, as [`DomainEvent::history_entry`] decides, so the count and the + /// feed agree, as far as a count by kind can: a refresh grant's revocation + /// is left out, since the history shows only a replay's, and a session's + /// expiry is counted, since the history hides only that reason. + const SECURITY: [&'static str; 29] = [ + "account_created", + "signed_in", + "session_revoked", + "passkey_added", + "passkey_renamed", + "passkey_removed", + "identity_linked", + "identity_unlinked", + "email_added", + "email_verified", + "primary_email_changed", + "email_removed", + "consent_granted", + "consent_revoked", + "code_replayed", + "account_disabled", + "account_enabled", + "account_viewed", + "administrator_granted", + "administrator_revoked", + "handle_changed", + "recovery_started", + "recovery_completed", + "recovery_undone", + "account_exported", + "account_deletion_scheduled", + "account_restored", + "compromise_reported", + "imported", + ]; +} + +impl AccountService { + /// Counts what happened to the account since `since`. + pub(crate) async fn activity( + &self, + viewer: &Viewer, + since: DateTime, + ) -> Result { + viewer.authorize(&self.database).await?; + let kinds = |kinds: &[&str]| { + kinds + .iter() + .map(|kind| (*kind).to_owned()) + .collect::>() + }; + let mut events = self.database.events(); + Ok(Activity { + app_sign_ins: events + .count_since(Some(viewer.user()), &kinds(&Activity::APP_SIGN_INS), since) + .await?, + security_events: events + .count_since(Some(viewer.user()), &kinds(&Activity::SECURITY), since) + .await?, + }) + } + + /// Whether the account administers Piquel, which its pages mark. + pub(crate) async fn is_administrator(&self, viewer: &Viewer) -> Result { + viewer.authorize(&self.database).await?; + Ok(self + .database + .administrators() + .contains(viewer.user()) + .await?) + } +} + impl HistoryApplication { /// Serves the history from `database`. pub(crate) const fn new(database: Database) -> Self { diff --git a/apps/auth-service/src/routes.rs b/apps/auth-service/src/routes.rs index ed3d0336c..12fca86f5 100644 --- a/apps/auth-service/src/routes.rs +++ b/apps/auth-service/src/routes.rs @@ -139,12 +139,15 @@ pub(crate) mod oidc { pub(crate) mod dashboard { /// Redeems auth's handoff code, signing the browser in to the dashboard. pub(crate) const SIGN_IN: &str = "/sign-in"; + /// Keeps the theme and sidebar preferences a page's forms post, in cookies. + pub(crate) const PREFERENCES: &str = "/preferences"; /// Every path the dashboard serves is one of these, or under one: the admin /// listener mounts the pages on them, and nowhere else. - pub(crate) const PREFIXES: [&str; 10] = [ + pub(crate) const PREFIXES: [&str; 11] = [ "/", SIGN_IN, "/sign-out", + PREFERENCES, "/assets", "/users", "/administrators", @@ -175,12 +178,16 @@ pub(crate) mod page { pub(crate) const RECOVER_UNDO: &str = "/recover/undo"; /// Hands an administrator's passkey session off to the admin dashboard. pub(crate) const ADMIN: &str = "/admin"; + /// Keeps the theme and sidebar preferences a page's forms post, in cookies. + pub(crate) const PREFERENCES: &str = "/preferences"; /// The account's settings, at the paths piquel.fr served them on, so its redirect /// keeps old links and sent emails working. pub(crate) mod settings { - /// Sign-in methods: passkeys and social sign-in. + /// The account at a glance. pub(crate) const HOME: &str = "/settings"; + /// Sign-in methods: passkeys and social sign-in. + pub(crate) const SIGN_IN: &str = "/settings/sign-in"; /// Email addresses. pub(crate) const EMAILS: &str = "/settings/emails"; /// Confirming an address, from its verification link. @@ -220,13 +227,15 @@ pub(crate) mod page { /// Every server-rendered page's route, which the security layer classifies as /// pages. - pub(crate) const ALL: [&str; 19] = [ + pub(crate) const ALL: [&str; 21] = [ LOGIN, REGISTER, CONSENT, LOGOUT, ADMIN, + PREFERENCES, settings::HOME, + settings::SIGN_IN, settings::EMAILS, settings::VERIFY, settings::SESSIONS, diff --git a/apps/auth-service/src/security/mod.rs b/apps/auth-service/src/security/mod.rs index 607940f7f..699abfb18 100644 --- a/apps/auth-service/src/security/mod.rs +++ b/apps/auth-service/src/security/mod.rs @@ -36,6 +36,7 @@ use piquel_repository::{ SessionAuthentication, SessionScope, StoredSession, }; use piquel_telemetry::{Counter, HttpTelemetry, Label}; +use piquel_ui::{PreferenceChange, Preferences}; use std::{ borrow::Cow, net::{IpAddr, SocketAddr}, @@ -50,8 +51,6 @@ pub(crate) const CSRF_HEADER: &str = "x-piquel-csrf"; const FETCH_SITE_HEADER: &str = "sec-fetch-site"; /// Trusted ingress must overwrite this header with exactly one client address. const FORWARDED_FOR_HEADER: &str = "x-forwarded-for"; -/// Request budget per category and client in each [`RATE_WINDOW`]. -const REQUESTS_PER_MINUTE: i32 = 120; /// Requests refused because their client's budget was exhausted, by category. static THROTTLED: Counter<[Label; 1]> = Counter::new( "piquel.auth.throttled", @@ -251,9 +250,16 @@ piquel_common::str_enum! { /// A sign-in to the admin dashboard awaiting auth's handoff, on the /// dashboard's origin. DashboardState = "__Host-piquel_dashboard_state", + /// The theme the browser chose, on each origin. + Theme = "__Host-piquel_theme", + /// The sidebar's width the browser chose, on each origin. + Sidebar = "__Host-piquel_sidebar", } } +/// How long a preference is kept: a year. +const PREFERENCE_MAX_AGE: u32 = 365 * 24 * 60 * 60; + impl BrowserCookie { /// Lifetime in seconds. Flow cookies outlive their server-side state slightly; a /// notice is shown on the page its change goes to, at once. @@ -266,9 +272,38 @@ impl BrowserCookie { | Self::DashboardState | Self::Restore => FLOW_COOKIE_MAX_AGE, Self::Notice => 60, + Self::Theme | Self::Sidebar => PREFERENCE_MAX_AGE, + } + } + + /// The theme and sidebar preferences the browser's cookies carry. A value + /// that is none counts as unset. + pub(crate) fn read_preferences(headers: &HeaderMap) -> Preferences { + Preferences { + theme: Self::Theme + .value(headers) + .and_then(|value| value.parse().ok()), + sidebar: Self::Sidebar + .value(headers) + .and_then(|value| value.parse().ok()), } } + /// Adds the `Set-Cookie` headers keeping what `change` chose, to the answer of + /// the preference page. + pub(crate) fn set_preferences_on( + response: &mut axum::http::Response, + change: &PreferenceChange, + ) -> Result<(), InvalidHeaderValue> { + if let Some(theme) = change.theme { + Self::Theme.append(response, theme.as_str(), Self::Theme.max_age())?; + } + if let Some(sidebar) = change.sidebar { + Self::Sidebar.append(response, sidebar.as_str(), Self::Sidebar.max_age())?; + } + Ok(()) + } + /// Reads this cookie's value. A duplicated cookie counts as absent, so an /// injected value can never shadow the browser's own. fn value(self, headers: &HeaderMap) -> Option<&str> { @@ -1229,6 +1264,8 @@ pub(crate) struct HttpSecurity { pub trusted_proxies: Arc>, /// Deadline for the whole request, handler included. pub request_timeout: StdDuration, + /// Request budget per category and client in each [`RATE_WINDOW`]. + pub requests_per_minute: i32, /// Origin of the listener's own pages, allowed on every endpoint. pub origin: url::Origin, /// Which listener it guards. @@ -1255,6 +1292,7 @@ impl HttpSecurity { database, trusted_proxies: Arc::new(config.trusted_proxies.clone()), request_timeout: REQUEST_TIMEOUT, + requests_per_minute: config.requests_per_minute, origin: config.passkey.origin.as_url().origin(), listener: Listener::Public, } @@ -1431,7 +1469,7 @@ impl HttpSecurity { if !self .database .security() - .allow_request(bucket.as_bytes(), REQUESTS_PER_MINUTE, RATE_WINDOW) + .allow_request(bucket.as_bytes(), self.requests_per_minute, RATE_WINDOW) .await? { THROTTLED.add(1, &[("category", category.as_str())]); diff --git a/apps/auth-service/src/security/tests.rs b/apps/auth-service/src/security/tests.rs index fc98ae93c..82ce7fd0d 100644 --- a/apps/auth-service/src/security/tests.rs +++ b/apps/auth-service/src/security/tests.rs @@ -2,7 +2,7 @@ use super::*; use crate::routes::{audit, federation, passkey}; -use crate::tests::Replicas; +use crate::tests::{REQUESTS_PER_MINUTE, Replicas}; use axum::{Router, body::Body, http::Request as HttpRequest, middleware, routing::any}; use piquel_common::{ Handle, TokenId, @@ -92,6 +92,7 @@ impl SecurityFixture { let policy = HttpSecurity { trusted_proxies: Arc::new(vec![]), request_timeout: std::time::Duration::from_secs(30), + requests_per_minute: REQUESTS_PER_MINUTE, database, origin: site(), listener: Listener::Public, diff --git a/apps/auth-service/src/tests.rs b/apps/auth-service/src/tests.rs index 7b49a88d0..f8bf77bf2 100644 --- a/apps/auth-service/src/tests.rs +++ b/apps/auth-service/src/tests.rs @@ -111,6 +111,7 @@ impl AuthConfig { key: Arc::new(NoteKey::generate("auth.piquel.fr/audit").expect("audit key")), }, trusted_proxies: vec![], + requests_per_minute: REQUESTS_PER_MINUTE, } } } @@ -184,6 +185,9 @@ impl Replicas { } } +/// The request budget the test configuration allows, as production does. +pub(crate) const REQUESTS_PER_MINUTE: i32 = 120; + /// Largest response body [`Browser::call`] and the page tests read. pub(crate) const MAX_RESPONSE_BYTES: usize = 256 * 1024; /// What a form on one of auth's pages sends: they have `Referrer-Policy: no-referrer`, diff --git a/apps/auth-service/src/web/account.rs b/apps/auth-service/src/web/account.rs index 66df419d2..ad9aa38ef 100644 --- a/apps/auth-service/src/web/account.rs +++ b/apps/auth-service/src/web/account.rs @@ -17,31 +17,29 @@ use crate::{ federation::FlowCookie, routes::page, security::{ApiError, BrowserCookie, SessionError}, + web::settings::TABS, }; use piquel_common::ErrorChain; -use piquel_ui::{Alert, Area, FieldError, LoginQuery, Messages, Notice, Query, Recovery, Section}; +use piquel_telemetry::HttpTelemetry; +use piquel_ui::{ + AccountNav, Alert, FieldError, LoginQuery, Messages, Notice, Query, Recovery, Section, Tab, Who, +}; use serde::{Deserialize, de::DeserializeOwned}; use topcoat::{ Error, context::{Cx, app_context}, router::{ - Body, RouteHandlerFn, StatusCode, + Body, Method, RouteHandlerFn, StatusCode, content::Form, error::see_other, parse_query_params, - request::{FromRequest, headers, uri}, + request::{FromRequest, headers, method, uri}, response::{IntoResponse, Response}, }, view::{Child, view}, }; use url::Url; -/// Each section of the account's pages and the page the account's bar links. -const SECTIONS: [(Section, &str); 2] = [ - (Section::Account, page::settings::HOME), - (Section::Developers, page::developers::HOME), -]; - /// A page of the signed-in account: its section and path, the change its form /// posts, its query, what a change does, and how the page renders. /// [`WebApplication::show`] and [`WebApplication::submit`] serve it. @@ -223,9 +221,11 @@ impl Reader { pub(super) struct Framed<'a> { /// The section it belongs to. pub(super) section: Section, + /// The settings tab it is, if it is one, which the sidebar marks. + pub(super) tab: Option, /// Its title in the browser. pub(super) title: &'a str, - /// What opens it, above its messages: the settings tabs, or an app's header. + /// What opens it, above its messages, such as an app's header. pub(super) head: Child<'a>, /// The page. pub(super) page: Child<'a>, @@ -350,6 +350,7 @@ impl WebApplication { let head = view! { cx => piquel_ui::back_to_apps(home: page::developers::HOME) }; let framed = Framed { section: P::SECTION, + tab: None, title: P::TITLE, head: Child::new(head), page: Child::default(), @@ -389,9 +390,9 @@ impl WebApplication { } /// Answers with the account page `framed`, at the status and with the messages - /// of `outcome`, in its section's frame, below the account's bar and what the - /// account's recovery that can still be undone asks, if any. Its forms may - /// redirect to `targets`. + /// of `outcome`, in the account's shell: the sidebar of its sections, then + /// what the account's recovery that can still be undone asks, if any. Its + /// forms may redirect to `targets`. pub(super) async fn account_page( &self, cx: &Cx, @@ -402,11 +403,13 @@ impl WebApplication { ) -> Result { let Framed { section, + tab, title, head, page, } = framed; - let profile = match self.account.profile(&reader.viewer()).await { + let viewer = reader.viewer(); + let profile = match self.account.profile(&viewer).await { Ok(profile) => profile, Err(AccountError::Owner(SessionError::Missing)) => { return self @@ -415,16 +418,55 @@ impl WebApplication { } Err(error) => return Err(error.into()), }; + let administrator = self.account.is_administrator(&viewer).await?; let session = reader.owner().session_id(); let confirmed = reader.owner().was_passkey_confirmed(); + // The preference forms come back here by GET, which a page answering a + // POST, such as one showing a new secret, cannot show again: those come + // back to the section's home. + let section_home = match section { + Section::Account => page::settings::HOME, + Section::Developers => page::developers::HOME, + }; + let here = if method(cx) == Method::POST { + section_home + } else { + uri(cx) + .path_and_query() + .map_or(page::settings::HOME, |path| path.as_str()) + }; + let who = Who { + user: Some(reader.owner().user()), + name: &profile.display_name, + handle: profile.handle.as_str(), + administrator, + }; + // Only an administrator's sidebar links the dashboard, on deployments + // that serve one; its origin starts the handoff itself. + let dashboard = self + .dashboard + .as_ref() + .filter(|_| administrator) + .map(|sign_in| sign_in.dashboard().serialized()); + let nav = AccountNav { + section, + tabs: &TABS, + current: tab, + developers: page::developers::HOME, + dashboard: dashboard.as_deref(), + }; let page = view! { cx => piquel_ui::account( - section: section, - user: reader.owner().user(), - display_name: &profile.display_name, - handle: profile.handle.as_str(), - sections: &SECTIONS, + nav: nav, + who: who, + title: title, + home: page::settings::HOME, sign_out: page::LOGOUT, + preferences: BrowserCookie::read_preferences(headers(cx)), + preferences_action: page::PREFERENCES, + here: here, + policies: self.policies.links(), + reference: HttpTelemetry::trace_id(status), recovery: view! { if let Some(recovery) = reader.recovery() { piquel_ui::recovery_banner( @@ -441,7 +483,7 @@ impl WebApplication { ) }; Ok(self - .render(cx, status, title, Area::Section(section), targets, page) + .render_document(cx, status, title, targets, false, page) .await?) } @@ -464,8 +506,6 @@ impl WebApplication { } .on(page::LOGIN)?; let page = view! { cx => piquel_ui::signed_out(section: section, sign_in: &sign_in) }; - Ok(self - .render(cx, status, title, Area::Section(section), &[], page) - .await?) + Ok(self.render(cx, status, title, &[], page).await?) } } diff --git a/apps/auth-service/src/web/admin/administrators.rs b/apps/auth-service/src/web/admin/administrators.rs index f46dc65c8..983c315c8 100644 --- a/apps/auth-service/src/web/admin/administrators.rs +++ b/apps/auth-service/src/web/admin/administrators.rs @@ -1,9 +1,10 @@ //! Who administers Piquel: the list, granting rights and revoking them. use super::AdminApplication as App; -use piquel_common::{UserId, admin::GrantAdministrator}; -use piquel_ui::AdministratorRow; -use serde::de::IgnoredAny; +use crate::AdminError; +use piquel_common::{UserId, admin::UserSearch}; +use piquel_ui::{Action, AdministratorRow, Change, Pager, Query, UserRow}; +use serde::{Deserialize, de::IgnoredAny}; use topcoat::{ Result, context::Cx, @@ -23,6 +24,7 @@ pub(super) async fn list(cx: &Cx) -> Result { .await?; // The viewer is an active administrator, so revoking anyone else's rights // leaves one; the service refuses the last active administrator's anyway. + let inline = admin.operator.is_confirmed(super::FORM_TIME); let rows: Vec<_> = administrators .iter() .map(|administrator| AdministratorRow { @@ -31,7 +33,10 @@ pub(super) async fn list(cx: &Cx) -> Result { revoke: if administrator.user_id == admin.user_id { Err("You cannot change your own rights.") } else { - Ok(href!(revoke, Administrator(administrator.user_id)).resolve(cx)) + Ok(Action { + href: href!(revoke, Administrator(administrator.user_id)).resolve(cx), + inline, + }) }, }) .collect(); @@ -39,37 +44,76 @@ pub(super) async fn list(cx: &Cx) -> Result { let page = view! { cx => piquel_ui::administrator_list(rows: rows, grant: granting.as_str()) }; - App::render(cx, StatusCode::OK, page).await + App::render(cx, StatusCode::OK, "Administrators", page).await } -/// `/administrators/grant`: makes an active account an administrator. +/// What [`grant`] takes: by `GET`, the search for the account, from its query; +/// by `POST`, the account to grant, from its form. One type, since the extractor +/// reads a `GET`'s query as its form. +#[derive(Clone, Deserialize)] +pub(super) struct GrantForm { + /// The account to grant rights, which the button posts. + user_id: Option, + /// What to search for. + #[serde(default)] + q: String, + /// The page wanted, counting from 1. + page: Option, +} + +/// `/administrators/grant`: finds the account, by handle, name, email or ID, then +/// makes it an administrator. #[route([GET, POST] "/administrators/grant")] -pub(super) async fn grant(cx: &Cx, form: Option>) -> Result { +pub(super) async fn grant(cx: &Cx, form: Option>) -> Result { let admin = App::admin(cx).await?; App::confirm(cx, admin)?; let service = &App::of(cx).service; let back = href!(list).resolve(cx); - let refusal = App::submit(cx, form, back.clone(), |input: GrantAdministrator| { - service.grant_administrator(&admin.operator, input.user_id) + let (q, page) = form + .as_ref() + .map(|Form(form)| (form.q.clone(), form.page)) + .unwrap_or_default(); + let refusal = App::submit(cx, form, back.clone(), |input: GrantForm| async move { + let user_id = input.user_id.ok_or(AdminError::UserNotFound)?; + service.grant_administrator(&admin.operator, user_id).await }) .await?; - let typed = refusal - .as_ref() - .map(|refused| refused.form.user_id.to_string()); + let found = service.search_users(&admin.operator, &q, page).await?; + let administrators: Vec<_> = service + .list_administrators(&admin.operator) + .await? + .into_iter() + .map(|administrator| administrator.user_id) + .collect(); + let action = href!(grant).resolve(cx); + let rows: Vec<_> = found + .users + .iter() + .map(|user| UserRow { + user, + administrator: administrators.contains(&user.id), + href: App::account(cx, user.id), + }) + .collect(); + let pager = Pager::of(found.paging, |page| { + UserSearch { + q: q.clone(), + page: Some(page), + } + .on(&action) + })?; + let (q, rows, pager, refusal) = (&q, &rows, &pager, refusal.as_deref()); let page = view! { cx => - piquel_ui::dashboard_change( - title: "Grant administrator rights", - description: "The account can use this dashboard and every admin operation. The dashboard cannot change it afterwards, until its rights are revoked.", - button: "Grant", + piquel_ui::grant_search( + action: action.as_str(), + q: q.as_str(), + rows: rows, + pages: pager, back: back.as_str(), - refusal: refusal.as_deref(), - + refusal: refusal, ) }; - App::render(cx, StatusCode::OK, page).await + App::render(cx, StatusCode::OK, "Grant rights", page).await } /// `/administrators/{administrator}/revoke`: removes another administrator's @@ -87,13 +131,10 @@ pub(super) async fn revoke(cx: &Cx, form: Option>) -> Result piquel_ui::dashboard_change( - title: "Revoke administrator rights", - description: "The account keeps its sessions, but can no longer use this dashboard.", - button: "Revoke", + change: Change::RevokeAdministrator, back: back.as_str(), refusal: refusal.as_deref(), - danger: true, ) }; - App::render(cx, StatusCode::OK, page).await + App::render(cx, StatusCode::OK, "Revoke rights", page).await } diff --git a/apps/auth-service/src/web/admin/audit.rs b/apps/auth-service/src/web/admin/audit.rs index 5cf6b72d2..69b3da496 100644 --- a/apps/auth-service/src/web/admin/audit.rs +++ b/apps/auth-service/src/web/admin/audit.rs @@ -34,5 +34,5 @@ pub(super) async fn verify(cx: &Cx) -> Result { .next .map(|after| format!("{}?after={after}", href!(verify).resolve(cx))); let view = view! { cx => piquel_ui::audit_page(page: page, later: later) }; - App::render(cx, StatusCode::OK, view).await + App::render(cx, StatusCode::OK, "Audit", view).await } diff --git a/apps/auth-service/src/web/admin/invitations.rs b/apps/auth-service/src/web/admin/invitations.rs index 2cead0da5..c2b98881a 100644 --- a/apps/auth-service/src/web/admin/invitations.rs +++ b/apps/auth-service/src/web/admin/invitations.rs @@ -4,7 +4,7 @@ use super::AdminApplication as App; use crate::{AdminError, InviteExpiry}; use chrono::Utc; use piquel_common::{TokenId, admin::CreateInvitation}; -use piquel_ui::InvitationRow; +use piquel_ui::{Action, Change, InvitationRow}; use serde::de::IgnoredAny; use topcoat::{ Result, @@ -39,13 +39,18 @@ pub(super) async fn list(cx: &Cx) -> Result { } else { None }; + let inline = admin.operator.is_confirmed(super::FORM_TIME); let rows: Option> = invitations.as_ref().map(|invitations| { invitations .iter() .map(|invitation| InvitationRow { invitation, - revoke: (invitation.redeemed_at.is_none() && invitation.revoked_at.is_none()) - .then(|| href!(revoke, Invitation(invitation.id)).resolve(cx)), + revoke: (invitation.redeemed_at.is_none() && invitation.revoked_at.is_none()).then( + || Action { + href: href!(revoke, Invitation(invitation.id)).resolve(cx), + inline, + }, + ), }) .collect() }); @@ -53,7 +58,7 @@ pub(super) async fn list(cx: &Cx) -> Result { let page = view! { cx => piquel_ui::invitation_list(rows: rows, create: creating.as_str(), now: Utc::now()) }; - App::render(cx, StatusCode::OK, page).await + App::render(cx, StatusCode::OK, "Invitations", page).await } /// `/invitations/new`: creates an invitation and shows its link, once. @@ -98,9 +103,7 @@ pub(super) async fn create(cx: &Cx, form: Option>) -> Res }, None => { piquel_ui::dashboard_change( - title: "Invite someone", - description: "Creates a single-use signup link.", - button: "Create link", + change: Change::Invite, back: back.as_str(), refusal: refused,