Skip to content

Commit 91f3667

Browse files
PiquelChipsclaude
andcommitted
fix(auth): lock clients across reads and writes, refuse kind changes
`ClientRegistry::update` now edits the stored client under a row lock, so concurrent updates cannot undo each other, and refuses to change a client's ID or kind. `rotate_secret` locks the client too, so two rotations cannot leave a secret without an expiry. Documents the previous release's startup behaviour and 0007's pending contract. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent eb063cf commit 91f3667

10 files changed

Lines changed: 163 additions & 63 deletions

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

Lines changed: 50 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use piquel_common::{
1212
events::{DomainEvent, EventContext},
1313
};
1414
use piquel_crypto::{ClientSecret, CryptoError};
15-
use piquel_repository::{Database, DatabaseError};
15+
use piquel_repository::{Database, DatabaseError, DatabaseTransaction, StoredOidcClient};
1616
use thiserror::Error;
1717

1818
/// Creates, updates, enables, disables and rotates the secrets of clients.
@@ -40,6 +40,10 @@ pub enum ClientRegistryError {
4040
/// Public clients authenticate without a secret.
4141
#[error("client {0} is public, so it has no secret")]
4242
Public(ClientId),
43+
/// An update changed the client's ID or kind, which would orphan its grants
44+
/// or secrets.
45+
#[error("client {0}'s ID and kind cannot change; register a new client instead")]
46+
Immutable(ClientId),
4347
/// A secret could not be generated.
4448
#[error("could not generate a client secret")]
4549
Crypto(#[from] CryptoError),
@@ -109,20 +113,40 @@ impl ClientRegistry {
109113
Ok(secret)
110114
}
111115

112-
/// Replaces a client's registration. Its enabled state and secrets stay.
116+
/// Replaces client `id`'s registration with what `edit` makes of the stored one.
117+
/// The client stays locked from the read to the write, so concurrent updates
118+
/// cannot undo each other. Its ID, kind, enabled state and secrets stay.
113119
///
114120
/// # Errors
115-
/// Fails if the client does not exist or the database fails.
116-
pub async fn update(
121+
/// Fails if the client does not exist, `edit` fails or changes the ID or kind,
122+
/// or the database fails.
123+
pub async fn update<E: From<ClientRegistryError>>(
117124
&self,
118125
context: &EventContext,
126+
id: &ClientId,
127+
edit: impl FnOnce(StoredOidcClient) -> Result<ClientRegistration, E>,
128+
) -> Result<(), E> {
129+
let mut tx = self
130+
.database
131+
.begin()
132+
.await
133+
.map_err(ClientRegistryError::from)?;
134+
let current = Self::locked(&mut tx, id).await?;
135+
let kind = current.kind;
136+
let registration = edit(current)?;
137+
if registration.id != *id || registration.kind != kind {
138+
return Err(ClientRegistryError::Immutable(id.clone()).into());
139+
}
140+
Ok(Self::replace(tx, context, &registration).await?)
141+
}
142+
143+
/// Writes an update checked by [`Self::update`] and records it.
144+
async fn replace(
145+
mut tx: DatabaseTransaction<'_>,
146+
context: &EventContext,
119147
registration: &ClientRegistration,
120148
) -> Result<(), ClientRegistryError> {
121-
let mut tx = self.database.begin().await?;
122-
tx.oidc()
123-
.update_client(registration)
124-
.await
125-
.map_err(ClientRegistryError::lookup(&registration.id))?;
149+
tx.oidc().update_client(registration).await?;
126150
tx.record(
127151
context,
128152
None,
@@ -178,11 +202,8 @@ impl ClientRegistry {
178202
grace: Duration,
179203
) -> Result<ClientSecret, ClientRegistryError> {
180204
let mut tx = self.database.begin().await?;
181-
let client = tx
182-
.oidc()
183-
.find_client(id.as_str())
184-
.await?
185-
.ok_or_else(|| ClientRegistryError::Unknown(id.clone()))?;
205+
// Locked, so a concurrent rotation cannot insert a secret this cap misses.
206+
let client = Self::locked(&mut tx, id).await?;
186207
if client.kind == ClientKind::Public {
187208
return Err(ClientRegistryError::Public(client.id));
188209
}
@@ -203,6 +224,21 @@ impl ClientRegistry {
203224
tx.commit().await?;
204225
Ok(secret)
205226
}
227+
228+
/// Locks client `id` for the rest of `tx`, then reads it.
229+
async fn locked(
230+
tx: &mut DatabaseTransaction<'_>,
231+
id: &ClientId,
232+
) -> Result<StoredOidcClient, ClientRegistryError> {
233+
tx.oidc()
234+
.lock_client(id)
235+
.await
236+
.map_err(ClientRegistryError::lookup(id))?;
237+
tx.oidc()
238+
.find_client(id.as_str())
239+
.await?
240+
.ok_or_else(|| ClientRegistryError::Unknown(id.clone()))
241+
}
206242
}
207243

208244
/// Changes made while auth serves requests apply to the next request.

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

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,12 @@ async fn changes_apply_to_the_next_request_on_every_replica() {
7777
client.redirect_uris =
7878
RedirectUris::new([format!("{second}/callback").parse().expect("callback")])
7979
.expect("one callback");
80-
registry.update(&operator(), &client).await.expect("update");
80+
registry
81+
.update(&operator(), &client.id, |_| {
82+
Ok::<_, ClientRegistryError>(client.clone())
83+
})
84+
.await
85+
.expect("update");
8186
assert!(
8287
!cors(&replicas.a, &first).await,
8388
"the old origin is dropped"
@@ -185,6 +190,17 @@ async fn rotated_secrets_overlap_until_their_grace_period_ends() {
185190
registry.create(&operator(), &public).await,
186191
Err(ClientRegistryError::Exists { .. })
187192
));
193+
assert!(matches!(
194+
registry
195+
.update(&operator(), &public.id, |_| {
196+
Ok(ClientRegistration {
197+
kind: ClientKind::Confidential,
198+
..public.clone()
199+
})
200+
})
201+
.await,
202+
Err(ClientRegistryError::Immutable(_))
203+
));
188204
assert!(matches!(
189205
registry
190206
.set_enabled(&operator(), &"unknown-client".parse().expect("ID"), false)

‎apps/auth-service/src/main.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -343,8 +343,10 @@ impl ClientCommand {
343343
println!("{}", serde_json::to_string_pretty(&details)?);
344344
}
345345
Self::Update(update) => {
346-
let client = Self::find(&database, &update.id).await?;
347-
registry.update(&context, &update.apply(client)?).await?;
346+
let id = update.id.clone();
347+
registry
348+
.update(&context, &id, |client| update.apply(client))
349+
.await?;
348350
}
349351
Self::Disable { id } => registry.set_enabled(&context, &id, false).await?,
350352
Self::Enable { id } => registry.set_enabled(&context, &id, true).await?,

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -763,8 +763,11 @@ async fn policy_reduction_blocks_outstanding_codes_and_refresh() {
763763
flow.client.allowed_scopes =
764764
AllowedScopes::new([Scope::OpenId, Scope::OfflineAccess].map(ScopeName::from))
765765
.expect("reduced scopes");
766+
let client = flow.client.clone();
766767
registry
767-
.update(&crate::tests::operator(), &flow.client)
768+
.update(&crate::tests::operator(), &client.id, |_| {
769+
Ok::<_, crate::ClientRegistryError>(client.clone())
770+
})
768771
.await
769772
.expect("apply reduced client scope policy");
770773
assert_eq!(
@@ -781,8 +784,11 @@ async fn policy_reduction_blocks_outstanding_codes_and_refresh() {
781784
let code = flow.code(REFRESH_SCOPES).await;
782785
let tokens = Flow::json(flow.exchange(&code, Flow::verifier(), None).await).await;
783786
flow.client.allow_refresh = false;
787+
let client = flow.client.clone();
784788
registry
785-
.update(&crate::tests::operator(), &flow.client)
789+
.update(&crate::tests::operator(), &client.id, |_| {
790+
Ok::<_, crate::ClientRegistryError>(client.clone())
791+
})
786792
.await
787793
.expect("disable client refresh permission");
788794
assert_eq!(

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

Lines changed: 22 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-6c4a75877ddf9ef28ed475d2845a3a90da618e35fc96ac13b82337df5f908ef5.json‎

Lines changed: 0 additions & 30 deletions
This file was deleted.

‎crates/database/.sqlx/query-7f812ce248ed9804d473c66c8bcf12ebfb0907138ae47648fabc7643a0c39334.json‎

Lines changed: 29 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: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ SET origin = regexp_replace(lower(substring(uri FROM '^[A-Za-z]+://[^/?#]+')), '
3838
CREATE INDEX oidc_redirect_uris_origin_idx ON oidc_redirect_uris (origin)
3939
WHERE kind = 'authorization';
4040

41+
-- The previous release still disables every client it does not find in its
42+
-- AUTH_CLIENTS_FILE whenever it starts. Register clients with the new release only
43+
-- once no previous replica can restart, and re-enable them after a rollback.
44+
--
4145
-- PENDING CONTRACT: oidc_clients.client_secret_hash stays, and auth keeps it equal
4246
-- to a confidential client's newest secret, because the previous release
4347
-- authenticates clients with it, and would take a confidential client without it

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

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,8 @@ impl OidcRepository<'_> {
131131
Ok(())
132132
}
133133

134-
/// Replaces a client's registration and redirect URIs. Its enabled state,
135-
/// secrets and audiences stay.
134+
/// Replaces a client's registration and redirect URIs. Its kind, enabled state,
135+
/// secrets and audiences stay: `ClientRegistry` refuses to change a kind.
136136
///
137137
/// # Errors
138138
///
@@ -144,28 +144,23 @@ impl OidcRepository<'_> {
144144
) -> Result<(), DatabaseError> {
145145
let redirects = RedirectRows::new(registration);
146146
// Every CTE runs; the statement returns the updated ID, so an unknown client
147-
// is `NotFound`. A public client clears the previous release's secret column.
147+
// is `NotFound`.
148148
run!(
149149
self,
150150
fetch_one,
151151
sqlx::query_scalar!(
152152
"WITH client AS (
153153
UPDATE oidc_clients
154154
SET display_name = $2,
155-
client_type = $3,
156-
allowed_scopes = $4,
157-
allow_refresh = $5,
158-
trusted = $6,
159-
client_secret_hash = CASE
160-
WHEN $3 = 'public' THEN NULL
161-
ELSE client_secret_hash
162-
END,
155+
allowed_scopes = $3,
156+
allow_refresh = $4,
157+
trusted = $5,
163158
updated_at = now()
164159
WHERE id = $1
165160
RETURNING id
166161
),
167162
desired (uri, kind, origin) AS (
168-
SELECT * FROM unnest($7::text[], $8::text[], $9::text[])
163+
SELECT * FROM unnest($6::text[], $7::text[], $8::text[])
169164
),
170165
upserted AS (
171166
INSERT INTO oidc_redirect_uris (client_id, uri, kind, origin)
@@ -184,7 +179,6 @@ impl OidcRepository<'_> {
184179
SELECT id FROM client",
185180
registration.id.as_str(),
186181
registration.display_name.as_str(),
187-
registration.kind.as_str(),
188182
Json(Self::scopes(registration)) as _,
189183
registration.allow_refresh,
190184
registration.trusted,
@@ -232,6 +226,25 @@ impl OidcRepository<'_> {
232226
)
233227
}
234228

229+
/// Locks a client's row until the transaction ends, so changes that read the
230+
/// client before writing it, such as an update or a rotation, run one at a time.
231+
///
232+
/// # Errors
233+
///
234+
/// Returns [`DatabaseError::NotFound`] for an unknown client, or another
235+
/// [`DatabaseError`] if the query fails.
236+
pub async fn lock_client(&mut self, id: &ClientId) -> Result<(), DatabaseError> {
237+
run!(
238+
self,
239+
fetch_one,
240+
sqlx::query_scalar!(
241+
"SELECT id FROM oidc_clients WHERE id = $1 FOR UPDATE",
242+
id.as_str(),
243+
)
244+
)?;
245+
Ok(())
246+
}
247+
235248
/// Finds a client, enabled or not, with its URI allowlists.
236249
///
237250
/// # Errors

‎docs/architecture/database-crate.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,9 @@ read back. `repositories/events/` stores events: the personal data split below,
135135
`read_after` and `acknowledge`.
136136
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
138-
drops it.
138+
drops it. Migration `0007` likewise keeps `oidc_clients.client_secret_hash`, which
139+
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.
139141

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

0 commit comments

Comments
 (0)