| | @@ -8,11 +8,12 @@ use std::time::{Duration, SystemTime}; |
| 8 | 8 | use sqlx::{Row, SqlitePool, sqlite::SqliteRow}; |
| 9 | 9 | |
| 10 | 10 | use crate::domain::{ |
| 11 | | − Email, Membership, MembershipId, OrgId, OrgName, Organization, PasswordHash, RepoId, RepoName, |
| 12 | | − Repository, Role, Session, SessionTokenHash, User, UserId, Visibility, |
| 11 | + Email, Membership, MembershipId, OrgId, OrgName, Organization, PasswordHash, |
| 12 | + PersonalAccessToken, RepoId, RepoName, Repository, Role, Session, SessionTokenHash, TokenHash, |
| 13 | + TokenId, User, UserId, Visibility, |
| 13 | 14 | repository::{ |
| 14 | 15 | MembershipRepository, OrgRepository, RepoRepository, RepositoryError, RepositoryResult, |
| 15 | | − SessionRepository, UserRepository, |
| 16 | + SessionRepository, TokenRepository, UserRepository, |
| 16 | 17 | }, |
| 17 | 18 | }; |
| 18 | 19 | |
| | @@ -389,12 +390,95 @@ impl RepoRepository for SqliteRepoRepo { |
| 389 | 390 | } |
| 390 | 391 | } |
| 391 | 392 | |
| 393 | +#[derive(Debug, Clone)] |
| 394 | +pub struct SqliteTokenRepo { |
| 395 | + pool: SqlitePool, |
| 396 | +} |
| 397 | + |
| 398 | +impl SqliteTokenRepo { |
| 399 | + pub fn new(pool: SqlitePool) -> Self { |
| 400 | + Self { pool } |
| 401 | + } |
| 402 | + |
| 403 | + /// `from_trusted`, because these values were validated on the way in. Revalidating |
| 404 | + /// stored rows means a tightened rule turns old rows unreadable. |
| 405 | + fn hydrate(row: &SqliteRow) -> PersonalAccessToken { |
| 406 | + PersonalAccessToken::from_trusted( |
| 407 | + TokenId::from_trusted(row.get::<String, _>("id")), |
| 408 | + UserId::from_trusted(row.get::<String, _>("user_id")), |
| 409 | + row.get::<String, _>("name"), |
| 410 | + row.get::<String, _>("prefix"), |
| 411 | + TokenHash::from_trusted(row.get::<String, _>("token_hash")), |
| 412 | + from_unix(row.get::<i64, _>("created_at")), |
| 413 | + ) |
| 414 | + } |
| 415 | +} |
| 416 | + |
| 417 | +impl TokenRepository for SqliteTokenRepo { |
| 418 | + async fn find_by_hash( |
| 419 | + &self, |
| 420 | + hash: &TokenHash, |
| 421 | + ) -> RepositoryResult<Option<PersonalAccessToken>> { |
| 422 | + // Matched in SQL by the hash, which is safe to compare with `=`: it is a digest, |
| 423 | + // not the secret. The constant-time comparison guards the value a client |
| 424 | + // presents, and that never reaches the database. |
| 425 | + let row = sqlx::query("select * from tokens where token_hash = ?") |
| 426 | + .bind(hash.as_str()) |
| 427 | + .fetch_optional(&self.pool) |
| 428 | + .await |
| 429 | + .map_err(backend)?; |
| 430 | + |
| 431 | + Ok(row.as_ref().map(Self::hydrate)) |
| 432 | + } |
| 433 | + |
| 434 | + async fn list_by_user(&self, user_id: &UserId) -> RepositoryResult<Vec<PersonalAccessToken>> { |
| 435 | + let rows = |
| 436 | + sqlx::query("select * from tokens where user_id = ? order by created_at desc, id asc") |
| 437 | + .bind(user_id.as_str()) |
| 438 | + .fetch_all(&self.pool) |
| 439 | + .await |
| 440 | + .map_err(backend)?; |
| 441 | + |
| 442 | + Ok(rows.iter().map(Self::hydrate).collect()) |
| 443 | + } |
| 444 | + |
| 445 | + async fn save(&self, token: &PersonalAccessToken) -> RepositoryResult<()> { |
| 446 | + sqlx::query( |
| 447 | + "insert into tokens (id, user_id, name, prefix, token_hash, created_at) |
| 448 | + values (?, ?, ?, ?, ?, ?) |
| 449 | + on conflict (id) do update set |
| 450 | + name = excluded.name", |
| 451 | + ) |
| 452 | + .bind(token.id.as_str()) |
| 453 | + .bind(token.user_id.as_str()) |
| 454 | + .bind(&token.name) |
| 455 | + .bind(&token.prefix) |
| 456 | + .bind(token.token_hash.as_str()) |
| 457 | + .bind(to_unix(token.created_at)) |
| 458 | + .execute(&self.pool) |
| 459 | + .await |
| 460 | + .map_err(backend)?; |
| 461 | + |
| 462 | + Ok(()) |
| 463 | + } |
| 464 | + |
| 465 | + async fn delete(&self, id: &TokenId) -> RepositoryResult<()> { |
| 466 | + sqlx::query("delete from tokens where id = ?") |
| 467 | + .bind(id.as_str()) |
| 468 | + .execute(&self.pool) |
| 469 | + .await |
| 470 | + .map_err(backend)?; |
| 471 | + |
| 472 | + Ok(()) |
| 473 | + } |
| 474 | +} |
| 475 | + |
| 392 | 476 | #[cfg(test)] |
| 393 | 477 | mod tests { |
| 394 | 478 | use super::*; |
| 395 | 479 | use crate::{ |
| 396 | 480 | application::{OwnerSpec, claim_instance, port::PasswordHasher}, |
| 397 | | − domain::SetupToken, |
| 481 | + domain::{SetupToken, TokenSecret}, |
| 398 | 482 | infrastructure::{database::test_support::test_pool, password::StubHasher}, |
| 399 | 483 | }; |
| 400 | 484 | |
| | @@ -830,4 +914,157 @@ mod tests { |
| 830 | 914 | |
| 831 | 915 | assert_eq!(found, None); |
| 832 | 916 | } |
| 917 | + |
| 918 | + // --- SqliteTokenRepo --------------------------------------------------------- |
| 919 | + |
| 920 | + /// A pool plus a user to hang tokens off, since the foreign key runs that way. |
| 921 | + async fn token_fixture() -> (SqliteTokenRepo, User, User) { |
| 922 | + let pool = test_pool().await; |
| 923 | + let repos = Repos { |
| 924 | + users: SqliteUserRepo::new(pool.clone()), |
| 925 | + orgs: SqliteOrgRepo::new(pool.clone()), |
| 926 | + memberships: SqliteMembershipRepo::new(pool.clone()), |
| 927 | + }; |
| 928 | + |
| 929 | + let org = saved_org(&repos, "acme").await; |
| 930 | + let owner = saved_user(&repos, "owner@example.com", &org).await; |
| 931 | + let other = saved_user(&repos, "other@example.com", &org).await; |
| 932 | + |
| 933 | + (SqliteTokenRepo::new(pool), owner, other) |
| 934 | + } |
| 935 | + |
| 936 | + fn issued(user: &User, name: &str, at: u64) -> (PersonalAccessToken, TokenSecret) { |
| 937 | + let secret = TokenSecret::generate(); |
| 938 | + let token = PersonalAccessToken::new( |
| 939 | + TokenId::generate(), |
| 940 | + user.id.clone(), |
| 941 | + name, |
| 942 | + &secret, |
| 943 | + SystemTime::UNIX_EPOCH + Duration::from_secs(at), |
| 944 | + ) |
| 945 | + .expect("valid token"); |
| 946 | + |
| 947 | + (token, secret) |
| 948 | + } |
| 949 | + |
| 950 | + #[tokio::test] |
| 951 | + async fn a_token_round_trips_through_its_hash() { |
| 952 | + let (tokens, owner, _) = token_fixture().await; |
| 953 | + let (token, secret) = issued(&owner, "laptop", 1_000); |
| 954 | + tokens.save(&token).await.expect("save"); |
| 955 | + |
| 956 | + let found = tokens |
| 957 | + .find_by_hash(&secret.hash()) |
| 958 | + .await |
| 959 | + .expect("lookup") |
| 960 | + .expect("should be found"); |
| 961 | + |
| 962 | + assert_eq!(found, token); |
| 963 | + assert_eq!(found.name, "laptop"); |
| 964 | + assert_eq!(found.prefix, secret.display_prefix()); |
| 965 | + } |
| 966 | + |
| 967 | + #[tokio::test] |
| 968 | + async fn an_unknown_hash_finds_nothing() { |
| 969 | + let (tokens, owner, _) = token_fixture().await; |
| 970 | + let (token, _) = issued(&owner, "laptop", 1_000); |
| 971 | + tokens.save(&token).await.expect("save"); |
| 972 | + |
| 973 | + let found = tokens |
| 974 | + .find_by_hash(&TokenSecret::generate().hash()) |
| 975 | + .await |
| 976 | + .expect("lookup"); |
| 977 | + |
| 978 | + assert!(found.is_none()); |
| 979 | + } |
| 980 | + |
| 981 | + #[tokio::test] |
| 982 | + async fn tokens_are_listed_newest_first_and_only_the_users_own() { |
| 983 | + let (tokens, owner, other) = token_fixture().await; |
| 984 | + |
| 985 | + for (user, name, at) in [ |
| 986 | + (&owner, "old", 1_000), |
| 987 | + (&owner, "new", 3_000), |
| 988 | + (&owner, "middle", 2_000), |
| 989 | + (&other, "theirs", 4_000), |
| 990 | + ] { |
| 991 | + let (token, _) = issued(user, name, at); |
| 992 | + tokens.save(&token).await.expect("save"); |
| 993 | + } |
| 994 | + |
| 995 | + let listed = tokens.list_by_user(&owner.id).await.expect("list"); |
| 996 | + |
| 997 | + assert_eq!( |
| 998 | + listed |
| 999 | + .iter() |
| 1000 | + .map(|token| token.name.as_str()) |
| 1001 | + .collect::<Vec<_>>(), |
| 1002 | + vec!["new", "middle", "old"] |
| 1003 | + ); |
| 1004 | + } |
| 1005 | + |
| 1006 | + #[tokio::test] |
| 1007 | + async fn deleting_a_token_stops_it_authenticating() { |
| 1008 | + // Revocation is a delete, so the credential is gone rather than flagged. |
| 1009 | + let (tokens, owner, _) = token_fixture().await; |
| 1010 | + let (token, secret) = issued(&owner, "laptop", 1_000); |
| 1011 | + tokens.save(&token).await.expect("save"); |
| 1012 | + |
| 1013 | + tokens.delete(&token.id).await.expect("delete"); |
| 1014 | + |
| 1015 | + assert!( |
| 1016 | + tokens |
| 1017 | + .find_by_hash(&secret.hash()) |
| 1018 | + .await |
| 1019 | + .expect("lookup") |
| 1020 | + .is_none() |
| 1021 | + ); |
| 1022 | + } |
| 1023 | + |
| 1024 | + #[tokio::test] |
| 1025 | + async fn deleting_a_token_that_is_not_there_succeeds() { |
| 1026 | + let (tokens, _, _) = token_fixture().await; |
| 1027 | + |
| 1028 | + tokens |
| 1029 | + .delete(&TokenId::generate()) |
| 1030 | + .await |
| 1031 | + .expect("deleting nothing should not fail"); |
| 1032 | + } |
| 1033 | + |
| 1034 | + #[tokio::test] |
| 1035 | + async fn a_second_token_with_the_same_hash_is_refused() { |
| 1036 | + // The unique constraint. Two rows answering one credential would make which |
| 1037 | + // user a token authenticates depend on row order. |
| 1038 | + let (tokens, owner, other) = token_fixture().await; |
| 1039 | + let (first, secret) = issued(&owner, "laptop", 1_000); |
| 1040 | + tokens.save(&first).await.expect("save"); |
| 1041 | + |
| 1042 | + let clash = PersonalAccessToken::new( |
| 1043 | + TokenId::generate(), |
| 1044 | + other.id.clone(), |
| 1045 | + "clash", |
| 1046 | + &secret, |
| 1047 | + SystemTime::UNIX_EPOCH, |
| 1048 | + ) |
| 1049 | + .expect("valid token"); |
| 1050 | + |
| 1051 | + assert!(tokens.save(&clash).await.is_err()); |
| 1052 | + } |
| 1053 | + |
| 1054 | + #[tokio::test] |
| 1055 | + async fn a_token_belonging_to_no_user_is_refused() { |
| 1056 | + // The foreign key. Without `foreign_keys(true)` per connection SQLite ignores it. |
| 1057 | + let (tokens, _, _) = token_fixture().await; |
| 1058 | + let secret = TokenSecret::generate(); |
| 1059 | + let orphan = PersonalAccessToken::new( |
| 1060 | + TokenId::generate(), |
| 1061 | + UserId::generate(), |
| 1062 | + "orphan", |
| 1063 | + &secret, |
| 1064 | + SystemTime::UNIX_EPOCH, |
| 1065 | + ) |
| 1066 | + .expect("valid token"); |
| 1067 | + |
| 1068 | + assert!(tokens.save(&orphan).await.is_err()); |
| 1069 | + } |
| 833 | 1070 | } |