Something went wrong. Try again.
A lexicon-driven AppView for ATProto.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335mod common;
use axum::body::Body;use axum::http::{Request, StatusCode};use http_body_util::BodyExt;use p256::elliptic_curve::sec1::ToSec1Point;use serde_json::{Value, json};use serial_test::serial;use tower::ServiceExt;
use common::app::TestApp;use common::fixtures;use common::plc;use common::tls;
async fn json_body(resp: axum::response::Response) -> Value { let body = resp.into_body().collect().await.unwrap().to_bytes(); serde_json::from_slice(&body).unwrap()}
fn admin_post( uri: &str, cookie: (axum::http::HeaderName, axum::http::HeaderValue), body: &Value,) -> Request<Body> { Request::builder() .method("POST") .uri(uri) .header(cookie.0, cookie.1) .header("content-type", "application/json") .body(Body::from(serde_json::to_vec(body).unwrap())) .unwrap()}
async fn seed_query_lexicon(app: &TestApp) { app.router .clone() .oneshot(admin_post( "/admin/lexicons", app.admin_cookie(), &json!({ "lexicon_json": fixtures::game_record_lexicon(), "backfill": false }), )) .await .unwrap();
app.router .clone() .oneshot(admin_post( "/admin/lexicons", app.admin_cookie(), &json!({ "lexicon_json": fixtures::list_games_query_lexicon(), "target_collection": "games.gamesgamesgamesgames.game" }), )) .await .unwrap();}
async fn seed_procedure_lexicon(app: &TestApp) { app.router .clone() .oneshot(admin_post( "/admin/lexicons", app.admin_cookie(), &json!({ "lexicon_json": fixtures::game_record_lexicon(), "backfill": false }), )) .await .unwrap();
app.router .clone() .oneshot(admin_post( "/admin/lexicons", app.admin_cookie(), &json!({ "lexicon_json": fixtures::create_game_procedure_lexicon(), "target_collection": "games.gamesgamesgamesgames.game" }), )) .await .unwrap();}
async fn seed_procedure_script(app: &TestApp, body: &str) { let resp = app .router .clone() .oneshot(admin_post( "/admin/scripts", app.admin_cookie(), &json!({ "id": "xrpc.procedure:games.gamesgamesgamesgames.createGame", "script_type": "lua", "body": body, "description": "test procedure" }), )) .await .unwrap();
assert!( resp.status().is_success(), "seed_procedure_script failed with status {}", resp.status(), );}
// ---------------------------------------------------------------------------// Setup status endpoint// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn setup_status_unconfigured() { common::require_db!(); let app = TestApp::new().await;
let resp = app .router .clone() .oneshot( app.authed_request() .uri("/api/setup/status") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::OK); let body = json_body(resp).await; assert_eq!(body["identity_configured"], false); assert!(body["identity_mode"].is_null());}
#[tokio::test]#[serial]async fn setup_status_after_did_web() { common::require_db!(); let mut app = TestApp::new().await; app.setup_did_web().await;
let resp = app .router .clone() .oneshot( app.authed_request() .uri("/api/setup/status") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::OK); let body = json_body(resp).await; assert_eq!(body["identity_configured"], true); assert_eq!(body["identity_mode"], "did_web");}
#[tokio::test]#[serial]async fn setup_status_after_not_exposed() { common::require_db!(); let mut app = TestApp::new().await; app.setup_not_exposed().await;
let resp = app .router .clone() .oneshot( app.authed_request() .uri("/api/setup/status") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::OK); let body = json_body(resp).await; assert_eq!(body["identity_mode"], "not_exposed");}
// ---------------------------------------------------------------------------// DID document generation// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn did_doc_returns_404_when_no_identity() { common::require_db!(); let app = TestApp::new().await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/.well-known/did.json") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);}
#[tokio::test]#[serial]async fn did_doc_empty_services() { common::require_db!(); let mut app = TestApp::new().await; let did = app.setup_did_web().await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/.well-known/did.json") .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::OK); let doc = json_body(resp).await; assert_eq!(doc["id"], did); assert!(!doc["verificationMethod"].as_array().unwrap().is_empty()); assert_eq!(doc["service"].as_array().unwrap().len(), 0);}
#[tokio::test]#[serial]async fn did_doc_with_entries() { common::require_db!(); let mut app = TestApp::new().await; let _did = app.setup_did_web().await;
let _id1 = app .create_service_entry("#chess", "ChessAppView", "all") .await; let _id2 = app .create_service_entry("#checkers", "CheckersAppView", "all") .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/.well-known/did.json") .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
let doc = json_body(resp).await; let services = doc["service"].as_array().unwrap(); assert_eq!(services.len(), 2); assert_eq!(services[0]["id"], "#chess"); assert_eq!(services[0]["type"], "ChessAppView"); assert_eq!(services[1]["id"], "#checkers");
happyview::service_entries::delete_entry(&app.state.db, app.state.db_backend, _id1) .await .unwrap();
let resp = app .router .clone() .oneshot( Request::builder() .uri("/.well-known/did.json") .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
let doc = json_body(resp).await; let services = doc["service"].as_array().unwrap(); assert_eq!(services.len(), 1); assert_eq!(services[0]["id"], "#checkers");}
// ---------------------------------------------------------------------------// Service auth — queries// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn service_auth_query_allowed() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_query_lexicon(&app).await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
let auth = app .service_auth_jwt(&plc_store, "did:plc:caller123", &did, "#chess") .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth) .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::OK);}
#[tokio::test]#[serial]async fn service_auth_query_denied() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_query_lexicon(&app).await;
app.create_service_entry("#chess", "ChessAppView", "specific") .await;
let auth = app .service_auth_jwt(&plc_store, "did:plc:caller456", &did, "#chess") .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth) .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); let body = json_body(resp).await; assert!(body["error"].as_str().unwrap().contains("not authorized"));}
#[tokio::test]#[serial]async fn service_auth_specific_xrpc_allowed() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_query_lexicon(&app).await;
let entry_id = app .create_service_entry("#chess", "ChessAppView", "specific") .await; app.add_entry_xrpcs(entry_id, &["games.gamesgamesgamesgames.listGames"]) .await;
let auth = app .service_auth_jwt(&plc_store, "did:plc:caller789", &did, "#chess") .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth) .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::OK);}
// ---------------------------------------------------------------------------// Service auth — procedures// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn service_auth_procedure_allowed() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_procedure_lexicon(&app).await; seed_procedure_script(&app, "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend").await;
let entry_id = app .create_service_entry("#chess", "ChessAppView", "specific") .await; app.add_entry_xrpcs(entry_id, &["games.gamesgamesgamesgames.createGame"]) .await;
let auth = app .service_auth_jwt(&plc_store, "did:plc:procallowed", &did, "#chess") .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("host", "127.0.0.1:0") .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::OK);}
#[tokio::test]#[serial]async fn service_auth_procedure_denied() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_procedure_lexicon(&app).await; seed_procedure_script(&app, "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend").await;
app.create_service_entry("#chess", "ChessAppView", "specific") .await;
let auth = app .service_auth_jwt(&plc_store, "did:plc:procdenied", &did, "#chess") .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("host", "127.0.0.1:0") .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); let body = json_body(resp).await; assert!(body["error"].as_str().unwrap().contains("not authorized"));}
#[tokio::test]#[serial]async fn token_scope_enforcement() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_procedure_lexicon(&app).await;
seed_procedure_script( &app, "function handle(input, params)\nlocal x = xrpc.query('games.birb.chess.getGame', {})\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend", ).await;
let entry_id = app .create_service_entry("#chess", "ChessAppView", "specific") .await; app.add_entry_xrpcs(entry_id, &["games.gamesgamesgamesgames.createGame"]) .await;
let auth = app .service_auth_jwt(&plc_store, "did:plc:scopecheck", &did, "#chess") .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("host", "127.0.0.1:0") .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); let body = json_body(resp).await; let msg = body["error"].as_str().unwrap(); assert!( msg.contains("games.birb.chess.getGame"), "error should list the missing scope XRPC" );}
// ---------------------------------------------------------------------------// Edge cases — identity modes, invalid JWTs, missing fragments// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn not_exposed_rejects_service_auth() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; app.setup_not_exposed().await;
seed_procedure_lexicon(&app).await; seed_procedure_script(&app, "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend").await;
let auth = app .raw_service_auth_jwt( &plc_store, "did:plc:notexposed", "did:plc:fake#chess", chrono::Utc::now().timestamp() as u64 + 60, ) .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::UNAUTHORIZED, "not_exposed should reject service auth" );}
#[tokio::test]#[serial]async fn wrong_aud_rejects_service_auth() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let _did = app.setup_did_web().await;
seed_procedure_lexicon(&app).await; seed_procedure_script(&app, "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend").await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
let auth = app .raw_service_auth_jwt( &plc_store, "did:plc:wrongaud", "did:web:wrong.example.com#chess", chrono::Utc::now().timestamp() as u64 + 60, ) .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::UNAUTHORIZED, "wrong aud should reject service auth" );}
#[tokio::test]#[serial]async fn expired_jwt_rejects_service_auth() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_procedure_lexicon(&app).await; seed_procedure_script(&app, "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend").await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
let auth = app .raw_service_auth_jwt( &plc_store, "did:plc:expired", &format!("{}#chess", did), 1000, ) .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::UNAUTHORIZED, "expired JWT should reject service auth" );}
#[tokio::test]#[serial]async fn nonexistent_fragment_denies_access() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_query_lexicon(&app).await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
let auth = app .service_auth_jwt(&plc_store, "did:plc:nofragment", &did, "#doesNotExist") .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth) .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); let body = json_body(resp).await; assert!(body["error"].as_str().unwrap().contains("not authorized"));}
#[tokio::test]#[serial]async fn did_plc_returns_404_for_did_json() { common::require_db!(); let mut app = TestApp::new().await; let _did = app.setup_did_plc().await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/.well-known/did.json") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);}
#[tokio::test]#[serial]async fn multiple_entries_matched_by_fragment() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_query_lexicon(&app).await;
app.create_service_entry("#chess", "ChessAppView", "all") .await; let checkers_id = app .create_service_entry("#checkers", "CheckersAppView", "specific") .await; app.add_entry_xrpcs(checkers_id, &["games.gamesgamesgamesgames.otherGame"]) .await;
let auth_chess = app .service_auth_jwt(&plc_store, "did:plc:multi1", &did, "#chess") .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth_chess) .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let auth_checkers = app .service_auth_jwt(&plc_store, "did:plc:multi2", &did, "#checkers") .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth_checkers) .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);}
#[tokio::test]#[serial]async fn scope_check_applies_with_access_mode_all() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_procedure_lexicon(&app).await; seed_procedure_script( &app, "function handle(input, params)\nlocal x = xrpc.query('games.birb.chess.getGame', {})\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend", ).await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
let auth = app .service_auth_jwt(&plc_store, "did:plc:scopeall", &did, "#chess") .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("host", "127.0.0.1:0") .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); let body = json_body(resp).await; let msg = body["error"].as_str().unwrap(); assert!( msg.contains("games.birb.chess.getGame"), "scope check should apply even with access_mode=all" );}
#[tokio::test]#[serial]async fn aud_missing_fragment_rejects() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_procedure_lexicon(&app).await; seed_procedure_script(&app, "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend").await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
// aud = instance DID with no fragment let auth = app .raw_service_auth_jwt( &plc_store, "did:plc:nofrag", &did, chrono::Utc::now().timestamp() as u64 + 60, ) .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::UNAUTHORIZED, "aud without fragment should reject" );}
// ---------------------------------------------------------------------------// Auth regression — existing auth paths still work// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn anonymous_access_still_works() { common::require_db!(); let mut app = TestApp::new().await; app.setup_did_web().await;
seed_query_lexicon(&app).await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::OK);}
// ---------------------------------------------------------------------------// Static analysis — outbound_xrpcs persistence// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn static_analysis_persistence() { common::require_db!(); let app = TestApp::new().await;
app.router .clone() .oneshot(admin_post( "/admin/lexicons", app.admin_cookie(), &json!({ "lexicon_json": fixtures::game_record_lexicon(), "backfill": false }), )) .await .unwrap();
app.router .clone() .oneshot(admin_post( "/admin/lexicons", app.admin_cookie(), &json!({ "lexicon_json": fixtures::create_game_procedure_lexicon(), "target_collection": "games.gamesgamesgamesgames.game" }), )) .await .unwrap();
let resp = app .router .clone() .oneshot(admin_post( "/admin/scripts", app.admin_cookie(), &json!({ "id": "xrpc.procedure:games.gamesgamesgamesgames.createGame", "script_type": "lua", "body": "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend", "description": "test procedure" }), )) .await .unwrap();
assert!( resp.status().is_success(), "POST /admin/scripts returned {}", resp.status() ); let body = json_body(resp).await; assert!( body["outbound_xrpcs"].is_null() || body["outbound_xrpcs"] .as_array() .is_some_and(|a| a.is_empty()), "expected null or empty outbound_xrpcs for script with no XRPC calls" );
let resp = app .router .clone() .oneshot( Request::builder() .method("PATCH") .uri("/admin/scripts/xrpc.procedure%3Agames.gamesgamesgamesgames.createGame") .header(app.admin_cookie().0, app.admin_cookie().1) .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({ "body": "function handle(input, params)\nlocal x = xrpc.query('games.birb.chess.getGame', {})\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend" })) .unwrap(), )) .unwrap(), ) .await .unwrap();
assert!( resp.status().is_success(), "PATCH script returned {}", resp.status() ); let body = json_body(resp).await; let xrpcs = body["outbound_xrpcs"] .as_array() .expect("expected outbound_xrpcs array"); assert_eq!(xrpcs.len(), 1); assert_eq!(xrpcs[0], "games.birb.chess.getGame");
let resp = app .router .clone() .oneshot( Request::builder() .method("PATCH") .uri("/admin/scripts/xrpc.procedure%3Agames.gamesgamesgamesgames.createGame") .header(app.admin_cookie().0, app.admin_cookie().1) .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({ "body": "function handle(input, params)\n-- local x = xrpc.query('games.birb.chess.getGame', {})\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend" })) .unwrap(), )) .unwrap(), ) .await .unwrap();
assert!( resp.status().is_success(), "second PATCH returned {}", resp.status() ); let body = json_body(resp).await; assert!( body["outbound_xrpcs"].is_null() || body["outbound_xrpcs"] .as_array() .is_some_and(|a| a.is_empty()), "expected null or empty outbound_xrpcs when only commented-out calls exist" );}
// ---------------------------------------------------------------------------// JWT edge cases — forbidden typ, unsupported DID, missing aud// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn forbidden_jwt_typ_rejected() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_procedure_lexicon(&app).await; seed_procedure_script(&app, "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend").await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
for forbidden_typ in ["at+jwt", "refresh+jwt", "dpop+jwt"] { let auth = app .custom_service_auth_jwt( &plc_store, &format!("did:plc:typ{}", forbidden_typ.replace('+', "")), json!({"alg": "ES256", "typ": forbidden_typ}), json!({ "iss": format!("did:plc:typ{}", forbidden_typ.replace('+', "")), "aud": format!("{}#chess", did), "exp": chrono::Utc::now().timestamp() as u64 + 60, }), ) .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::UNAUTHORIZED, "JWT with typ={} should be rejected", forbidden_typ ); }}
#[tokio::test]#[serial]async fn unsupported_did_method_rejected() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_procedure_lexicon(&app).await; seed_procedure_script(&app, "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend").await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
// Use did:key: which is not supported by resolve_signing_key let auth = app .custom_service_auth_jwt( &plc_store, "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK", json!({"alg": "ES256"}), json!({ "iss": "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK", "aud": format!("{}#chess", did), "exp": chrono::Utc::now().timestamp() as u64 + 60, }), ) .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::UNAUTHORIZED, "unsupported DID method should be rejected" );}
#[tokio::test]#[serial]async fn jwt_without_aud_field_rejected() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let _did = app.setup_did_web().await;
seed_procedure_lexicon(&app).await; seed_procedure_script(&app, "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend").await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
// JWT payload with no aud field — JwtPayload deserialization fails let auth = app .custom_service_auth_jwt( &plc_store, "did:plc:noaud", json!({"alg": "ES256"}), json!({ "iss": "did:plc:noaud", "exp": chrono::Utc::now().timestamp() as u64 + 60, }), ) .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::UNAUTHORIZED, "JWT without aud should be rejected" );}
// ---------------------------------------------------------------------------// Setup identity — AttachAccount mode stores attached DID// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn set_identity_attach_account_mode() { common::require_db!(); let app = TestApp::new().await;
let resp = app .router .clone() .oneshot( app.authed_request() .method("POST") .uri("/api/setup/identity") .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({ "mode": "attach_account", "attached_account_did": "did:plc:testaccount" })) .unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
// Verify status reflects the mode let resp = app .router .clone() .oneshot( app.authed_request() .uri("/api/setup/status") .body(Body::empty()) .unwrap(), ) .await .unwrap();
let body = json_body(resp).await; assert_eq!(body["identity_mode"], "attach_account");}
// ---------------------------------------------------------------------------// Setup HTTP flow — full endpoint-driven setup produces working identity// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn setup_http_flow_did_web_produces_valid_did_doc() { common::require_db!(); let mut app = TestApp::new().await; app.state.config.token_encryption_key = Some([0x42u8; 32]); app.rebuild_router();
// Step 1: POST /api/setup/identity with mode=did_web let resp = app .router .clone() .oneshot( app.authed_request() .method("POST") .uri("/api/setup/identity") .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"mode": "did_web"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
// Step 2: POST /api/setup/complete let resp = app .router .clone() .oneshot( app.authed_request() .method("POST") .uri("/api/setup/complete") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
// Step 3: Rebuild router to pick up identity changes, then verify DID doc app.rebuild_router();
let resp = app .router .clone() .oneshot( Request::builder() .uri("/.well-known/did.json") .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::OK); let doc = json_body(resp).await; assert_eq!(doc["id"], "did:web:127.0.0.1%3A0"); assert!(!doc["verificationMethod"].as_array().unwrap().is_empty());
// Step 4: Verify status shows complete let resp = app .router .clone() .oneshot( app.authed_request() .uri("/api/setup/status") .body(Body::empty()) .unwrap(), ) .await .unwrap();
let status = json_body(resp).await; assert_eq!(status["identity_mode"], "did_web"); assert_eq!(status["identity_configured"], true); assert_eq!(status["setup_complete"], true);}
// ---------------------------------------------------------------------------// setup_complete reset — mode change resets setup_complete flag// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn mode_change_resets_setup_complete() { common::require_db!(); let mut app = TestApp::new().await; let _did = app.setup_did_web().await; let cookie = app.admin_cookie();
// Verify setup_complete is true after setup_did_web let resp = app .router .clone() .oneshot( Request::builder() .uri("/admin/service-identity") .header(cookie.0.clone(), cookie.1.clone()) .body(Body::empty()) .unwrap(), ) .await .unwrap();
let body = json_body(resp).await; assert_eq!(body["setup_complete"], true);
// Change mode via PUT — this should reset setup_complete let resp = app .router .clone() .oneshot( Request::builder() .method("PUT") .uri("/admin/service-identity") .header(cookie.0.clone(), cookie.1.clone()) .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"mode": "not_exposed"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
// Verify setup_complete was reset to false let resp = app .router .clone() .oneshot( Request::builder() .uri("/admin/service-identity") .header(cookie.0.clone(), cookie.1.clone()) .body(Body::empty()) .unwrap(), ) .await .unwrap();
let body = json_body(resp).await; assert_eq!(body["mode"], "not_exposed"); assert_eq!( body["setup_complete"], false, "mode change should reset setup_complete" );}
// ---------------------------------------------------------------------------// did:web issuer resolution via TLS// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn did_web_issuer_resolved_via_https() { common::require_db!(); let mut app = TestApp::new().await; let instance_did = app.setup_did_web().await;
seed_query_lexicon(&app).await;
app.create_service_entry("#appview", "TestAppView", "all") .await;
let mut key_bytes = [0u8; 32]; rand::Rng::fill_bytes(&mut rand::rng(), &mut key_bytes); let issuer_key = p256::ecdsa::SigningKey::from_slice(&key_bytes[..]).unwrap(); let public_key = p256::PublicKey::from(issuer_key.verifying_key()); let compressed = public_key.to_sec1_point(true); let pub_bytes = compressed.as_bytes().to_vec();
let server = tls::start_did_web_server(move |did| plc::test_did_document(did, &pub_bytes)).await; let issuer_did = server.issuer_did().to_string();
app.use_permissive_http_client();
let auth = app.did_web_service_auth_jwt(&issuer_key, &issuer_did, &instance_did, "#appview");
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth) .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::OK, "did:web issuer should resolve via HTTPS and be allowed with access_mode=all" );}
// ---------------------------------------------------------------------------// Service auth with no service entries at all// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn service_auth_rejected_when_no_entries_exist() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_query_lexicon(&app).await;
let auth = app .service_auth_jwt(&plc_store, "did:plc:noentries", &did, "#chess") .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth) .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED); let body = json_body(resp).await; assert!(body["error"].as_str().unwrap().contains("not authorized"));}
// ---------------------------------------------------------------------------// Service auth with did:plc identity mode// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn service_auth_works_with_did_plc_identity() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_plc().await;
seed_query_lexicon(&app).await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
let auth = app .service_auth_jwt(&plc_store, "did:plc:plccaller", &did, "#chess") .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth) .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::OK, "service auth should work when instance uses did:plc identity" );}
// ---------------------------------------------------------------------------// Service auth — ES256K (secp256k1)// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn service_auth_es256k_query_allowed() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_query_lexicon(&app).await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
// Generate a secp256k1 key pair use k256::ecdsa::{SigningKey as K256SigningKey, signature::Signer as K256Signer}; use rand::Rng;
let mut key_bytes = [0u8; 32]; rand::rng().fill_bytes(&mut key_bytes); let k256_signing_key = K256SigningKey::from_slice(&key_bytes[..]).unwrap(); let k256_verifying_key = k256_signing_key.verifying_key(); let compressed = k256_verifying_key.to_sec1_point(true); let pub_bytes = compressed.as_bytes();
// Build a DID document with secp256k1 key using EcdsaSecp256k1VerificationKey2019 // This type uses raw SEC1 key bytes (no multicodec prefix) let multibase_key = multibase::encode(multibase::Base::Base58Btc, pub_bytes);
let issuer_did = "did:plc:es256kcaller"; let did_doc = json!({ "@context": ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/multikey/v1"], "id": issuer_did, "verificationMethod": [{ "id": format!("{issuer_did}#atproto"), "type": "EcdsaSecp256k1VerificationKey2019", "controller": issuer_did, "publicKeyMultibase": multibase_key }], "service": [] });
plc_store .write() .await .insert(issuer_did.to_string(), did_doc);
// Sign a JWT with ES256K use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD;
let header = json!({"alg": "ES256K"}); let payload = json!({ "iss": issuer_did, "aud": format!("{did}#chess"), "exp": chrono::Utc::now().timestamp() as u64 + 60, });
let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap()); let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap()); let message = format!("{}.{}", header_b64, payload_b64);
let signature: k256::ecdsa::Signature = k256_signing_key.sign(message.as_bytes()); let sig_b64 = URL_SAFE_NO_PAD.encode(signature.to_bytes());
let auth = format!("Bearer {}.{}.{}", header_b64, payload_b64, sig_b64);
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth) .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::OK, "ES256K service auth should be accepted" );}
// ---------------------------------------------------------------------------// Anonymous POST to procedure is rejected// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn anonymous_procedure_rejected() { common::require_db!(); let mut app = TestApp::new().await; app.setup_did_web().await;
seed_procedure_lexicon(&app).await; seed_procedure_script(&app, "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend").await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&serde_json::json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::UNAUTHORIZED, "anonymous POST to procedure should be rejected" );}
// ---------------------------------------------------------------------------// Proxy config blocking — XRPC method blocked by proxy policy// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn proxy_config_disabled_rejects_unknown_method() { common::require_db!(); let mut app = TestApp::new().await; app.setup_did_web().await;
// Set proxy config to disabled app.state .proxy_config .store(std::sync::Arc::new(happyview::proxy_config::ProxyConfig { mode: happyview::proxy_config::ProxyMode::Disabled, nsids: vec![], }));
app.rebuild_router();
// Query an unknown method (not in lexicon registry) — should be blocked let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/com.unknown.method") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::FORBIDDEN, "disabled proxy config should reject unknown methods" );}
#[tokio::test]#[serial]async fn proxy_config_allowlist_rejects_unlisted_method() { common::require_db!(); let mut app = TestApp::new().await; app.setup_did_web().await;
// Set proxy config to allowlist with a specific pattern app.state .proxy_config .store(std::sync::Arc::new(happyview::proxy_config::ProxyConfig { mode: happyview::proxy_config::ProxyMode::Allowlist, nsids: vec!["com.allowed.*".to_string()], }));
app.rebuild_router();
// Query an unlisted method — should be blocked let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/com.blocked.method") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::FORBIDDEN, "allowlist proxy config should reject unlisted methods" );}
// ---------------------------------------------------------------------------// Non-scripted procedure via service auth — falls through to OAuth path// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn service_auth_non_scripted_procedure_fails_gracefully() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
// Seed a procedure lexicon but do NOT seed a script for it seed_procedure_lexicon(&app).await;
let entry_id = app .create_service_entry("#chess", "ChessAppView", "specific") .await; app.add_entry_xrpcs(entry_id, &["games.gamesgamesgamesgames.createGame"]) .await;
let auth = app .service_auth_jwt(&plc_store, "did:plc:noscript", &did, "#chess") .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
// Without a script, service auth goes to the OAuth session path which will fail // because there's no stored session for the service auth caller. This should // return a server error, not panic. assert!( resp.status().is_client_error() || resp.status().is_server_error(), "non-scripted procedure via service auth should fail gracefully, got {}", resp.status() );}
// ---------------------------------------------------------------------------// JWT unsupported algorithm rejected// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn unsupported_jwt_algorithm_rejected() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_procedure_lexicon(&app).await; seed_procedure_script(&app, "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend").await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
// JWT with RS256 algorithm (unsupported) let auth = app .custom_service_auth_jwt( &plc_store, "did:plc:rs256test", json!({"alg": "RS256"}), json!({ "iss": "did:plc:rs256test", "aud": format!("{}#chess", did), "exp": chrono::Utc::now().timestamp() as u64 + 60, }), ) .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.createGame") .header("authorization", &auth) .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"title": "test"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::UNAUTHORIZED, "unsupported JWT algorithm should be rejected" );}
// ---------------------------------------------------------------------------// Unauthenticated access to admin service identity endpoints// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn unauthenticated_get_service_identity_rejected() { common::require_db!(); let app = TestApp::new().await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/admin/service-identity") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert!( resp.status().is_client_error(), "unauthenticated GET /admin/service-identity should be rejected, got {}", resp.status() );}
#[tokio::test]#[serial]async fn unauthenticated_put_service_identity_rejected() { common::require_db!(); let app = TestApp::new().await;
let resp = app .router .clone() .oneshot( Request::builder() .method("PUT") .uri("/admin/service-identity") .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"mode": "not_exposed"})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert!( resp.status().is_client_error(), "unauthenticated PUT /admin/service-identity should be rejected, got {}", resp.status() );}
// ---------------------------------------------------------------------------// Lexicon type mismatch — GET to procedure, POST to query// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn get_to_procedure_endpoint_rejected() { common::require_db!(); let mut app = TestApp::new().await; app.setup_did_web().await;
seed_procedure_lexicon(&app).await; seed_procedure_script(&app, "function handle(input, params)\nreturn { uri = 'at://test/games.gamesgamesgamesgames.game/1' }\nend").await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.createGame") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::BAD_REQUEST, "GET to a procedure endpoint should return 400" );}
#[tokio::test]#[serial]async fn post_to_query_endpoint_rejected() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_query_lexicon(&app).await; app.create_service_entry("#chess", "ChessAppView", "all") .await;
let auth = app .service_auth_jwt(&plc_store, "did:plc:postquery", &did, "#chess") .await;
let resp = app .router .clone() .oneshot( Request::builder() .method("POST") .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth) .header("host", "127.0.0.1:0") .header("content-type", "application/json") .body(Body::from( serde_json::to_vec(&json!({"test": true})).unwrap(), )) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::BAD_REQUEST, "POST to a query endpoint should return 400" );}
// ---------------------------------------------------------------------------// DID doc missing #atproto verification method// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn did_doc_missing_atproto_vm_rejected() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_query_lexicon(&app).await; app.create_service_entry("#chess", "ChessAppView", "all") .await;
use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use p256::ecdsa::{SigningKey, signature::Signer}; use rand::Rng;
let mut key_bytes = [0u8; 32]; rand::rng().fill_bytes(&mut key_bytes); let signing_key = SigningKey::from_slice(&key_bytes[..]).unwrap();
let issuer_did = "did:plc:noatprotovm"; let did_doc = json!({ "@context": ["https://www.w3.org/ns/did/v1"], "id": issuer_did, "verificationMethod": [{ "id": format!("{issuer_did}#wrongId"), "type": "Multikey", "controller": issuer_did, "publicKeyMultibase": "zNotARealKey" }], "service": [] }); plc_store .write() .await .insert(issuer_did.to_string(), did_doc);
let header = json!({"alg": "ES256"}); let payload = json!({ "iss": issuer_did, "aud": format!("{}#chess", did), "exp": chrono::Utc::now().timestamp() as u64 + 60, }); let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap()); let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap()); let message = format!("{}.{}", header_b64, payload_b64); let signature: p256::ecdsa::Signature = signing_key.sign(message.as_bytes()); let sig_b64 = URL_SAFE_NO_PAD.encode(signature.to_bytes()); let auth = format!("Bearer {}.{}.{}", header_b64, payload_b64, sig_b64);
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth) .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::UNAUTHORIZED, "DID doc without #atproto VM should reject service auth" );}
#[tokio::test]#[serial]async fn did_doc_missing_public_key_multibase_rejected() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_query_lexicon(&app).await; app.create_service_entry("#chess", "ChessAppView", "all") .await;
use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use p256::ecdsa::{SigningKey, signature::Signer}; use rand::Rng;
let mut key_bytes = [0u8; 32]; rand::rng().fill_bytes(&mut key_bytes); let signing_key = SigningKey::from_slice(&key_bytes[..]).unwrap();
let issuer_did = "did:plc:nokeymultibase"; let did_doc = json!({ "@context": ["https://www.w3.org/ns/did/v1"], "id": issuer_did, "verificationMethod": [{ "id": format!("{issuer_did}#atproto"), "type": "Multikey", "controller": issuer_did }], "service": [] }); plc_store .write() .await .insert(issuer_did.to_string(), did_doc);
let header = json!({"alg": "ES256"}); let payload = json!({ "iss": issuer_did, "aud": format!("{}#chess", did), "exp": chrono::Utc::now().timestamp() as u64 + 60, }); let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap()); let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap()); let message = format!("{}.{}", header_b64, payload_b64); let signature: p256::ecdsa::Signature = signing_key.sign(message.as_bytes()); let sig_b64 = URL_SAFE_NO_PAD.encode(signature.to_bytes()); let auth = format!("Bearer {}.{}.{}", header_b64, payload_b64, sig_b64);
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth) .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::UNAUTHORIZED, "DID doc without publicKeyMultibase should reject service auth" );}
// ---------------------------------------------------------------------------// JWT allowed typ (e.g., "JWT") is accepted// ---------------------------------------------------------------------------
#[tokio::test]#[serial]async fn jwt_with_allowed_typ_accepted() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let did = app.setup_did_web().await;
seed_query_lexicon(&app).await;
app.create_service_entry("#chess", "ChessAppView", "all") .await;
let auth = app .custom_service_auth_jwt( &plc_store, "did:plc:goodtyp", json!({"alg": "ES256", "typ": "JWT"}), json!({ "iss": "did:plc:goodtyp", "aud": format!("{}#chess", did), "exp": chrono::Utc::now().timestamp() as u64 + 60, }), ) .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/xrpc/games.gamesgamesgamesgames.listGames") .header("authorization", &auth) .header("host", "127.0.0.1:0") .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::OK, "JWT with typ=JWT should be accepted" );}
// ---------------------------------------------------------------------------// Service auth — audience validation on the admin/UserAuth path (H6)// ---------------------------------------------------------------------------
/// Seed a super user directly, so an authenticated request reaches a 200 rather/// than a permission error.async fn seed_super_user(app: &TestApp, did: &str) { let sql = happyview::db::adapt_sql( "INSERT INTO happyview_users (id, did, is_super, created_at) VALUES (?, ?, ?, ?)", app.state.db_backend, ); happyview::db::query(&sql) .bind(uuid::Uuid::new_v4().to_string()) .bind(did) .bind(1_i32) .bind(happyview::db::now_rfc3339()) .execute(&app.state.db) .await .expect("seed super user");}
/// A service-auth JWT addressed to THIS instance authenticates on an admin route.#[tokio::test]#[serial]async fn service_auth_correct_aud_accepted_on_admin_route() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let instance_did = app.setup_did_plc().await;
let issuer = "did:plc:h6-good-issuer"; seed_super_user(&app, issuer).await;
let exp = chrono::Utc::now().timestamp() as u64 + 60; let auth = app .raw_service_auth_jwt(&plc_store, issuer, &format!("{instance_did}#appview"), exp) .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/admin/stats") .header("authorization", &auth) .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::OK);}
/// A service-auth JWT the user minted for a DIFFERENT audience must NOT/// authenticate on the admin path — otherwise it impersonates the issuer.#[tokio::test]#[serial]async fn service_auth_wrong_aud_rejected_on_admin_route() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let _instance_did = app.setup_did_plc().await;
// The issuer is even a super user — so if the token authenticated, it would // return 200. The point is that the wrong audience blocks it entirely. let issuer = "did:plc:h6-bad-issuer"; seed_super_user(&app, issuer).await;
let exp = chrono::Utc::now().timestamp() as u64 + 60; let auth = app .raw_service_auth_jwt(&plc_store, issuer, "did:web:evil.example#appview", exp) .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/admin/stats") .header("authorization", &auth) .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!( resp.status(), StatusCode::UNAUTHORIZED, "a service-auth JWT for a different audience must not authenticate here" );}
/// A service-auth JWT valid absurdly far into the future is rejected even when/// correctly addressed to this instance (bounds the replay window).#[tokio::test]#[serial]async fn service_auth_excessive_lifetime_rejected() { common::require_db!(); let mut app = TestApp::new().await; let plc_store = plc::setup_mock_plc(&app.mock_server).await; let instance_did = app.setup_did_plc().await;
let issuer = "did:plc:h6-longlived"; seed_super_user(&app, issuer).await;
// exp two hours out — well beyond the accepted max. let exp = chrono::Utc::now().timestamp() as u64 + 7200; let auth = app .raw_service_auth_jwt(&plc_store, issuer, &format!("{instance_did}#appview"), exp) .await;
let resp = app .router .clone() .oneshot( Request::builder() .uri("/admin/stats") .header("authorization", &auth) .body(Body::empty()) .unwrap(), ) .await .unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);}