entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Registered-client view type for authorization-server checks.
//!
//! [`RegisteredClient`] is a read-only projection of a single OAuth client
//! as the authorization server knows it. The caller loads the row from its
//! own database and constructs this view; the server-side validators
//! ([`super::authorize`], [`super::code`]) borrow it to make their
//! decisions. It owns no persistence and performs no I/O.

use core::fmt;

use crate::crypto::constant_time::constant_time_eq;
use crate::util::validation::{is_valid_client_id, is_valid_redirect_uri, is_valid_scope};

// ---------------------------------------------------------------------------
// Client type
// ---------------------------------------------------------------------------

/// Whether a registered client can keep a secret (RFC 6749 §2.1).
#[doc(alias = "client_type")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ClientType {
    /// A confidential client (server-side app) that can hold a
    /// `client_secret` securely.
    Confidential,
    /// A public client (SPA, native app) that cannot hold a secret;
    /// security rests on PKCE and exact redirect-URI matching.
    Public,
}

impl ClientType {
    /// Returns `true` for [`ClientType::Confidential`].
    #[must_use]
    #[inline]
    pub fn is_confidential(self) -> bool {
        matches!(self, Self::Confidential)
    }

    /// Returns `true` for [`ClientType::Public`].
    #[must_use]
    #[inline]
    pub fn is_public(self) -> bool {
        matches!(self, Self::Public)
    }
}

// ---------------------------------------------------------------------------
// Registered client
// ---------------------------------------------------------------------------

/// A read-only view of a registered OAuth client.
///
/// Built from the caller's persisted client record and handed to the
/// server-side validators. Holds no secret material — client-secret
/// verification is performed by the caller (or by
/// [`super::code::TokenRequestPresented`] via a pre-computed
/// [`ClientAuthResult`](super::code::ClientAuthResult)).
///
/// # Example
///
/// ```
/// use entropy_auth::oauth::server::{ClientType, RegisteredClient};
///
/// let client = RegisteredClient::builder("entropy_website", ClientType::Confidential)
///     .redirect_uri("https://app.example.com/callback")
///     .allowed_scope("openid")
///     .allowed_scope("profile")
///     .require_pkce(true)
///     .active(true)
///     .build()
///     .expect("valid registration");
///
/// assert!(client.is_registered_redirect_uri("https://app.example.com/callback"));
/// assert!(!client.is_registered_redirect_uri("https://evil.example.com/callback"));
/// ```
#[doc(alias = "oauth_client")]
#[derive(Debug, Clone)]
pub struct RegisteredClient {
    client_id: String,
    client_type: ClientType,
    redirect_uris: Vec<String>,
    allowed_scopes: Vec<String>,
    require_pkce: bool,
    active: bool,
}

impl RegisteredClient {
    /// Starts building a [`RegisteredClient`] for `client_id`.
    pub fn builder(
        client_id: impl Into<String>,
        client_type: ClientType,
    ) -> RegisteredClientBuilder {
        RegisteredClientBuilder {
            client_id: client_id.into(),
            client_type,
            redirect_uris: Vec::new(),
            allowed_scopes: Vec::new(),
            // SECURITY: PKCE defaults to required and the client defaults to
            // active only once `build` is called with explicit values; the
            // builder fields start at the safe defaults.
            require_pkce: true,
            active: true,
        }
    }

    /// Returns the client identifier.
    #[must_use]
    #[inline]
    pub fn client_id(&self) -> &str {
        &self.client_id
    }

    /// Returns the client type.
    #[must_use]
    #[inline]
    pub fn client_type(&self) -> ClientType {
        self.client_type
    }

    /// Returns the registered redirect URIs.
    #[must_use]
    #[inline]
    pub fn redirect_uris(&self) -> &[String] {
        &self.redirect_uris
    }

    /// Returns the scopes this client is allowed to request.
    #[must_use]
    #[inline]
    pub fn allowed_scopes(&self) -> &[String] {
        &self.allowed_scopes
    }

    /// Returns `true` if PKCE is required for this client.
    #[must_use]
    #[inline]
    pub fn require_pkce(&self) -> bool {
        self.require_pkce
    }

    /// Returns `true` if the client is active (not disabled).
    #[must_use]
    #[inline]
    pub fn active(&self) -> bool {
        self.active
    }

    /// Returns `true` if `uri` is an exact, byte-for-byte match of one of
    /// the registered redirect URIs.
    ///
    /// # Security
    ///
    /// SECURITY: Redirect-URI matching is **exact** per OAuth 2.0 Security
    /// BCP (RFC 9700 §2.1) — no prefix, substring, or normalisation match.
    /// The comparison is constant-time so a malicious `redirect_uri` cannot
    /// be brute-forced character by character via timing.
    #[must_use]
    pub fn is_registered_redirect_uri(&self, uri: &str) -> bool {
        self.redirect_uris
            .iter()
            .any(|registered| constant_time_eq(registered.as_bytes(), uri.as_bytes()))
    }

    /// Returns `true` if every scope in `requested` is in the client's
    /// allowed set.
    ///
    /// `requested` is the space-delimited `scope` parameter (RFC 6749
    /// §3.3). An empty request is a trivial subset and returns `true`.
    #[must_use]
    pub fn allows_scopes(&self, requested: &str) -> bool {
        requested
            .split(' ')
            .filter(|s| !s.is_empty())
            .all(|s| self.allowed_scopes.iter().any(|allowed| allowed == s))
    }
}

// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------

/// Builder for [`RegisteredClient`].
///
/// All fields beyond `client_id` and `client_type` are optional; redirect
/// URIs and allowed scopes accumulate across calls. PKCE defaults to
/// required and the client defaults to active.
#[doc(alias = "client_builder")]
#[derive(Debug, Clone)]
#[must_use = "a builder does nothing until `build` is called"]
pub struct RegisteredClientBuilder {
    client_id: String,
    client_type: ClientType,
    redirect_uris: Vec<String>,
    allowed_scopes: Vec<String>,
    require_pkce: bool,
    active: bool,
}

impl RegisteredClientBuilder {
    /// Registers a redirect URI. May be called multiple times.
    #[inline]
    pub fn redirect_uri(mut self, uri: impl Into<String>) -> Self {
        self.redirect_uris.push(uri.into());
        self
    }

    /// Adds an allowed scope. May be called multiple times.
    #[inline]
    pub fn allowed_scope(mut self, scope: impl Into<String>) -> Self {
        self.allowed_scopes.push(scope.into());
        self
    }

    /// Sets whether PKCE is required (default `true`).
    #[inline]
    pub fn require_pkce(mut self, required: bool) -> Self {
        self.require_pkce = required;
        self
    }

    /// Sets whether the client is active (default `true`).
    #[inline]
    pub fn active(mut self, active: bool) -> Self {
        self.active = active;
        self
    }

    /// Finalises the [`RegisteredClient`], validating the registration.
    ///
    /// This is the authorization server's trust anchor for every later
    /// open-redirect decision, so the registration data is validated up
    /// front rather than trusted blindly.
    ///
    /// # Errors
    ///
    /// Returns [`RegisteredClientError`] if the `client_id` is malformed, a
    /// registered redirect URI is not a valid HTTPS (or loopback-`http`) URI
    /// free of fragments (RFC 6749 §3.1.2 / RFC 8252), or an allowed scope
    /// contains invalid characters.
    ///
    /// A client MAY register **zero** redirect URIs: a purely
    /// machine-to-machine client (client-credentials grant only) has no
    /// redirect-based flow. The redirect-based flows enforce registration at
    /// use — [`validate_authorize_request`](super::validate_authorize_request)
    /// rejects any `redirect_uri` not returned by
    /// [`is_registered_redirect_uri`](RegisteredClient::is_registered_redirect_uri),
    /// and a client with none matches nothing — so an empty set simply makes
    /// the authorization-code flow unusable for that client, which is correct.
    pub fn build(self) -> Result<RegisteredClient, RegisteredClientError> {
        if !is_valid_client_id(&self.client_id) {
            return Err(RegisteredClientError {
                kind: RegisteredClientErrorKind::InvalidClientId,
            });
        }
        if !self.redirect_uris.iter().all(|u| is_valid_redirect_uri(u)) {
            return Err(RegisteredClientError {
                kind: RegisteredClientErrorKind::InvalidRedirectUri,
            });
        }
        if !self.allowed_scopes.iter().all(|s| is_valid_scope(s)) {
            return Err(RegisteredClientError {
                kind: RegisteredClientErrorKind::InvalidScope,
            });
        }
        Ok(RegisteredClient {
            client_id: self.client_id,
            client_type: self.client_type,
            redirect_uris: self.redirect_uris,
            allowed_scopes: self.allowed_scopes,
            require_pkce: self.require_pkce,
            active: self.active,
        })
    }
}

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// The category of [`RegisteredClientBuilder::build`] failure.
// Each variant names the specific field that was invalid; the shared prefix is
// intentional (they map 1:1 to the builder's validation steps).
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone, PartialEq, Eq)]
enum RegisteredClientErrorKind {
    /// The `client_id` is empty or contains invalid characters.
    InvalidClientId,
    /// A redirect URI is not a valid HTTPS/loopback URI, or carries a fragment.
    InvalidRedirectUri,
    /// An allowed scope contains invalid characters.
    InvalidScope,
}

/// Error returned when [`RegisteredClientBuilder::build`] rejects a
/// registration.
#[doc(alias = "registered_client_error")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegisteredClientError {
    kind: RegisteredClientErrorKind,
}

impl RegisteredClientError {
    /// Returns `true` if the `client_id` was malformed.
    #[must_use]
    #[inline]
    pub fn is_invalid_client_id(&self) -> bool {
        self.kind == RegisteredClientErrorKind::InvalidClientId
    }

    /// Returns `true` if a registered redirect URI was invalid.
    #[must_use]
    #[inline]
    pub fn is_invalid_redirect_uri(&self) -> bool {
        self.kind == RegisteredClientErrorKind::InvalidRedirectUri
    }

    /// Returns `true` if an allowed scope was invalid.
    #[must_use]
    #[inline]
    pub fn is_invalid_scope(&self) -> bool {
        self.kind == RegisteredClientErrorKind::InvalidScope
    }
}

impl fmt::Display for RegisteredClientError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let msg = match self.kind {
            RegisteredClientErrorKind::InvalidClientId => "invalid client_id",
            RegisteredClientErrorKind::InvalidRedirectUri => {
                "invalid redirect URI (must be HTTPS or loopback http, no fragment)"
            }
            RegisteredClientErrorKind::InvalidScope => "invalid scope",
        };
        write!(f, "registered client: {msg}")
    }
}

impl std::error::Error for RegisteredClientError {}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn client() -> RegisteredClient {
        RegisteredClient::builder("c1", ClientType::Confidential)
            .redirect_uri("https://app.example.com/callback")
            .redirect_uri("https://app.example.com/callback2")
            .allowed_scope("openid")
            .allowed_scope("profile")
            .allowed_scope("email")
            .build()
            .expect("valid test client")
    }

    #[test]
    fn accessors() {
        let c = client();
        assert_eq!(c.client_id(), "c1");
        assert_eq!(c.client_type(), ClientType::Confidential);
        assert!(c.client_type().is_confidential());
        assert!(!c.client_type().is_public());
        assert_eq!(c.redirect_uris().len(), 2);
        assert_eq!(c.allowed_scopes(), &["openid", "profile", "email"]);
        assert!(c.require_pkce());
        assert!(c.active());
    }

    #[test]
    fn redirect_uri_exact_match() {
        let c = client();
        assert!(c.is_registered_redirect_uri("https://app.example.com/callback"));
        assert!(c.is_registered_redirect_uri("https://app.example.com/callback2"));
    }

    #[test]
    fn redirect_uri_rejects_non_exact() {
        let c = client();
        // Prefix / suffix / trailing-slash variations must all fail.
        assert!(!c.is_registered_redirect_uri("https://app.example.com/callback/"));
        assert!(!c.is_registered_redirect_uri("https://app.example.com/callbac"));
        assert!(!c.is_registered_redirect_uri("https://app.example.com/callback?x=1"));
        assert!(!c.is_registered_redirect_uri("https://evil.example.com/callback"));
        assert!(!c.is_registered_redirect_uri(""));
    }

    #[test]
    fn scope_subset() {
        let c = client();
        assert!(c.allows_scopes("openid"));
        assert!(c.allows_scopes("openid profile"));
        assert!(c.allows_scopes("openid profile email"));
        assert!(c.allows_scopes("")); // empty is a trivial subset
    }

    #[test]
    fn scope_superset_rejected() {
        let c = client();
        assert!(!c.allows_scopes("openid admin"));
        assert!(!c.allows_scopes("offline_access"));
    }

    #[test]
    fn scope_handles_extra_whitespace() {
        let c = client();
        assert!(c.allows_scopes("openid  profile"));
        assert!(c.allows_scopes(" openid "));
    }

    #[test]
    fn builder_flags() {
        let public = RegisteredClient::builder("spa", ClientType::Public)
            .redirect_uri("https://spa.example.com/cb")
            .require_pkce(false)
            .active(false)
            .build()
            .expect("valid test client");
        assert!(public.client_type().is_public());
        assert!(!public.require_pkce());
        assert!(!public.active());
    }

    #[test]
    fn build_allows_no_redirect_uri_for_m2m_client() {
        // A machine-to-machine (client-credentials-only) client registers no
        // redirect URIs. It builds, and — having none — matches no redirect,
        // so the authorization-code flow is simply unusable for it.
        let client = RegisteredClient::builder("svc_c1", ClientType::Confidential)
            .allowed_scope("read")
            .require_pkce(false)
            .build()
            .expect("m2m client builds without redirect URIs");
        assert!(client.redirect_uris().is_empty());
        assert!(!client.is_registered_redirect_uri("https://app.example.com/cb"));
    }

    #[test]
    fn build_rejects_plaintext_http_redirect() {
        let err = RegisteredClient::builder("c1", ClientType::Confidential)
            .redirect_uri("http://evil.example.com/cb")
            .build()
            .unwrap_err();
        assert!(err.is_invalid_redirect_uri());
    }

    #[test]
    fn build_rejects_redirect_with_fragment() {
        let err = RegisteredClient::builder("c1", ClientType::Confidential)
            .redirect_uri("https://app.example.com/cb#frag")
            .build()
            .unwrap_err();
        assert!(err.is_invalid_redirect_uri());
    }

    #[test]
    fn build_rejects_invalid_client_id() {
        let err = RegisteredClient::builder("", ClientType::Confidential)
            .redirect_uri("https://app.example.com/cb")
            .build()
            .unwrap_err();
        assert!(err.is_invalid_client_id());
    }

    #[test]
    fn build_allows_loopback_http_redirect() {
        // RFC 8252 §8.3: loopback http is permitted for native apps.
        RegisteredClient::builder("native", ClientType::Public)
            .redirect_uri("http://127.0.0.1:8080/cb")
            .require_pkce(true)
            .build()
            .expect("loopback http is valid");
    }
}