diff --git a/Cargo.lock b/Cargo.lock index 2d2d899..f572b30 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -712,7 +712,6 @@ dependencies = [ "chrono", "dotenvy", "futures-util", - "hex", "http-body-util", "jsonwebtoken", "p256", diff --git a/Cargo.toml b/Cargo.toml index 11e85ee..13b66de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,7 +23,6 @@ tokio-tungstenite = { version = "0.26", features = ["rustls-tls-webpki-roots"] } tower-http = { version = "0.6", features = ["cors", "trace"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] } -hex = "0.4.3" [dev-dependencies] wiremock = "0.6" diff --git a/docker-compose.yml b/docker-compose.yml index d81fc33..3bc063d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -50,7 +50,6 @@ services: environment: DATABASE_URL: postgres://happyview:happyview@postgres/happyview AIP_URL: http://aip:8080 - ADMIN_SECRET: ${ADMIN_SECRET:-dev-secret} depends_on: postgres: condition: service_healthy diff --git a/migrations/20260218000000_admin_did_auth.sql b/migrations/20260218000000_admin_did_auth.sql new file mode 100644 index 0000000..0b18ae7 --- /dev/null +++ b/migrations/20260218000000_admin_did_auth.sql @@ -0,0 +1,3 @@ +ALTER TABLE admins DROP COLUMN api_key_hash; +ALTER TABLE admins DROP COLUMN name; +ALTER TABLE admins ADD COLUMN did TEXT NOT NULL UNIQUE; diff --git a/src/admin/admins.rs b/src/admin/admins.rs index b0cbd2f..5f46e2f 100644 --- a/src/admin/admins.rs +++ b/src/admin/admins.rs @@ -7,38 +7,31 @@ use crate::AppState; use crate::error::AppError; use super::auth::AdminAuth; -use super::hash::hash_api_key; use super::types::{AdminSummary, CreateAdminBody}; -/// POST /admin/admins — create a new admin. Returns the API key once. +/// POST /admin/admins — add a new admin by DID. pub(super) async fn create_admin( State(state): State, _admin: AdminAuth, Json(body): Json, ) -> Result<(StatusCode, Json), AppError> { - let api_key = uuid::Uuid::new_v4().to_string(); - let key_hash = hash_api_key(&api_key); - - let row: (String,) = sqlx::query_as( - "INSERT INTO admins (name, api_key_hash) VALUES ($1, $2) RETURNING id::text", - ) - .bind(&body.name) - .bind(&key_hash) - .fetch_one(&state.db) - .await - .map_err(|e| AppError::Internal(format!("failed to create admin: {e}")))?; + let row: (String,) = + sqlx::query_as("INSERT INTO admins (did) VALUES ($1) RETURNING id::text") + .bind(&body.did) + .fetch_one(&state.db) + .await + .map_err(|e| AppError::Internal(format!("failed to create admin: {e}")))?; Ok(( StatusCode::CREATED, Json(serde_json::json!({ "id": row.0, - "name": body.name, - "api_key": api_key, + "did": body.did, })), )) } -/// GET /admin/admins — list all admins (without keys). +/// GET /admin/admins — list all admins. pub(super) async fn list_admins( State(state): State, _admin: AdminAuth, @@ -50,7 +43,7 @@ pub(super) async fn list_admins( chrono::DateTime, Option>, )> = sqlx::query_as( - "SELECT id::text, name, created_at, last_used_at FROM admins ORDER BY created_at", + "SELECT id::text, did, created_at, last_used_at FROM admins ORDER BY created_at", ) .fetch_all(&state.db) .await @@ -58,9 +51,9 @@ pub(super) async fn list_admins( let admins: Vec = rows .into_iter() - .map(|(id, name, created_at, last_used_at)| AdminSummary { + .map(|(id, did, created_at, last_used_at)| AdminSummary { id, - name, + did, created_at, last_used_at, }) diff --git a/src/admin/auth.rs b/src/admin/auth.rs index b175b4c..7d0bc0b 100644 --- a/src/admin/auth.rs +++ b/src/admin/auth.rs @@ -1,59 +1,74 @@ +use axum::extract::FromRequestParts; +use axum::http::request::Parts; + use crate::AppState; +use crate::auth::middleware::Claims; use crate::error::AppError; -use super::hash::hash_api_key; +/// Axum extractor for admin auth. Validates the Bearer token via AIP OAuth +/// (same as `Claims`), then checks if the returned DID exists in the `admins` +/// table. If no admins exist yet, the first authenticated user is +/// auto-bootstrapped as the initial admin. +pub struct AdminAuth { + did: String, +} -/// Axum extractor for admin auth. Checks the Bearer token against: -/// 1. The `admins` table (hashed key lookup) -/// 2. Falls back to `ADMIN_SECRET` env var for bootstrap -pub struct AdminAuth; +impl AdminAuth { + /// The authenticated admin's DID. + pub fn did(&self) -> &str { + &self.did + } +} -impl axum::extract::FromRequestParts for AdminAuth { +impl FromRequestParts for AdminAuth { type Rejection = AppError; async fn from_request_parts( - parts: &mut axum::http::request::Parts, + parts: &mut Parts, state: &AppState, ) -> Result { - let header = parts - .headers - .get("authorization") - .and_then(|v| v.to_str().ok()) - .ok_or_else(|| AppError::Auth("missing Authorization header".into()))?; - - let token = header - .strip_prefix("Bearer ") - .ok_or_else(|| AppError::Auth("invalid Authorization scheme".into()))?; - - // Check admins table first - let key_hash = hash_api_key(token); + // Validate the Bearer token via AIP userinfo (reuse Claims extractor). + let claims = Claims::from_request_parts(parts, state).await?; + let did = claims.did().to_string(); + + // Check whether the admins table is empty (auto-bootstrap case). + let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM admins") + .fetch_one(&state.db) + .await + .map_err(|e| AppError::Internal(format!("admin count query failed: {e}")))?; + + if count.0 == 0 { + // First authenticated user becomes the initial admin. + sqlx::query("INSERT INTO admins (did) VALUES ($1) ON CONFLICT DO NOTHING") + .bind(&did) + .execute(&state.db) + .await + .map_err(|e| AppError::Internal(format!("auto-bootstrap admin failed: {e}")))?; + + tracing::info!(did = %did, "auto-bootstrapped first admin"); + } + + // Look up the DID in the admins table. let found: Option<(String,)> = - sqlx::query_as("SELECT id::text FROM admins WHERE api_key_hash = $1") - .bind(&key_hash) + sqlx::query_as("SELECT id::text FROM admins WHERE did = $1") + .bind(&did) .fetch_optional(&state.db) .await .map_err(|e| AppError::Internal(format!("admin auth query failed: {e}")))?; - if let Some((admin_id,)) = found { - // Update last_used_at in the background - let db = state.db.clone(); - let admin_id = admin_id.clone(); - tokio::spawn(async move { - let _ = sqlx::query("UPDATE admins SET last_used_at = NOW() WHERE id::text = $1") - .bind(&admin_id) - .execute(&db) - .await; - }); - return Ok(AdminAuth); - } + let Some((admin_id,)) = found else { + return Err(AppError::Forbidden("not an admin".into())); + }; - // Fall back to ADMIN_SECRET env var - if let Some(ref secret) = state.config.admin_secret - && token == secret - { - return Ok(AdminAuth); - } + // Update last_used_at in the background. + let db = state.db.clone(); + tokio::spawn(async move { + let _ = sqlx::query("UPDATE admins SET last_used_at = NOW() WHERE id::text = $1") + .bind(&admin_id) + .execute(&db) + .await; + }); - Err(AppError::Auth("invalid admin credentials".into())) + Ok(AdminAuth { did }) } } diff --git a/src/admin/bootstrap.rs b/src/admin/bootstrap.rs deleted file mode 100644 index 66f633f..0000000 --- a/src/admin/bootstrap.rs +++ /dev/null @@ -1,25 +0,0 @@ -use super::hash::hash_api_key; - -/// Bootstrap: if no admins exist and ADMIN_SECRET is set, create a bootstrap admin. -pub async fn bootstrap(db: &sqlx::PgPool, admin_secret: &Option) { - let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM admins") - .fetch_one(db) - .await - .unwrap_or((0,)); - - if count.0 > 0 { - return; - } - - if let Some(secret) = admin_secret { - let key_hash = hash_api_key(secret); - let _ = sqlx::query( - "INSERT INTO admins (name, api_key_hash) VALUES ($1, $2) ON CONFLICT DO NOTHING", - ) - .bind("bootstrap") - .bind(&key_hash) - .execute(db) - .await; - tracing::info!("created bootstrap admin from ADMIN_SECRET"); - } -} diff --git a/src/admin/hash.rs b/src/admin/hash.rs deleted file mode 100644 index 6c00b3e..0000000 --- a/src/admin/hash.rs +++ /dev/null @@ -1,38 +0,0 @@ -use sha2::{Digest, Sha256}; - -/// SHA-256 hash a plaintext API key for storage/comparison. -pub(crate) fn hash_api_key(key: &str) -> String { - let hash = Sha256::digest(key.as_bytes()); - hex::encode(hash) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn hash_api_key_produces_deterministic_sha256_hex() { - let h1 = hash_api_key("test-key"); - let h2 = hash_api_key("test-key"); - assert_eq!(h1, h2); - assert_eq!(h1.len(), 64); - assert!(h1.chars().all(|c| c.is_ascii_hexdigit())); - } - - #[test] - fn hash_api_key_different_inputs_differ() { - let h1 = hash_api_key("key-a"); - let h2 = hash_api_key("key-b"); - assert_ne!(h1, h2); - } - - #[test] - fn hash_api_key_known_value() { - // SHA-256 of "hello" is well-known - let hash = hash_api_key("hello"); - assert_eq!( - hash, - "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" - ); - } -} diff --git a/src/admin/mod.rs b/src/admin/mod.rs index db821ec..b80a886 100644 --- a/src/admin/mod.rs +++ b/src/admin/mod.rs @@ -1,8 +1,6 @@ mod admins; pub(crate) mod auth; mod backfill; -pub(crate) mod bootstrap; -pub(crate) mod hash; mod lexicons; mod stats; mod types; @@ -12,8 +10,6 @@ use axum::routing::{delete, get, post}; use crate::AppState; -pub use bootstrap::bootstrap; - pub fn admin_routes(_state: AppState) -> Router { Router::new() .route( diff --git a/src/admin/types.rs b/src/admin/types.rs index 60fb1c4..f689c6e 100644 --- a/src/admin/types.rs +++ b/src/admin/types.rs @@ -74,13 +74,13 @@ pub(super) struct BackfillJob { #[derive(Deserialize)] pub(super) struct CreateAdminBody { - pub(super) name: String, + pub(super) did: String, } #[derive(Serialize)] pub(super) struct AdminSummary { pub(super) id: String, - pub(super) name: String, + pub(super) did: String, pub(super) created_at: chrono::DateTime, pub(super) last_used_at: Option>, } diff --git a/src/config.rs b/src/config.rs index 7bd8dfe..5dfc664 100644 --- a/src/config.rs +++ b/src/config.rs @@ -8,7 +8,6 @@ pub struct Config { pub database_url: String, pub aip_url: String, pub jetstream_url: String, - pub admin_secret: Option, pub relay_url: String, pub plc_url: String, } @@ -25,7 +24,6 @@ impl Config { aip_url: env::var("AIP_URL").expect("AIP_URL must be set"), jetstream_url: env::var("JETSTREAM_URL") .unwrap_or_else(|_| "wss://jetstream2.us-west.bsky.network/subscribe".into()), - admin_secret: env::var("ADMIN_SECRET").ok(), relay_url: env::var("RELAY_URL").unwrap_or_else(|_| "https://bsky.network".into()), plc_url: env::var("PLC_URL").unwrap_or_else(|_| "https://plc.directory".into()), } @@ -50,7 +48,6 @@ mod tests { "DATABASE_URL", "AIP_URL", "JETSTREAM_URL", - "ADMIN_SECRET", "RELAY_URL", "PLC_URL", ] { @@ -75,7 +72,6 @@ mod tests { database_url: String::new(), aip_url: String::new(), jetstream_url: String::new(), - admin_secret: None, relay_url: String::new(), plc_url: String::new(), }; @@ -110,7 +106,6 @@ mod tests { assert!(config.jetstream_url.contains("jetstream")); assert_eq!(config.relay_url, "https://bsky.network"); assert_eq!(config.plc_url, "https://plc.directory"); - assert!(config.admin_secret.is_none()); } #[test] @@ -121,14 +116,12 @@ mod tests { set_required_env(); env::set_var("HOST", "10.0.0.1"); env::set_var("PORT", "9090"); - env::set_var("ADMIN_SECRET", "s3cret"); env::set_var("RELAY_URL", "https://relay.example.com"); env::set_var("PLC_URL", "https://plc.example.com"); } let config = Config::from_env(); assert_eq!(config.host, "10.0.0.1"); assert_eq!(config.port, 9090); - assert_eq!(config.admin_secret, Some("s3cret".into())); assert_eq!(config.relay_url, "https://relay.example.com"); assert_eq!(config.plc_url, "https://plc.example.com"); } diff --git a/src/error.rs b/src/error.rs index 319689e..62c6d8e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -6,6 +6,7 @@ use bytes::Bytes; pub enum AppError { Auth(String), BadRequest(String), + Forbidden(String), Internal(String), NotFound(String), PdsError(StatusCode, Bytes), @@ -16,6 +17,7 @@ impl std::fmt::Display for AppError { match self { AppError::Auth(msg) => write!(f, "auth error: {msg}"), AppError::BadRequest(msg) => write!(f, "bad request: {msg}"), + AppError::Forbidden(msg) => write!(f, "forbidden: {msg}"), AppError::Internal(msg) => write!(f, "internal error: {msg}"), AppError::NotFound(msg) => write!(f, "not found: {msg}"), AppError::PdsError(status, _) => write!(f, "PDS error: {status}"), @@ -36,6 +38,7 @@ impl IntoResponse for AppError { let (status, message) = match &other { AppError::Auth(msg) => (StatusCode::UNAUTHORIZED, msg.clone()), AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg.clone()), + AppError::Forbidden(msg) => (StatusCode::FORBIDDEN, msg.clone()), AppError::Internal(msg) => { tracing::error!("{msg}"); ( diff --git a/src/main.rs b/src/main.rs index c7c11ab..3cf7705 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,6 @@ use happyview::config::Config; use happyview::lexicon::LexiconRegistry; -use happyview::{AppState, admin, backfill, jetstream, server}; +use happyview::{AppState, backfill, jetstream, server}; use tokio::sync::watch; use tracing::info; @@ -29,8 +29,6 @@ async fn main() { .await .expect("failed to run migrations"); - admin::bootstrap(&db, &config.admin_secret).await; - let lexicons = LexiconRegistry::new(); lexicons .load_from_db(&db) diff --git a/tests/common/app.rs b/tests/common/app.rs index 1bba7b0..1c43f47 100644 --- a/tests/common/app.rs +++ b/tests/common/app.rs @@ -1,7 +1,7 @@ use axum::Router; use happyview::config::Config; use happyview::lexicon::LexiconRegistry; -use happyview::{AppState, admin, server}; +use happyview::{AppState, server}; use tokio::sync::watch; use wiremock::MockServer; @@ -11,7 +11,10 @@ pub struct TestApp { pub router: Router, pub state: AppState, pub mock_server: MockServer, - pub admin_secret: String, + /// DID that is seeded as an admin in the test DB. + pub admin_did: String, + /// Bearer token used for admin requests (validated by the mocked AIP). + pub admin_token: String, } impl TestApp { @@ -24,7 +27,8 @@ impl TestApp { let mock_server = MockServer::start().await; let mock_url = mock_server.uri(); - let admin_secret = "test-admin-secret".to_string(); + let admin_did = "did:plc:testadmin".to_string(); + let admin_token = "test-admin-token".to_string(); let config = Config { host: "127.0.0.1".into(), @@ -32,12 +36,16 @@ impl TestApp { database_url: String::new(), // not used — pool is already connected aip_url: mock_url.clone(), jetstream_url: String::new(), - admin_secret: Some(admin_secret.clone()), relay_url: mock_url.clone(), plc_url: mock_url.clone(), }; - admin::bootstrap(&pool, &config.admin_secret).await; + // Seed the admin DID directly so tests don't rely on auto-bootstrap. + sqlx::query("INSERT INTO admins (did) VALUES ($1) ON CONFLICT DO NOTHING") + .bind(&admin_did) + .execute(&pool) + .await + .expect("failed to seed admin DID"); let lexicons = LexiconRegistry::new(); lexicons @@ -62,7 +70,15 @@ impl TestApp { router, state, mock_server, - admin_secret, + admin_did, + admin_token, } } + + /// Mount the AIP userinfo mock that maps `self.admin_token` to + /// `self.admin_did`. Call this before any admin request. + pub async fn mock_admin_userinfo(&self) { + use crate::common::auth::mock_aip_userinfo; + mock_aip_userinfo(&self.mock_server, &self.admin_did).await; + } } diff --git a/tests/e2e_admin.rs b/tests/e2e_admin.rs index 0c5eee5..a1edc0d 100644 --- a/tests/e2e_admin.rs +++ b/tests/e2e_admin.rs @@ -78,6 +78,7 @@ async fn admin_no_auth_returns_401() { async fn admin_wrong_token_returns_401() { let app = TestApp::new().await; + // No AIP mock mounted — the userinfo request will fail. let resp = app .router .oneshot(admin_get("/admin/lexicons", "wrong-token")) @@ -91,16 +92,67 @@ async fn admin_wrong_token_returns_401() { #[serial] async fn admin_valid_token_returns_200() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; let resp = app .router - .oneshot(admin_get("/admin/lexicons", &app.admin_secret)) + .oneshot(admin_get("/admin/lexicons", &app.admin_token)) .await .unwrap(); assert_eq!(resp.status(), StatusCode::OK); } +#[tokio::test] +#[serial] +async fn admin_non_admin_did_returns_403() { + let app = TestApp::new().await; + + // Mock AIP returning a DID that is NOT in the admins table. + common::auth::mock_aip_userinfo(&app.mock_server, "did:plc:notadmin").await; + + let resp = app + .router + .oneshot(admin_get("/admin/lexicons", "some-token")) + .await + .unwrap(); + + assert_eq!(resp.status(), StatusCode::FORBIDDEN); +} + +#[tokio::test] +#[serial] +async fn admin_auto_bootstrap_first_user() { + let app = TestApp::new().await; + + // Clear the seeded admin so the table is empty. + sqlx::query("DELETE FROM admins") + .execute(&app.state.db) + .await + .unwrap(); + + // Mock AIP returning a new DID. + let bootstrap_did = "did:plc:bootstrap"; + common::auth::mock_aip_userinfo(&app.mock_server, bootstrap_did).await; + + let resp = app + .router + .oneshot(admin_get("/admin/lexicons", "bootstrap-token")) + .await + .unwrap(); + + // The first user should be auto-bootstrapped as admin. + assert_eq!(resp.status(), StatusCode::OK); + + // Verify the DID was inserted. + let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM admins WHERE did = $1") + .bind(bootstrap_did) + .fetch_one(&app.state.db) + .await + .unwrap(); + assert_eq!(count.0, 1); +} + // --------------------------------------------------------------------------- // Lexicon CRUD // --------------------------------------------------------------------------- @@ -109,6 +161,7 @@ async fn admin_valid_token_returns_200() { #[serial] async fn lexicon_create_returns_201() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; let body = json!({ "lexicon_json": fixtures::game_record_lexicon(), "backfill": true @@ -116,7 +169,7 @@ async fn lexicon_create_returns_201() { let resp = app .router - .oneshot(admin_post("/admin/lexicons", &app.admin_secret, &body)) + .oneshot(admin_post("/admin/lexicons", &app.admin_token, &body)) .await .unwrap(); @@ -130,6 +183,7 @@ async fn lexicon_create_returns_201() { #[serial] async fn lexicon_upsert_returns_200_with_incremented_revision() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; let body = json!({ "lexicon_json": fixtures::game_record_lexicon(), "backfill": true @@ -139,7 +193,7 @@ async fn lexicon_upsert_returns_200_with_incremented_revision() { let resp = app .router .clone() - .oneshot(admin_post("/admin/lexicons", &app.admin_secret, &body)) + .oneshot(admin_post("/admin/lexicons", &app.admin_token, &body)) .await .unwrap(); assert_eq!(resp.status(), StatusCode::CREATED); @@ -147,7 +201,7 @@ async fn lexicon_upsert_returns_200_with_incremented_revision() { // Upsert let resp = app .router - .oneshot(admin_post("/admin/lexicons", &app.admin_secret, &body)) + .oneshot(admin_post("/admin/lexicons", &app.admin_token, &body)) .await .unwrap(); assert_eq!(resp.status(), StatusCode::OK); @@ -159,13 +213,14 @@ async fn lexicon_upsert_returns_200_with_incremented_revision() { #[serial] async fn lexicon_invalid_version_returns_400() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; let body = json!({ "lexicon_json": { "lexicon": 99, "id": "test.bad" }, }); let resp = app .router - .oneshot(admin_post("/admin/lexicons", &app.admin_secret, &body)) + .oneshot(admin_post("/admin/lexicons", &app.admin_token, &body)) .await .unwrap(); @@ -176,13 +231,14 @@ async fn lexicon_invalid_version_returns_400() { #[serial] async fn lexicon_missing_id_returns_400() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; let body = json!({ "lexicon_json": { "lexicon": 1 }, }); let resp = app .router - .oneshot(admin_post("/admin/lexicons", &app.admin_secret, &body)) + .oneshot(admin_post("/admin/lexicons", &app.admin_token, &body)) .await .unwrap(); @@ -193,13 +249,14 @@ async fn lexicon_missing_id_returns_400() { #[serial] async fn lexicon_list_all() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; // Seed a lexicon app.router .clone() .oneshot(admin_post( "/admin/lexicons", - &app.admin_secret, + &app.admin_token, &json!({ "lexicon_json": fixtures::game_record_lexicon() }), )) .await @@ -207,7 +264,7 @@ async fn lexicon_list_all() { let resp = app .router - .oneshot(admin_get("/admin/lexicons", &app.admin_secret)) + .oneshot(admin_get("/admin/lexicons", &app.admin_token)) .await .unwrap(); @@ -222,12 +279,13 @@ async fn lexicon_list_all() { #[serial] async fn lexicon_get_by_id() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; app.router .clone() .oneshot(admin_post( "/admin/lexicons", - &app.admin_secret, + &app.admin_token, &json!({ "lexicon_json": fixtures::game_record_lexicon() }), )) .await @@ -237,7 +295,7 @@ async fn lexicon_get_by_id() { .router .oneshot(admin_get( "/admin/lexicons/games.gamesgamesgamesgames.game", - &app.admin_secret, + &app.admin_token, )) .await .unwrap(); @@ -251,12 +309,13 @@ async fn lexicon_get_by_id() { #[serial] async fn lexicon_get_not_found() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; let resp = app .router .oneshot(admin_get( "/admin/lexicons/nonexistent.lexicon", - &app.admin_secret, + &app.admin_token, )) .await .unwrap(); @@ -268,12 +327,13 @@ async fn lexicon_get_not_found() { #[serial] async fn lexicon_delete() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; app.router .clone() .oneshot(admin_post( "/admin/lexicons", - &app.admin_secret, + &app.admin_token, &json!({ "lexicon_json": fixtures::game_record_lexicon() }), )) .await @@ -283,7 +343,7 @@ async fn lexicon_delete() { .router .oneshot(admin_delete( "/admin/lexicons/games.gamesgamesgamesgames.game", - &app.admin_secret, + &app.admin_token, )) .await .unwrap(); @@ -295,12 +355,13 @@ async fn lexicon_delete() { #[serial] async fn lexicon_delete_not_found() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; let resp = app .router .oneshot(admin_delete( "/admin/lexicons/nonexistent.lexicon", - &app.admin_secret, + &app.admin_token, )) .await .unwrap(); @@ -316,10 +377,11 @@ async fn lexicon_delete_not_found() { #[serial] async fn stats_empty_db() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; let resp = app .router - .oneshot(admin_get("/admin/stats", &app.admin_secret)) + .oneshot(admin_get("/admin/stats", &app.admin_token)) .await .unwrap(); @@ -333,6 +395,7 @@ async fn stats_empty_db() { #[serial] async fn stats_with_seeded_records() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; // Seed records directly sqlx::query( @@ -350,7 +413,7 @@ async fn stats_with_seeded_records() { let resp = app .router - .oneshot(admin_get("/admin/stats", &app.admin_secret)) + .oneshot(admin_get("/admin/stats", &app.admin_token)) .await .unwrap(); @@ -369,11 +432,12 @@ async fn stats_with_seeded_records() { #[serial] async fn backfill_create_job() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; let body = json!({ "collection": "test.collection" }); let resp = app .router - .oneshot(admin_post("/admin/backfill", &app.admin_secret, &body)) + .oneshot(admin_post("/admin/backfill", &app.admin_token, &body)) .await .unwrap(); @@ -387,17 +451,18 @@ async fn backfill_create_job() { #[serial] async fn backfill_list_jobs() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; // Create a job first app.router .clone() - .oneshot(admin_post("/admin/backfill", &app.admin_secret, &json!({}))) + .oneshot(admin_post("/admin/backfill", &app.admin_token, &json!({}))) .await .unwrap(); let resp = app .router - .oneshot(admin_get("/admin/backfill/status", &app.admin_secret)) + .oneshot(admin_get("/admin/backfill/status", &app.admin_token)) .await .unwrap(); @@ -412,43 +477,45 @@ async fn backfill_list_jobs() { #[tokio::test] #[serial] -async fn admin_create_returns_api_key() { +async fn admin_create_returns_did() { let app = TestApp::new().await; - let body = json!({ "name": "test-admin" }); + app.mock_admin_userinfo().await; + let body = json!({ "did": "did:plc:newadmin" }); let resp = app .router - .oneshot(admin_post("/admin/admins", &app.admin_secret, &body)) + .oneshot(admin_post("/admin/admins", &app.admin_token, &body)) .await .unwrap(); assert_eq!(resp.status(), StatusCode::CREATED); let json = json_body(resp).await; - assert_eq!(json["name"], "test-admin"); - assert!(json.get("api_key").is_some()); + assert_eq!(json["did"], "did:plc:newadmin"); assert!(json.get("id").is_some()); } #[tokio::test] #[serial] -async fn admin_created_key_authenticates() { +async fn admin_created_did_authenticates() { let app = TestApp::new().await; - let body = json!({ "name": "new-admin" }); + app.mock_admin_userinfo().await; - // Create admin - let resp = app - .router + let new_did = "did:plc:newadmin2"; + let body = json!({ "did": new_did }); + + // Create admin via the existing admin + app.router .clone() - .oneshot(admin_post("/admin/admins", &app.admin_secret, &body)) + .oneshot(admin_post("/admin/admins", &app.admin_token, &body)) .await .unwrap(); - let json = json_body(resp).await; - let api_key = json["api_key"].as_str().unwrap(); - // Use the new key + // Now mock AIP returning the new DID for a different token + common::auth::mock_aip_userinfo(&app.mock_server, new_did).await; + let resp = app .router - .oneshot(admin_get("/admin/lexicons", api_key)) + .oneshot(admin_get("/admin/lexicons", "new-admin-token")) .await .unwrap(); @@ -457,12 +524,13 @@ async fn admin_created_key_authenticates() { #[tokio::test] #[serial] -async fn admin_list_excludes_keys() { +async fn admin_list_returns_dids() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; let resp = app .router - .oneshot(admin_get("/admin/admins", &app.admin_secret)) + .oneshot(admin_get("/admin/admins", &app.admin_token)) .await .unwrap(); @@ -470,8 +538,8 @@ async fn admin_list_excludes_keys() { let json = json_body(resp).await; let admins = json.as_array().unwrap(); assert!(!admins.is_empty()); - // No admin should expose api_key or api_key_hash for admin in admins { + assert!(admin.get("did").is_some()); assert!(admin.get("api_key").is_none()); assert!(admin.get("api_key_hash").is_none()); } @@ -481,6 +549,7 @@ async fn admin_list_excludes_keys() { #[serial] async fn admin_delete_returns_204() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; // Create an admin to delete let resp = app @@ -488,8 +557,8 @@ async fn admin_delete_returns_204() { .clone() .oneshot(admin_post( "/admin/admins", - &app.admin_secret, - &json!({ "name": "disposable" }), + &app.admin_token, + &json!({ "did": "did:plc:disposable" }), )) .await .unwrap(); @@ -500,7 +569,7 @@ async fn admin_delete_returns_204() { .router .oneshot(admin_delete( &format!("/admin/admins/{id}"), - &app.admin_secret, + &app.admin_token, )) .await .unwrap(); @@ -512,12 +581,13 @@ async fn admin_delete_returns_204() { #[serial] async fn admin_delete_not_found() { let app = TestApp::new().await; + app.mock_admin_userinfo().await; let resp = app .router .oneshot(admin_delete( "/admin/admins/00000000-0000-0000-0000-000000000000", - &app.admin_secret, + &app.admin_token, )) .await .unwrap(); diff --git a/tests/e2e_xrpc.rs b/tests/e2e_xrpc.rs index 66f9df4..f98b8af 100644 --- a/tests/e2e_xrpc.rs +++ b/tests/e2e_xrpc.rs @@ -43,12 +43,14 @@ fn authed_get(uri: &str, token: &str) -> Request { /// Seed the game record lexicon and a query lexicon into the test app. async fn seed_lexicons(app: &TestApp) { + app.mock_admin_userinfo().await; + // Record lexicon app.router .clone() .oneshot(admin_post( "/admin/lexicons", - &app.admin_secret, + &app.admin_token, &json!({ "lexicon_json": fixtures::game_record_lexicon(), "backfill": false @@ -62,7 +64,7 @@ async fn seed_lexicons(app: &TestApp) { .clone() .oneshot(admin_post( "/admin/lexicons", - &app.admin_secret, + &app.admin_token, &json!({ "lexicon_json": fixtures::list_games_query_lexicon(), "target_collection": "games.gamesgamesgamesgames.game" @@ -76,7 +78,7 @@ async fn seed_lexicons(app: &TestApp) { .clone() .oneshot(admin_post( "/admin/lexicons", - &app.admin_secret, + &app.admin_token, &json!({ "lexicon_json": fixtures::create_game_procedure_lexicon(), "target_collection": "games.gamesgamesgamesgames.game"