feat(appview): Bearer-Auth für Timeline und Notifications

Die AppView hatte keinerlei Authentifizierung: jeder konnte
/api/notifications?did=<beliebig> lesen und per /seen als gelesen
markieren. Mit Phase 8 sind das die ersten privaten Daten im System.

Das Access-JWT der PDS trug von Anfang an sub, scope
"com.atproto.access" und aud "did:web:appview…" — es war für die
AppView ausgestellt, nur hat sie es nie geprüft. Neu ist deshalb vor
allem die Schlüsselbeschaffung: auth.rs holt das DID-Dokument der PDS
(PDS_INTERNAL_URL, sonst PDS_PUBLIC_URL), cached den Schlüssel und lädt
ihn bei einem Verifikationsfehler nach — höchstens einmal pro Minute,
damit Müll-Tokens kein Werkzeug werden, die PDS zu fluten. Ein
Schlüsselwechsel braucht damit keinen Neustart.

Ist die PDS beim Start weg, warnt die AppView nur und startet trotzdem
(sie indiziert den Firehose, der von der lokalen PDS unabhängig ist).
Ist der Schlüssel beim Prüfen eines Tokens nicht zu beschaffen, gibt es
503 — fail closed.

Geschützt: /api/timeline/home und die drei Notification-Endpoints, jeweils
mit sub == did. Öffentlich bleiben Profile, Suche, Posts, Threads und die
Follower-Listen; das sind in AT Proto öffentliche Records.

401 AuthMissing / 401 TokenInvalid / 403 Forbidden / 503 AuthUnavailable.
TokenInvalid ist ein Vertrag mit dem Client: daran erkennt er, dass er
sein Token erneuern und einmal wiederholen muss.

Dazu CORS: statt Any für alles jetzt eine Allowlist über
APPVIEW_CORS_ORIGINS (unset = altes Verhalten plus Warnung), und
/internal/ingest-commit liegt außerhalb der CORS-Schicht — die Route
wird server-zu-server aufgerufen, ein Allow-Origin darauf würde nur
einer Webseite helfen, in den Index zu schreiben.

APPVIEW_AUTH_REQUIRED=false stellt das alte Verhalten her (VPN-Instanz,
fail-open-Tests) und warnt beim Start in Großbuchstaben.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013HC9HLrUU1LNwkzp8nkDLX
This commit is contained in:
tomdebone
2026-09-09 23:02:27 +02:00
co-authored by Claude Opus 5
parent 786a892658
commit a2a371b7d9
14 changed files with 1520 additions and 147 deletions
+45 -50
View File
@@ -7,6 +7,9 @@
//! rather than panicking — so `cargo test --workspace` stays green in
//! environments where the appview hasn't been started.
mod common;
use common::TestAuth;
use serde_json::{json, Value};
use std::time::Duration;
@@ -46,6 +49,36 @@ async fn db_reachable() -> bool {
)
}
/// How this suite authenticates against `/api/timeline/home`, which is
/// no longer public. `None` means the AppView enforces auth but the
/// test process cannot mint a token (no `PDS_JWT_SECRET`), in which
/// case the test skips like it does for a missing service.
async fn auth_or_skip() -> Option<TestAuth> {
TestAuth::probe(&client().await, APPVIEW_URL).await
}
/// `GET /api/timeline/home` as `did`, with the bearer token attached
/// when the instance requires one. The seeded DIDs are synthetic, so
/// the token is minted from the PDS's own signing secret — see
/// `tests/common/mod.rs`.
async fn get_timeline(
c: &reqwest::Client,
auth: &TestAuth,
did: &str,
extra: &[(&str, &str)],
) -> reqwest::Response {
let mut params: Vec<(&str, &str)> = vec![("did", did)];
params.extend_from_slice(extra);
auth.apply(
c.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&params),
did,
)
.send()
.await
.unwrap()
}
async fn post_ingest(c: &reqwest::Client, body: Value) -> reqwest::Response {
c.post(format!("{APPVIEW_URL}/internal/ingest-commit"))
.json(&body)
@@ -120,6 +153,7 @@ async fn timeline_returns_seeded_posts() {
return;
}
let c = client().await;
let Some(auth) = auth_or_skip().await else { return };
let did = did_for_test("tl");
// Seed 3 posts with distinct rkeys.
@@ -157,12 +191,7 @@ async fn timeline_returns_seeded_posts() {
// machine that has run this suite twice) the three rows we just
// seeded fall outside a 10-row window and the assertions below
// fail for reasons that have nothing to do with the timeline.
let resp = c
.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&[("did", did.as_str()), ("limit", "100")])
.send()
.await
.unwrap();
let resp = get_timeline(&c, &auth, &did, &[("limit", "100")]).await;
assert_eq!(resp.status().as_u16(), 200);
let body: Value = resp.json().await.unwrap();
let posts = body["posts"].as_array().expect("posts is array");
@@ -222,6 +251,7 @@ async fn timeline_paginates_with_cursor() {
return;
}
let c = client().await;
let Some(auth) = auth_or_skip().await else { return };
let did = did_for_test("pg");
// Seed 50 posts.
@@ -246,28 +276,14 @@ async fn timeline_paginates_with_cursor() {
tokio::time::sleep(Duration::from_millis(100)).await;
// Page 1: limit=20.
let resp = c
.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&[("did", did.as_str()), ("limit", "20")])
.send()
.await
.unwrap();
let resp = get_timeline(&c, &auth, &did, &[("limit", "20")]).await;
let body: Value = resp.json().await.unwrap();
let page1 = body["posts"].as_array().unwrap().clone();
let cursor1 = body["cursor"].as_str().expect("page1 cursor");
assert_eq!(page1.len(), 20, "page1 should be exactly 20");
// Page 2: with cursor.
let resp = c
.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&[
("did", did.as_str()),
("limit", "20"),
("cursor", cursor1),
])
.send()
.await
.unwrap();
let resp = get_timeline(&c, &auth, &did, &[("limit", "20"), ("cursor", cursor1)]).await;
let body: Value = resp.json().await.unwrap();
let page2 = body["posts"].as_array().unwrap().clone();
assert_eq!(page2.len(), 20, "page2 should be exactly 20");
@@ -285,16 +301,7 @@ async fn timeline_paginates_with_cursor() {
// Page 3: tail — fewer than 20 expected, cursor=null.
let cursor2 = body["cursor"].as_str().expect("page2 cursor");
let resp = c
.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&[
("did", did.as_str()),
("limit", "20"),
("cursor", cursor2),
])
.send()
.await
.unwrap();
let resp = get_timeline(&c, &auth, &did, &[("limit", "20"), ("cursor", cursor2)]).await;
let body: Value = resp.json().await.unwrap();
let page3 = body["posts"].as_array().unwrap().clone();
assert!(page3.len() <= 20, "page3 should be <= 20");
@@ -484,6 +491,7 @@ async fn timeline_filters_to_followees() {
return;
}
let c = client().await;
let Some(auth) = auth_or_skip().await else { return };
let url = std::env::var("DATABASE_URL_APPVIEW").unwrap();
let pool = sqlx::PgPool::connect(&url).await.unwrap();
@@ -503,12 +511,7 @@ async fn timeline_filters_to_followees() {
tokio::time::sleep(Duration::from_millis(100)).await;
let resp = c
.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&[("did", alice.as_str()), ("limit", "100")])
.send()
.await
.unwrap();
let resp = get_timeline(&c, &auth, &alice, &[("limit", "100")]).await;
assert_eq!(resp.status().as_u16(), 200);
let body: Value = resp.json().await.unwrap();
let posts = body["posts"].as_array().expect("posts is array");
@@ -555,18 +558,14 @@ async fn timeline_includes_own_posts() {
return;
}
let c = client().await;
let Some(auth) = auth_or_skip().await else { return };
let alice = did_for_test("alone");
// Alice posts without seeding any follows.
seed_posts(&c, &alice, &["alice's first post", "alice's second post"]).await;
tokio::time::sleep(Duration::from_millis(100)).await;
let resp = c
.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&[("did", alice.as_str()), ("limit", "100")])
.send()
.await
.unwrap();
let resp = get_timeline(&c, &auth, &alice, &[("limit", "100")]).await;
assert_eq!(resp.status().as_u16(), 200);
let body: Value = resp.json().await.unwrap();
let posts = body["posts"].as_array().expect("posts is array");
@@ -605,6 +604,7 @@ async fn timeline_caps_followee_list() {
return;
}
let c = client().await;
let Some(auth) = auth_or_skip().await else { return };
let url = std::env::var("DATABASE_URL_APPVIEW").unwrap();
let pool = sqlx::PgPool::connect(&url).await.unwrap();
@@ -624,12 +624,7 @@ async fn timeline_caps_followee_list() {
seed_posts(&c, &alice, &["poweruser post"]).await;
tokio::time::sleep(Duration::from_millis(100)).await;
let resp = c
.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&[("did", alice.as_str()), ("limit", "50")])
.send()
.await
.unwrap();
let resp = get_timeline(&c, &auth, &alice, &[("limit", "50")]).await;
assert_eq!(resp.status().as_u16(), 200);
let body: Value = resp.json().await.unwrap();
let posts = body["posts"].as_array().expect("posts is array");
+311
View File
@@ -0,0 +1,311 @@
//! End-to-end tests for AppView authentication.
//!
//! Unlike the other suites in this directory these use a **real**
//! token: the test creates an account on the running PDS
//! (`com.atproto.server.createAccount`, the same call the desktop
//! client makes at signup) and presents the access JWT it gets back to
//! the AppView. That is the whole point — it exercises the actual key
//! distribution path (PDS signs → publishes its public key at
//! `/.well-known/did.json` → AppView fetches and verifies), which a
//! self-minted token would bypass.
//!
//! Fail-open like the rest of the suites: if the PDS or the AppView
//! isn't running, or the AppView runs with `APPVIEW_AUTH_REQUIRED=false`,
//! the test prints a notice and returns successfully.
use serde_json::{json, Value};
use std::time::Duration;
const PDS_URL: &str = "http://127.0.0.1:2583";
fn appview_url() -> String {
std::env::var("APPVIEW_TEST_URL").unwrap_or_else(|_| "http://127.0.0.1:2584".to_string())
}
/// 30 s, not the 5 s the sibling suites use.
///
/// The authenticated happy path for `/api/timeline/home` runs the
/// cold-start query (a brand-new account follows nobody, so the handler
/// falls back to the global recent feed). On a developer machine whose
/// AppView has been indexing the public firehose for a while that scan
/// takes seconds — a timeout there would look like an auth failure and
/// is nothing of the sort.
fn client() -> reqwest::Client {
reqwest::Client::builder()
.timeout(Duration::from_secs(30))
.build()
.unwrap()
}
async fn up(c: &reqwest::Client, base: &str) -> bool {
for _ in 0..20 {
if let Ok(r) = c.get(format!("{base}/healthz")).send().await {
if r.status().is_success() {
return true;
}
}
tokio::time::sleep(Duration::from_millis(250)).await;
}
false
}
/// A freshly created PDS account.
struct Account {
did: String,
access_jwt: String,
refresh_jwt: String,
}
/// Guard for every test here: both services up **and** the AppView
/// actually enforcing auth. Returns the client plus a new account.
async fn ready() -> Option<(reqwest::Client, Account)> {
let c = client();
if !up(&c, &appview_url()).await {
eprintln!("appview not running, skipping");
return None;
}
if !up(&c, PDS_URL).await {
eprintln!("pds not running, skipping");
return None;
}
// Probe: does this instance enforce auth? An operator running with
// `APPVIEW_AUTH_REQUIRED=false` (the mode the other suites use)
// would otherwise see every assertion here fail for the one reason
// that isn't a bug.
let probe = c
.get(format!("{}/api/notifications/count", appview_url()))
.query(&[("did", "did:plc:auth_probe")])
.send()
.await
.ok()?;
if probe.status().as_u16() != 401 {
eprintln!(
"appview does not enforce auth (probe returned {}), skipping",
probe.status()
);
return None;
}
let acc = create_account(&c).await?;
Some((c, acc))
}
async fn create_account(c: &reqwest::Client) -> Option<Account> {
let handle = format!("auth_{}.maarcadetweet.local", uuid::Uuid::new_v4().simple());
let r: Value = c
.post(format!("{PDS_URL}/xrpc/com.atproto.server.createAccount"))
.json(&json!({ "handle": handle, "password": "hunter2hunter2" }))
.send()
.await
.ok()?
.json()
.await
.ok()?;
Some(Account {
did: r["did"].as_str()?.to_string(),
access_jwt: r["access_jwt"].as_str()?.to_string(),
refresh_jwt: r["refresh_jwt"].as_str()?.to_string(),
})
}
/// `GET /api/notifications?did=…` with an optional bearer token.
async fn get_notifications(
c: &reqwest::Client,
did: &str,
token: Option<&str>,
) -> reqwest::Response {
let mut rb = c
.get(format!("{}/api/notifications", appview_url()))
.query(&[("did", did)]);
if let Some(t) = token {
rb = rb.bearer_auth(t);
}
rb.send().await.unwrap()
}
/// Assert the AppView's standard error envelope: the status, and the
/// `error` code the desktop client branches on.
async fn assert_error(r: reqwest::Response, status: u16, code: &str) {
let got = r.status().as_u16();
let body: Value = r.json().await.unwrap();
assert_eq!(got, status, "unexpected status; body = {body}");
assert_eq!(body["error"], json!(code), "unexpected error code: {body}");
assert!(
body["message"].is_string(),
"error body must carry a message: {body}"
);
}
#[tokio::test]
async fn own_token_reads_own_notifications() {
let Some((c, acc)) = ready().await else { return };
let r = get_notifications(&c, &acc.did, Some(&acc.access_jwt)).await;
assert_eq!(r.status().as_u16(), 200);
let body: Value = r.json().await.unwrap();
// A brand-new account has no notifications, but the shape must be
// the normal list response, not an error.
assert!(body["notifications"].is_array(), "body = {body}");
}
#[tokio::test]
async fn no_token_is_401_auth_missing() {
let Some((c, acc)) = ready().await else { return };
let r = get_notifications(&c, &acc.did, None).await;
assert_error(r, 401, "AuthMissing").await;
}
#[tokio::test]
async fn foreign_did_is_403() {
let Some((c, acc)) = ready().await else { return };
// A valid token, but asking about somebody else's inbox. This is
// the case the endpoint used to answer with a 200.
let r = get_notifications(&c, "did:plc:somebodyelse", Some(&acc.access_jwt)).await;
assert_error(r, 403, "Forbidden").await;
}
#[tokio::test]
async fn garbage_token_is_401_token_invalid() {
let Some((c, acc)) = ready().await else { return };
let r = get_notifications(&c, &acc.did, Some("not.a.jwt")).await;
assert_error(r, 401, "TokenInvalid").await;
}
#[tokio::test]
async fn refresh_token_is_not_accepted() {
let Some((c, acc)) = ready().await else { return };
// Signed by the same key and valid for 90 days — only the `scope`
// claim separates it from a session credential.
let r = get_notifications(&c, &acc.did, Some(&acc.refresh_jwt)).await;
assert_error(r, 401, "TokenInvalid").await;
}
#[tokio::test]
async fn seen_write_requires_matching_token() {
let Some((c, acc)) = ready().await else { return };
let url = format!("{}/api/notifications/seen", appview_url());
// Somebody else's unread badge: 403, nothing written.
let r = c
.post(&url)
.bearer_auth(&acc.access_jwt)
.json(&json!({ "did": "did:plc:somebodyelse" }))
.send()
.await
.unwrap();
assert_error(r, 403, "Forbidden").await;
// No credential at all: 401.
let r = c
.post(&url)
.json(&json!({ "did": &acc.did }))
.send()
.await
.unwrap();
assert_error(r, 401, "AuthMissing").await;
// Own inbox: allowed (zero rows updated — the account is new).
let r = c
.post(&url)
.bearer_auth(&acc.access_jwt)
.json(&json!({ "did": &acc.did }))
.send()
.await
.unwrap();
assert_eq!(r.status().as_u16(), 200);
let body: Value = r.json().await.unwrap();
assert_eq!(body["ok"], json!(true));
}
#[tokio::test]
async fn timeline_home_is_authenticated() {
let Some((c, acc)) = ready().await else { return };
let base = appview_url();
let r = c
.get(format!("{base}/api/timeline/home"))
.query(&[("did", acc.did.as_str())])
.send()
.await
.unwrap();
assert_error(r, 401, "AuthMissing").await;
let r = c
.get(format!("{base}/api/timeline/home"))
.query(&[("did", "did:plc:somebodyelse")])
.bearer_auth(&acc.access_jwt)
.send()
.await
.unwrap();
assert_error(r, 403, "Forbidden").await;
let r = c
.get(format!("{base}/api/timeline/home"))
.query(&[("did", acc.did.as_str())])
.bearer_auth(&acc.access_jwt)
.send()
.await
.unwrap();
assert_eq!(r.status().as_u16(), 200);
}
#[tokio::test]
async fn public_endpoints_stay_public() {
let Some((c, acc)) = ready().await else { return };
let base = appview_url();
// Profiles, search, follower lists and the health probe are public
// records in AT Proto. Putting them behind auth would be a
// behaviour change no protocol rule asks for — assert they still
// answer without a token.
for (path, params) in [
("/api/profile", vec![("did", acc.did.as_str())]),
("/api/search", vec![("q", "hello")]),
("/api/followers", vec![("did", acc.did.as_str())]),
("/api/following", vec![("did", acc.did.as_str())]),
("/healthz", vec![]),
] {
let r = c
.get(format!("{base}{path}"))
.query(&params)
.send()
.await
.unwrap();
assert_eq!(
r.status().as_u16(),
200,
"{path} must remain public, got {}",
r.status()
);
}
}
/// The AppView can only verify anything because the PDS publishes its
/// public key. If this document ever stops carrying a usable key, every
/// authenticated request degrades to `503 AuthUnavailable` — so assert
/// the shape the AppView parses.
#[tokio::test]
async fn pds_publishes_a_usable_signing_key() {
let c = client();
if !up(&c, PDS_URL).await {
eprintln!("pds not running, skipping");
return;
}
let doc: Value = c
.get(format!("{PDS_URL}/.well-known/did.json"))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let id = doc["id"].as_str().expect("did document needs an id");
assert!(id.starts_with("did:web:"), "id = {id}");
let vm = &doc["verificationMethod"][0];
assert_eq!(vm["type"], json!("Multikey"));
assert_eq!(vm["controller"], json!(id));
let key = vm["publicKeyMultibase"]
.as_str()
.expect("verificationMethod needs publicKeyMultibase");
// base58-btc multibase: the `z` prefix is what the AppView's
// decoder expects.
assert!(key.starts_with('z'), "key = {key}");
}
+167
View File
@@ -0,0 +1,167 @@
//! Shared test support for the AppView integration suites.
//!
//! ## Why the suites need this
//!
//! `/api/notifications*` and `/api/timeline/home` require a
//! PDS-issued access token whose `sub` equals the `did` in the request.
//! The suites, however, seed synthetic DIDs (`did:plc:ntf_…`) through
//! `/internal/ingest-commit` — accounts the PDS has never heard of, so
//! there is no `createSession` that would hand out a token for them.
//!
//! The way out is that a token is just an ES256 JWT signed with the
//! server key derived from `PDS_JWT_SECRET`. A test that can read that
//! secret (from the process environment, or from the repo `.env` the
//! dev stack itself was started with) can mint a token for any DID it
//! likes — the same thing `pds-server/src/jwt_issuer.rs` does.
//!
//! ## Fail-open, like the rest of the suites
//!
//! [`TestAuth::probe`] asks the running AppView whether it enforces
//! auth at all:
//!
//! - not enforcing (`APPVIEW_AUTH_REQUIRED=false`) → no header needed;
//! - enforcing and we have the secret → mint per-DID tokens;
//! - enforcing and we don't → `None`, and the caller skips, exactly as
//! it already skips when the service or the database is down.
#![allow(dead_code)]
use at_crypto::ecdsa::P256Keypair;
use at_crypto::jwt::{issue_jwt, JwtClaims};
/// Audience the PDS stamps into access tokens. Not validated by
/// `verify_jwt` today (`validate_aud = false`), but minting a token
/// that differs from the real thing would make this helper a poor
/// stand-in for the client.
const APPVIEW_AUD: &str = "did:web:appview.maarcadetweet.local";
/// The scope the AppView insists on. A token with any other scope —
/// `com.atproto.refresh`, say — is rejected with `TokenInvalid`.
pub const ACCESS_SCOPE: &str = "com.atproto.access";
/// How the suite should authenticate against the AppView under test.
///
/// `Clone` because a test that pages through results in a closure has
/// to hand each iteration its own copy, exactly like the client and the
/// base URL next to it.
#[derive(Clone)]
pub enum TestAuth {
/// `APPVIEW_AUTH_REQUIRED=false`: send no `Authorization` header.
Disabled,
/// Auth is enforced; mint tokens with this hex secret.
Secret(String),
}
impl TestAuth {
/// Decide how (or whether) this suite can talk to the AppView.
///
/// Returns `None` when the AppView enforces auth but no
/// `PDS_JWT_SECRET` is reachable — the caller should print a notice
/// and return, keeping `cargo test --workspace` green on a machine
/// without the dev stack's environment.
pub async fn probe(c: &reqwest::Client, base_url: &str) -> Option<Self> {
// An unauthenticated probe against a private endpoint. We only
// look at the status: 401 means the extractor is active. A DID
// that doesn't exist is fine — the auth check runs first.
let status = c
.get(format!("{base_url}/api/notifications/count"))
.query(&[("did", "did:plc:auth_probe")])
.send()
.await
.ok()?
.status()
.as_u16();
if status != 401 && status != 503 {
return Some(TestAuth::Disabled);
}
match pds_jwt_secret() {
Some(secret) => Some(TestAuth::Secret(secret)),
None => {
eprintln!(
"appview enforces auth (probe returned {status}) but PDS_JWT_SECRET \
is not set and no .env was found — skipping"
);
None
}
}
}
/// Attach an `Authorization: Bearer` header for `did`, if needed.
pub fn apply(&self, rb: reqwest::RequestBuilder, did: &str) -> reqwest::RequestBuilder {
match self {
TestAuth::Disabled => rb,
TestAuth::Secret(secret) => match mint_access_jwt(secret, did, ACCESS_SCOPE, 3600) {
Some(token) => rb.bearer_auth(token),
None => rb,
},
}
}
/// A token for `did` — for tests that want to send a *wrong* one on
/// purpose. `None` when auth is disabled, in which case the test
/// that needs it should skip.
pub fn token_for(&self, did: &str) -> Option<String> {
match self {
TestAuth::Disabled => None,
TestAuth::Secret(secret) => mint_access_jwt(secret, did, ACCESS_SCOPE, 3600),
}
}
}
/// `PDS_JWT_SECRET` from the environment, falling back to the repo
/// `.env` — the same file the running dev stack loaded at startup, so
/// the minted tokens verify against the key the PDS actually publishes.
pub fn pds_jwt_secret() -> Option<String> {
if let Ok(v) = std::env::var("PDS_JWT_SECRET") {
if !v.trim().is_empty() {
return Some(v);
}
}
// `dotenvy::dotenv` walks up from the current directory, which for
// a test binary is the crate root — so this finds the workspace
// `.env` two levels up. It never overrides a real env var.
let _ = dotenvy::dotenv();
std::env::var("PDS_JWT_SECRET")
.ok()
.filter(|v| !v.trim().is_empty())
}
/// Mint an access JWT for `did`, signed with the PDS's server key.
///
/// Mirrors `pds-server/src/jwt_issuer.rs`: the P-256 secret scalar is
/// the **first 32 bytes** of `PDS_JWT_SECRET` (the config allows a
/// longer secret), i.e. the first 64 hex characters.
///
/// `ttl_secs` may be negative to build a deliberately expired token.
pub fn mint_access_jwt(
secret_hex: &str,
did: &str,
scope: &str,
ttl_secs: i64,
) -> Option<String> {
let hex = secret_hex.trim().trim_start_matches("0x");
if hex.len() < 64 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
eprintln!("PDS_JWT_SECRET is not ≥32 bytes of hex; cannot mint a test token");
return None;
}
let kp = P256Keypair {
secret_hex: hex[..64].to_string(),
// Only the signing half is used by `issue_jwt`; the verifier
// fetches the public key from the PDS's DID document.
public_multibase: String::new(),
};
let now = chrono::Utc::now().timestamp();
issue_jwt(
&kp,
&JwtClaims {
iss: "did:web:test".into(),
sub: did.to_string(),
aud: APPVIEW_AUD.into(),
iat: now - 1,
exp: now + ttl_secs,
jti: None,
scope: Some(scope.to_string()),
},
)
.ok()
}
+36 -24
View File
@@ -15,6 +15,9 @@
//! and returns rather than panicking. The point of the tests is to
//! catch regressions in CI where the service IS up.
mod common;
use common::TestAuth;
use serde_json::{json, Value};
use std::time::Duration;
@@ -50,6 +53,32 @@ async fn db_reachable() -> bool {
)
}
/// `/api/timeline/home` requires a token whose `sub` is the requested
/// DID. The DIDs here are synthetic, so the token is minted from the
/// PDS signing secret — see `tests/common/mod.rs`. `None` → skip.
async fn auth_or_skip() -> Option<TestAuth> {
TestAuth::probe(&client().await, APPVIEW_URL).await
}
/// `GET /api/timeline/home` as `did`, authenticated when required.
async fn get_timeline(
c: &reqwest::Client,
auth: &TestAuth,
did: &str,
extra: &[(&str, &str)],
) -> reqwest::Response {
let mut params: Vec<(&str, &str)> = vec![("did", did)];
params.extend_from_slice(extra);
auth.apply(
c.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&params),
did,
)
.send()
.await
.unwrap()
}
async fn post_ingest(c: &reqwest::Client, body: Value) -> reqwest::Response {
c.post(format!("{APPVIEW_URL}/internal/ingest-commit"))
.json(&body)
@@ -125,6 +154,7 @@ async fn timeline_includes_embed() {
return;
}
let c = client().await;
let Some(auth) = auth_or_skip().await else { return };
let did = did_for_test("img");
let uri = seed_post(
&c,
@@ -160,12 +190,7 @@ async fn timeline_includes_embed() {
)
.await;
let resp = c
.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&[("did", did.as_str()), ("limit", "10")])
.send()
.await
.unwrap();
let resp = get_timeline(&c, &auth, &did, &[("limit", "10")]).await;
assert_eq!(resp.status().as_u16(), 200);
let body: Value = resp.json().await.unwrap();
let posts = body["posts"].as_array().unwrap();
@@ -199,6 +224,7 @@ async fn timeline_includes_external_embed() {
return;
}
let c = client().await;
let Some(auth) = auth_or_skip().await else { return };
let did = did_for_test("ext");
let uri = seed_post(
&c,
@@ -222,12 +248,7 @@ async fn timeline_includes_external_embed() {
)
.await;
let resp = c
.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&[("did", did.as_str()), ("limit", "10")])
.send()
.await
.unwrap();
let resp = get_timeline(&c, &auth, &did, &[("limit", "10")]).await;
assert_eq!(resp.status().as_u16(), 200);
let body: Value = resp.json().await.unwrap();
let posts = body["posts"].as_array().unwrap();
@@ -241,12 +262,7 @@ async fn timeline_includes_external_embed() {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
let resp = c
.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&[("did", did.as_str()), ("limit", "10")])
.send()
.await
.unwrap();
let resp = get_timeline(&c, &auth, &did, &[("limit", "10")]).await;
let body: Value = resp.json().await.unwrap();
our = body["posts"]
.as_array()
@@ -410,6 +426,7 @@ async fn timeline_post_without_embed_has_null_embed() {
return;
}
let c = client().await;
let Some(auth) = auth_or_skip().await else { return };
let did = did_for_test("plain");
let uri = seed_post(
&c,
@@ -421,12 +438,7 @@ async fn timeline_post_without_embed_has_null_embed() {
)
.await;
let resp = c
.get(format!("{APPVIEW_URL}/api/timeline/home"))
.query(&[("did", did.as_str()), ("limit", "10")])
.send()
.await
.unwrap();
let resp = get_timeline(&c, &auth, &did, &[("limit", "10")]).await;
assert_eq!(resp.status().as_u16(), 200);
let body: Value = resp.json().await.unwrap();
let our = body["posts"]
@@ -14,6 +14,9 @@
//! API. That's deliberate: it's the only way to catch a mismatch
//! between what the write path stores and what the read path joins.
mod common;
use common::TestAuth;
use serde_json::{json, Value};
use std::time::Duration;
@@ -55,8 +58,12 @@ async fn db_pool() -> Option<sqlx::PgPool> {
}
/// Guard used at the top of every test. Returns `None` (→ skip) unless
/// both the HTTP service and the database are up.
async fn ready() -> Option<(reqwest::Client, sqlx::PgPool)> {
/// the HTTP service is up, the database is reachable, **and** we know
/// how to authenticate: `/api/notifications*` now requires a token
/// whose `sub` is the requested DID, and the DIDs seeded here are
/// synthetic, so the token has to be minted from the PDS's signing
/// secret. See `tests/common/mod.rs`.
async fn ready() -> Option<(reqwest::Client, sqlx::PgPool, TestAuth)> {
if !wait_for_appview_db().await {
eprintln!("appview not running, skipping");
return None;
@@ -65,7 +72,32 @@ async fn ready() -> Option<(reqwest::Client, sqlx::PgPool)> {
eprintln!("appview DB unreachable, skipping");
return None;
};
Some((client().await, pool))
let c = client().await;
let auth = TestAuth::probe(&c, &appview_url()).await?;
Some((c, pool, auth))
}
/// `GET <url>` against a private endpoint, carrying the token for
/// `did` when the instance enforces auth.
fn authed_get(
c: &reqwest::Client,
auth: &TestAuth,
url: String,
did: &str,
) -> reqwest::RequestBuilder {
auth.apply(c.get(url), did)
}
/// `POST <url>` against a private endpoint. Same rule as
/// [`authed_get`] — `/api/notifications/seen` is a write into one
/// user's read state.
fn authed_post(
c: &reqwest::Client,
auth: &TestAuth,
url: String,
did: &str,
) -> reqwest::RequestBuilder {
auth.apply(c.post(url), did)
}
async fn post_ingest(c: &reqwest::Client, body: Value) -> reqwest::Response {
@@ -181,7 +213,7 @@ async fn seed_follow(c: &reqwest::Client, follower: &str, subject: &str) {
#[tokio::test]
async fn notifications_list_count_and_seen() {
let base = appview_url();
let Some((c, _pool)) = ready().await else {
let Some((c, _pool, auth)) = ready().await else {
return;
};
let alice = did_for_test("alice");
@@ -196,8 +228,7 @@ async fn notifications_list_count_and_seen() {
let reply_uri = seed_reply(&c, &carol, &post_uri, &post_uri, "carol's reply").await;
seed_follow(&c, &bob, &alice).await;
let resp = c
.get(format!("{base}/api/notifications"))
let resp = authed_get(&c, &auth, format!("{base}/api/notifications"), &alice)
.query(&[("did", alice.as_str()), ("limit", "50")])
.send()
.await
@@ -253,8 +284,7 @@ async fn notifications_list_count_and_seen() {
}
// The unread count agrees with the list.
let resp = c
.get(format!("{base}/api/notifications/count"))
let resp = authed_get(&c, &auth, format!("{base}/api/notifications/count"), &alice)
.query(&[("did", alice.as_str())])
.send()
.await
@@ -264,8 +294,7 @@ async fn notifications_list_count_and_seen() {
assert_eq!(body["count"], json!(3));
// Mark everything seen.
let resp = c
.post(format!("{base}/api/notifications/seen"))
let resp = authed_post(&c, &auth, format!("{base}/api/notifications/seen"), &alice)
.json(&json!({ "did": alice }))
.send()
.await
@@ -276,8 +305,7 @@ async fn notifications_list_count_and_seen() {
assert_eq!(body["updated"], json!(3));
// Idempotent: a second call updates nothing and still succeeds.
let resp = c
.post(format!("{base}/api/notifications/seen"))
let resp = authed_post(&c, &auth, format!("{base}/api/notifications/seen"), &alice)
.json(&json!({ "did": alice }))
.send()
.await
@@ -286,8 +314,7 @@ async fn notifications_list_count_and_seen() {
assert_eq!(body["updated"], json!(0));
// Count is now zero and the rows carry a read_at.
let resp = c
.get(format!("{base}/api/notifications/count"))
let resp = authed_get(&c, &auth, format!("{base}/api/notifications/count"), &alice)
.query(&[("did", alice.as_str())])
.send()
.await
@@ -295,8 +322,7 @@ async fn notifications_list_count_and_seen() {
let body: Value = resp.json().await.unwrap();
assert_eq!(body["count"], json!(0));
let resp = c
.get(format!("{base}/api/notifications"))
let resp = authed_get(&c, &auth, format!("{base}/api/notifications"), &alice)
.query(&[("did", alice.as_str())])
.send()
.await
@@ -311,8 +337,7 @@ async fn notifications_list_count_and_seen() {
"/api/notifications",
"/api/notifications/count",
] {
let resp = c
.get(format!("{base}{path}"))
let resp = authed_get(&c, &auth, format!("{base}{path}"), &alice)
.query(&[("did", "")])
.send()
.await
@@ -326,7 +351,7 @@ async fn notifications_list_count_and_seen() {
#[tokio::test]
async fn notifications_skip_self_interactions() {
let base = appview_url();
let Some((c, _pool)) = ready().await else {
let Some((c, _pool, auth)) = ready().await else {
return;
};
let alice = did_for_test("solo");
@@ -335,8 +360,7 @@ async fn notifications_skip_self_interactions() {
seed_reply(&c, &alice, &post_uri, &post_uri, "and replying too").await;
seed_follow(&c, &alice, &alice).await;
let resp = c
.get(format!("{base}/api/notifications"))
let resp = authed_get(&c, &auth, format!("{base}/api/notifications"), &alice)
.query(&[("did", alice.as_str())])
.send()
.await
@@ -355,7 +379,7 @@ async fn notifications_skip_self_interactions() {
#[tokio::test]
async fn notifications_paginate_with_cursor() {
let base = appview_url();
let Some((c, _pool)) = ready().await else {
let Some((c, _pool, auth)) = ready().await else {
return;
};
let alice = did_for_test("popular");
@@ -372,9 +396,9 @@ async fn notifications_paginate_with_cursor() {
let c = c.clone();
let alice = alice.clone();
let base = base.clone();
let auth = auth.clone();
async move {
let mut req = c
.get(format!("{base}/api/notifications"))
let mut req = authed_get(&c, &auth, format!("{base}/api/notifications"), &alice)
.query(&[("did", alice.as_str()), ("limit", "5")]);
if let Some(cur) = cursor {
req = req.query(&[("cursor", cur.as_str())]);
@@ -417,8 +441,7 @@ async fn notifications_paginate_with_cursor() {
assert_eq!(all.len(), 12);
// A mangled cursor is a 400, not a silent restart at page 1.
let resp = c
.get(format!("{base}/api/notifications"))
let resp = authed_get(&c, &auth, format!("{base}/api/notifications"), &alice)
.query(&[("did", alice.as_str()), ("cursor", "!!!garbage!!!")])
.send()
.await
@@ -431,7 +454,7 @@ async fn notifications_paginate_with_cursor() {
#[tokio::test]
async fn notifications_seen_respects_watermark() {
let base = appview_url();
let Some((c, _pool)) = ready().await else {
let Some((c, _pool, auth)) = ready().await else {
return;
};
let alice = did_for_test("watermark");
@@ -442,8 +465,7 @@ async fn notifications_seen_respects_watermark() {
// Read back the first notification's indexed_at — that's the
// watermark a client would echo after rendering page 1.
let body: Value = c
.get(format!("{base}/api/notifications"))
let body: Value = authed_get(&c, &auth, format!("{base}/api/notifications"), &alice)
.query(&[("did", alice.as_str())])
.send()
.await
@@ -461,8 +483,7 @@ async fn notifications_seen_respects_watermark() {
let second = did_for_test("late");
seed_like(&c, &second, &post_uri).await;
let resp = c
.post(format!("{base}/api/notifications/seen"))
let resp = authed_post(&c, &auth, format!("{base}/api/notifications/seen"), &alice)
.json(&json!({ "did": alice, "seenAt": watermark }))
.send()
.await
@@ -475,8 +496,7 @@ async fn notifications_seen_respects_watermark() {
);
// The later one is still unread.
let body: Value = c
.get(format!("{base}/api/notifications/count"))
let body: Value = authed_get(&c, &auth, format!("{base}/api/notifications/count"), &alice)
.query(&[("did", alice.as_str())])
.send()
.await
@@ -487,8 +507,7 @@ async fn notifications_seen_respects_watermark() {
assert_eq!(body["count"], json!(1));
// snake_case spelling must work identically.
let resp = c
.post(format!("{base}/api/notifications/seen"))
let resp = authed_post(&c, &auth, format!("{base}/api/notifications/seen"), &alice)
.json(&json!({ "did": alice, "seen_at": null }))
.send()
.await
@@ -502,7 +521,7 @@ async fn notifications_seen_respects_watermark() {
#[tokio::test]
async fn followers_and_following_lists() {
let base = appview_url();
let Some((c, _pool)) = ready().await else {
let Some((c, _pool, _auth)) = ready().await else {
return;
};
let hub = did_for_test("hub");
@@ -591,7 +610,8 @@ async fn followers_and_following_lists() {
assert_eq!(unique.len(), seen.len(), "paged followers repeat: {seen:?}");
assert_eq!(seen.len(), 3, "paging lost a follower: {seen:?}");
// `did` is mandatory.
// `did` is mandatory. These two stay public — a follow edge is a
// public record — so no token is involved.
for path in ["/api/followers", "/api/following"] {
let resp = c
.get(format!("{base}{path}"))
@@ -610,7 +630,7 @@ async fn followers_and_following_lists() {
#[tokio::test]
async fn thread_returns_parents_and_replies() {
let base = appview_url();
let Some((c, _pool)) = ready().await else {
let Some((c, _pool, _auth)) = ready().await else {
return;
};
let a = did_for_test("root");
@@ -689,7 +709,7 @@ async fn thread_returns_parents_and_replies() {
#[tokio::test]
async fn post_by_uri_stays_backwards_compatible() {
let base = appview_url();
let Some((c, _pool)) = ready().await else {
let Some((c, _pool, _auth)) = ready().await else {
return;
};
let a = did_for_test("compat_a");