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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! OAuth 2.0 provider configuration with builder pattern.
//!
//! [`OAuthConfig`] holds all the provider-specific parameters needed to
//! drive an Authorization Code flow: client credentials, endpoint URLs,
//! redirect URI, and requested scopes.
//!
//! The [`OAuthConfigBuilder`] validates every field before producing a
//! config, ensuring that invalid values are caught at construction time
//! rather than at request time.

use std::fmt;

use crate::crypto::zeroize::Zeroizing;
use crate::util::log::{info, warn};
use crate::util::validation::{is_valid_client_id, is_valid_redirect_uri, is_valid_scope};

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

/// The category of configuration validation failure.
#[derive(Debug, Clone, PartialEq, Eq)]
enum OAuthConfigErrorKind {
    /// `client_id` failed validation.
    InvalidClientId,
    /// `redirect_uri` failed validation.
    InvalidRedirectUri,
    /// One or more scopes failed validation.
    InvalidScope,
    /// `authorization_endpoint` is missing.
    MissingAuthorizationEndpoint,
    /// `token_endpoint` is missing.
    MissingTokenEndpoint,
    /// `redirect_uri` is missing.
    MissingRedirectUri,
    /// `authorization_endpoint` does not use HTTPS.
    InsecureAuthorizationEndpoint,
    /// `token_endpoint` does not use HTTPS.
    InsecureTokenEndpoint,
    /// `client_secret` is empty.
    EmptyClientSecret,
}

/// Error returned when [`OAuthConfigBuilder::build`] fails validation.
///
/// Error messages never contain secret material (client secrets are
/// excluded from all diagnostic output).
#[doc(alias = "config_error")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OAuthConfigError {
    kind: OAuthConfigErrorKind,
}

impl OAuthConfigError {
    const fn new(kind: OAuthConfigErrorKind) -> Self {
        Self { kind }
    }
}

impl fmt::Display for OAuthConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind {
            OAuthConfigErrorKind::InvalidClientId => {
                write!(f, "oauth config: invalid client_id")
            }
            OAuthConfigErrorKind::InvalidRedirectUri => {
                write!(f, "oauth config: invalid redirect_uri")
            }
            OAuthConfigErrorKind::InvalidScope => {
                write!(f, "oauth config: invalid scope")
            }
            OAuthConfigErrorKind::MissingAuthorizationEndpoint => {
                write!(f, "oauth config: missing authorization_endpoint")
            }
            OAuthConfigErrorKind::MissingTokenEndpoint => {
                write!(f, "oauth config: missing token_endpoint")
            }
            OAuthConfigErrorKind::MissingRedirectUri => {
                write!(f, "oauth config: missing redirect_uri")
            }
            OAuthConfigErrorKind::InsecureAuthorizationEndpoint => {
                write!(
                    f,
                    "oauth config: insecure authorization_endpoint (HTTPS required)"
                )
            }
            OAuthConfigErrorKind::InsecureTokenEndpoint => {
                write!(f, "oauth config: insecure token_endpoint (HTTPS required)")
            }
            OAuthConfigErrorKind::EmptyClientSecret => {
                write!(f, "oauth config: empty client_secret")
            }
        }
    }
}

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

// ---------------------------------------------------------------------------
// OAuthConfig
// ---------------------------------------------------------------------------

/// OAuth 2.0 provider configuration.
///
/// Holds the client credentials, endpoint URLs, redirect URI, and
/// requested scopes for an Authorization Code flow. Construct via
/// [`OAuthConfig::builder`].
///
/// # Security
///
/// The `client_secret` is stored in a [`Zeroizing`] wrapper that clears
/// memory on drop. The [`Debug`] implementation redacts the secret to
/// prevent accidental logging.
#[doc(alias = "oauth_config")]
pub struct OAuthConfig {
    client_id: String,
    // SECURITY: Client secret is wrapped in Zeroizing to clear memory on drop.
    client_secret: Zeroizing<String>,
    authorization_endpoint: String,
    token_endpoint: String,
    redirect_uri: String,
    scopes: Vec<String>,
}

impl OAuthConfig {
    /// Creates a new [`OAuthConfigBuilder`] with the required client
    /// credentials.
    ///
    /// The `client_id` and `client_secret` are validated at build time,
    /// not here — the builder is infallible until [`OAuthConfigBuilder::build`]
    /// is called.
    #[must_use]
    pub fn builder(client_id: &str, client_secret: &str) -> OAuthConfigBuilder {
        OAuthConfigBuilder {
            client_id: client_id.to_owned(),
            // SECURITY: Wrap client secret immediately to minimize plaintext window.
            client_secret: Zeroizing::new(client_secret.to_owned()),
            authorization_endpoint: None,
            token_endpoint: None,
            redirect_uri: None,
            scopes: Vec::new(),
        }
    }

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

    /// Returns the OAuth client secret.
    ///
    /// # Security
    ///
    /// SECURITY: The caller must take care not to log or display this value.
    /// It is returned as `&str` for convenience in building POST bodies.
    #[must_use]
    #[inline]
    pub fn client_secret(&self) -> &str {
        &self.client_secret
    }

    /// Returns the authorization endpoint URL.
    #[must_use]
    #[inline]
    pub fn authorization_endpoint(&self) -> &str {
        &self.authorization_endpoint
    }

    /// Returns the token endpoint URL.
    #[must_use]
    #[inline]
    pub fn token_endpoint(&self) -> &str {
        &self.token_endpoint
    }

    /// Returns the redirect URI.
    #[must_use]
    #[inline]
    pub fn redirect_uri(&self) -> &str {
        &self.redirect_uri
    }

    /// Returns the requested scopes.
    #[must_use]
    #[inline]
    pub fn scopes(&self) -> &[String] {
        &self.scopes
    }
}

// SECURITY: Debug redacts the client secret to prevent accidental logging.
impl fmt::Debug for OAuthConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OAuthConfig")
            .field("client_id", &self.client_id)
            .field("client_secret", &"[REDACTED]")
            .field("authorization_endpoint", &self.authorization_endpoint)
            .field("token_endpoint", &self.token_endpoint)
            .field("redirect_uri", &self.redirect_uri)
            .field("scopes", &self.scopes)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// OAuthConfigBuilder
// ---------------------------------------------------------------------------

/// Builder for [`OAuthConfig`].
///
/// All endpoint URLs and the redirect URI must be set before calling
/// [`build`](OAuthConfigBuilder::build). Scopes are optional — if none
/// are added, the scopes list will be empty.
#[doc(alias = "config_builder")]
pub struct OAuthConfigBuilder {
    client_id: String,
    // SECURITY: Client secret is wrapped in Zeroizing from construction onward.
    client_secret: Zeroizing<String>,
    authorization_endpoint: Option<String>,
    token_endpoint: Option<String>,
    redirect_uri: Option<String>,
    scopes: Vec<String>,
}

// SECURITY: Debug redacts the client secret to prevent accidental logging.
impl fmt::Debug for OAuthConfigBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OAuthConfigBuilder")
            .field("client_id", &self.client_id)
            .field("client_secret", &"[REDACTED]")
            .field("authorization_endpoint", &self.authorization_endpoint)
            .field("token_endpoint", &self.token_endpoint)
            .field("redirect_uri", &self.redirect_uri)
            .field("scopes", &self.scopes)
            .finish()
    }
}

impl OAuthConfigBuilder {
    /// Sets the authorization endpoint URL.
    #[must_use]
    pub fn authorization_endpoint(mut self, url: &str) -> Self {
        self.authorization_endpoint = Some(url.to_owned());
        self
    }

    /// Sets the token endpoint URL.
    #[must_use]
    pub fn token_endpoint(mut self, url: &str) -> Self {
        self.token_endpoint = Some(url.to_owned());
        self
    }

    /// Sets the redirect URI.
    #[must_use]
    pub fn redirect_uri(mut self, uri: &str) -> Self {
        self.redirect_uri = Some(uri.to_owned());
        self
    }

    /// Adds a scope to the requested scope list.
    ///
    /// Each scope is validated individually at build time per RFC 6749 §3.3.
    #[must_use]
    pub fn scope(mut self, scope: &str) -> Self {
        self.scopes.push(scope.to_owned());
        self
    }

    /// Validates all fields and builds the [`OAuthConfig`].
    ///
    /// # Errors
    ///
    /// Returns [`OAuthConfigError`] if:
    /// - `client_id` fails [`is_valid_client_id`] validation.
    /// - `redirect_uri` is missing or fails [`is_valid_redirect_uri`] validation.
    /// - Any scope fails [`is_valid_scope`] validation.
    /// - `authorization_endpoint` is missing.
    /// - `token_endpoint` is missing.
    pub fn build(self) -> Result<OAuthConfig, OAuthConfigError> {
        // Validate client_id.
        if !is_valid_client_id(&self.client_id) {
            warn!("oauth: config validation failed: invalid client_id");
            return Err(OAuthConfigError::new(OAuthConfigErrorKind::InvalidClientId));
        }

        // SECURITY: Reject empty client secrets to prevent misconfiguration.
        if self.client_secret.is_empty() {
            warn!("oauth: config validation failed: empty client_secret");
            return Err(OAuthConfigError::new(
                OAuthConfigErrorKind::EmptyClientSecret,
            ));
        }

        // Validate required endpoints.
        let authorization_endpoint = self.authorization_endpoint.ok_or_else(|| {
            warn!("oauth: config validation failed: missing authorization_endpoint");
            OAuthConfigError::new(OAuthConfigErrorKind::MissingAuthorizationEndpoint)
        })?;
        let token_endpoint = self.token_endpoint.ok_or_else(|| {
            warn!("oauth: config validation failed: missing token_endpoint");
            OAuthConfigError::new(OAuthConfigErrorKind::MissingTokenEndpoint)
        })?;

        // SECURITY: Require HTTPS for both endpoints to prevent credential interception.
        if !crate::util::validation::is_https_url(&authorization_endpoint) {
            warn!("oauth: config validation failed: insecure authorization_endpoint");
            return Err(OAuthConfigError::new(
                OAuthConfigErrorKind::InsecureAuthorizationEndpoint,
            ));
        }
        if !crate::util::validation::is_https_url(&token_endpoint) {
            warn!("oauth: config validation failed: insecure token_endpoint");
            return Err(OAuthConfigError::new(
                OAuthConfigErrorKind::InsecureTokenEndpoint,
            ));
        }

        // Validate redirect URI.
        let redirect_uri = self.redirect_uri.ok_or_else(|| {
            warn!("oauth: config validation failed: missing redirect_uri");
            OAuthConfigError::new(OAuthConfigErrorKind::MissingRedirectUri)
        })?;
        if !is_valid_redirect_uri(&redirect_uri) {
            warn!("oauth: config validation failed: invalid redirect_uri");
            return Err(OAuthConfigError::new(
                OAuthConfigErrorKind::InvalidRedirectUri,
            ));
        }

        // Validate scopes individually.
        for scope in &self.scopes {
            if !is_valid_scope(scope) {
                warn!("oauth: config validation failed: invalid scope");
                return Err(OAuthConfigError::new(OAuthConfigErrorKind::InvalidScope));
            }
        }

        // SECURITY: Log only non-secret fields — never log client_secret.
        info!(client_id = %self.client_id, "oauth: provider configured");

        Ok(OAuthConfig {
            client_id: self.client_id,
            // SECURITY: Already wrapped in Zeroizing since builder construction.
            client_secret: self.client_secret,
            authorization_endpoint,
            token_endpoint,
            redirect_uri,
            scopes: self.scopes,
        })
    }
}

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

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

    fn valid_builder() -> OAuthConfigBuilder {
        OAuthConfig::builder("my-client-id", "my-client-secret")
            .authorization_endpoint("https://auth.example.com/authorize")
            .token_endpoint("https://auth.example.com/token")
            .redirect_uri("https://myapp.example.com/callback")
    }

    // --- Builder pattern ---

    #[test]
    fn build_valid_config() {
        let config = valid_builder()
            .scope("openid")
            .scope("profile")
            .build()
            .unwrap();

        assert_eq!(config.client_id(), "my-client-id");
        assert_eq!(config.client_secret(), "my-client-secret");
        assert_eq!(
            config.authorization_endpoint(),
            "https://auth.example.com/authorize",
        );
        assert_eq!(config.token_endpoint(), "https://auth.example.com/token");
        assert_eq!(config.redirect_uri(), "https://myapp.example.com/callback",);
        assert_eq!(config.scopes().len(), 2);
        assert_eq!(config.scopes()[0], "openid");
        assert_eq!(config.scopes()[1], "profile");
    }

    #[test]
    fn build_no_scopes_is_valid() {
        let config = valid_builder().build().unwrap();
        assert!(config.scopes().is_empty());
    }

    // --- Validation errors ---

    #[test]
    fn build_rejects_empty_client_id() {
        let result = OAuthConfig::builder("", "secret")
            .authorization_endpoint("https://auth.example.com/authorize")
            .token_endpoint("https://auth.example.com/token")
            .redirect_uri("https://myapp.example.com/callback")
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("client_id"));
    }

    #[test]
    fn build_rejects_invalid_client_id() {
        let result = OAuthConfig::builder("client\x00id", "secret")
            .authorization_endpoint("https://auth.example.com/authorize")
            .token_endpoint("https://auth.example.com/token")
            .redirect_uri("https://myapp.example.com/callback")
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("client_id"));
    }

    #[test]
    fn build_rejects_missing_authorization_endpoint() {
        let result = OAuthConfig::builder("client", "secret")
            .token_endpoint("https://auth.example.com/token")
            .redirect_uri("https://myapp.example.com/callback")
            .build();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("authorization_endpoint"),
        );
    }

    #[test]
    fn build_rejects_missing_token_endpoint() {
        let result = OAuthConfig::builder("client", "secret")
            .authorization_endpoint("https://auth.example.com/authorize")
            .redirect_uri("https://myapp.example.com/callback")
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("token_endpoint"),);
    }

    #[test]
    fn build_rejects_missing_redirect_uri() {
        let result = OAuthConfig::builder("client", "secret")
            .authorization_endpoint("https://auth.example.com/authorize")
            .token_endpoint("https://auth.example.com/token")
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("redirect_uri"));
    }

    #[test]
    fn build_rejects_invalid_redirect_uri() {
        let result = OAuthConfig::builder("client", "secret")
            .authorization_endpoint("https://auth.example.com/authorize")
            .token_endpoint("https://auth.example.com/token")
            .redirect_uri("http://evil.com/callback")
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("redirect_uri"));
    }

    #[test]
    fn build_rejects_invalid_scope() {
        let result = valid_builder().scope("open\"id").build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("scope"));
    }

    // --- Accessor correctness ---

    #[test]
    fn accessors_return_configured_values() {
        let config = valid_builder().scope("email").build().unwrap();

        assert_eq!(config.client_id(), "my-client-id");
        assert_eq!(config.client_secret(), "my-client-secret");
        assert_eq!(config.scopes(), &["email"]);
    }

    // --- Debug redaction ---

    #[test]
    fn debug_redacts_client_secret() {
        let config = valid_builder().build().unwrap();
        let debug_output = format!("{config:?}");
        assert!(
            debug_output.contains("[REDACTED]"),
            "debug output should contain [REDACTED]: {debug_output}",
        );
        assert!(
            !debug_output.contains("my-client-secret"),
            "debug output must not contain the client secret",
        );
    }

    // --- Error Display ---

    #[test]
    fn error_display_messages() {
        let err = OAuthConfigError::new(OAuthConfigErrorKind::InvalidClientId);
        assert_eq!(err.to_string(), "oauth config: invalid client_id");

        let err = OAuthConfigError::new(OAuthConfigErrorKind::InvalidRedirectUri);
        assert_eq!(err.to_string(), "oauth config: invalid redirect_uri");

        let err = OAuthConfigError::new(OAuthConfigErrorKind::InvalidScope);
        assert_eq!(err.to_string(), "oauth config: invalid scope");

        let err = OAuthConfigError::new(OAuthConfigErrorKind::MissingAuthorizationEndpoint);
        assert_eq!(
            err.to_string(),
            "oauth config: missing authorization_endpoint",
        );

        let err = OAuthConfigError::new(OAuthConfigErrorKind::MissingTokenEndpoint);
        assert_eq!(err.to_string(), "oauth config: missing token_endpoint");

        let err = OAuthConfigError::new(OAuthConfigErrorKind::MissingRedirectUri);
        assert_eq!(err.to_string(), "oauth config: missing redirect_uri");
    }

    #[test]
    fn error_implements_std_error() {
        let err: Box<dyn std::error::Error> =
            Box::new(OAuthConfigError::new(OAuthConfigErrorKind::InvalidClientId));
        let _ = err.to_string();
    }

    // --- S2: HTTPS endpoint validation ---

    #[test]
    fn build_rejects_http_authorization_endpoint() {
        let result = OAuthConfig::builder("client", "secret")
            .authorization_endpoint("http://auth.example.com/authorize")
            .token_endpoint("https://auth.example.com/token")
            .redirect_uri("https://myapp.example.com/callback")
            .build();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("insecure authorization_endpoint"),
        );
    }

    #[test]
    fn build_rejects_http_token_endpoint() {
        let result = OAuthConfig::builder("client", "secret")
            .authorization_endpoint("https://auth.example.com/authorize")
            .token_endpoint("http://auth.example.com/token")
            .redirect_uri("https://myapp.example.com/callback")
            .build();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("insecure token_endpoint"),
        );
    }

    #[test]
    fn build_accepts_https_endpoints() {
        let result = OAuthConfig::builder("client", "secret")
            .authorization_endpoint("https://auth.example.com/authorize")
            .token_endpoint("https://auth.example.com/token")
            .redirect_uri("https://myapp.example.com/callback")
            .build();
        assert!(result.is_ok());
    }

    // --- S3: Empty client_secret validation ---

    #[test]
    fn build_rejects_empty_client_secret() {
        let result = OAuthConfig::builder("client", "")
            .authorization_endpoint("https://auth.example.com/authorize")
            .token_endpoint("https://auth.example.com/token")
            .redirect_uri("https://myapp.example.com/callback")
            .build();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("empty client_secret"),
        );
    }

    // --- Error Display for new variants ---

    #[test]
    fn error_display_new_variants() {
        let err = OAuthConfigError::new(OAuthConfigErrorKind::InsecureAuthorizationEndpoint);
        assert_eq!(
            err.to_string(),
            "oauth config: insecure authorization_endpoint (HTTPS required)",
        );

        let err = OAuthConfigError::new(OAuthConfigErrorKind::InsecureTokenEndpoint);
        assert_eq!(
            err.to_string(),
            "oauth config: insecure token_endpoint (HTTPS required)",
        );

        let err = OAuthConfigError::new(OAuthConfigErrorKind::EmptyClientSecret);
        assert_eq!(err.to_string(), "oauth config: empty client_secret");
    }
}