Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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` |
Expand Down
3 changes: 3 additions & 0 deletions apps/auth-service/src/admin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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};
Expand Down
197 changes: 197 additions & 0 deletions apps/auth-service/src/admin/overview.rs
Original file line number Diff line number Diff line change
@@ -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<Utc>,
},
}

/// 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<Event>,
/// The newest accounts.
pub newest: Vec<User>,
/// The emails waiting to be sent.
pub email_backlog: DeliveryBacklog,
/// When it was read.
pub now: DateTime<Utc>,
}

impl Overview {
/// What needs attention, most pressing first.
#[must_use]
pub fn problems(&self) -> Vec<Problem> {
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<Overview, AdminError> {
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<Rate, AdminError> {
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::<Email>().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");
}
}
48 changes: 21 additions & 27 deletions apps/auth-service/src/admin/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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,
}
Expand Down Expand Up @@ -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<UserId>,
page: Option<u32>,
) -> Result<UserPage, AdminError> {
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,
Expand Down Expand Up @@ -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<EventPage, AdminError> {
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| {
Expand All @@ -836,7 +830,7 @@ impl AdminService {
})
})
.collect::<Result<_, serde_json::Error>>()?;
Ok(EventPage { events, next })
Ok(EventPage { events, paging })
}

/// Lists the accounts whose current handle is reserved, by handle: ones an
Expand Down
2 changes: 1 addition & 1 deletion apps/auth-service/src/admin/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading