Skip to content

Commit f675d8d

Browse files
authored
refactor(auth): tests share one way to send requests and read replies (#574)
Part of #544. Builds on #571 and #573 (merged). Test modules kept their own copies of request code that `crate::tests` already has, or should have: - **Requests.** The emails harness had its own `Account` type, request builder and body reader, copies of `Browser`'s. It now uses `Browser`. The new `Browser::send_from` sends from a request context of the test's own, and `Browser::send` calls it. - **Body readers.** `html`, `json` and `reply` share one private body reader. The OIDC `Flow::json`/`Flow::text` and passkey `Fixture::json` are gone, and the clients registry tests read the token endpoint's error with `json` too. - **Event history.** The OIDC, passkey, admin and federation tests use a new `EventRepository::known_history` fixture (added to `crates/database/src/fixtures.rs` here, with its first callers) instead of writing out "this account's known events, newest first". - **Reasons.** `deletion/tests.rs` drops its copy of `crate::tests::reason`. ### Differences No test reads any of these: - The shared readers read up to `MAX_RESPONSE_BYTES` (256 KiB), as `Browser::call` and the page tests already did. OIDC's `Flow::json` and `Flow::text` read up to 1 MiB. Passkey's `Fixture::json` and the registry reader read up to 64 KiB. No response comes near any of these limits, and none is an assertion. The readers' panic messages change with them. - The emails tests send their signed-out requests as `Browser::signed_out()`, with an empty `Cookie` header instead of none, as every other signed-out test does. The service reads an empty header as no cookie. ### Unchanged - No test was merged or removed. Every file keeps the same test names as `origin/main`. - Every assertion checks what it did. - Outside auth-service's test modules, only `crates/database/src/fixtures.rs` (for `known_history`) and `docs/dev/testing.md` (naming the shared readers) change. ### Checks - `cargo clippy -p auth-service` and `-p sourceorigin-repository`, `--all-targets`, pass with and without `--all-features`, `-D warnings`. `just docs` passes. - `just db test` on the latest `main`: all 499 tests pass, and the query cache check passes. - Each commit builds on its own: `known_history` comes before its first callers. ## Council review Rounds: 2 | Delegate | Round 1 | Round 2 | | --- | --- | --- | | GPT 6.1 Sol | 9/10 | 9/10 | | Claude Opus 5.5 | 8/10 | 8.5/10 | | Claude Fable 5.2 | 8.5/10 | 9/10 | Round 2 found no code defects. Its should-fixes were these descriptions, and its nits are applied. > [!NOTE] > Written by Claude Opus 5.5 in Claude Code and reviewed by GPT 6.1 Sol, Claude Opus 5.5 and Claude Fable 5.2 (via T3 Code)
1 parent 319b802 commit f675d8d

25 files changed

Lines changed: 200 additions & 243 deletions

File tree

‎apps/auth-service/src/admin/tests/mod.rs‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -121,14 +121,7 @@ impl Harness {
121121

122122
/// The kinds of the events concerning `user_id`, newest first.
123123
async fn events(&self, user_id: UserId) -> Vec<DomainEvent> {
124-
self.database
125-
.events()
126-
.history_for_user(user_id, 100)
127-
.await
128-
.expect("history")
129-
.into_iter()
130-
.map(|stored| stored.event.known().cloned().expect("a known event"))
131-
.collect()
124+
self.database.events().known_history(user_id, 100).await
132125
}
133126
}
134127

‎apps/auth-service/src/clients/tests/registry.rs‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,14 @@
22
//! applying a deployment's client, and the registration quota.
33
use super::*;
44
use crate::oidc::OAuthCode;
5-
use crate::tests::operator;
5+
use crate::tests::{json, operator};
66
use axum::{
77
Router,
8-
body::{Body, to_bytes},
8+
body::Body,
99
http::{Method, Request, StatusCode, header},
1010
response::Response,
1111
};
1212
use base64::Engine;
13-
use serde_json::Value;
1413
use sourceorigin_common::clients::AllowedScopes;
1514
use sourceorigin_crypto::Secret;
1615
use tower::ServiceExt;
@@ -57,11 +56,7 @@ async fn cors(replica: &Router, origin: &str) -> bool {
5756
async fn authenticates(replica: &Router, id: &ClientId, origin: &str) -> bool {
5857
let form = format!("grant_type=authorization_code&code=unusable&client_id={id}");
5958
let response = send(replica, Method::POST, "/oauth/token", origin, &form, None).await;
60-
let body = to_bytes(response.into_body(), 64 * 1024)
61-
.await
62-
.expect("token response");
63-
let error: Value = serde_json::from_slice(&body).expect("OAuth error");
64-
error["error"] != OAuthCode::InvalidClient.as_str()
59+
json(response).await["error"] != OAuthCode::InvalidClient.as_str()
6560
}
6661

6762
/// Creating, updating, disabling and enabling a public client changes CORS and

‎apps/auth-service/src/deletion/tests.rs‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@
33
44
use super::*;
55
use crate::{
6-
AdminError, AdminService, Reason,
6+
AdminError, AdminService,
77
jobs::AccountPurge,
88
security::SessionError,
99
tests::{
10-
Browser, Replicas, change, operator, refresh_grant, register, registration,
10+
Browser, Replicas, change, operator, reason, refresh_grant, register, registration,
1111
verified_address,
1212
},
1313
};
@@ -385,11 +385,6 @@ const fn user(browser: &Browser) -> Actor {
385385
}
386386
}
387387

388-
/// Why the scenarios' operators act.
389-
fn reason() -> Reason {
390-
Reason::parse("Asked by email".into()).expect("reason")
391-
}
392-
393388
/// An export needs a recent passkey confirmation, and is recorded. It holds a
394389
/// section for every table the inventory says it exports, what ended but is
395390
/// still stored, and every event about the account but views, and no

‎apps/auth-service/src/emails/tests.rs‎

Lines changed: 46 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,16 @@ use super::*;
55
use crate::security::tests::assert_step_up_required;
66
use crate::{
77
account::AccountApplication,
8-
tests::{AUTH_ORIGIN, Browser, MAX_RESPONSE_BYTES, Replicas},
8+
tests::{AUTH_ORIGIN, Browser, Replicas, reply},
99
};
1010
use axum::{
11-
body::{Body, to_bytes},
12-
http::{Method, Request, header},
11+
http::{Method, header},
1312
response::Response,
1413
};
1514
use serde_json::{Value, json};
1615
use sourceorigin_common::AuthenticationMethod;
1716
use sourceorigin_repository::DeliverySummary;
1817
use std::net::{IpAddr, Ipv6Addr};
19-
use tower::ServiceExt;
20-
21-
/// A scenario account with one signed-in browser.
22-
struct Account {
23-
/// The account.
24-
user_id: UserId,
25-
/// The browser's session cookie pair.
26-
cookie: String,
27-
}
2818

2919
/// The address routes over the test database, as requests from one client IP of
3020
/// their own, so no other test shares its verification limit.
@@ -58,70 +48,45 @@ impl Harness {
5848

5949
/// Creates an account and signs a browser in to it with `method`. Only a
6050
/// passkey sign-in confirms the session.
61-
async fn account(&self, method: AuthenticationMethod) -> Account {
51+
async fn account(&self, method: AuthenticationMethod) -> Browser {
6252
let user_id = self.database.users().insert_named("email").await;
63-
let browser = Browser::sign_in_by(&self.database, self.context, user_id, method.into());
64-
Account {
65-
user_id,
66-
cookie: browser.await.cookie,
67-
}
53+
Browser::sign_in_by(&self.database, self.context, user_id, method.into()).await
6854
}
6955

70-
/// Sends a request, as `account`'s browser if any.
56+
/// Sends a request as `browser`.
7157
async fn send(
7258
&self,
73-
account: Option<&Account>,
59+
browser: &Browser,
7460
method: Method,
7561
path: &str,
7662
body: Option<Value>,
7763
) -> Response {
78-
let mut request = Request::builder()
79-
.extension(self.context)
80-
.method(method)
81-
.uri(path)
82-
.header(header::CONTENT_TYPE, "application/json");
83-
if let Some(account) = account {
84-
request = request.header(header::COOKIE, &account.cookie);
85-
}
86-
let body = body.map_or_else(Body::empty, |body| Body::from(body.to_string()));
87-
self.router
88-
.clone()
89-
.oneshot(request.body(body).expect("request"))
64+
browser
65+
.send_from(&self.router, self.context, method, path, body)
9066
.await
91-
.expect("response")
9267
}
9368

9469
/// Sends a request and returns its status and JSON body.
9570
async fn call(
9671
&self,
97-
account: Option<&Account>,
72+
browser: &Browser,
9873
method: Method,
9974
path: &str,
10075
body: Option<Value>,
10176
) -> (StatusCode, Value) {
102-
let response = self.send(account, method, path, body).await;
103-
let status = response.status();
104-
let body = to_bytes(response.into_body(), MAX_RESPONSE_BYTES)
105-
.await
106-
.expect("body");
107-
(status, serde_json::from_slice(&body).unwrap_or(Value::Null))
77+
reply(self.send(browser, method, path, body).await).await
10878
}
10979

110-
/// Adds `address` to `account`, returning the status and body.
111-
async fn add(&self, account: &Account, address: &str) -> (StatusCode, Value) {
80+
/// Adds `address` to `browser`'s account, returning the status and body.
81+
async fn add(&self, browser: &Browser, address: &str) -> (StatusCode, Value) {
11282
let body = json!({ "email": address });
113-
self.call(
114-
Some(account),
115-
Method::POST,
116-
routes::emails::LIST,
117-
Some(body),
118-
)
119-
.await
83+
self.call(browser, Method::POST, routes::emails::LIST, Some(body))
84+
.await
12085
}
12186

122-
/// Adds `address` to `account` and returns its ID.
123-
async fn added(&self, account: &Account, address: &str) -> EmailId {
124-
let (status, body) = self.add(account, address).await;
87+
/// Adds `address` to `browser`'s account and returns its ID.
88+
async fn added(&self, browser: &Browser, address: &str) -> EmailId {
89+
let (status, body) = self.add(browser, address).await;
12590
assert_eq!(status, StatusCode::CREATED, "{body}");
12691
body["id"].as_str().expect("id").parse().expect("email ID")
12792
}
@@ -135,34 +100,39 @@ impl Harness {
135100
/// Presents `token`, signed out.
136101
async fn verify_token(&self, token: &str) -> (StatusCode, Value) {
137102
let body = json!({ "token": token });
138-
self.call(None, Method::POST, routes::emails::VERIFY, Some(body))
139-
.await
103+
self.call(
104+
&Browser::signed_out(),
105+
Method::POST,
106+
routes::emails::VERIFY,
107+
Some(body),
108+
)
109+
.await
140110
}
141111

142-
/// Makes `id` the primary address of `account`.
143-
async fn make_primary(&self, account: &Account, id: EmailId) -> (StatusCode, Value) {
112+
/// Makes `id` the primary address of `browser`'s account.
113+
async fn make_primary(&self, browser: &Browser, id: EmailId) -> (StatusCode, Value) {
144114
let path = routes::emails::PRIMARY.replace("{id}", &id.to_string());
145-
self.call(Some(account), Method::POST, &path, None).await
115+
self.call(browser, Method::POST, &path, None).await
146116
}
147117

148-
/// Removes `id` from `account`.
149-
async fn remove(&self, account: &Account, id: EmailId) -> (StatusCode, Value) {
118+
/// Removes `id` from `browser`'s account.
119+
async fn remove(&self, browser: &Browser, id: EmailId) -> (StatusCode, Value) {
150120
let path = routes::emails::ITEM.replace("{id}", &id.to_string());
151-
self.call(Some(account), Method::DELETE, &path, None).await
121+
self.call(browser, Method::DELETE, &path, None).await
152122
}
153123

154-
/// `account`'s addresses, as it lists them.
155-
async fn list(&self, account: &Account) -> Vec<Value> {
124+
/// The addresses of `browser`'s account, as it lists them.
125+
async fn list(&self, browser: &Browser) -> Vec<Value> {
156126
let (status, body) = self
157-
.call(Some(account), Method::GET, routes::emails::LIST, None)
127+
.call(browser, Method::GET, routes::emails::LIST, None)
158128
.await;
159129
assert_eq!(status, StatusCode::OK, "{body}");
160130
body.as_array().expect("addresses").clone()
161131
}
162132

163-
/// The email deliveries queued for `account`.
164-
async fn deliveries(&self, account: &Account) -> Vec<DeliverySummary> {
165-
let destination = format!("account {}", account.user_id);
133+
/// The email deliveries queued for `browser`'s account.
134+
async fn deliveries(&self, browser: &Browser) -> Vec<DeliverySummary> {
135+
let destination = format!("account {}", browser.user_id);
166136
self.database
167137
.deliveries()
168138
.list(None, Some("email"), 1000)
@@ -186,12 +156,7 @@ async fn adding_asks_for_confirmation_first() {
186156
let body = json!({ "email": "not an address" });
187157
assert_step_up_required(
188158
harness
189-
.send(
190-
Some(&social),
191-
Method::POST,
192-
routes::emails::LIST,
193-
Some(body),
194-
)
159+
.send(&social, Method::POST, routes::emails::LIST, Some(body))
195160
.await,
196161
)
197162
.await;
@@ -340,19 +305,24 @@ async fn verification_checks_the_signed_in_account() {
340305

341306
let first = format!("{}-first@example.com", owner.user_id);
342307
let first = harness.added(&owner, &first).await;
343-
let (status, body) = verify(Some(&other), first).await;
308+
let (status, body) = verify(&other, first).await;
344309
assert_eq!(status, StatusCode::CONFLICT);
345310
assert_eq!(
346311
body["error"],
347312
"This link adds the address to an Origin Account other than the one you are signed in \
348313
to. Sign out first if you meant to confirm it."
349314
);
350315
assert_eq!(harness.list(&owner).await[0]["verified"], false);
351-
assert_eq!(verify(None, first).await.0, StatusCode::OK, "link kept");
316+
let signed_out = Browser::signed_out();
317+
assert_eq!(
318+
verify(&signed_out, first).await.0,
319+
StatusCode::OK,
320+
"link kept"
321+
);
352322

353323
let second = format!("{}-second@example.com", owner.user_id);
354324
let second = harness.added(&owner, &second).await;
355-
assert_eq!(verify(Some(&owner), second).await.0, StatusCode::OK);
325+
assert_eq!(verify(&owner, second).await.0, StatusCode::OK);
356326
let verified = harness
357327
.database
358328
.events()
@@ -414,7 +384,7 @@ async fn expired_links_replacements_and_limits() {
414384
}
415385
let response = harness
416386
.send(
417-
Some(&account),
387+
&account,
418388
Method::POST,
419389
routes::emails::LIST,
420390
Some(json!({ "email": "sixth@example.com" })),

‎apps/auth-service/src/federation/tests/signup.rs‎

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -135,16 +135,7 @@ async fn signup_imports_the_provider_address_verified_only_where_the_provider_is
135135
assert_eq!(email.normalized_email, address);
136136
assert_eq!(email.verified_at.is_some(), authoritative);
137137
assert_eq!(email.is_primary, authoritative);
138-
let history: Vec<_> = test
139-
.app
140-
.database
141-
.events()
142-
.history_for_user(user, 10)
143-
.await
144-
.expect("history")
145-
.into_iter()
146-
.map(|stored| stored.event.known().cloned().expect("known"))
147-
.collect();
138+
let history = test.app.database.events().known_history(user, 10).await;
148139
assert!(
149140
history.iter().any(|event| matches!(
150141
event,

‎apps/auth-service/src/oidc/tests/app_removal.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ async fn an_administrator_removes_an_app_with_a_reason() {
5454
async fn removing_an_app_ends_its_access() {
5555
let flow = Flow::new(false, false).await;
5656
let code = flow.code(REFRESH_SCOPES).await;
57-
let tokens = Flow::json(flow.exchange(&code, Flow::verifier(), None).await).await;
57+
let tokens = json(flow.exchange(&code, Flow::verifier(), None).await).await;
5858
let refresh = tokens["refresh_token"].as_str().expect("refresh token");
5959
let outstanding = flow.code(REFRESH_SCOPES).await;
6060
let service = crate::account::AccountService::new(flow.app.database.clone());
@@ -124,7 +124,7 @@ async fn an_exchange_waits_for_a_removal_and_finds_its_code_expired() {
124124
let exchanging = flow.clone();
125125
let exchange = tokio::spawn(async move {
126126
let response = exchanging.exchange(&code, Flow::verifier(), None).await;
127-
(response.status(), Flow::json(response).await)
127+
(response.status(), json(response).await)
128128
});
129129
until_blocked(&mut removal, 1).await;
130130
removal

‎apps/auth-service/src/oidc/tests/authorization.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ async fn public_consent_pkce_claim_scoping_and_replay() {
2727
let code = flow.code(Scope::OpenId.as_str()).await;
2828
let response = flow.exchange(&code, Flow::verifier(), None).await;
2929
assert_eq!(response.status(), StatusCode::OK);
30-
let tokens = Flow::json(response).await;
30+
let tokens = json(response).await;
3131
let claims: IdTokenClaims = flow
3232
.app
3333
.keys

‎apps/auth-service/src/oidc/tests/errors.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ async fn state_is_optional_and_bounded_before_it_goes_back() {
6969
let uri = request_uri(&flow, &[("state", &long), ("response_type", "token")], &[]);
7070
let response = flow.request(Method::GET, &uri, &[], None).await;
7171
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
72-
assert!(!Flow::text(response).await.contains(&long));
72+
assert!(!html(response).await.contains(&long));
7373
}
7474

7575
/// A pushed request's `request_uri` decides the request: other parameters, even
@@ -100,7 +100,7 @@ async fn pushed_requests_are_read_before_other_parameters() {
100100
let response = flow.post_query(&url, flow.basic.as_deref()).await;
101101
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
102102
assert_eq!(
103-
Flow::json(response).await["error"],
103+
json(response).await["error"],
104104
OAuthCode::InvalidRequest.as_str()
105105
);
106106
}
@@ -145,7 +145,7 @@ async fn token_endpoint_errors_follow_rfc_6749() {
145145
)
146146
.await;
147147
assert_eq!(
148-
Flow::json(response).await["error"],
148+
json(response).await["error"],
149149
OAuthCode::InvalidRequest.as_str(),
150150
"{grant}"
151151
);
@@ -191,7 +191,7 @@ async fn userinfo_needs_the_openid_scope() {
191191
"Bearer error=\"insufficient_scope\", scope=\"openid\""
192192
);
193193
assert_eq!(
194-
Flow::json(response).await["error"],
194+
json(response).await["error"],
195195
OAuthCode::InsufficientScope.as_str()
196196
);
197197
}

‎apps/auth-service/src/oidc/tests/logout.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ async fn a_hint_naming_another_account_says_so() {
309309
.request(Method::POST, routes::page::LOGOUT, &fields, None)
310310
.await;
311311
assert_eq!(warned.status(), StatusCode::OK);
312-
let page = Flow::text(warned).await;
312+
let page = html(warned).await;
313313
assert!(page.contains("a different account"), "{page}");
314314
assert!(page.contains(r#"name="warned""#), "{page}");
315315
let database = &flow.app.database;

0 commit comments

Comments
 (0)