Skip to content

Commit b4fbdb2

Browse files
PiquelChipsclaude
andcommitted
fix(auth): mirror the previous release's client writes, parse legacy origins
While the previous release still runs, it writes `client_secret_hash` directly; a trigger now mirrors those writes into `oidc_client_secrets` and `client_type`, so a confidential client it registers is never taken for a public one. Redirect origins are filled in by `run_migrations` with the URL parser instead of a SQL regex, which missed forms such as `https://app.example:0443/` and Unicode hosts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 91f3667 commit b4fbdb2

7 files changed

Lines changed: 157 additions & 18 deletions

File tree

‎crates/database/.sqlx/query-0bf8e1a326f07f2570ad98c8eab89ba1a77157a32d2e393951b46ce73930eabb.json‎

Lines changed: 15 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/database/.sqlx/query-41dc83078062bd3e0643424bfb7aa49ca71c383f91d87a9f99b06196cf29dbc1.json‎

Lines changed: 20 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/database/migrations/0007_oidc_client_registry.sql‎

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,42 @@ SELECT uuidv7(), id, client_secret_hash, created_at
2626
FROM oidc_clients
2727
WHERE client_secret_hash IS NOT NULL;
2828

29+
-- The previous release keeps writing client_secret_hash directly while it runs:
30+
-- at startup it registers its file's clients, and an old replica may restart during
31+
-- a deploy or after a rollback. Mirror those writes, so the new release never takes
32+
-- a confidential client for a public one. Auth's own writes insert the secret row in
33+
-- the same statement, so they match an existing secret and change nothing here. A
34+
-- legacy write of a new hash replaces the previous secrets at once, as it used to.
35+
-- A legacy write that clears the hash changes nothing: the client stays
36+
-- confidential, and fails closed.
37+
CREATE FUNCTION oidc_clients_mirror_legacy_secret() RETURNS trigger
38+
LANGUAGE plpgsql AS $$
39+
BEGIN
40+
IF NOT EXISTS (
41+
SELECT 1 FROM oidc_client_secrets
42+
WHERE client_id = NEW.id AND secret_digest = NEW.client_secret_hash
43+
) THEN
44+
UPDATE oidc_clients SET client_type = 'confidential' WHERE id = NEW.id;
45+
UPDATE oidc_client_secrets SET expires_at = now()
46+
WHERE client_id = NEW.id AND (expires_at IS NULL OR expires_at > now());
47+
INSERT INTO oidc_client_secrets (id, client_id, secret_digest)
48+
VALUES (uuidv7(), NEW.id, NEW.client_secret_hash);
49+
END IF;
50+
RETURN NULL;
51+
END
52+
$$;
53+
CREATE TRIGGER oidc_clients_mirror_legacy_secret
54+
AFTER INSERT OR UPDATE OF client_secret_hash ON oidc_clients
55+
FOR EACH ROW WHEN (NEW.client_secret_hash IS NOT NULL)
56+
EXECUTE FUNCTION oidc_clients_mirror_legacy_secret();
57+
2958
-- The origin of each redirect URI, as browsers send it in an Origin header. A
3059
-- public client's authorization redirect origins may call the token and UserInfo
31-
-- endpoints, which look them up per request. Auth computes it on write; existing
32-
-- rows are HTTPS URLs without credentials, so their origin is the scheme and
33-
-- authority, lower-cased, without the default port. It stays nullable while the
34-
-- previous release, which does not write it, may still register clients.
60+
-- endpoints, which look them up per request. Auth computes it on write. Existing
61+
-- rows, and rows the previous release writes, have none: `auth-service migrate`
62+
-- fills them in after the migrations, with the URL parser browsers' origins follow
63+
-- (`OidcRepository::fill_redirect_origins`), which SQL cannot reproduce.
3564
ALTER TABLE oidc_redirect_uris ADD COLUMN origin TEXT;
36-
UPDATE oidc_redirect_uris
37-
SET origin = regexp_replace(lower(substring(uri FROM '^[A-Za-z]+://[^/?#]+')), ':443$', '');
3865
CREATE INDEX oidc_redirect_uris_origin_idx ON oidc_redirect_uris (origin)
3966
WHERE kind = 'authorization';
4067

@@ -45,5 +72,6 @@ CREATE INDEX oidc_redirect_uris_origin_idx ON oidc_redirect_uris (origin)
4572
-- PENDING CONTRACT: oidc_clients.client_secret_hash stays, and auth keeps it equal
4673
-- to a confidential client's newest secret, because the previous release
4774
-- authenticates clients with it, and would take a confidential client without it
48-
-- for a public one. Once no deployed release reads it, a new migration must
49-
-- DROP COLUMN client_secret_hash and make oidc_redirect_uris.origin NOT NULL.
75+
-- for a public one. Once no deployed release reads or writes it, a new migration
76+
-- must drop the oidc_clients_mirror_legacy_secret trigger and function, DROP COLUMN
77+
-- client_secret_hash, and make oidc_redirect_uris.origin NOT NULL.

‎crates/database/src/connection/mod.rs‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -190,17 +190,20 @@ impl Database {
190190
.map_err(Into::into)
191191
}
192192

193-
/// Runs schema migrations when explicitly requested through the auth binary.
193+
/// Runs schema migrations when explicitly requested through the auth binary,
194+
/// then fills in the data they leave to Rust: redirect URI origins.
194195
///
195196
/// # Errors
196197
///
197198
/// Returns [`DatabaseError::Operation`] if a migration fails or the applied
198-
/// history differs from the embedded migrations.
199+
/// history differs from the embedded migrations, or another [`DatabaseError`]
200+
/// if filling in data fails.
199201
pub async fn run_migrations(&self) -> Result<(), DatabaseError> {
200202
sqlx::migrate!("./migrations")
201203
.run(&self.pool)
202204
.await
203-
.map_err(|error| DatabaseError::Operation(Box::new(error)))
205+
.map_err(|error| DatabaseError::Operation(Box::new(error)))?;
206+
self.oidc().fill_redirect_origins().await
204207
}
205208
}
206209

‎crates/database/src/repositories/oidc/clients.rs‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use piquel_common::{
1616
};
1717
use serde::Serialize;
1818
use sqlx::types::Json;
19+
use url::Url;
1920

2021
/// A registered client with its exact URI allowlists.
2122
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
@@ -296,6 +297,46 @@ impl OidcRepository<'_> {
296297
)
297298
}
298299

300+
/// Fills in the origin of redirect URIs that have none: those registered before
301+
/// migration `0007`, or by the previous release since. Origins are serialized
302+
/// by the same URL parser as on registration, which SQL cannot reproduce for
303+
/// forms such as `https://app.example:0443/` or Unicode hosts. A URI without a
304+
/// tuple origin keeps none, and allows no browser origin.
305+
///
306+
/// # Errors
307+
///
308+
/// Returns [`DatabaseError`] if a query fails.
309+
pub async fn fill_redirect_origins(&mut self) -> Result<(), DatabaseError> {
310+
let missing = run!(
311+
self,
312+
fetch_all,
313+
sqlx::query_scalar!("SELECT DISTINCT uri FROM oidc_redirect_uris WHERE origin IS NULL")
314+
)?;
315+
let (uris, origins): (Vec<String>, Vec<String>) = missing
316+
.into_iter()
317+
.filter_map(|uri| {
318+
let origin = Url::parse(&uri).ok()?.origin();
319+
origin
320+
.is_tuple()
321+
.then(|| (uri, origin.ascii_serialization()))
322+
})
323+
.unzip();
324+
run!(
325+
self,
326+
execute,
327+
sqlx::query!(
328+
"UPDATE oidc_redirect_uris r
329+
SET origin = f.origin
330+
FROM unnest($1::text[], $2::text[]) AS f(uri, origin)
331+
WHERE r.uri = f.uri
332+
AND r.origin IS NULL",
333+
&uris,
334+
&origins,
335+
)
336+
)?;
337+
Ok(())
338+
}
339+
299340
/// Whether an enabled public client has an authorization redirect URI on
300341
/// `origin`, serialized as browsers send it in an `Origin` header.
301342
///

‎crates/database/src/repositories/oidc/tests.rs‎

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,8 @@ async fn public_client_origins_follow_registrations() {
155155
}
156156

157157
/// Clients the startup file registered keep working after the migration: a
158-
/// confidential client keeps its secret, and redirect origins are filled in.
158+
/// confidential client keeps its secret, redirect origins are filled in as URL
159+
/// parsing serializes them, and the previous release's writes are mirrored.
159160
/// It runs in a scratch schema, since the test database is migrated.
160161
#[tokio::test]
161162
#[ignore = "requires a disposable TEST_DATABASE_URL"]
@@ -187,7 +188,9 @@ async fn migration_keeps_file_clients_and_their_secrets() {
187188
"INSERT INTO oidc_clients (id, display_name, allowed_scopes, allowed_audiences)
188189
VALUES ('web', 'Web', '[\"openid\"]', '[\"web\"]');
189190
INSERT INTO oidc_redirect_uris (client_id, uri, kind)
190-
VALUES ('web', 'https://Web.Example:443/callback', 'authorization');",
191+
VALUES
192+
('web', 'https://Web.Example:0443/callback', 'authorization'),
193+
('web', 'https://bücher.example/callback', 'authorization');",
191194
)
192195
.execute(&mut connection)
193196
.await
@@ -208,7 +211,27 @@ async fn migration_keeps_file_clients_and_their_secrets() {
208211
.await
209212
.expect("migration");
210213

214+
// The previous release, still running, registers a confidential client.
215+
let legacy = [8_u8; 32];
216+
sqlx::query(
217+
"INSERT INTO oidc_clients (
218+
id, display_name, allowed_scopes, allowed_audiences, client_secret_hash
219+
) VALUES ('legacy', 'Legacy', '[\"openid\"]', '[\"legacy\"]', $1)",
220+
)
221+
.bind(legacy.as_slice())
222+
.execute(&mut connection)
223+
.await
224+
.expect("legacy confidential client");
225+
// It then restarts with a new secret in its file, which replaces the old one.
226+
let replaced = [7_u8; 32];
227+
sqlx::query("UPDATE oidc_clients SET client_secret_hash = $1 WHERE id = 'legacy'")
228+
.bind(replaced.as_slice())
229+
.execute(&mut connection)
230+
.await
231+
.expect("legacy secret change");
232+
211233
let mut oidc = OidcRepository::from_connection(&mut connection);
234+
oidc.fill_redirect_origins().await.expect("origins");
212235
let kind = async |oidc: &mut OidcRepository<'_>, id| {
213236
oidc.find_client(id)
214237
.await
@@ -222,11 +245,17 @@ async fn migration_keeps_file_clients_and_their_secrets() {
222245
oidc.active_secret_digests("api").await.expect("secrets"),
223246
[digest.to_vec()]
224247
);
225-
assert!(
226-
oidc.public_client_origin("https://web.example")
227-
.await
228-
.expect("origin")
248+
assert_eq!(kind(&mut oidc, "legacy").await, ClientKind::Confidential);
249+
assert_eq!(
250+
oidc.active_secret_digests("legacy").await.expect("secrets"),
251+
[replaced.to_vec()]
229252
);
253+
for origin in ["https://web.example", "https://xn--bcher-kva.example"] {
254+
assert!(
255+
oidc.public_client_origin(origin).await.expect("origin"),
256+
"{origin}"
257+
);
258+
}
230259
sqlx::raw_sql(&format!("DROP SCHEMA {schema} CASCADE"))
231260
.execute(&mut connection)
232261
.await

‎docs/architecture/database-crate.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,10 @@ Migration `0005` imports the log but keeps the table, which the previous release
137137
writes to during a deploy; a later release imports the rows written since and
138138
drops it. Migration `0007` likewise keeps `oidc_clients.client_secret_hash`, which
139139
auth keeps equal to a confidential client's newest secret for the previous
140-
release; a later release drops it and makes `oidc_redirect_uris.origin` NOT NULL.
140+
release, and a trigger mirrors the previous release's writes to it into
141+
`oidc_client_secrets`. Redirect URI origins need URL parsing, so `run_migrations`
142+
fills in the ones the previous release leaves empty. A later release drops the
143+
trigger and the column, and makes `oidc_redirect_uris.origin` NOT NULL.
141144

142145
Variants hold only typed IDs, enums, scopes, timestamps and counts, so a secret,
143146
token, `WebAuthn` state or raw header cannot end up in one. Anything that identifies

0 commit comments

Comments
 (0)