nythos-core 0.2.1

Infrastructure-free Rust core library for Nythos authentication and authorization.
Documentation
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 provider and external identity domain models.
//!
//! This module contains the infrastructure-free OAuth domain surface used by
//! `nythos-core`. Provider redirects, state/CSRF, PKCE, authorization-code and
//! token exchange, ID-token validation, JWKS fetching, provider userinfo calls,
//! cookies, client credentials, provider SDKs, HTTP routes, database schema, and
//! runtime/framework behavior remain outside core.
//!
//! The gateway or provider adapter verifies OAuth provider data first and then
//! constructs `VerifiedExternalProfile`. Core treats that value as the trust
//! boundary and does not validate OAuth tokens or call providers.

use std::{fmt, str::FromStr, time::SystemTime};

use crate::{AuthError, DisplayName, Email, NythosResult, TenantId, UserId};

/// Supported OAuth/OIDC provider kinds known to the core domain.
///
/// The stable string representation is intentionally lowercase and suitable for
/// persistence. This enum is non-exhaustive so future providers can be added
/// without forcing downstream exhaustive matches.
///
/// Provider-specific endpoints, scopes, client IDs, client secrets, SDK choices,
/// and runtime behavior are not represented here.
#[non_exhaustive]
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
pub enum OAuthProviderKind {
    Google,
    GitHub,
    Microsoft,
}

impl OAuthProviderKind {
    /// Returns the stable lowercase provider identifier.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Google => "google",
            Self::GitHub => "github",
            Self::Microsoft => "microsoft",
        }
    }

    /// Parses a stable provider identifier.
    pub fn parse(input: impl AsRef<str>) -> NythosResult<Self> {
        match input.as_ref().trim().to_ascii_lowercase().as_str() {
            "google" => Ok(Self::Google),
            "github" => Ok(Self::GitHub),
            "microsoft" => Ok(Self::Microsoft),
            _ => Err(AuthError::ValidationError(
                "unknown OAuth provider kind".to_owned(),
            )),
        }
    }
}

impl fmt::Display for OAuthProviderKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

impl FromStr for OAuthProviderKind {
    type Err = AuthError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// A provider identity linked to a Nythos user inside one tenant.
///
/// The natural key is:
/// `(tenant_id, provider_kind, provider_subject)`.
///
/// The provider subject is the stable opaque subject/user ID issued by the
/// external provider. Provider email and display name are metadata captured at
/// link time and must not replace the provider subject as the login key.
///
/// Storage adapters must enforce uniqueness for the natural key inside the
/// tenant. Cross-tenant identity resolution is outside the core contract.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ExternalIdentity {
    tenant_id: TenantId,
    user_id: UserId,
    provider_kind: OAuthProviderKind,
    provider_subject: String,
    provider_email: Option<Email>,
    provider_display_name: Option<DisplayName>,
    linked_at: SystemTime,
    last_seen_at: SystemTime,
}

impl ExternalIdentity {
    /// Creates a new external identity with matching link and last-seen times.
    pub fn new(
        tenant_id: TenantId,
        user_id: UserId,
        provider_kind: OAuthProviderKind,
        provider_subject: impl AsRef<str>,
        provider_email: Option<Email>,
        provider_display_name: Option<DisplayName>,
        now: SystemTime,
    ) -> NythosResult<Self> {
        Self::with_timestamps(
            tenant_id,
            user_id,
            provider_kind,
            provider_subject,
            provider_email,
            provider_display_name,
            now,
            now,
        )
    }

    /// Creates an external identity with explicit timestamps.
    ///
    /// This is useful for repository hydration and deterministic tests.
    #[allow(clippy::too_many_arguments)]
    pub fn with_timestamps(
        tenant_id: TenantId,
        user_id: UserId,
        provider_kind: OAuthProviderKind,
        provider_subject: impl AsRef<str>,
        provider_email: Option<Email>,
        provider_display_name: Option<DisplayName>,
        linked_at: SystemTime,
        last_seen_at: SystemTime,
    ) -> NythosResult<Self> {
        let provider_subject = validate_provider_subject(provider_subject.as_ref())?;

        Ok(Self {
            tenant_id,
            user_id,
            provider_kind,
            provider_subject,
            provider_email,
            provider_display_name,
            linked_at,
            last_seen_at,
        })
    }

    pub const fn tenant_id(&self) -> TenantId {
        self.tenant_id
    }

    pub const fn user_id(&self) -> UserId {
        self.user_id
    }

    pub const fn provider_kind(&self) -> OAuthProviderKind {
        self.provider_kind
    }

    pub fn provider_subject(&self) -> &str {
        &self.provider_subject
    }

    pub fn provider_email(&self) -> Option<&Email> {
        self.provider_email.as_ref()
    }

    pub fn provider_display_name(&self) -> Option<&DisplayName> {
        self.provider_display_name.as_ref()
    }

    pub const fn linked_at(&self) -> SystemTime {
        self.linked_at
    }

    pub const fn last_seen_at(&self) -> SystemTime {
        self.last_seen_at
    }

    /// Updates the last successful provider login timestamp.
    pub fn touch(&mut self, now: SystemTime) {
        self.last_seen_at = now;
    }
}

/// Core's tenant-scoped OAuth provider configuration.
///
/// This type intentionally contains only domain decisions the core needs:
/// whether the provider is enabled and whether registration through it is
/// allowed. Secrets, client IDs, redirect URIs, provider endpoints, JWKS URLs,
/// token endpoints, provider URLs, and HTTP metadata belong to
/// gateway/infrastructure code and must not be added to this type.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct TenantOAuthProviderConfig {
    tenant_id: TenantId,
    provider_kind: OAuthProviderKind,
    enabled: bool,
    registration_allowed: bool,
}

impl TenantOAuthProviderConfig {
    pub const fn new(
        tenant_id: TenantId,
        provider_kind: OAuthProviderKind,
        enabled: bool,
        registration_allowed: bool,
    ) -> Self {
        Self {
            tenant_id,
            provider_kind,
            enabled,
            registration_allowed,
        }
    }

    pub const fn tenant_id(&self) -> TenantId {
        self.tenant_id
    }

    pub const fn provider_kind(&self) -> OAuthProviderKind {
        self.provider_kind
    }

    pub const fn is_enabled(&self) -> bool {
        self.enabled
    }

    pub const fn registration_allowed(&self) -> bool {
        self.registration_allowed
    }
}

/// A normalized external profile that has already been verified by gateway.
///
/// This is a trust boundary type. `nythos-core` does not validate OAuth tokens,
/// call provider APIs, fetch JWKS documents, or verify provider signatures.
/// Gateway/provider adapters must complete those checks before constructing
/// this value.
///
/// `email()` exposes provider metadata. Unverified email must not be used for
/// account linking, auto-linking, or account matching decisions. Use
/// `verified_email()` for those decisions; it returns `Some(&Email)` only when
/// `email_verified` is true.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct VerifiedExternalProfile {
    provider_kind: OAuthProviderKind,
    provider_subject: String,
    email: Option<Email>,
    email_verified: bool,
    display_name: Option<DisplayName>,
}

impl VerifiedExternalProfile {
    pub fn new(
        provider_kind: OAuthProviderKind,
        provider_subject: impl AsRef<str>,
        email: Option<Email>,
        email_verified: bool,
        display_name: Option<DisplayName>,
    ) -> NythosResult<Self> {
        let provider_subject = validate_provider_subject(provider_subject.as_ref())?;

        Ok(Self {
            provider_kind,
            provider_subject,
            email,
            email_verified,
            display_name,
        })
    }

    pub const fn provider_kind(&self) -> OAuthProviderKind {
        self.provider_kind
    }

    pub fn provider_subject(&self) -> &str {
        &self.provider_subject
    }

    /// Returns the provider email metadata, whether or not the provider marked
    /// it verified.
    ///
    /// This accessor is not safe for account matching or automatic linking.
    /// Use `verified_email()` for those decisions.
    pub fn email(&self) -> Option<&Email> {
        self.email.as_ref()
    }

    /// Returns whether the provider adapter marked the profile email verified.
    pub const fn email_verified(&self) -> bool {
        self.email_verified
    }

    pub fn display_name(&self) -> Option<&DisplayName> {
        self.display_name.as_ref()
    }

    /// Returns the email only when the provider explicitly verified it.
    ///
    /// This is the safe accessor for account matching/linking decisions.
    pub fn verified_email(&self) -> Option<&Email> {
        if self.email_verified {
            self.email.as_ref()
        } else {
            None
        }
    }
}

fn validate_provider_subject(input: &str) -> NythosResult<String> {
    let value = input.trim();

    if value.is_empty() {
        return Err(AuthError::ValidationError(
            "provider subject cannot be empty".to_owned(),
        ));
    }

    Ok(value.to_owned())
}

#[cfg(test)]
mod tests {
    use super::{
        ExternalIdentity, OAuthProviderKind, TenantOAuthProviderConfig, VerifiedExternalProfile,
    };
    use crate::{AuthError, DisplayName, Email, TenantId, UserId};
    use std::{
        str::FromStr,
        time::{Duration, SystemTime},
    };

    #[test]
    fn provider_kind_uses_stable_lowercase_strings() {
        assert_eq!(OAuthProviderKind::Google.as_str(), "google");
        assert_eq!(OAuthProviderKind::GitHub.as_str(), "github");
        assert_eq!(OAuthProviderKind::Microsoft.as_str(), "microsoft");
    }

    #[test]
    fn provider_kind_displays_stable_string() {
        assert_eq!(OAuthProviderKind::Google.to_string(), "google");
        assert_eq!(OAuthProviderKind::GitHub.to_string(), "github");
        assert_eq!(OAuthProviderKind::Microsoft.to_string(), "microsoft");
    }

    #[test]
    fn provider_kind_parses_stable_settings() {
        assert_eq!(
            OAuthProviderKind::parse("google").unwrap(),
            OAuthProviderKind::Google
        );
        assert_eq!(
            OAuthProviderKind::parse("github").unwrap(),
            OAuthProviderKind::GitHub
        );
        assert_eq!(
            OAuthProviderKind::parse("microsoft").unwrap(),
            OAuthProviderKind::Microsoft
        );
    }

    #[test]
    fn provider_kind_parse_trims_and_accepts_case_variations() {
        assert_eq!(
            OAuthProviderKind::parse("  Google  ").unwrap(),
            OAuthProviderKind::Google
        );
        assert_eq!(
            OAuthProviderKind::parse("GITHUB").unwrap(),
            OAuthProviderKind::GitHub
        );
        assert_eq!(
            OAuthProviderKind::parse("Microsoft").unwrap(),
            OAuthProviderKind::Microsoft
        );
    }

    #[test]
    fn provider_kind_from_str_matches_parse() {
        assert_eq!(
            OAuthProviderKind::from_str("github").unwrap(),
            OAuthProviderKind::GitHub
        );
    }

    #[test]
    fn provider_kind_rejects_unknown_provider() {
        let result = OAuthProviderKind::parse("yahoo");

        assert!(matches!(result, Err(AuthError::ValidationError(_))));
    }

    #[test]
    fn external_identity_new_sets_linked_and_last_seen_to_now() {
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);

        let identity = ExternalIdentity::new(
            TenantId::generate(),
            UserId::generate(),
            OAuthProviderKind::Google,
            "google-sub-123",
            None,
            None,
            now,
        )
        .unwrap();

        assert_eq!(identity.linked_at(), now);
        assert_eq!(identity.last_seen_at(), now);
    }

    #[test]
    fn external_identity_with_timestamps_allows_explicit_times() {
        let linked_at = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        let last_seen_at = linked_at + Duration::from_secs(3600);

        let identity = ExternalIdentity::with_timestamps(
            TenantId::generate(),
            UserId::generate(),
            OAuthProviderKind::GitHub,
            "github-sub-456",
            None,
            None,
            linked_at,
            last_seen_at,
        )
        .unwrap();

        assert_eq!(identity.linked_at(), linked_at);
        assert_eq!(identity.last_seen_at(), last_seen_at);
    }

    #[test]
    fn external_identity_rejects_empty_provider_subject() {
        let result = ExternalIdentity::new(
            TenantId::generate(),
            UserId::generate(),
            OAuthProviderKind::Microsoft,
            "   ",
            None,
            None,
            SystemTime::UNIX_EPOCH,
        );

        assert!(matches!(result, Err(AuthError::ValidationError(_))));
    }

    #[test]
    fn external_identity_stores_tenant_user_provider_and_subject() {
        let tenant_id = TenantId::generate();
        let user_id = UserId::generate();
        let email = Email::parse("Person@Example.com").unwrap();
        let display_name = DisplayName::parse("Example Person").unwrap();

        let identity = ExternalIdentity::new(
            tenant_id,
            user_id,
            OAuthProviderKind::Microsoft,
            "microsoft-sub-789",
            Some(email.clone()),
            Some(display_name.clone()),
            SystemTime::UNIX_EPOCH,
        )
        .unwrap();

        assert_eq!(identity.tenant_id(), tenant_id);
        assert_eq!(identity.user_id(), user_id);
        assert_eq!(identity.provider_kind(), OAuthProviderKind::Microsoft);
        assert_eq!(identity.provider_subject(), "microsoft-sub-789");
        assert_eq!(identity.provider_email(), Some(&email));
        assert_eq!(identity.provider_display_name(), Some(&display_name));
    }

    #[test]
    fn external_identity_subject_is_trimmed_for_stable_lookup() {
        let identity = ExternalIdentity::new(
            TenantId::generate(),
            UserId::generate(),
            OAuthProviderKind::Google,
            "  google-sub-123  ",
            None,
            None,
            SystemTime::UNIX_EPOCH,
        )
        .unwrap();

        assert_eq!(identity.provider_subject(), "google-sub-123");
    }

    #[test]
    fn external_identity_touch_updates_only_last_seen_at() {
        let tenant_id = TenantId::generate();
        let user_id = UserId::generate();
        let linked_at = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        let first_seen_at = linked_at + Duration::from_secs(60);
        let next_seen_at = first_seen_at + Duration::from_secs(120);

        let mut identity = ExternalIdentity::with_timestamps(
            tenant_id,
            user_id,
            OAuthProviderKind::GitHub,
            "github-sub-456",
            None,
            None,
            linked_at,
            first_seen_at,
        )
        .unwrap();

        identity.touch(next_seen_at);

        assert_eq!(identity.tenant_id(), tenant_id);
        assert_eq!(identity.user_id(), user_id);
        assert_eq!(identity.provider_kind(), OAuthProviderKind::GitHub);
        assert_eq!(identity.provider_subject(), "github-sub-456");
        assert_eq!(identity.linked_at(), linked_at);
        assert_eq!(identity.last_seen_at(), next_seen_at);
    }

    #[test]
    fn tenant_oauth_provider_config_models_enabled_and_registration_flags() {
        let tenant_id = TenantId::generate();
        let config =
            TenantOAuthProviderConfig::new(tenant_id, OAuthProviderKind::Google, true, false);

        assert_eq!(config.tenant_id(), tenant_id);
        assert_eq!(config.provider_kind(), OAuthProviderKind::Google);
        assert!(config.is_enabled());
        assert!(!config.registration_allowed());
    }

    #[test]
    fn tenant_oauth_provider_config_can_disable_provider_and_registration() {
        let config = TenantOAuthProviderConfig::new(
            TenantId::generate(),
            OAuthProviderKind::GitHub,
            false,
            false,
        );

        assert!(!config.is_enabled());
        assert!(!config.registration_allowed());
    }

    #[test]
    fn verified_external_profile_requires_subject() {
        let result =
            VerifiedExternalProfile::new(OAuthProviderKind::Google, "   ", None, true, None);

        assert!(matches!(result, Err(AuthError::ValidationError(_))));
    }

    #[test]
    fn verified_external_profile_stores_provider_subject_and_metadata() {
        let email = Email::parse("Person@Example.com").unwrap();
        let display_name = DisplayName::parse("Person Example").unwrap();
        let profile = VerifiedExternalProfile::new(
            OAuthProviderKind::Microsoft,
            "  microsoft-sub-123  ",
            Some(email.clone()),
            true,
            Some(display_name.clone()),
        )
        .unwrap();

        assert_eq!(profile.provider_kind(), OAuthProviderKind::Microsoft);
        assert_eq!(profile.provider_subject(), "microsoft-sub-123");
        assert_eq!(profile.email(), Some(&email));
        assert!(profile.email_verified());
        assert_eq!(profile.display_name(), Some(&display_name));
    }

    #[test]
    fn verified_external_profile_exposes_only_verified_email() {
        let email = Email::parse("Person@Example.com").unwrap();
        let profile = VerifiedExternalProfile::new(
            OAuthProviderKind::Google,
            "google-sub-123",
            Some(email.clone()),
            true,
            None,
        )
        .unwrap();

        assert_eq!(profile.email(), Some(&email));
        assert_eq!(profile.verified_email(), Some(&email));
    }

    #[test]
    fn verified_external_profile_hides_unverified_email() {
        let email = Email::parse("Person@Example.com").unwrap();
        let profile = VerifiedExternalProfile::new(
            OAuthProviderKind::Google,
            "google-sub-123",
            Some(email.clone()),
            false,
            None,
        )
        .unwrap();

        assert_eq!(profile.email(), Some(&email));
        assert!(profile.verified_email().is_none());
    }

    #[test]
    fn verified_external_profile_without_email_has_no_verified_email() {
        let profile = VerifiedExternalProfile::new(
            OAuthProviderKind::GitHub,
            "github-sub-123",
            None,
            true,
            None,
        )
        .unwrap();

        assert!(profile.email().is_none());
        assert!(profile.verified_email().is_none());
    }
}