//! Plain data types of the accounts and sessions, as the store returns them. //! //! These structs hold what is in the rows and nothing more. Rules that decide what a person may //! do with them live in the store (as single conditional statements) or in the web layer. //! Timestamps are the stored text form from `time.rs`. /// A person who can sign in. `id` is the OIDC `sub` once OIDC exists, and is never reused. #[derive(Clone, PartialEq, Eq)] pub struct User { /// ULID. pub id: String, /// The normalised address (trimmed, lowercased). Unique. pub email: String, /// Display name, 1 to 100 characters. pub name: String, /// Argon2id PHC string. pub password_hash: String, /// Instance administrator. pub is_admin: bool, /// Set when the account is disabled. A disabled account cannot sign in. pub disabled_at: Option, /// The sealed TOTP secret, kept after two-factor sign-in is enabled. pub totp_secret_sealed: Option, /// Set when two-factor sign-in is on. pub totp_enabled_at: Option, /// The last TOTP step that was accepted. A code of this step or an earlier one is refused. pub totp_last_step: Option, /// `en` or `tr`. Used only when `locale_auto` is false. pub locale: String, /// True when the interface language follows the browser (`Accept-Language`) instead of `locale`. pub locale_auto: bool, /// IANA time zone name. pub zoneinfo: String, /// `system`, `light` or `dark`. pub theme: String, /// MIME type of the stored photo, when there is one. pub photo_mime: Option, /// Bumps when the photo changes, so caches can tell two photos apart. pub picture_version: i64, /// Creation time. pub created_at: String, /// Last change of the row. pub updated_at: String, } /// Prints every field, except that the password hash and the sealed TOTP secret print as ``, so a /// debug log never holds them. impl std::fmt::Debug for User { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("User") .field("id", &self.id) .field("email", &self.email) .field("name", &self.name) .field("password_hash", &format_args!("")) .field("is_admin", &self.is_admin) .field("disabled_at", &self.disabled_at) .field("totp_secret_sealed", &format_args!("")) .field("totp_enabled_at", &self.totp_enabled_at) .field("totp_last_step", &self.totp_last_step) .field("locale", &self.locale) .field("locale_auto", &self.locale_auto) .field("zoneinfo", &self.zoneinfo) .field("theme", &self.theme) .field("photo_mime", &self.photo_mime) .field("picture_version", &self.picture_version) .field("created_at", &self.created_at) .field("updated_at", &self.updated_at) .finish() } } impl User { /// True when two-factor sign-in is on: the secret is stored and enrolment was confirmed. pub fn totp_enabled(&self) -> bool { self.totp_enabled_at.is_some() && self.totp_secret_sealed.is_some() } /// True when the account is disabled. pub fn is_disabled(&self) -> bool { self.disabled_at.is_some() } } /// How a session was authenticated. Stored in `sessions.amr`, and the CHECK constraint accepts /// exactly these three values. pub mod amr { /// Password only. pub const PASSWORD: &str = "pwd"; /// Password and a TOTP code. pub const PASSWORD_TOTP: &str = "pwd otp"; /// Password and a recovery code. pub const PASSWORD_RECOVERY: &str = "pwd rc"; /// The RFC 8176 `amr` values of a stored method, for the ID token and the access token. /// /// The table keeps the short labels above, because its CHECK constraint names them. The tokens /// carry the standard values: TOTP is `pwd`, `otp` and `mfa`; a recovery code is `pwd` and `mfa` /// (a recovery code is a second factor that is not an OTP, so it is not `otp`). Anything else /// proved only the password. pub fn rfc8176(stored: &str) -> &'static [&'static str] { match stored { PASSWORD_TOTP => &["pwd", "otp", "mfa"], PASSWORD_RECOVERY => &["pwd", "mfa"], _ => &["pwd"], } } } /// A browser session. The cookie holds the token; the row holds only its hash. #[derive(Clone, PartialEq, Eq)] pub struct Session { /// ULID. This is the OIDC `sid` once OIDC exists. pub id: String, /// The owner. pub user_id: String, /// Hex SHA-256 of the cookie token. pub token_hash: String, /// Per-session CSRF token. Every state-changing form carries it. pub csrf_token: String, /// Creation time (the sign-in time). pub created_at: String, /// Expiry, moved forward on use (idle extension). Never later than `hard_expires_at`. pub expires_at: String, /// The hard cap: creation plus `session_max_days`. Idle extension stops here. pub hard_expires_at: String, /// Last time the session was used. Written at most once every five minutes. pub last_seen_at: String, /// Address the session was created from. pub ip: Option, /// The `User-Agent` at sign-in, truncated. pub user_agent: Option, /// Time of the authentication that created the session. pub auth_time: String, /// One of the [`amr`] values. pub amr: String, } /// Prints every field, except that the token hash and the CSRF token print as ``. impl std::fmt::Debug for Session { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Session") .field("id", &self.id) .field("user_id", &self.user_id) .field("token_hash", &format_args!("")) .field("csrf_token", &format_args!("")) .field("created_at", &self.created_at) .field("expires_at", &self.expires_at) .field("hard_expires_at", &self.hard_expires_at) .field("last_seen_at", &self.last_seen_at) .field("ip", &self.ip) .field("user_agent", &self.user_agent) .field("auth_time", &self.auth_time) .field("amr", &self.amr) .finish() } } /// What an audit entry is about. The variants are the values stored in `audit_log.action`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum AuditAction { /// The first administrator was created. SetupDone, /// A sign-in succeeded (password, or password and a second factor). LoginSuccess, /// A sign-in was refused. The data says why. LoginFailed, /// A second-factor check was refused. Login2faFailed, /// The person signed out. Logout, /// The password was changed. PasswordChanged, /// Two-factor sign-in was turned on. TotpEnabled, /// Two-factor sign-in was turned off. TotpDisabled, /// The display name was changed. NameChanged, /// A profile photo was uploaded. PhotoChanged, /// The profile photo was removed. PhotoRemoved, /// Language, time zone or theme was changed. PreferencesChanged, /// A new set of recovery codes was issued. RecoveryCodesIssued, /// One session was ended by its owner. SessionRevoked, /// Every session except the current one was ended. SessionsRevoked, /// An administrator invited someone. InviteCreated, /// An invitation was accepted and its account created. InviteAccepted, /// A password reset was asked for, for an account that exists and is enabled. ResetRequested, /// A password was set through a reset link. Every session of the person ended. PasswordReset, /// An email change was asked for. EmailChangeRequested, /// One half of an email change was confirmed. The data says which half. EmailChangeConfirmed, /// An email change was cancelled from its old-address link. EmailChangeCancelled, /// The address of an account was changed. EmailChanged, /// An administrator disabled an account. UserDisabled, /// An administrator enabled an account again. UserEnabled, /// An administrator made an account an administrator. AdminGranted, /// An administrator removed the administrator flag of an account. AdminRemoved, /// An administrator reset the two-factor sign-in of an account. AdminTwoFactorReset, /// An administrator ended every session of an account. AdminSessionsRevoked, /// An administrator deleted an account. UserDeleted, /// An administrator revoked an invitation. InviteRevoked, /// An administrator registered an OpenID client. ClientCreated, /// An administrator changed a client's settings. ClientUpdated, /// An administrator issued a new client secret. ClientSecretRotated, /// An administrator disabled a client. ClientDisabled, /// An administrator sent a failed mail again. MailRetried, /// An administrator gave up on a mail. MailAbandoned, /// An administrator queued a test mail. MailTestQueued, /// An administrator queued a message to everyone or to one address. MessageSent, /// An administrator saved policy settings. SettingsChanged, /// An administrator rotated the signing key. KeyRotated, /// An administrator retired a signing key. KeyRetired, /// A backup set was written (scheduled, or by `im backup now`). BackupWritten, /// An administrator asked for a backup now from the admin health page. BackupRequested, } impl AuditAction { /// The stored text of the action. pub fn as_str(self) -> &'static str { match self { AuditAction::SetupDone => "setup.done", AuditAction::LoginSuccess => "login.success", AuditAction::LoginFailed => "login.failed", AuditAction::Login2faFailed => "login.2fa_failed", AuditAction::Logout => "logout", AuditAction::PasswordChanged => "password.changed", AuditAction::TotpEnabled => "totp.enabled", AuditAction::TotpDisabled => "totp.disabled", AuditAction::NameChanged => "profile.name", AuditAction::PhotoChanged => "profile.photo", AuditAction::PhotoRemoved => "profile.photo_removed", AuditAction::PreferencesChanged => "preferences.changed", AuditAction::RecoveryCodesIssued => "recovery.issued", AuditAction::SessionRevoked => "session.revoked", AuditAction::SessionsRevoked => "sessions.revoked", AuditAction::InviteCreated => "invite.created", AuditAction::InviteAccepted => "invite.accepted", AuditAction::ResetRequested => "reset.requested", AuditAction::PasswordReset => "password.reset", AuditAction::EmailChangeRequested => "email_change.requested", AuditAction::EmailChangeConfirmed => "email_change.confirmed", AuditAction::EmailChangeCancelled => "email_change.cancelled", AuditAction::EmailChanged => "email.changed", AuditAction::UserDisabled => "user.disabled", AuditAction::UserEnabled => "user.enabled", AuditAction::AdminGranted => "admin.granted", AuditAction::AdminRemoved => "admin.removed", AuditAction::AdminTwoFactorReset => "admin.2fa_reset", AuditAction::AdminSessionsRevoked => "admin.sessions_revoked", AuditAction::UserDeleted => "user.deleted", AuditAction::InviteRevoked => "invite.revoked", AuditAction::ClientCreated => "client.created", AuditAction::ClientUpdated => "client.updated", AuditAction::ClientSecretRotated => "client.secret_rotated", AuditAction::ClientDisabled => "client.disabled", AuditAction::MailRetried => "mail.retried", AuditAction::MailAbandoned => "mail.abandoned", AuditAction::MailTestQueued => "mail.test", AuditAction::MessageSent => "message.sent", AuditAction::SettingsChanged => "settings.changed", AuditAction::KeyRotated => "keys.rotated", AuditAction::KeyRetired => "keys.retired", AuditAction::BackupWritten => "backup.written", AuditAction::BackupRequested => "backup.requested", } } } /// One row of the audit log. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AuditEntry { /// ULID. Ordered by `(at, id)` together. pub id: String, /// When the change was made. pub at: String, /// Who acted, when known. Not a foreign key, so the trail outlives the account. pub actor_id: Option, /// `user`, `client`, `cli`, `system` or `anonymous`. pub actor_kind: String, /// The action, as [`AuditAction::as_str`] or a later kind. pub action: String, /// What the action is about, such as `user`. pub target_kind: Option, /// The id of that thing. pub target_id: Option, /// Client address, when known. pub ip: Option, /// JSON with extra detail. Never holds a secret. pub data: Option, } /// An OpenID Connect client: one family app, or another client that asks for tokens. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Client { /// ULID. This is the `client_id`. pub id: String, /// Display name, shown by the admin pages and the CLI. pub name: String, /// Hex SHA-256 of the client secret. The secret itself is shown once, at creation. pub secret_hash: String, /// When the secret was last issued. pub secret_rotated_at: String, /// Exact redirect URIs. A request matches only a string equal to one of them. pub redirect_uris: Vec, /// Exact post-logout redirect URIs (used by RP-initiated logout). pub post_logout_redirect_uris: Vec, /// Back-channel logout endpoint of the client, when it has one. pub backchannel_logout_uri: Option, /// Space-separated scopes the client may ask for. pub allowed_scopes: String, /// Family key such as `in`, when the client is a family service. pub service_key: Option, /// Creation time. pub created_at: String, /// Set when the client is disabled. A disabled client authenticates nowhere. pub disabled_at: Option, } impl Client { /// True when the client is disabled. pub fn is_disabled(&self) -> bool { self.disabled_at.is_some() } /// True when the client may ask for `scope`. pub fn allows_scope(&self, scope: &str) -> bool { self.allowed_scopes.split_whitespace().any(|s| s == scope) } } /// An authorization code row. Only the hash of the code is stored. #[derive(Debug, Clone, PartialEq, Eq)] pub struct AuthCode { /// Hex SHA-256 of the code. pub code_hash: String, /// The client the code was issued to. pub client_id: String, /// The person who signed in. pub user_id: String, /// The browser session the code was issued in. Its time and method go into the tokens. pub session_id: String, /// The redirect URI of the request, which the exchange must repeat. pub redirect_uri: String, /// The granted scope. pub scope: String, /// The nonce of the request, when there was one. pub nonce: Option, /// The PKCE challenge (S256) of the request. pub code_challenge: String, /// When the code stops being usable. pub expires_at: String, /// Set when the code was exchanged. A code is exchanged once. pub used_at: Option, /// The `jti` of the access token issued at the exchange. A replay revokes it. pub access_jti: Option, /// When that access token expires; its revocation is kept until then. pub access_expires_at: Option, } /// A refresh token row. Only the hash of the token is stored. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RefreshToken { /// ULID. pub id: String, /// Hex SHA-256 of the token. pub token_hash: String, /// The first token of the chain. Reuse revokes every token with this family id. pub family_id: String, /// The client the token was issued to. pub client_id: String, /// The person. pub user_id: String, /// The browser session the chain belongs to. pub session_id: String, /// Hash of the authorization code the chain began with, when it began with one. pub code_hash: Option, /// The granted scope. pub scope: String, /// Creation time. pub created_at: String, /// Expiry. pub expires_at: String, /// Set when the token was rotated. Presenting a used token is reuse. pub used_at: Option, /// Set when the token or its family was revoked. pub revoked_at: Option, } /// One token-signing key. The private part is sealed under the instance key. #[derive(Debug, Clone, PartialEq, Eq)] pub struct KeyRecord { /// Key id, published in the JWKS and in every token header. pub kid: String, /// The 32-byte Ed25519 seed, sealed with `secret::seal`. pub private_sealed: String, /// The 32-byte Ed25519 public key. pub public_raw: Vec, /// Creation time. pub created_at: String, /// When the key starts signing. Published before this time. pub activates_at: String, /// When the key stops signing. It stays published for a while after this time. pub retires_at: Option, } /// One row of the service switcher (contracts.md 4). #[derive(Debug, Clone, PartialEq, Eq)] pub struct Service { /// Family key, such as `in`. pub key: String, /// Display name. pub name: String, /// Public origin. pub url: String, /// The last health probe's answer, `None` before the first probe. pub healthy: Option, /// When the last probe ran. pub checked_at: Option, }