| 1 | |
| 2 | |
| 3 | use std::{ |
| 4 | fmt, |
| 5 | str::FromStr, |
| 6 | time::{Duration, SystemTime}, |
| 7 | }; |
| 8 | |
| 9 | use sha2::{Digest, Sha256}; |
| 10 | use subtle::ConstantTimeEq; |
| 11 | |
| 12 | use super::{DomainError, TokenId, UserId}; |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | const TOKEN_PREFIX: &str = "steid_pat_"; |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | const DISPLAY_CHARS: usize = 8; |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | #[derive(Clone)] |
| 32 | pub struct TokenSecret(String); |
| 33 | |
| 34 | impl TokenSecret { |
| 35 | |
| 36 | const BYTES: usize = 32; |
| 37 | |
| 38 | |
| 39 | pub fn generate() -> Self { |
| 40 | use rand::Rng; |
| 41 | |
| 42 | let mut bytes = [0u8; Self::BYTES]; |
| 43 | rand::rng().fill_bytes(&mut bytes); |
| 44 | |
| 45 | let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect(); |
| 46 | |
| 47 | Self(format!("{TOKEN_PREFIX}{random}")) |
| 48 | } |
| 49 | |
| 50 | |
| 51 | pub fn from_presented(value: impl Into<String>) -> Self { |
| 52 | Self(value.into()) |
| 53 | } |
| 54 | |
| 55 | |
| 56 | pub fn hash(&self) -> TokenHash { |
| 57 | TokenHash::of(&self.0) |
| 58 | } |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | pub fn display_prefix(&self) -> String { |
| 65 | self.0 |
| 66 | .strip_prefix(TOKEN_PREFIX) |
| 67 | .unwrap_or_default() |
| 68 | .chars() |
| 69 | .take(DISPLAY_CHARS) |
| 70 | .collect() |
| 71 | } |
| 72 | |
| 73 | |
| 74 | pub fn reveal(&self) -> &str { |
| 75 | &self.0 |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | |
| 80 | impl fmt::Debug for TokenSecret { |
| 81 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 82 | f.write_str("TokenSecret(redacted)") |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | |
| 92 | #[derive(Clone, PartialEq, Eq, Hash)] |
| 93 | pub struct TokenHash(String); |
| 94 | |
| 95 | impl TokenHash { |
| 96 | |
| 97 | pub fn of(plaintext: &str) -> Self { |
| 98 | let digest = Sha256::digest(plaintext.as_bytes()); |
| 99 | |
| 100 | Self(digest.iter().map(|byte| format!("{byte:02x}")).collect()) |
| 101 | } |
| 102 | |
| 103 | |
| 104 | pub fn from_trusted(value: impl Into<String>) -> Self { |
| 105 | Self(value.into()) |
| 106 | } |
| 107 | |
| 108 | pub fn as_str(&self) -> &str { |
| 109 | &self.0 |
| 110 | } |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | pub fn matches(&self, other: &Self) -> bool { |
| 118 | self.0.as_bytes().ct_eq(other.0.as_bytes()).into() |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | |
| 123 | |
| 124 | impl fmt::Debug for TokenHash { |
| 125 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 126 | f.write_str("TokenHash(redacted)") |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 137 | pub enum TokenLifetime { |
| 138 | Days30, |
| 139 | #[default] |
| 140 | Days90, |
| 141 | Year, |
| 142 | |
| 143 | |
| 144 | |
| 145 | Never, |
| 146 | } |
| 147 | |
| 148 | impl TokenLifetime { |
| 149 | |
| 150 | pub const ALL: [Self; 4] = [Self::Days30, Self::Days90, Self::Year, Self::Never]; |
| 151 | |
| 152 | |
| 153 | pub fn as_str(&self) -> &'static str { |
| 154 | match self { |
| 155 | Self::Days30 => "30d", |
| 156 | Self::Days90 => "90d", |
| 157 | Self::Year => "1y", |
| 158 | Self::Never => "never", |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | |
| 163 | pub fn label(&self) -> &'static str { |
| 164 | match self { |
| 165 | Self::Days30 => "30 days", |
| 166 | Self::Days90 => "90 days", |
| 167 | Self::Year => "1 year", |
| 168 | Self::Never => "No expiry", |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | pub fn expires_at(&self, from: SystemTime) -> Option<SystemTime> { |
| 178 | let days = match self { |
| 179 | Self::Days30 => 30, |
| 180 | Self::Days90 => 90, |
| 181 | Self::Year => 365, |
| 182 | Self::Never => return None, |
| 183 | }; |
| 184 | |
| 185 | Some(from + Duration::from_secs(days * 86_400)) |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | |
| 190 | |
| 191 | impl FromStr for TokenLifetime { |
| 192 | type Err = DomainError; |
| 193 | |
| 194 | fn from_str(value: &str) -> Result<Self, Self::Err> { |
| 195 | Self::ALL |
| 196 | .into_iter() |
| 197 | .find(|lifetime| lifetime.as_str() == value) |
| 198 | .ok_or_else(|| DomainError::validation("expiry", "choose one of the offered periods")) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 208 | pub struct PersonalAccessToken { |
| 209 | pub id: TokenId, |
| 210 | pub user_id: UserId, |
| 211 | |
| 212 | pub name: String, |
| 213 | |
| 214 | pub prefix: String, |
| 215 | pub token_hash: TokenHash, |
| 216 | pub created_at: SystemTime, |
| 217 | |
| 218 | pub expires_at: Option<SystemTime>, |
| 219 | |
| 220 | |
| 221 | pub last_used_at: Option<SystemTime>, |
| 222 | } |
| 223 | |
| 224 | impl PersonalAccessToken { |
| 225 | |
| 226 | const MAX_NAME: usize = 100; |
| 227 | |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | pub const USE_RESOLUTION: Duration = Duration::from_secs(60); |
| 235 | |
| 236 | |
| 237 | pub fn new( |
| 238 | id: TokenId, |
| 239 | user_id: UserId, |
| 240 | name: impl AsRef<str>, |
| 241 | secret: &TokenSecret, |
| 242 | created_at: SystemTime, |
| 243 | lifetime: TokenLifetime, |
| 244 | ) -> Result<Self, DomainError> { |
| 245 | let name = name.as_ref().trim(); |
| 246 | |
| 247 | if name.is_empty() { |
| 248 | return Err(DomainError::validation( |
| 249 | "name", |
| 250 | "give the token a name so you can tell it apart later", |
| 251 | )); |
| 252 | } |
| 253 | |
| 254 | if name.chars().count() > Self::MAX_NAME { |
| 255 | return Err(DomainError::validation( |
| 256 | "name", |
| 257 | format!("a token name is at most {} characters", Self::MAX_NAME), |
| 258 | )); |
| 259 | } |
| 260 | |
| 261 | Ok(Self { |
| 262 | id, |
| 263 | user_id, |
| 264 | name: name.to_owned(), |
| 265 | prefix: secret.display_prefix(), |
| 266 | token_hash: secret.hash(), |
| 267 | created_at, |
| 268 | expires_at: lifetime.expires_at(created_at), |
| 269 | last_used_at: None, |
| 270 | }) |
| 271 | } |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | #[allow(clippy::too_many_arguments)] |
| 278 | pub fn from_trusted( |
| 279 | id: TokenId, |
| 280 | user_id: UserId, |
| 281 | name: impl Into<String>, |
| 282 | prefix: impl Into<String>, |
| 283 | token_hash: TokenHash, |
| 284 | created_at: SystemTime, |
| 285 | expires_at: Option<SystemTime>, |
| 286 | last_used_at: Option<SystemTime>, |
| 287 | ) -> Self { |
| 288 | Self { |
| 289 | id, |
| 290 | user_id, |
| 291 | name: name.into(), |
| 292 | prefix: prefix.into(), |
| 293 | token_hash, |
| 294 | created_at, |
| 295 | expires_at, |
| 296 | last_used_at, |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | |
| 301 | |
| 302 | |
| 303 | |
| 304 | |
| 305 | pub fn is_expired(&self, now: SystemTime) -> bool { |
| 306 | self.expires_at.is_some_and(|expires| now >= expires) |
| 307 | } |
| 308 | |
| 309 | |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | pub fn should_record_use(&self, now: SystemTime) -> bool { |
| 316 | let Some(last) = self.last_used_at else { |
| 317 | return true; |
| 318 | }; |
| 319 | |
| 320 | now.duration_since(last) |
| 321 | .is_ok_and(|since| since >= Self::USE_RESOLUTION) |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | #[cfg(test)] |
| 326 | mod tests { |
| 327 | use super::*; |
| 328 | |
| 329 | fn token(name: &str) -> Result<PersonalAccessToken, DomainError> { |
| 330 | PersonalAccessToken::new( |
| 331 | TokenId::generate(), |
| 332 | UserId::generate(), |
| 333 | name, |
| 334 | &TokenSecret::generate(), |
| 335 | SystemTime::UNIX_EPOCH, |
| 336 | TokenLifetime::default(), |
| 337 | ) |
| 338 | } |
| 339 | |
| 340 | fn at(seconds: u64) -> SystemTime { |
| 341 | SystemTime::UNIX_EPOCH + Duration::from_secs(seconds) |
| 342 | } |
| 343 | |
| 344 | fn issued(lifetime: TokenLifetime) -> PersonalAccessToken { |
| 345 | PersonalAccessToken::new( |
| 346 | TokenId::generate(), |
| 347 | UserId::generate(), |
| 348 | "laptop", |
| 349 | &TokenSecret::generate(), |
| 350 | at(1_000), |
| 351 | lifetime, |
| 352 | ) |
| 353 | .expect("valid") |
| 354 | } |
| 355 | |
| 356 | #[test] |
| 357 | fn a_generated_token_is_recognisable_and_full_width() { |
| 358 | let secret = TokenSecret::generate(); |
| 359 | |
| 360 | assert!(secret.reveal().starts_with("steid_pat_")); |
| 361 | assert_eq!( |
| 362 | secret.reveal().len(), |
| 363 | "steid_pat_".len() + TokenSecret::BYTES * 2 |
| 364 | ); |
| 365 | } |
| 366 | |
| 367 | #[test] |
| 368 | fn tokens_are_unique_per_generation() { |
| 369 | assert_ne!( |
| 370 | TokenSecret::generate().reveal(), |
| 371 | TokenSecret::generate().reveal() |
| 372 | ); |
| 373 | } |
| 374 | |
| 375 | #[test] |
| 376 | fn a_token_hashes_to_the_same_value_every_time() { |
| 377 | let secret = TokenSecret::generate(); |
| 378 | |
| 379 | assert!(secret.hash().matches(&secret.hash())); |
| 380 | } |
| 381 | |
| 382 | #[test] |
| 383 | fn different_tokens_hash_differently() { |
| 384 | let first = TokenSecret::generate(); |
| 385 | let second = TokenSecret::generate(); |
| 386 | |
| 387 | assert!(!first.hash().matches(&second.hash())); |
| 388 | } |
| 389 | |
| 390 | #[test] |
| 391 | fn a_presented_value_hashes_the_same_as_the_token_it_copies() { |
| 392 | |
| 393 | |
| 394 | let secret = TokenSecret::generate(); |
| 395 | let presented = TokenSecret::from_presented(secret.reveal()); |
| 396 | |
| 397 | assert!(presented.hash().matches(&secret.hash())); |
| 398 | } |
| 399 | |
| 400 | #[test] |
| 401 | fn the_hash_is_not_the_token() { |
| 402 | let secret = TokenSecret::generate(); |
| 403 | |
| 404 | assert_ne!(secret.hash().as_str(), secret.reveal()); |
| 405 | assert_eq!(secret.hash().as_str().len(), 64); |
| 406 | } |
| 407 | |
| 408 | #[test] |
| 409 | fn the_display_prefix_identifies_without_revealing() { |
| 410 | let secret = TokenSecret::generate(); |
| 411 | let prefix = secret.display_prefix(); |
| 412 | |
| 413 | assert_eq!(prefix.len(), 8); |
| 414 | assert!(secret.reveal().contains(&prefix)); |
| 415 | assert!( |
| 416 | !prefix.starts_with("steid_pat_"), |
| 417 | "the prefix should identify the token, not the product" |
| 418 | ); |
| 419 | } |
| 420 | |
| 421 | #[test] |
| 422 | fn a_value_that_is_not_a_steid_token_has_no_prefix() { |
| 423 | assert_eq!(TokenSecret::from_presented("hunter2").display_prefix(), ""); |
| 424 | } |
| 425 | |
| 426 | #[test] |
| 427 | fn debug_output_redacts_both_the_token_and_its_hash() { |
| 428 | let secret = TokenSecret::generate(); |
| 429 | |
| 430 | assert_eq!(format!("{secret:?}"), "TokenSecret(redacted)"); |
| 431 | assert_eq!(format!("{:?}", secret.hash()), "TokenHash(redacted)"); |
| 432 | assert!(!format!("{:?}", token("laptop").expect("valid")).contains(secret.reveal())); |
| 433 | } |
| 434 | |
| 435 | #[test] |
| 436 | fn a_token_records_its_prefix_and_hash() { |
| 437 | let secret = TokenSecret::generate(); |
| 438 | let record = PersonalAccessToken::new( |
| 439 | TokenId::generate(), |
| 440 | UserId::generate(), |
| 441 | " laptop ", |
| 442 | &secret, |
| 443 | SystemTime::UNIX_EPOCH, |
| 444 | TokenLifetime::default(), |
| 445 | ) |
| 446 | .expect("valid"); |
| 447 | |
| 448 | assert_eq!(record.name, "laptop", "the name should be trimmed"); |
| 449 | assert_eq!(record.prefix, secret.display_prefix()); |
| 450 | assert!(record.token_hash.matches(&secret.hash())); |
| 451 | } |
| 452 | |
| 453 | #[test] |
| 454 | fn a_token_needs_a_name() { |
| 455 | assert!(token("").is_err()); |
| 456 | assert!(token(" ").is_err()); |
| 457 | } |
| 458 | |
| 459 | #[test] |
| 460 | fn a_name_has_a_limit() { |
| 461 | assert!(token(&"a".repeat(PersonalAccessToken::MAX_NAME)).is_ok()); |
| 462 | assert!(token(&"a".repeat(PersonalAccessToken::MAX_NAME + 1)).is_err()); |
| 463 | } |
| 464 | |
| 465 | |
| 466 | |
| 467 | #[test] |
| 468 | fn a_lifetime_round_trips_through_its_form_value() { |
| 469 | for lifetime in TokenLifetime::ALL { |
| 470 | assert_eq!( |
| 471 | lifetime.as_str().parse::<TokenLifetime>().expect("known"), |
| 472 | lifetime |
| 473 | ); |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | #[test] |
| 478 | fn an_unknown_lifetime_is_an_error_rather_than_a_default() { |
| 479 | |
| 480 | assert!("".parse::<TokenLifetime>().is_err()); |
| 481 | assert!("forever".parse::<TokenLifetime>().is_err()); |
| 482 | assert!("30".parse::<TokenLifetime>().is_err()); |
| 483 | } |
| 484 | |
| 485 | #[test] |
| 486 | fn the_default_lifetime_is_ninety_days() { |
| 487 | assert_eq!(TokenLifetime::default(), TokenLifetime::Days90); |
| 488 | assert_eq!( |
| 489 | TokenLifetime::Days90.expires_at(at(0)), |
| 490 | Some(at(90 * 86_400)) |
| 491 | ); |
| 492 | } |
| 493 | |
| 494 | #[test] |
| 495 | fn a_token_records_the_expiry_its_lifetime_implies() { |
| 496 | assert_eq!( |
| 497 | issued(TokenLifetime::Days30).expires_at, |
| 498 | Some(at(1_000 + 30 * 86_400)) |
| 499 | ); |
| 500 | assert_eq!( |
| 501 | issued(TokenLifetime::Year).expires_at, |
| 502 | Some(at(1_000 + 365 * 86_400)) |
| 503 | ); |
| 504 | assert_eq!(issued(TokenLifetime::Never).expires_at, None); |
| 505 | } |
| 506 | |
| 507 | #[test] |
| 508 | fn a_token_expires_at_its_expiry_and_not_before() { |
| 509 | let token = issued(TokenLifetime::Days30); |
| 510 | let expires = at(1_000 + 30 * 86_400); |
| 511 | |
| 512 | assert!(!token.is_expired(expires - Duration::from_secs(1))); |
| 513 | assert!(token.is_expired(expires)); |
| 514 | assert!(token.is_expired(expires + Duration::from_secs(1))); |
| 515 | } |
| 516 | |
| 517 | #[test] |
| 518 | fn a_token_with_no_expiry_never_expires() { |
| 519 | assert!(!issued(TokenLifetime::Never).is_expired(at(u32::MAX as u64))); |
| 520 | } |
| 521 | |
| 522 | |
| 523 | |
| 524 | #[test] |
| 525 | fn a_token_starts_never_used() { |
| 526 | let token = issued(TokenLifetime::Days90); |
| 527 | |
| 528 | assert_eq!(token.last_used_at, None); |
| 529 | assert!(token.should_record_use(at(1_000))); |
| 530 | } |
| 531 | |
| 532 | #[test] |
| 533 | fn a_use_within_the_minute_is_not_worth_writing_down() { |
| 534 | let mut token = issued(TokenLifetime::Days90); |
| 535 | token.last_used_at = Some(at(1_000)); |
| 536 | |
| 537 | assert!(!token.should_record_use(at(1_000))); |
| 538 | assert!(!token.should_record_use(at(1_059))); |
| 539 | assert!(token.should_record_use(at(1_060))); |
| 540 | } |
| 541 | |
| 542 | #[test] |
| 543 | fn a_recorded_use_in_the_future_does_not_make_every_request_a_write() { |
| 544 | |
| 545 | |
| 546 | let mut token = issued(TokenLifetime::Days90); |
| 547 | token.last_used_at = Some(at(10_000)); |
| 548 | |
| 549 | assert!(!token.should_record_use(at(1_000))); |
| 550 | } |
| 551 | } |