Skip to content

Commit eb063cf

Browse files
PiquelChipsclaude
andcommitted
feat(auth): store OIDC clients in PostgreSQL and remove AUTH_CLIENTS_FILE
Clients are registered and changed at runtime with `auth-service client` instead of being copied from a JSON file at every startup. - Typed registration (`piquel_common::clients`): every field validates itself and names the rejected value. `ClientId` is now validated. - `ClientRegistry` is the one place that creates, updates, enables, disables and rotates clients, recording each change as a domain event. - Clients can hold several secrets; rotation caps earlier secrets at a grace period. Auth generates `pqcs_` secrets and stores SHA-256 digests. - CORS for public clients is looked up per request, so changes apply at once on every replica. - Migration 0007 moves secrets into `oidc_client_secrets` and adds `client_type` and redirect origins, keeping `client_secret_hash` (dual-written) for the previous release. - Startup refuses a set AUTH_CLIENTS_FILE; `auth-service secret` and `just auth secret` are removed. Closes #42 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 829224d commit eb063cf

61 files changed

Lines changed: 2946 additions & 1090 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -194,20 +194,6 @@ jobs:
194194
run: |
195195
just auth generate-key "$RUNNER_TEMP/key.pem"
196196
export AUTH_KEY_PROVIDER="file://$RUNNER_TEMP/key.pem"
197-
export AUTH_CLIENTS_FILE="$RUNNER_TEMP/clients.json"
198-
cat > "$AUTH_CLIENTS_FILE" <<'EOF'
199-
[
200-
{
201-
"id": "browser-e2e",
202-
"display_name": "Browser E2E",
203-
"redirect_uris": ["https://localhost:4443/callback"],
204-
"post_logout_uris": ["https://localhost:4443/settings"],
205-
"allowed_scopes": ["openid", "profile", "email"],
206-
"allow_refresh": false,
207-
"trusted": false
208-
}
209-
]
210-
EOF
211197
cat > "$RUNNER_TEMP/Caddyfile" <<'EOF'
212198
{
213199
auto_https disable_redirects
@@ -222,6 +208,7 @@ jobs:
222208
EOF
223209
docker run --detach --name caddy --network host --volume "$RUNNER_TEMP/Caddyfile:/etc/caddy/Caddyfile:ro" caddy:2-alpine
224210
target/debug/auth-service migrate
211+
just web browser-client https://localhost:4443
225212
target/debug/auth-service serve > "$RUNNER_TEMP/auth.log" 2>&1 &
226213
AUTH_ORIGIN="$E2E_AUTH_URL" ORIGIN=https://localhost:4443 HOST=127.0.0.1 PORT=4173 node apps/piquel-web/build > "$RUNNER_TEMP/settings.log" 2>&1 &
227214
curl -kfsS --retry 30 --retry-delay 1 --retry-all-errors "$E2E_AUTH_URL/health/ready"

‎README.md‎

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,6 @@ piquel-web with Vite against an auth service on `http://localhost:3000`.
5151
| `AUTH_PUBLIC_LISTENER` | Listener address; defaults to `127.0.0.1:8080` |
5252
| `AUTH_KEY_PROVIDER` | Required persistent RSA private-key reference, `file:///absolute/path/key.pem` or `env://VARIABLE_NAME` |
5353
| `AUTH_SIGNING_KEY_ID` | Stable ID for that signing key; defaults to `primary` |
54-
| `AUTH_CLIENTS_FILE` | JSON client configuration; omitted means no OIDC clients |
5554
| `AUTH_INVITE_REQUIRED` | `true` by default; set `false` to allow public registration |
5655
| `AUTH_GITHUB_CLIENT_ID`, `AUTH_GITHUB_CLIENT_SECRET` | Both required to enable GitHub; secret is an env/file reference |
5756
| `AUTH_GOOGLE_CLIENT_ID`, `AUTH_GOOGLE_CLIENT_SECRET` | Both required to enable Google; secret is an env/file reference |
@@ -115,27 +114,41 @@ behind it. See `docs/architecture/delivery-queue.md`.
115114

116115
### OIDC clients
117116

118-
`AUTH_CLIENTS_FILE` is authoritative: startup disables clients omitted from it.
119-
Client IDs must be unique. A minimal public web client looks like:
120-
121-
```json
122-
[
123-
{
124-
"id": "piquel-web",
125-
"display_name": "Piquel",
126-
"redirect_uris": ["https://piquel.fr/callback"],
127-
"post_logout_uris": ["https://piquel.fr/"],
128-
"allowed_scopes": ["openid", "profile", "email"],
129-
"trusted": true,
130-
"allow_refresh": false
131-
}
132-
]
117+
Clients live in the database. Register and change them with `auth-service client`
118+
(`just auth client` here). A change applies to the next request on every replica,
119+
without a restart, and is recorded as an event attributed to the operator.
120+
121+
```sh
122+
just auth client create piquel-web --name Piquel --trusted \
123+
--redirect-uri https://piquel.fr/callback --post-logout-uri https://piquel.fr/
124+
just auth client create notes --name Notes --confidential --refresh \
125+
--redirect-uri https://notes.example/callback --scope openid --scope notes:read
126+
just auth client list # --output json for scripts
127+
just auth client show notes # registration and secret lifetimes
128+
just auth client update piquel-web --add-redirect-uri https://piquel.fr/auth/callback
129+
just auth client disable notes # enable undoes it
130+
just auth client rotate-secret notes --grace 24h
133131
```
134132

135-
For a confidential backend client, add `"client_secret": "env://MY_CLIENT_SECRET"`.
136-
Generate its random secret with `just auth secret`. Clients use
137-
`client_secret_basic` when confidential and `none` when public; both require S256
138-
PKCE. Redirect URLs must match exactly and use HTTPS.
133+
Clients are public by default and authenticate with PKCE alone (`none`).
134+
Confidential clients (`--confidential`) use `client_secret_basic` with a secret
135+
that auth generates; both require S256 PKCE. `create` and `rotate-secret` print
136+
the secret once, and auth stores only its SHA-256 digest. Secrets start with
137+
`pqcs_` so secret scanners can recognize them. After `rotate-secret`, the earlier
138+
secrets keep working for the grace period (24 hours by default, at most 30 days;
139+
`--grace 0` revokes them at once), so the client can switch without downtime.
140+
141+
Redirect URIs must match exactly. They use HTTPS, or HTTP on a loopback IP for
142+
native apps, without credentials or a fragment, and are written as URL parsing
143+
normalizes them: `https://app.example/`, not `https://APP.example`. The origins of
144+
an enabled public client's redirect URIs may call the token, revocation and
145+
userinfo endpoints from a browser. Scopes default to `openid`, `profile` and
146+
`email`. `--refresh` allows refresh tokens when the client also requests
147+
`offline_access`; `--trusted` skips the consent screen and is meant for
148+
first-party clients only.
149+
150+
`AUTH_CLIENTS_FILE` was removed, and startup refuses to run while it is set. The
151+
clients it registered are already in the database.
139152

140153
Discovery is served at both `/.well-known/openid-configuration` (OIDC) and
141154
`/.well-known/oauth-authorization-server` (RFC 8414, read by OAuth-only and MCP

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

Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
//! The one place that changes OIDC client registrations. Each change commits with
2+
//! the event that records it. The `client` command uses it; the owner API (#43),
3+
//! dynamic registration (#44) and the admin API (#38) will too.
4+
//!
5+
//! Nothing is cached: every request reads the registration it needs from the
6+
//! database, so a change applies to the next request on every replica.
7+
8+
use chrono::Duration;
9+
use piquel_common::{
10+
ClientId,
11+
clients::{ClientKind, ClientRegistration},
12+
events::{DomainEvent, EventContext},
13+
};
14+
use piquel_crypto::{ClientSecret, CryptoError};
15+
use piquel_repository::{Database, DatabaseError};
16+
use thiserror::Error;
17+
18+
/// Creates, updates, enables, disables and rotates the secrets of clients.
19+
#[derive(Clone)]
20+
pub struct ClientRegistry {
21+
/// Where registrations and their events are stored.
22+
database: Database,
23+
}
24+
25+
/// Why a client change was refused.
26+
#[derive(Debug, Error)]
27+
pub enum ClientRegistryError {
28+
/// Another client has this ID.
29+
#[error("a client with ID {id} already exists")]
30+
Exists {
31+
/// The requested ID.
32+
id: ClientId,
33+
/// The uniqueness violation.
34+
#[source]
35+
source: DatabaseError,
36+
},
37+
/// No client has this ID.
38+
#[error("no client has ID {0}")]
39+
Unknown(ClientId),
40+
/// Public clients authenticate without a secret.
41+
#[error("client {0} is public, so it has no secret")]
42+
Public(ClientId),
43+
/// A secret could not be generated.
44+
#[error("could not generate a client secret")]
45+
Crypto(#[from] CryptoError),
46+
/// The database failed.
47+
#[error("client registration database operation failed")]
48+
Database(#[from] DatabaseError),
49+
}
50+
51+
impl ClientRegistryError {
52+
/// Reports `NotFound` as an unknown client `id`.
53+
fn lookup(id: &ClientId) -> impl FnOnce(DatabaseError) -> Self {
54+
move |error| match error {
55+
DatabaseError::NotFound => Self::Unknown(id.clone()),
56+
error => error.into(),
57+
}
58+
}
59+
}
60+
61+
impl ClientRegistry {
62+
/// Changes the registrations stored in `database`.
63+
#[must_use]
64+
pub const fn new(database: Database) -> Self {
65+
Self { database }
66+
}
67+
68+
/// Registers an enabled client. A confidential client gets its first secret,
69+
/// returned here once; only its digest is stored.
70+
///
71+
/// # Errors
72+
/// Fails if the ID is taken, a secret cannot be generated or the database fails.
73+
pub async fn create(
74+
&self,
75+
context: &EventContext,
76+
registration: &ClientRegistration,
77+
) -> Result<Option<ClientSecret>, ClientRegistryError> {
78+
let mut tx = self.database.begin().await?;
79+
tx.oidc()
80+
.create_client(registration)
81+
.await
82+
.map_err(|error| match error {
83+
DatabaseError::Conflict(_) => ClientRegistryError::Exists {
84+
id: registration.id.clone(),
85+
source: error,
86+
},
87+
error => error.into(),
88+
})?;
89+
let secret = match registration.kind {
90+
ClientKind::Public => None,
91+
ClientKind::Confidential => {
92+
let secret = ClientSecret::generate()?;
93+
tx.oidc()
94+
.insert_client_secret(&registration.id, secret.digest().as_bytes())
95+
.await?;
96+
Some(secret)
97+
}
98+
};
99+
tx.record(
100+
context,
101+
None,
102+
DomainEvent::ClientRegistered {
103+
client_id: registration.id.clone(),
104+
kind: registration.kind,
105+
},
106+
)
107+
.await?;
108+
tx.commit().await?;
109+
Ok(secret)
110+
}
111+
112+
/// Replaces a client's registration. Its enabled state and secrets stay.
113+
///
114+
/// # Errors
115+
/// Fails if the client does not exist or the database fails.
116+
pub async fn update(
117+
&self,
118+
context: &EventContext,
119+
registration: &ClientRegistration,
120+
) -> 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))?;
126+
tx.record(
127+
context,
128+
None,
129+
DomainEvent::ClientUpdated {
130+
client_id: registration.id.clone(),
131+
},
132+
)
133+
.await?;
134+
tx.commit().await?;
135+
Ok(())
136+
}
137+
138+
/// Enables or disables a client. A client already in that state records nothing.
139+
///
140+
/// # Errors
141+
/// Fails if the client does not exist or the database fails.
142+
pub async fn set_enabled(
143+
&self,
144+
context: &EventContext,
145+
id: &ClientId,
146+
enabled: bool,
147+
) -> Result<(), ClientRegistryError> {
148+
let mut tx = self.database.begin().await?;
149+
let changed = tx
150+
.oidc()
151+
.set_client_enabled(id, enabled)
152+
.await
153+
.map_err(ClientRegistryError::lookup(id))?;
154+
if changed {
155+
let client_id = id.clone();
156+
let event = if enabled {
157+
DomainEvent::ClientEnabled { client_id }
158+
} else {
159+
DomainEvent::ClientDisabled { client_id }
160+
};
161+
tx.record(context, None, event).await?;
162+
}
163+
tx.commit().await?;
164+
Ok(())
165+
}
166+
167+
/// Gives a confidential client a new secret, returned here once. Its earlier
168+
/// secrets keep working for `grace` at most, so it can redeploy in between;
169+
/// zero revokes them now.
170+
///
171+
/// # Errors
172+
/// Fails if the client does not exist or is public, a secret cannot be
173+
/// generated or the database fails.
174+
pub async fn rotate_secret(
175+
&self,
176+
context: &EventContext,
177+
id: &ClientId,
178+
grace: Duration,
179+
) -> Result<ClientSecret, ClientRegistryError> {
180+
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()))?;
186+
if client.kind == ClientKind::Public {
187+
return Err(ClientRegistryError::Public(client.id));
188+
}
189+
let secret = ClientSecret::generate()?;
190+
let previous_expire_at = tx.oidc().cap_client_secrets(id, grace).await?;
191+
tx.oidc()
192+
.insert_client_secret(id, secret.digest().as_bytes())
193+
.await?;
194+
tx.record(
195+
context,
196+
None,
197+
DomainEvent::ClientSecretRotated {
198+
client_id: client.id,
199+
previous_expire_at,
200+
},
201+
)
202+
.await?;
203+
tx.commit().await?;
204+
Ok(secret)
205+
}
206+
}
207+
208+
/// Changes made while auth serves requests apply to the next request.
209+
#[cfg(test)]
210+
mod tests;

0 commit comments

Comments
 (0)