im
Clone
https://git.tahinli.com/Tahinli/im.git
0 watching·0 forks·Rust·AGPL-3.0·542.8 KiB·b9f0726·Tahinli·27 days ago·34 commits
| 1 | //! Plain data types of the accounts and sessions, as the store returns them. |
| 2 | //! |
| 3 | //! These structs hold what is in the rows and nothing more. Rules that decide what a person may |
| 4 | //! do with them live in the store (as single conditional statements) or in the web layer. |
| 5 | //! Timestamps are the stored text form from `time.rs`. |
| 6 | |
| 7 | /// A person who can sign in. `id` is the OIDC `sub` once OIDC exists, and is never reused. |
| 8 | #[derive(Clone, PartialEq, Eq)] |
| 9 | pub struct User { |
| 10 | /// ULID. |
| 11 | pub id: String, |
| 12 | /// The normalised address (trimmed, lowercased). Unique. |
| 13 | pub email: String, |
| 14 | /// Display name, 1 to 100 characters. |
| 15 | pub name: String, |
| 16 | /// Argon2id PHC string. |
| 17 | pub password_hash: String, |
| 18 | /// Instance administrator. |
| 19 | pub is_admin: bool, |
| 20 | /// Set when the account is disabled. A disabled account cannot sign in. |
| 21 | pub disabled_at: Option<String>, |
| 22 | /// The sealed TOTP secret, kept after two-factor sign-in is enabled. |
| 23 | pub totp_secret_sealed: Option<String>, |
| 24 | /// Set when two-factor sign-in is on. |
| 25 | pub totp_enabled_at: Option<String>, |
| 26 | /// The last TOTP step that was accepted. A code of this step or an earlier one is refused. |
| 27 | pub totp_last_step: Option<i64>, |
| 28 | /// `en` or `tr`. Used only when `locale_auto` is false. |
| 29 | pub locale: String, |
| 30 | /// True when the interface language follows the browser (`Accept-Language`) instead of `locale`. |
| 31 | pub locale_auto: bool, |
| 32 | /// IANA time zone name. |
| 33 | pub zoneinfo: String, |
| 34 | /// `system`, `light` or `dark`. |
| 35 | pub theme: String, |
| 36 | /// MIME type of the stored photo, when there is one. |
| 37 | pub photo_mime: Option<String>, |
| 38 | /// Bumps when the photo changes, so caches can tell two photos apart. |
| 39 | pub picture_version: i64, |
| 40 | /// Creation time. |
| 41 | pub created_at: String, |
| 42 | /// Last change of the row. |
| 43 | pub updated_at: String, |
| 44 | } |
| 45 | |
| 46 | /// Prints every field, except that the password hash and the sealed TOTP secret print as `<redacted>`, so a |
| 47 | /// debug log never holds them. |
| 48 | impl std::fmt::Debug for User { |
| 49 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 50 | f.debug_struct("User") |
| 51 | .field("id", &self.id) |
| 52 | .field("email", &self.email) |
| 53 | .field("name", &self.name) |
| 54 | .field("password_hash", &format_args!("<redacted>")) |
| 55 | .field("is_admin", &self.is_admin) |
| 56 | .field("disabled_at", &self.disabled_at) |
| 57 | .field("totp_secret_sealed", &format_args!("<redacted>")) |
| 58 | .field("totp_enabled_at", &self.totp_enabled_at) |
| 59 | .field("totp_last_step", &self.totp_last_step) |
| 60 | .field("locale", &self.locale) |
| 61 | .field("locale_auto", &self.locale_auto) |
| 62 | .field("zoneinfo", &self.zoneinfo) |
| 63 | .field("theme", &self.theme) |
| 64 | .field("photo_mime", &self.photo_mime) |
| 65 | .field("picture_version", &self.picture_version) |
| 66 | .field("created_at", &self.created_at) |
| 67 | .field("updated_at", &self.updated_at) |
| 68 | .finish() |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | impl User { |
| 73 | /// True when two-factor sign-in is on: the secret is stored and enrolment was confirmed. |
| 74 | pub fn totp_enabled(&self) -> bool { |
| 75 | self.totp_enabled_at.is_some() && self.totp_secret_sealed.is_some() |
| 76 | } |
| 77 | |
| 78 | /// True when the account is disabled. |
| 79 | pub fn is_disabled(&self) -> bool { |
| 80 | self.disabled_at.is_some() |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | /// How a session was authenticated. Stored in `sessions.amr`, and the CHECK constraint accepts |
| 85 | /// exactly these three values. |
| 86 | pub mod amr { |
| 87 | /// Password only. |
| 88 | pub const PASSWORD: &str = "pwd"; |
| 89 | /// Password and a TOTP code. |
| 90 | pub const PASSWORD_TOTP: &str = "pwd otp"; |
| 91 | /// Password and a recovery code. |
| 92 | pub const PASSWORD_RECOVERY: &str = "pwd rc"; |
| 93 | |
| 94 | /// The RFC 8176 `amr` values of a stored method, for the ID token and the access token. |
| 95 | /// |
| 96 | /// The table keeps the short labels above, because its CHECK constraint names them. The tokens |
| 97 | /// carry the standard values: TOTP is `pwd`, `otp` and `mfa`; a recovery code is `pwd` and `mfa` |
| 98 | /// (a recovery code is a second factor that is not an OTP, so it is not `otp`). Anything else |
| 99 | /// proved only the password. |
| 100 | pub fn rfc8176(stored: &str) -> &'static [&'static str] { |
| 101 | match stored { |
| 102 | PASSWORD_TOTP => &["pwd", "otp", "mfa"], |
| 103 | PASSWORD_RECOVERY => &["pwd", "mfa"], |
| 104 | _ => &["pwd"], |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /// A browser session. The cookie holds the token; the row holds only its hash. |
| 110 | #[derive(Clone, PartialEq, Eq)] |
| 111 | pub struct Session { |
| 112 | /// ULID. This is the OIDC `sid` once OIDC exists. |
| 113 | pub id: String, |
| 114 | /// The owner. |
| 115 | pub user_id: String, |
| 116 | /// Hex SHA-256 of the cookie token. |
| 117 | pub token_hash: String, |
| 118 | /// Per-session CSRF token. Every state-changing form carries it. |
| 119 | pub csrf_token: String, |
| 120 | /// Creation time (the sign-in time). |
| 121 | pub created_at: String, |
| 122 | /// Expiry, moved forward on use (idle extension). Never later than `hard_expires_at`. |
| 123 | pub expires_at: String, |
| 124 | /// The hard cap: creation plus `session_max_days`. Idle extension stops here. |
| 125 | pub hard_expires_at: String, |
| 126 | /// Last time the session was used. Written at most once every five minutes. |
| 127 | pub last_seen_at: String, |
| 128 | /// Address the session was created from. |
| 129 | pub ip: Option<String>, |
| 130 | /// The `User-Agent` at sign-in, truncated. |
| 131 | pub user_agent: Option<String>, |
| 132 | /// Time of the authentication that created the session. |
| 133 | pub auth_time: String, |
| 134 | /// One of the [`amr`] values. |
| 135 | pub amr: String, |
| 136 | } |
| 137 | |
| 138 | /// Prints every field, except that the token hash and the CSRF token print as `<redacted>`. |
| 139 | impl std::fmt::Debug for Session { |
| 140 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 141 | f.debug_struct("Session") |
| 142 | .field("id", &self.id) |
| 143 | .field("user_id", &self.user_id) |
| 144 | .field("token_hash", &format_args!("<redacted>")) |
| 145 | .field("csrf_token", &format_args!("<redacted>")) |
| 146 | .field("created_at", &self.created_at) |
| 147 | .field("expires_at", &self.expires_at) |
| 148 | .field("hard_expires_at", &self.hard_expires_at) |
| 149 | .field("last_seen_at", &self.last_seen_at) |
| 150 | .field("ip", &self.ip) |
| 151 | .field("user_agent", &self.user_agent) |
| 152 | .field("auth_time", &self.auth_time) |
| 153 | .field("amr", &self.amr) |
| 154 | .finish() |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | /// What an audit entry is about. The variants are the values stored in `audit_log.action`. |
| 159 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 160 | pub enum AuditAction { |
| 161 | /// The first administrator was created. |
| 162 | SetupDone, |
| 163 | /// A sign-in succeeded (password, or password and a second factor). |
| 164 | LoginSuccess, |
| 165 | /// A sign-in was refused. The data says why. |
| 166 | LoginFailed, |
| 167 | /// A second-factor check was refused. |
| 168 | Login2faFailed, |
| 169 | /// The person signed out. |
| 170 | Logout, |
| 171 | /// The password was changed. |
| 172 | PasswordChanged, |
| 173 | /// Two-factor sign-in was turned on. |
| 174 | TotpEnabled, |
| 175 | /// Two-factor sign-in was turned off. |
| 176 | TotpDisabled, |
| 177 | /// The display name was changed. |
| 178 | NameChanged, |
| 179 | /// A profile photo was uploaded. |
| 180 | PhotoChanged, |
| 181 | /// The profile photo was removed. |
| 182 | PhotoRemoved, |
| 183 | /// Language, time zone or theme was changed. |
| 184 | PreferencesChanged, |
| 185 | /// A new set of recovery codes was issued. |
| 186 | RecoveryCodesIssued, |
| 187 | /// One session was ended by its owner. |
| 188 | SessionRevoked, |
| 189 | /// Every session except the current one was ended. |
| 190 | SessionsRevoked, |
| 191 | /// An administrator invited someone. |
| 192 | InviteCreated, |
| 193 | /// An invitation was accepted and its account created. |
| 194 | InviteAccepted, |
| 195 | /// A password reset was asked for, for an account that exists and is enabled. |
| 196 | ResetRequested, |
| 197 | /// A password was set through a reset link. Every session of the person ended. |
| 198 | PasswordReset, |
| 199 | /// An email change was asked for. |
| 200 | EmailChangeRequested, |
| 201 | /// One half of an email change was confirmed. The data says which half. |
| 202 | EmailChangeConfirmed, |
| 203 | /// An email change was cancelled from its old-address link. |
| 204 | EmailChangeCancelled, |
| 205 | /// The address of an account was changed. |
| 206 | EmailChanged, |
| 207 | /// An administrator disabled an account. |
| 208 | UserDisabled, |
| 209 | /// An administrator enabled an account again. |
| 210 | UserEnabled, |
| 211 | /// An administrator made an account an administrator. |
| 212 | AdminGranted, |
| 213 | /// An administrator removed the administrator flag of an account. |
| 214 | AdminRemoved, |
| 215 | /// An administrator reset the two-factor sign-in of an account. |
| 216 | AdminTwoFactorReset, |
| 217 | /// An administrator ended every session of an account. |
| 218 | AdminSessionsRevoked, |
| 219 | /// An administrator deleted an account. |
| 220 | UserDeleted, |
| 221 | /// An administrator revoked an invitation. |
| 222 | InviteRevoked, |
| 223 | /// An administrator registered an OpenID client. |
| 224 | ClientCreated, |
| 225 | /// An administrator changed a client's settings. |
| 226 | ClientUpdated, |
| 227 | /// An administrator issued a new client secret. |
| 228 | ClientSecretRotated, |
| 229 | /// An administrator disabled a client. |
| 230 | ClientDisabled, |
| 231 | /// An administrator sent a failed mail again. |
| 232 | MailRetried, |
| 233 | /// An administrator gave up on a mail. |
| 234 | MailAbandoned, |
| 235 | /// An administrator queued a test mail. |
| 236 | MailTestQueued, |
| 237 | /// An administrator queued a message to everyone or to one address. |
| 238 | MessageSent, |
| 239 | /// An administrator saved policy settings. |
| 240 | SettingsChanged, |
| 241 | /// An administrator rotated the signing key. |
| 242 | KeyRotated, |
| 243 | /// An administrator retired a signing key. |
| 244 | KeyRetired, |
| 245 | /// A backup set was written (scheduled, or by `im backup now`). |
| 246 | BackupWritten, |
| 247 | /// An administrator asked for a backup now from the admin health page. |
| 248 | BackupRequested, |
| 249 | } |
| 250 | |
| 251 | impl AuditAction { |
| 252 | /// The stored text of the action. |
| 253 | pub fn as_str(self) -> &'static str { |
| 254 | match self { |
| 255 | AuditAction::SetupDone => "setup.done", |
| 256 | AuditAction::LoginSuccess => "login.success", |
| 257 | AuditAction::LoginFailed => "login.failed", |
| 258 | AuditAction::Login2faFailed => "login.2fa_failed", |
| 259 | AuditAction::Logout => "logout", |
| 260 | AuditAction::PasswordChanged => "password.changed", |
| 261 | AuditAction::TotpEnabled => "totp.enabled", |
| 262 | AuditAction::TotpDisabled => "totp.disabled", |
| 263 | AuditAction::NameChanged => "profile.name", |
| 264 | AuditAction::PhotoChanged => "profile.photo", |
| 265 | AuditAction::PhotoRemoved => "profile.photo_removed", |
| 266 | AuditAction::PreferencesChanged => "preferences.changed", |
| 267 | AuditAction::RecoveryCodesIssued => "recovery.issued", |
| 268 | AuditAction::SessionRevoked => "session.revoked", |
| 269 | AuditAction::SessionsRevoked => "sessions.revoked", |
| 270 | AuditAction::InviteCreated => "invite.created", |
| 271 | AuditAction::InviteAccepted => "invite.accepted", |
| 272 | AuditAction::ResetRequested => "reset.requested", |
| 273 | AuditAction::PasswordReset => "password.reset", |
| 274 | AuditAction::EmailChangeRequested => "email_change.requested", |
| 275 | AuditAction::EmailChangeConfirmed => "email_change.confirmed", |
| 276 | AuditAction::EmailChangeCancelled => "email_change.cancelled", |
| 277 | AuditAction::EmailChanged => "email.changed", |
| 278 | AuditAction::UserDisabled => "user.disabled", |
| 279 | AuditAction::UserEnabled => "user.enabled", |
| 280 | AuditAction::AdminGranted => "admin.granted", |
| 281 | AuditAction::AdminRemoved => "admin.removed", |
| 282 | AuditAction::AdminTwoFactorReset => "admin.2fa_reset", |
| 283 | AuditAction::AdminSessionsRevoked => "admin.sessions_revoked", |
| 284 | AuditAction::UserDeleted => "user.deleted", |
| 285 | AuditAction::InviteRevoked => "invite.revoked", |
| 286 | AuditAction::ClientCreated => "client.created", |
| 287 | AuditAction::ClientUpdated => "client.updated", |
| 288 | AuditAction::ClientSecretRotated => "client.secret_rotated", |
| 289 | AuditAction::ClientDisabled => "client.disabled", |
| 290 | AuditAction::MailRetried => "mail.retried", |
| 291 | AuditAction::MailAbandoned => "mail.abandoned", |
| 292 | AuditAction::MailTestQueued => "mail.test", |
| 293 | AuditAction::MessageSent => "message.sent", |
| 294 | AuditAction::SettingsChanged => "settings.changed", |
| 295 | AuditAction::KeyRotated => "keys.rotated", |
| 296 | AuditAction::KeyRetired => "keys.retired", |
| 297 | AuditAction::BackupWritten => "backup.written", |
| 298 | AuditAction::BackupRequested => "backup.requested", |
| 299 | } |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | /// One row of the audit log. |
| 304 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 305 | pub struct AuditEntry { |
| 306 | /// ULID. Ordered by `(at, id)` together. |
| 307 | pub id: String, |
| 308 | /// When the change was made. |
| 309 | pub at: String, |
| 310 | /// Who acted, when known. Not a foreign key, so the trail outlives the account. |
| 311 | pub actor_id: Option<String>, |
| 312 | /// `user`, `client`, `cli`, `system` or `anonymous`. |
| 313 | pub actor_kind: String, |
| 314 | /// The action, as [`AuditAction::as_str`] or a later kind. |
| 315 | pub action: String, |
| 316 | /// What the action is about, such as `user`. |
| 317 | pub target_kind: Option<String>, |
| 318 | /// The id of that thing. |
| 319 | pub target_id: Option<String>, |
| 320 | /// Client address, when known. |
| 321 | pub ip: Option<String>, |
| 322 | /// JSON with extra detail. Never holds a secret. |
| 323 | pub data: Option<String>, |
| 324 | } |
| 325 | |
| 326 | /// An OpenID Connect client: one family app, or another client that asks for tokens. |
| 327 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 328 | pub struct Client { |
| 329 | /// ULID. This is the `client_id`. |
| 330 | pub id: String, |
| 331 | /// Display name, shown by the admin pages and the CLI. |
| 332 | pub name: String, |
| 333 | /// Hex SHA-256 of the client secret. The secret itself is shown once, at creation. |
| 334 | pub secret_hash: String, |
| 335 | /// When the secret was last issued. |
| 336 | pub secret_rotated_at: String, |
| 337 | /// Exact redirect URIs. A request matches only a string equal to one of them. |
| 338 | pub redirect_uris: Vec<String>, |
| 339 | /// Exact post-logout redirect URIs (used by RP-initiated logout). |
| 340 | pub post_logout_redirect_uris: Vec<String>, |
| 341 | /// Back-channel logout endpoint of the client, when it has one. |
| 342 | pub backchannel_logout_uri: Option<String>, |
| 343 | /// Space-separated scopes the client may ask for. |
| 344 | pub allowed_scopes: String, |
| 345 | /// Family key such as `in`, when the client is a family service. |
| 346 | pub service_key: Option<String>, |
| 347 | /// Creation time. |
| 348 | pub created_at: String, |
| 349 | /// Set when the client is disabled. A disabled client authenticates nowhere. |
| 350 | pub disabled_at: Option<String>, |
| 351 | } |
| 352 | |
| 353 | impl Client { |
| 354 | /// True when the client is disabled. |
| 355 | pub fn is_disabled(&self) -> bool { |
| 356 | self.disabled_at.is_some() |
| 357 | } |
| 358 | |
| 359 | /// True when the client may ask for `scope`. |
| 360 | pub fn allows_scope(&self, scope: &str) -> bool { |
| 361 | self.allowed_scopes.split_whitespace().any(|s| s == scope) |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | /// An authorization code row. Only the hash of the code is stored. |
| 366 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 367 | pub struct AuthCode { |
| 368 | /// Hex SHA-256 of the code. |
| 369 | pub code_hash: String, |
| 370 | /// The client the code was issued to. |
| 371 | pub client_id: String, |
| 372 | /// The person who signed in. |
| 373 | pub user_id: String, |
| 374 | /// The browser session the code was issued in. Its time and method go into the tokens. |
| 375 | pub session_id: String, |
| 376 | /// The redirect URI of the request, which the exchange must repeat. |
| 377 | pub redirect_uri: String, |
| 378 | /// The granted scope. |
| 379 | pub scope: String, |
| 380 | /// The nonce of the request, when there was one. |
| 381 | pub nonce: Option<String>, |
| 382 | /// The PKCE challenge (S256) of the request. |
| 383 | pub code_challenge: String, |
| 384 | /// When the code stops being usable. |
| 385 | pub expires_at: String, |
| 386 | /// Set when the code was exchanged. A code is exchanged once. |
| 387 | pub used_at: Option<String>, |
| 388 | /// The `jti` of the access token issued at the exchange. A replay revokes it. |
| 389 | pub access_jti: Option<String>, |
| 390 | /// When that access token expires; its revocation is kept until then. |
| 391 | pub access_expires_at: Option<String>, |
| 392 | } |
| 393 | |
| 394 | /// A refresh token row. Only the hash of the token is stored. |
| 395 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 396 | pub struct RefreshToken { |
| 397 | /// ULID. |
| 398 | pub id: String, |
| 399 | /// Hex SHA-256 of the token. |
| 400 | pub token_hash: String, |
| 401 | /// The first token of the chain. Reuse revokes every token with this family id. |
| 402 | pub family_id: String, |
| 403 | /// The client the token was issued to. |
| 404 | pub client_id: String, |
| 405 | /// The person. |
| 406 | pub user_id: String, |
| 407 | /// The browser session the chain belongs to. |
| 408 | pub session_id: String, |
| 409 | /// Hash of the authorization code the chain began with, when it began with one. |
| 410 | pub code_hash: Option<String>, |
| 411 | /// The granted scope. |
| 412 | pub scope: String, |
| 413 | /// Creation time. |
| 414 | pub created_at: String, |
| 415 | /// Expiry. |
| 416 | pub expires_at: String, |
| 417 | /// Set when the token was rotated. Presenting a used token is reuse. |
| 418 | pub used_at: Option<String>, |
| 419 | /// Set when the token or its family was revoked. |
| 420 | pub revoked_at: Option<String>, |
| 421 | } |
| 422 | |
| 423 | /// One token-signing key. The private part is sealed under the instance key. |
| 424 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 425 | pub struct KeyRecord { |
| 426 | /// Key id, published in the JWKS and in every token header. |
| 427 | pub kid: String, |
| 428 | /// The 32-byte Ed25519 seed, sealed with `secret::seal`. |
| 429 | pub private_sealed: String, |
| 430 | /// The 32-byte Ed25519 public key. |
| 431 | pub public_raw: Vec<u8>, |
| 432 | /// Creation time. |
| 433 | pub created_at: String, |
| 434 | /// When the key starts signing. Published before this time. |
| 435 | pub activates_at: String, |
| 436 | /// When the key stops signing. It stays published for a while after this time. |
| 437 | pub retires_at: Option<String>, |
| 438 | } |
| 439 | |
| 440 | /// One row of the service switcher (contracts.md 4). |
| 441 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 442 | pub struct Service { |
| 443 | /// Family key, such as `in`. |
| 444 | pub key: String, |
| 445 | /// Display name. |
| 446 | pub name: String, |
| 447 | /// Public origin. |
| 448 | pub url: String, |
| 449 | /// The last health probe's answer, `None` before the first probe. |
| 450 | pub healthy: Option<bool>, |
| 451 | /// When the last probe ran. |
| 452 | pub checked_at: Option<String>, |
| 453 | } |