Skip to content

Commit c9bee61

Browse files
PiquelChipsclaude
andcommitted
refactor(auth): define each admin and settings API body once
The database crate repeated three admin API bodies field for field, and the admin API repeated the settings API's passkey, identity and error bodies and its confirmation age. The bodies both APIs return now live in `piquel-auth-protocol`, admin-only queries decode straight into the admin API's bodies, and shared records convert into them with `From`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 8acf5f5 commit c9bee61

29 files changed

Lines changed: 287 additions & 448 deletions

‎Cargo.lock‎

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

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,13 @@ mod caller;
2626
mod error;
2727
/// The operations shared by the admin API and the CLI.
2828
mod operations;
29-
/// Validated inputs, and the API bodies built from stored records.
29+
/// Validated inputs.
3030
mod types;
3131

3232
pub use caller::Operator;
3333
use caller::{Admin, AdminTokens, ConfirmedAdmin};
3434
pub use error::AdminError;
3535
pub use operations::AdminOperations;
36-
use types::View;
3736
pub use types::{InvalidInviteExpiry, InviteExpiry, Reason};
3837

3938
/// Admin API routes and the operations behind them.

‎apps/auth-service/src/admin/operations.rs‎

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Every administrative operation, shared by the admin API and the CLI.
22
3-
use super::{AdminError, InviteExpiry, Operator, Reason, View};
3+
use super::{AdminError, InviteExpiry, Operator, Reason};
44
use chrono::Utc;
55
use piquel_admin_api::{
66
Administrator, Client, CreatedInvitation, Event, EventPage, EventSearch, Invitation,
@@ -115,10 +115,7 @@ impl AdminOperations {
115115
let next = (users.len() == usize::from(USER_PAGE_SIZE))
116116
.then(|| users.last().map(|user| user.id))
117117
.flatten();
118-
Ok(UserPage {
119-
users: users.into_iter().map(View::view).collect(),
120-
next,
121-
})
118+
Ok(UserPage { users, next })
122119
}
123120

124121
/// Returns an account's profile, emails, status, passkey labels, identities,
@@ -136,12 +133,12 @@ impl AdminOperations {
136133
.ok_or(AdminError::UserNotFound)?;
137134
let detail = UserDetail {
138135
administrator: tx.administrators().contains(user_id).await?,
139-
emails: Self::views(tx.emails().list_for_user(user_id).await?),
136+
emails: tx.emails().list_for_user(user_id).await?,
140137
passkeys: Self::views(tx.passkeys().list_active(user_id).await?),
141138
identities: Self::views(tx.federation().list_active(user_id).await?),
142-
sessions: Self::views(tx.sessions().list_active_for_user(user_id).await?),
143-
consents: Self::views(tx.oidc().list_consents(user_id).await?),
144-
user: user.view(),
139+
sessions: tx.sessions().list_active_for_user(user_id).await?,
140+
consents: tx.oidc().list_consents(user_id).await?,
141+
user: user.into(),
145142
};
146143
tx.record(
147144
&operator.context(),
@@ -153,9 +150,9 @@ impl AdminOperations {
153150
Ok(detail)
154151
}
155152

156-
/// Shows each stored record.
157-
fn views<S: View<T>, T>(records: Vec<S>) -> Vec<T> {
158-
records.into_iter().map(View::view).collect()
153+
/// Shows each stored record without what the API never returns.
154+
fn views<S: Into<T>, T>(records: Vec<S>) -> Vec<T> {
155+
records.into_iter().map(Into::into).collect()
159156
}
160157

161158
/// Disables an account and ends all its sessions and refresh grants in one
@@ -274,9 +271,7 @@ impl AdminOperations {
274271

275272
/// Lists invitations that have not been purged yet, newest first.
276273
pub(crate) async fn list_invitations(&self) -> Result<Vec<Invitation>, AdminError> {
277-
Ok(Self::views(
278-
self.database.security().list_invitations().await?,
279-
))
274+
Ok(self.database.security().list_invitations().await?)
280275
}
281276

282277
/// Creates a single-use signup link to the registration page on `origin`, auth's
@@ -334,7 +329,7 @@ impl AdminOperations {
334329
.oidc()
335330
.find_client(id)
336331
.await?
337-
.map(View::view)
332+
.map(Into::into)
338333
.ok_or(AdminError::ClientNotFound)
339334
}
340335

@@ -373,7 +368,7 @@ impl AdminOperations {
373368
/// # Errors
374369
/// Fails when the query fails.
375370
pub async fn list_administrators(&self) -> Result<Vec<Administrator>, AdminError> {
376-
Ok(Self::views(self.database.administrators().list().await?))
371+
Ok(self.database.administrators().list().await?)
377372
}
378373

379374
/// Makes the active account `user_id` an administrator. Administrators cannot

‎apps/auth-service/src/admin/types.rs‎

Lines changed: 1 addition & 123 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,7 @@
1-
//! Validated admin inputs, and the admin API's bodies built from stored records.
1+
//! Validated admin inputs.
22
33
use super::AdminError;
44
use chrono::Duration;
5-
use piquel_admin_api::{
6-
Administrator, Client, Consent, Email, Identity, Invitation, Passkey, Session, User,
7-
};
8-
use piquel_auth_protocol::oauth::ClientAuthMethod;
9-
use piquel_repository::{
10-
StoredAdministrator, StoredConsent, StoredEmail, StoredExternalIdentity, StoredInvitation,
11-
StoredOidcClient, StoredPasskey, StoredSession, StoredUser,
12-
};
135
use std::str::FromStr;
146
use thiserror::Error;
157

@@ -97,120 +89,6 @@ impl Reason {
9789
}
9890
}
9991

100-
/// Builds the admin API body that shows a stored record. A trait, since both
101-
/// types belong to other crates.
102-
pub(super) trait View<T> {
103-
/// The body showing `self`.
104-
fn view(self) -> T;
105-
}
106-
107-
impl View<User> for StoredUser {
108-
fn view(self) -> User {
109-
User {
110-
id: self.id,
111-
username: self.username,
112-
display_name: self.display_name,
113-
status: self.status,
114-
created_at: self.created_at,
115-
}
116-
}
117-
}
118-
119-
impl View<Email> for StoredEmail {
120-
fn view(self) -> Email {
121-
Email {
122-
address: self.normalized_email,
123-
verified_at: self.verified_at,
124-
primary: self.is_primary,
125-
}
126-
}
127-
}
128-
129-
impl View<Passkey> for StoredPasskey {
130-
/// Shows the label only, never the credential.
131-
fn view(self) -> Passkey {
132-
Passkey {
133-
id: self.id,
134-
name: self.friendly_name,
135-
}
136-
}
137-
}
138-
139-
impl View<Identity> for StoredExternalIdentity {
140-
fn view(self) -> Identity {
141-
Identity {
142-
provider: self.provider,
143-
email: self.linked_email,
144-
}
145-
}
146-
}
147-
148-
impl View<Session> for StoredSession {
149-
fn view(self) -> Session {
150-
Session {
151-
id: self.id,
152-
methods: self.authentication_methods,
153-
authenticated_at: self.authenticated_at,
154-
passkey_confirmed_at: self.passkey_confirmed_at,
155-
last_seen_at: self.last_seen_at,
156-
expires_at: self.expires_at,
157-
}
158-
}
159-
}
160-
161-
impl View<Consent> for StoredConsent {
162-
fn view(self) -> Consent {
163-
Consent {
164-
client_id: self.client_id,
165-
audience: self.audience,
166-
scopes: self.scopes,
167-
}
168-
}
169-
}
170-
171-
impl View<Invitation> for StoredInvitation {
172-
fn view(self) -> Invitation {
173-
Invitation {
174-
id: self.id,
175-
created_at: self.created_at,
176-
expires_at: self.expires_at,
177-
redeemed_at: self.redeemed_at,
178-
revoked_at: self.revoked_at,
179-
}
180-
}
181-
}
182-
183-
impl View<Client> for StoredOidcClient {
184-
/// Replaces the secret digest with the authentication method it implies.
185-
fn view(self) -> Client {
186-
Client {
187-
token_endpoint_auth_method: match self.client_secret_hash {
188-
Some(_) => ClientAuthMethod::ClientSecretBasic,
189-
None => ClientAuthMethod::None,
190-
},
191-
id: self.id,
192-
display_name: self.display_name,
193-
redirect_uris: self.redirect_uris,
194-
post_logout_uris: self.post_logout_uris,
195-
allowed_scopes: self.allowed_scopes,
196-
allowed_audiences: self.allowed_audiences,
197-
allow_refresh: self.allow_refresh,
198-
enabled: self.enabled,
199-
trusted: self.trusted,
200-
}
201-
}
202-
}
203-
204-
impl View<Administrator> for StoredAdministrator {
205-
fn view(self) -> Administrator {
206-
Administrator {
207-
user_id: self.user_id,
208-
username: self.username,
209-
granted_at: self.granted_at,
210-
}
211-
}
212-
}
213-
21492
#[cfg(test)]
21593
mod tests {
21694
//! Invitation lifetime parsing and reason bounds.

‎apps/auth-service/src/federation/identities.rs‎

Lines changed: 9 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use axum::{
88
http::{HeaderMap, StatusCode},
99
response::{IntoResponse, Response},
1010
};
11-
use piquel_auth_protocol::{TokenId, UserId};
11+
use piquel_auth_protocol::{TokenId, UserId, api::Identity};
1212
use piquel_repository::{
1313
Database, DatabaseTransaction, DomainEvent, EventContext, InsertExternalIdentity,
1414
PendingFederation, Personal, RevocationReason,
@@ -225,20 +225,14 @@ impl FederationApplication {
225225
pub(super) async fn list_identities(
226226
State(app): State<Self>,
227227
security::Session(session): security::Session,
228-
) -> Result<Json<Vec<SocialIdentityView>>, ApiError> {
229-
Ok(Json(
230-
app.database
231-
.federation()
232-
.list_active(session.user_id)
233-
.await
234-
.map_err(FederationError::from)?
235-
.into_iter()
236-
.map(|identity| SocialIdentityView {
237-
provider: identity.provider,
238-
linked_email: identity.linked_email,
239-
})
240-
.collect(),
241-
))
228+
) -> Result<Json<Vec<Identity>>, ApiError> {
229+
let identities = app
230+
.database
231+
.federation()
232+
.list_active(session.user_id)
233+
.await
234+
.map_err(FederationError::from)?;
235+
Ok(Json(identities.into_iter().map(Into::into).collect()))
242236
}
243237

244238
/// Removes an account's provider link after a recent passkey confirmation.
@@ -324,12 +318,3 @@ struct LinkResponse {
324318
/// Stored, validated continuation for the browser.
325319
return_to: String,
326320
}
327-
328-
/// Account settings view of an active social identity.
329-
#[derive(Serialize)]
330-
pub(super) struct SocialIdentityView {
331-
/// Linked provider.
332-
provider: Provider,
333-
/// Optional contact address observed at linking time.
334-
linked_email: Option<String>,
335-
}

‎apps/auth-service/src/passkey/mod.rs‎

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use axum::{
1010
response::{IntoResponse, Response},
1111
routing::{get, patch, post},
1212
};
13-
use piquel_auth_protocol::{AuthenticationMethod, PasskeyId, UserId};
13+
use piquel_auth_protocol::{AuthenticationMethod, PasskeyId, UserId, api};
1414
use piquel_crypto::Secret;
1515
use piquel_repository::{
1616
Actor, Database, DatabaseError, DatabaseTransaction, DomainEvent, EventContext, InsertPasskey,
@@ -39,7 +39,7 @@ pub use error::PasskeyConfigError;
3939
use error::PasskeyError;
4040
use types::{
4141
AuthenticationFinish, DisplayName, EnrollmentStart, LoginStart, PasskeyKind, PasskeyName,
42-
PasskeyView, RegistrationFinish, RegistrationStart, Rename, SessionView, UserView, Username,
42+
RegistrationFinish, RegistrationStart, Rename, SessionView, UserView, Username,
4343
};
4444

4545
/// Browser passkey ceremonies, passkey management and session confirmation.
@@ -767,19 +767,9 @@ impl PasskeyApplication {
767767
async fn list(
768768
State(app): State<Self>,
769769
security::Session(session): security::Session,
770-
) -> Result<Json<Vec<PasskeyView>>, ApiError> {
771-
Ok(Json(
772-
app.database
773-
.passkeys()
774-
.list_active(session.user_id)
775-
.await?
776-
.into_iter()
777-
.map(|key| PasskeyView {
778-
id: key.id,
779-
friendly_name: key.friendly_name,
780-
})
781-
.collect(),
782-
))
770+
) -> Result<Json<Vec<api::Passkey>>, ApiError> {
771+
let passkeys = app.database.passkeys().list_active(session.user_id).await?;
772+
Ok(Json(passkeys.into_iter().map(Into::into).collect()))
783773
}
784774

785775
/// Changes a credential label. A name grants nothing, so a session is enough.

‎apps/auth-service/src/passkey/types.rs‎

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Validated names and the browser API's request and response bodies.
22
33
use super::PasskeyError;
4-
use piquel_auth_protocol::{PasskeyId, TokenId, UserId};
4+
use piquel_auth_protocol::{TokenId, UserId};
55
use serde::{Deserialize, Serialize};
66
use webauthn_rs::prelude::{PublicKeyCredential, RegisterPublicKeyCredential};
77

@@ -169,15 +169,6 @@ pub(super) struct CeremonyResponse {
169169
pub(super) public_key: serde_json::Value,
170170
}
171171

172-
/// Public credential metadata, excluding the credential's cryptographic contents.
173-
#[derive(Serialize)]
174-
pub(super) struct PasskeyView {
175-
/// User-chosen credential label.
176-
pub(super) friendly_name: String,
177-
/// Credential row identifier used for rename and removal.
178-
pub(super) id: PasskeyId,
179-
}
180-
181172
/// Account identity shown in the browser session view.
182173
#[derive(Serialize)]
183174
pub(super) struct UserView {

0 commit comments

Comments
 (0)