Skip to main content

auth_framework/
client.rs

1//! OAuth 2.0 client types — canonical definitions (RFC 6749 §2.1).
2//!
3//! [`ClientType`] and [`ClientConfig`] are the single source of truth for client
4//! classification used throughout the OAuth 2.0/2.1 stack (domain layer, server
5//! layer, and storage layer).  All other modules import these types rather than
6//! defining their own copies.
7
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10use uuid::Uuid;
11
12/// OAuth 2.0 client classification (RFC 6749 §2.1).
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub enum ClientType {
15    /// Confidential clients can securely store their credentials (server-side apps).
16    Confidential,
17    /// Public clients cannot securely store credentials (SPAs, native apps).
18    Public,
19}
20
21/// Full configuration record for a registered OAuth 2.0 client.
22#[derive(Clone, Serialize, Deserialize)]
23pub struct ClientConfig {
24    /// Unique client identifier
25    pub client_id: String,
26    /// Client secret — only present for `Confidential` clients
27    pub client_secret: Option<String>,
28    /// RFC 6749 §2.1 client classification
29    pub client_type: ClientType,
30    /// Authorised redirect URIs
31    pub redirect_uris: crate::types::RedirectUris,
32    /// Scopes this client is allowed to request
33    pub authorized_scopes: crate::types::Scopes,
34    /// Grant types this client is allowed to use
35    pub authorized_grant_types: crate::types::GrantTypes,
36    /// Response types this client is allowed to use
37    pub authorized_response_types: crate::types::ResponseTypes,
38    /// Human-readable display name
39    pub client_name: Option<String>,
40    /// Optional description
41    pub client_description: Option<String>,
42    /// Arbitrary metadata (e.g. logo_uri, tos_uri, contacts, …)
43    pub metadata: HashMap<String, serde_json::Value>,
44}
45
46impl std::fmt::Debug for ClientConfig {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        let mut d = f.debug_struct("ClientConfig");
49        d.field("client_id", &self.client_id);
50        d.field(
51            "client_secret",
52            &crate::utils::redact::redacted(&self.client_secret),
53        );
54        d.field("client_type", &self.client_type);
55        d.field("redirect_uris", &self.redirect_uris);
56        d.field("authorized_scopes", &self.authorized_scopes);
57        d.field("authorized_grant_types", &self.authorized_grant_types);
58        d.field("authorized_response_types", &self.authorized_response_types);
59        d.field("client_name", &self.client_name);
60        d.field("client_description", &self.client_description);
61        d.field("metadata", &self.metadata);
62        d.finish()
63    }
64}
65
66impl Default for ClientConfig {
67    fn default() -> Self {
68        Self {
69            client_id: Uuid::new_v4().to_string(),
70            client_secret: None,
71            client_type: ClientType::Public,
72            redirect_uris: crate::types::RedirectUris::empty(),
73            authorized_scopes: crate::types::Scopes::from(vec!["read".to_string()]),
74            authorized_grant_types: crate::types::GrantTypes::from(vec![
75                "authorization_code".to_string(),
76            ]),
77            authorized_response_types: crate::types::ResponseTypes::from(vec!["code".to_string()]),
78            client_name: None,
79            client_description: None,
80            metadata: HashMap::new(),
81        }
82    }
83}
84
85/// Builder for creating `ClientConfig` instances with fluent API.
86///
87/// Reduces cognitive load when registering OAuth clients with many optional fields.
88/// Required fields are set in `new()`, optional fields via builder methods.
89///
90/// # Example
91///
92/// ```rust
93/// use auth_framework::client::{ClientConfig, ClientType};
94/// use auth_framework::types::{RedirectUris, Scopes, GrantTypes, ResponseTypes};
95///
96/// let config = ClientConfig::builder("client123", ClientType::Confidential)
97///     .client_secret("secret456")
98///     .redirect_uris(RedirectUris::new(vec!["https://example.com/callback".to_string()]))
99///     .authorized_scopes(Scopes::new(vec!["read".to_string(), "write".to_string()]))
100///     .client_name("My App")
101///     .build();
102/// ```
103#[derive(Clone)]
104pub struct ClientConfigBuilder {
105    client_id: String,
106    client_secret: Option<String>,
107    client_type: ClientType,
108    redirect_uris: crate::types::RedirectUris,
109    authorized_scopes: crate::types::Scopes,
110    authorized_grant_types: crate::types::GrantTypes,
111    authorized_response_types: crate::types::ResponseTypes,
112    client_name: Option<String>,
113    client_description: Option<String>,
114    metadata: HashMap<String, serde_json::Value>,
115}
116
117impl std::fmt::Debug for ClientConfigBuilder {
118    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        let mut d = f.debug_struct("ClientConfigBuilder");
120        d.field("client_id", &self.client_id);
121        d.field(
122            "client_secret",
123            &crate::utils::redact::redacted(&self.client_secret),
124        );
125        d.field("client_type", &self.client_type);
126        d.field("redirect_uris", &self.redirect_uris);
127        d.field("authorized_scopes", &self.authorized_scopes);
128        d.field("authorized_grant_types", &self.authorized_grant_types);
129        d.field("authorized_response_types", &self.authorized_response_types);
130        d.field("client_name", &self.client_name);
131        d.field("client_description", &self.client_description);
132        d.field("metadata", &self.metadata);
133        d.finish()
134    }
135}
136
137impl ClientConfigBuilder {
138    /// Create a new builder with required fields.
139    ///
140    /// Sets sensible defaults for optional fields:
141    /// - `client_secret`: None
142    /// - `redirect_uris`: empty
143    /// - `authorized_scopes`: ["read"]
144    /// - `authorized_grant_types`: ["authorization_code"]
145    /// - `authorized_response_types`: ["code"]
146    /// - `client_name`, `client_description`: None
147    /// - `metadata`: empty
148    ///
149    /// # Example
150    ///
151    /// ```rust
152    /// use auth_framework::client::{ClientConfigBuilder, ClientType};
153    ///
154    /// let builder = ClientConfigBuilder::new("my-app", ClientType::Public);
155    /// let config = builder.build();
156    /// assert_eq!(config.client_id, "my-app");
157    /// ```
158    pub fn new(client_id: impl Into<String>, client_type: ClientType) -> Self {
159        Self {
160            client_id: client_id.into(),
161            client_secret: None,
162            client_type,
163            redirect_uris: crate::types::RedirectUris::empty(),
164            authorized_scopes: crate::types::Scopes::from(vec!["read".to_string()]),
165            authorized_grant_types: crate::types::GrantTypes::from(vec![
166                "authorization_code".to_string(),
167            ]),
168            authorized_response_types: crate::types::ResponseTypes::from(vec!["code".to_string()]),
169            client_name: None,
170            client_description: None,
171            metadata: HashMap::new(),
172        }
173    }
174
175    /// Set the client secret.
176    ///
177    /// # Example
178    ///
179    /// ```rust
180    /// use auth_framework::client::{ClientConfigBuilder, ClientType};
181    ///
182    /// let config = ClientConfigBuilder::new("app", ClientType::Confidential)
183    ///     .client_secret("s3cret")
184    ///     .build();
185    /// assert_eq!(config.client_secret.unwrap(), "s3cret");
186    /// ```
187    pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
188        self.client_secret = Some(client_secret.into());
189        self
190    }
191
192    /// Set the authorized redirect URIs.
193    ///
194    /// # Example
195    ///
196    /// ```rust
197    /// use auth_framework::client::{ClientConfigBuilder, ClientType};
198    /// use auth_framework::types::RedirectUris;
199    ///
200    /// let config = ClientConfigBuilder::new("app", ClientType::Public)
201    ///     .redirect_uris(RedirectUris::new(vec!["https://example.com/cb".into()]))
202    ///     .build();
203    /// ```
204    pub fn redirect_uris(mut self, redirect_uris: crate::types::RedirectUris) -> Self {
205        self.redirect_uris = redirect_uris;
206        self
207    }
208
209    /// Set the authorized scopes.
210    ///
211    /// # Example
212    ///
213    /// ```rust
214    /// use auth_framework::client::{ClientConfigBuilder, ClientType};
215    /// use auth_framework::types::Scopes;
216    ///
217    /// let config = ClientConfigBuilder::new("app", ClientType::Public)
218    ///     .authorized_scopes(Scopes::new(vec!["read".into(), "write".into()]))
219    ///     .build();
220    /// ```
221    pub fn authorized_scopes(mut self, authorized_scopes: crate::types::Scopes) -> Self {
222        self.authorized_scopes = authorized_scopes;
223        self
224    }
225
226    /// Set the authorized grant types.
227    ///
228    /// # Example
229    ///
230    /// ```rust
231    /// use auth_framework::client::{ClientConfigBuilder, ClientType};
232    /// use auth_framework::types::GrantTypes;
233    ///
234    /// let config = ClientConfigBuilder::new("app", ClientType::Confidential)
235    ///     .authorized_grant_types(GrantTypes::new(vec!["client_credentials".into()]))
236    ///     .build();
237    /// ```
238    pub fn authorized_grant_types(
239        mut self,
240        authorized_grant_types: crate::types::GrantTypes,
241    ) -> Self {
242        self.authorized_grant_types = authorized_grant_types;
243        self
244    }
245
246    /// Set the authorized response types.
247    ///
248    /// # Example
249    ///
250    /// ```rust
251    /// use auth_framework::client::{ClientConfigBuilder, ClientType};
252    /// use auth_framework::types::ResponseTypes;
253    ///
254    /// let config = ClientConfigBuilder::new("app", ClientType::Public)
255    ///     .authorized_response_types(ResponseTypes::new(vec!["code".into()]))
256    ///     .build();
257    /// ```
258    pub fn authorized_response_types(
259        mut self,
260        authorized_response_types: crate::types::ResponseTypes,
261    ) -> Self {
262        self.authorized_response_types = authorized_response_types;
263        self
264    }
265
266    /// Set the client name.
267    ///
268    /// # Example
269    ///
270    /// ```rust
271    /// use auth_framework::client::{ClientConfigBuilder, ClientType};
272    ///
273    /// let config = ClientConfigBuilder::new("app", ClientType::Public)
274    ///     .client_name("My Application")
275    ///     .build();
276    /// assert_eq!(config.client_name.unwrap(), "My Application");
277    /// ```
278    pub fn client_name(mut self, client_name: impl Into<String>) -> Self {
279        self.client_name = Some(client_name.into());
280        self
281    }
282
283    /// Set the client description.
284    ///
285    /// # Example
286    ///
287    /// ```rust
288    /// use auth_framework::client::{ClientConfigBuilder, ClientType};
289    ///
290    /// let config = ClientConfigBuilder::new("app", ClientType::Public)
291    ///     .client_description("OAuth 2.0 demo app")
292    ///     .build();
293    /// assert_eq!(config.client_description.unwrap(), "OAuth 2.0 demo app");
294    /// ```
295    pub fn client_description(mut self, client_description: impl Into<String>) -> Self {
296        self.client_description = Some(client_description.into());
297        self
298    }
299
300    /// Set the metadata.
301    ///
302    /// # Example
303    ///
304    /// ```rust
305    /// use auth_framework::client::{ClientConfigBuilder, ClientType};
306    /// use std::collections::HashMap;
307    ///
308    /// let mut meta = HashMap::new();
309    /// meta.insert("logo_uri".into(), serde_json::json!("https://example.com/logo.png"));
310    /// let config = ClientConfigBuilder::new("app", ClientType::Public)
311    ///     .metadata(meta)
312    ///     .build();
313    /// assert!(config.metadata.contains_key("logo_uri"));
314    /// ```
315    pub fn metadata(mut self, metadata: HashMap<String, serde_json::Value>) -> Self {
316        self.metadata = metadata;
317        self
318    }
319
320    /// Add a metadata key-value pair.
321    ///
322    /// # Example
323    ///
324    /// ```rust
325    /// use auth_framework::client::{ClientConfigBuilder, ClientType};
326    ///
327    /// let config = ClientConfigBuilder::new("app", ClientType::Public)
328    ///     .with_metadata("tos_uri", serde_json::json!("https://example.com/tos"))
329    ///     .build();
330    /// assert!(config.metadata.contains_key("tos_uri"));
331    /// ```
332    pub fn with_metadata(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
333        self.metadata.insert(key.into(), value);
334        self
335    }
336
337    /// Build the `ClientConfig` instance.
338    ///
339    /// # Example
340    ///
341    /// ```rust
342    /// use auth_framework::client::{ClientConfigBuilder, ClientType};
343    ///
344    /// let config = ClientConfigBuilder::new("app", ClientType::Public).build();
345    /// assert_eq!(config.client_id, "app");
346    /// ```
347    pub fn build(self) -> ClientConfig {
348        ClientConfig {
349            client_id: self.client_id,
350            client_secret: self.client_secret,
351            client_type: self.client_type,
352            redirect_uris: self.redirect_uris,
353            authorized_scopes: self.authorized_scopes,
354            authorized_grant_types: self.authorized_grant_types,
355            authorized_response_types: self.authorized_response_types,
356            client_name: self.client_name,
357            client_description: self.client_description,
358            metadata: self.metadata,
359        }
360    }
361}
362
363impl ClientConfig {
364    /// Start building a `ClientConfig` with fluent setters.
365    ///
366    /// # Example
367    ///
368    /// ```rust
369    /// use auth_framework::client::{ClientConfig, ClientType};
370    ///
371    /// let config = ClientConfig::builder("client123", ClientType::Public)
372    ///     .client_name("My SPA")
373    ///     .build();
374    /// ```
375    pub fn builder(client_id: impl Into<String>, client_type: ClientType) -> ClientConfigBuilder {
376        ClientConfigBuilder::new(client_id, client_type)
377    }
378}