chisel-auth 0.1.0

Chisel platform authentication: JWT sessions with a closed role vocabulary, and the OIDC desktop-loopback seam over the kit estate.
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
//! Chisel platform authentication: JWT sessions with a closed role
//! vocabulary, and the OIDC desktop-loopback seam over the kit estate.
//!
//! Two kit surfaces composed here, both kept behind thin Chisel vocabulary:
//!
//! - [`tokenkit`](https://crates.io/crates/tokenkit) — JWT issue/validate
//!   with rotation-capable configuration ([`SessionService`]).
//! - [`oauth_toolkit`](https://crates.io/crates/oauth-toolkit) — the OIDC
//!   desktop-loopback flow with PKCE and CSRF state ([`LoginFlow`]).
//!
//! The v0.1 rule: everything here is testable offline. The one network step
//! in OIDC (the authorization-code exchange at the provider's token
//! endpoint) is behind the [`TokenExchanger`] trait — the HTTP
//! implementation arrives with the service slice, and tests inject a stub.

use chrono::{Duration, Utc};
use serde::{Deserialize, Serialize};

/// Authentication failures.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The presented token is invalid, expired, or wrongly scoped.
    #[error("invalid session token: {0}")]
    Token(String),
    /// The actor's roles do not permit the operation.
    #[error("role {actor_role:?} does not permit {needed:?}")]
    Forbidden {
        /// The role the session carried.
        actor_role: String,
        /// The capability that was requested.
        needed: String,
    },
    /// The underlying kit rejected an operation.
    #[error("kit error: {0}")]
    Kit(String),
    /// A configuration error (empty secret, malformed issuer, …).
    #[error("configuration error: {0}")]
    Config(String),
}

/// Convenient alias for auth operations.
pub type Result<T> = std::result::Result<T, Error>;

/// The closed role vocabulary for the platform, declared weakest-first so
/// the derived ordering matches strength (`Auditor < Reviewer < Editor <
/// Owner`); capabilities accumulate upward.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Role {
    /// Read-only, plus the full audit trail.
    Auditor,
    /// Read and comment; no mutations.
    Reviewer,
    /// Edit documents and manage redactions.
    Editor,
    /// Full control, including membership and deletion.
    Owner,
}

impl Role {
    /// The role's name as serialized into tokens.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Role::Owner => "owner",
            Role::Editor => "editor",
            Role::Reviewer => "reviewer",
            Role::Auditor => "auditor",
        }
    }

    /// Parses a role name from a token claim.
    #[must_use]
    pub fn parse(name: &str) -> Option<Self> {
        match name {
            "owner" => Some(Role::Owner),
            "editor" => Some(Role::Editor),
            "reviewer" => Some(Role::Reviewer),
            "auditor" => Some(Role::Auditor),
            _ => None,
        }
    }

    /// Whether this role permits the given capability. Capabilities are a
    /// closed set; new capabilities must name every role that holds them.
    #[must_use]
    pub fn permits(self, capability: Capability) -> bool {
        match capability {
            Capability::Read => true,
            Capability::ReadAudit => true,
            Capability::Edit => matches!(self, Role::Owner | Role::Editor),
            Capability::Redact => matches!(self, Role::Owner | Role::Editor),
            Capability::Sign => matches!(self, Role::Owner | Role::Editor),
            Capability::ManageMembers => matches!(self, Role::Owner),
            Capability::Delete => matches!(self, Role::Owner),
        }
    }
}

/// The closed capability set. A capability is a verb-like permission the UI
/// and the service both check before acting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Capability {
    /// Read document content.
    Read,
    /// Read the audit trail (every role can).
    ReadAudit,
    /// Mutate document content.
    Edit,
    /// Apply redactions.
    Redact,
    /// Apply digital signatures.
    Sign,
    /// Manage membership.
    ManageMembers,
    /// Delete documents.
    Delete,
}

/// The claims carried by a Chisel session token: `tokenkit`'s standard
/// claims (whose `role` field carries the session's role name) plus the
/// session id.
///
/// A session carries exactly one role — the Acrobat actor model is one
/// identity, one job — so the vocabulary stays a flat enum, not a set.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChiselClaims {
    /// The standard registered claims; `role` holds the role name.
    #[serde(flatten)]
    pub standard: tokenkit::claims::StandardClaims,
    /// The session this token belongs to (refresh pairs share it).
    pub sid: String,
}

impl ChiselClaims {
    /// The session's parsed role, if the name is in the current vocabulary.
    #[must_use]
    pub fn role(&self) -> Option<Role> {
        self.standard.role.as_deref().and_then(Role::parse)
    }

    /// Whether the session's role permits a capability.
    #[must_use]
    pub fn permits(&self, capability: Capability) -> bool {
        self.role().is_some_and(|r| r.permits(capability))
    }

    /// Enforces a capability, mapping failure to [`Error::Forbidden`].
    ///
    /// # Errors
    ///
    /// When the session's role does not permit the capability.
    pub fn require(&self, capability: Capability) -> Result<()> {
        if self.permits(capability) {
            Ok(())
        } else {
            Err(Error::Forbidden {
                actor_role: self.role().map_or("none".into(), |r| r.as_str().to_owned()),
                needed: format!("{capability:?}"),
            })
        }
    }
}

/// Issues and validates Chisel session tokens over `tokenkit`'s JWT service
/// with rotation-capable secrets.
#[derive(Clone)]
pub struct SessionService {
    inner: std::sync::Arc<tokenkit::service::JwtService>,
    issuer: String,
    audience: String,
    session_ttl: Duration,
    refresh_ttl: Duration,
}

impl std::fmt::Debug for SessionService {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SessionService")
            .field("issuer", &self.issuer)
            .field("audience", &self.audience)
            .field("session_ttl", &self.session_ttl)
            .finish_non_exhaustive()
    }
}

/// The token pair handed out at login and refresh.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionTokens {
    /// Short-lived access token (carries the roles).
    pub access: String,
    /// Long-lived refresh token (same `sid`, longer expiry).
    pub refresh: String,
    /// The session id both tokens share.
    pub sid: String,
}

impl SessionService {
    /// Creates a service.
    ///
    /// # Errors
    ///
    /// [`Error::Config`] when the signing secret is empty or the issuer or
    /// audience is empty — a service started unconfigured must fail loudly
    /// now, not at the first login.
    pub fn new(
        signing_secret: impl Into<String>,
        issuer: impl Into<String>,
        audience: impl Into<String>,
    ) -> Result<Self> {
        let secret = signing_secret.into();
        let issuer = issuer.into();
        let audience = audience.into();
        if secret.is_empty() {
            return Err(Error::Config("signing secret cannot be empty".into()));
        }
        if issuer.is_empty() || audience.is_empty() {
            return Err(Error::Config("issuer and audience cannot be empty".into()));
        }
        // v0.1 pins a single HS256 secret. tokenkit's secret-rotation
        // builder is behind its `rotation` feature; enable it here when the
        // service slice lands and the secrets move to the settings store.
        // The config carries the issuer and audience so VALIDATION enforces
        // that tokens presented to this service are its own — not just
        // correctly signed by it.
        let config = tokenkit::service::JwtConfig {
            secret,
            issuer: Some(issuer.clone()),
            audience: Some(audience.clone()),
            ..tokenkit::service::JwtConfig::default()
        };
        Ok(Self {
            inner: std::sync::Arc::new(tokenkit::service::JwtService::new(config)),
            issuer,
            audience,
            session_ttl: Duration::hours(12),
            refresh_ttl: Duration::days(30),
        })
    }

    /// Issues an access + refresh pair for a user with the given role.
    ///
    /// # Errors
    ///
    /// Propagates encoding failures from the kit.
    pub fn issue(&self, user: &chisel_kernel::UserId, role: Role) -> Result<SessionTokens> {
        let sid = chisel_kernel::SessionId::try_from(format!(
            "{}-{}",
            user.as_str(),
            Utc::now().timestamp_millis()
        ))
        .map_err(Error::Config)?;
        let access = self.encode_session(user, role, &sid, self.session_ttl)?;
        let refresh = self.encode_session(user, role, &sid, self.refresh_ttl)?;
        Ok(SessionTokens {
            access,
            refresh,
            sid: sid.to_string(),
        })
    }

    /// Validates an access token into its claims.
    ///
    /// # Errors
    ///
    /// [`Error::Token`] when the kit rejects the token (signature, expiry,
    /// audience); propagation otherwise.
    pub fn validate(&self, token: &str) -> Result<ChiselClaims> {
        self.inner
            .decode::<ChiselClaims>(token)
            .map_err(|e| Error::Token(e.to_string()))
    }

    /// Validates a refresh token and issues a fresh pair for the same
    /// session, preserving the role recorded at login.
    ///
    /// # Errors
    ///
    /// Same as [`validate`](Self::validate).
    pub fn refresh(&self, refresh_token: &str) -> Result<SessionTokens> {
        let claims = self.validate(refresh_token)?;
        self.refresh_from_claims(&claims)
    }

    /// Issues a fresh pair from already-validated claims. Split from
    /// [`refresh`](Self::refresh) so the no-role branch is reachable in
    /// tests with a hand-built claims value.
    ///
    /// # Errors
    ///
    /// When the claims carry no role from the current vocabulary, or the
    /// subject/session ids are malformed.
    pub fn refresh_from_claims(&self, claims: &ChiselClaims) -> Result<SessionTokens> {
        let role = claims.role().ok_or_else(|| {
            Error::Token("refresh token carries no role from the current vocabulary".into())
        })?;
        let user = chisel_kernel::UserId::try_from(claims.standard.sub.clone().unwrap_or_default())
            .map_err(Error::Token)?;
        let sid = chisel_kernel::SessionId::try_from(claims.sid.clone()).map_err(Error::Token)?;
        let access = self.encode_session(&user, role, &sid, self.session_ttl)?;
        let refresh = self.encode_session(&user, role, &sid, self.refresh_ttl)?;
        Ok(SessionTokens {
            access,
            refresh,
            sid: sid.to_string(),
        })
    }

    fn encode_session(
        &self,
        user: &chisel_kernel::UserId,
        role: Role,
        sid: &chisel_kernel::SessionId,
        ttl: Duration,
    ) -> Result<String> {
        let now = Utc::now();
        let claims = ChiselClaims {
            standard: tokenkit::claims::StandardClaims {
                sub: Some(user.as_str().to_owned()),
                iss: Some(self.issuer.clone()),
                aud: Some(self.audience.clone()),
                exp: Some(now + ttl),
                iat: Some(now),
                jti: None,
                role: Some(role.as_str().to_owned()),
                permissions: Vec::new(),
                extra: std::collections::HashMap::new(),
            },
            sid: sid.to_string(),
        };
        self.inner
            .encode(&claims)
            .map_err(|e| Error::Kit(e.to_string()))
    }
}

/// The OIDC provider facts the desktop login needs. The app supplies them
/// (from its settings or the provider's discovery document).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OidcProviderConfig {
    /// The provider's issuer URL (e.g. `https://id.example.com`).
    pub issuer: String,
    /// The authorization endpoint.
    pub authorization_url: String,
    /// The token endpoint (used by the service-side exchanger).
    pub token_url: String,
    /// The OIDC client id registered for the desktop app.
    pub client_id: String,
    /// Scopes to request; `openid email profile` is the floor.
    pub scopes: Vec<String>,
}

/// The outcome of starting a desktop login: open `url` in a browser, then
/// `wait()` for the loopback capture.
pub struct LoginStart {
    flow: oauth_toolkit::loopback::LoopbackFlow,
}

impl LoginStart {
    /// The URL to open in the system browser.
    #[must_use]
    pub fn url(&self) -> &str {
        self.flow.authorization_url()
    }

    /// Blocks for up to the flow's timeout waiting for the provider to call
    /// back on the loopback listener.
    ///
    /// # Errors
    ///
    /// Propagates the kit's capture errors (timeout, state mismatch, deny).
    pub fn wait(self) -> Result<oauth_toolkit::loopback::CapturedCode> {
        self.flow
            .wait_for_code()
            .map_err(|e| Error::Kit(e.to_string()))
    }
}

/// Exchanges an authorization code for OIDC tokens at the provider's token
/// endpoint. The HTTP implementation belongs to the service slice; tests
/// inject closures.
pub trait TokenExchanger: Send + Sync {
    /// The token response as a raw JSON value (the caller validates it via
    /// the kit's OIDC validator).
    fn exchange(
        &self,
        token_url: &str,
        code: &str,
        code_verifier: &str,
        client_id: &str,
    ) -> Result<serde_json::Value>;
}

impl<F> TokenExchanger for F
where
    F: Fn(&str, &str, &str, &str) -> Result<serde_json::Value> + Send + Sync,
{
    fn exchange(
        &self,
        token_url: &str,
        code: &str,
        code_verifier: &str,
        client_id: &str,
    ) -> Result<serde_json::Value> {
        self(token_url, code, code_verifier, client_id)
    }
}

/// Starts a desktop OIDC login against `provider`: builds the PKCE pair and
/// CSRF state via the kit, binds the loopback listener, and returns the URL
/// to open. Complete the flow by waiting and exchanging the code.
///
/// # Errors
///
/// Propagates the kit's flow-start errors (bind failure, URL build).
pub fn start_login(
    provider: &OidcProviderConfig,
    scopes: &[String],
    timeout: std::time::Duration,
) -> Result<LoginStart> {
    let flow = oauth_toolkit::loopback::LoopbackFlow::start(
        &provider.authorization_url,
        &provider.client_id,
        scopes,
        None,
        timeout,
    )
    .map_err(|e| Error::Kit(e.to_string()))?;
    Ok(LoginStart { flow })
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used, clippy::unwrap_used)]
    use super::*;
    use chisel_kernel::UserId;

    const SECRET: &str = "test-signing-secret-do-not-use";
    const ISSUER: &str = "https://auth.chisel.test";
    const AUDIENCE: &str = "chisel-desktop";

    fn service() -> SessionService {
        SessionService::new(SECRET, ISSUER, AUDIENCE).expect("valid config")
    }

    #[test]
    fn config_failures_are_loud_and_early() {
        assert!(SessionService::new("", ISSUER, AUDIENCE).is_err());
        assert!(SessionService::new(SECRET, "", AUDIENCE).is_err());
        assert!(SessionService::new(SECRET, ISSUER, "").is_err());
    }

    #[test]
    fn issue_then_validate_round_trips_role_and_identity() -> Result<()> {
        let svc = service();
        let user = UserId::try_from("alice").map_err(Error::Token)?;
        let tokens = svc.issue(&user, Role::Editor)?;

        let claims = svc.validate(&tokens.access)?;
        assert_eq!(claims.standard.sub.as_deref(), Some("alice"));
        assert_eq!(claims.standard.role.as_deref(), Some("editor"));
        assert_eq!(claims.sid, tokens.sid);
        assert!(claims.permits(Capability::Edit));
        assert!(!claims.permits(Capability::ManageMembers));
        Ok(())
    }

    #[test]
    fn refresh_preserves_the_session_and_role() -> Result<()> {
        let svc = service();
        let user = UserId::try_from("bob").map_err(Error::Token)?;
        let tokens = svc.issue(&user, Role::Auditor)?;

        let fresh = svc.refresh(&tokens.refresh)?;
        assert_eq!(fresh.sid, tokens.sid);
        let claims = svc.validate(&fresh.access)?;
        assert_eq!(claims.standard.role.as_deref(), Some("auditor"));
        assert!(claims.permits(Capability::ReadAudit));
        assert!(!claims.permits(Capability::Edit));
        Ok(())
    }

    #[test]
    fn a_foreign_issuer_is_rejected() -> Result<()> {
        let svc = service();
        let user = UserId::try_from("alice").map_err(Error::Token)?;
        let tokens = svc.issue(&user, Role::Reviewer)?;

        let other = SessionService::new(SECRET, "https://elsewhere.test", AUDIENCE)?;
        assert!(matches!(
            other.validate(&tokens.access),
            Err(Error::Token(_))
        ));
        Ok(())
    }

    #[test]
    fn capability_checks_name_the_missing_role() -> Result<()> {
        let svc = service();
        let user = UserId::try_from("dan").map_err(Error::Token)?;
        let tokens = svc.issue(&user, Role::Reviewer)?;
        let claims = svc.validate(&tokens.access)?;
        let err = claims.require(Capability::Redact).unwrap_err();
        assert!(err.to_string().contains("reviewer"), "{err}");
        assert!(err.to_string().contains("Redact"), "{err}");
        Ok(())
    }

    #[test]
    fn the_role_vocabulary_is_total_and_ordered() {
        for (name, role) in [
            ("owner", Role::Owner),
            ("editor", Role::Editor),
            ("reviewer", Role::Reviewer),
            ("auditor", Role::Auditor),
        ] {
            assert_eq!(Role::parse(name), Some(role));
            assert_eq!(role.as_str(), name);
        }
        assert!(Role::Auditor < Role::Reviewer);
        assert!(Role::Reviewer < Role::Editor);
        assert!(Role::Editor < Role::Owner);
        for r in [Role::Owner, Role::Editor, Role::Reviewer, Role::Auditor] {
            assert!(r.permits(Capability::Read));
            assert!(!r.permits(Capability::Delete) || r == Role::Owner);
        }
    }

    #[test]
    fn start_login_builds_a_loopback_flow_against_the_provider() -> Result<()> {
        let provider = OidcProviderConfig {
            issuer: "https://id.example.test".into(),
            authorization_url: "https://id.example.test/authorize".into(),
            token_url: "https://id.example.test/token".into(),
            client_id: "chisel-desktop".into(),
            scopes: vec!["openid".into(), "email".into(), "profile".into()],
        };
        let start = start_login(
            &provider,
            &provider.scopes,
            std::time::Duration::from_secs(30),
        )?;
        assert!(
            start.url().starts_with("https://id.example.test/authorize"),
            "{}",
            start.url()
        );
        assert!(
            start.url().contains("code_challenge="),
            "PKCE challenge present"
        );
        assert!(start.url().contains("state="), "CSRF state present");
        Ok(())
    }

    #[test]
    fn sign_capability_splits_editors_from_auditors() {
        assert!(Role::Owner.permits(Capability::Sign));
        assert!(Role::Editor.permits(Capability::Sign));
        assert!(!Role::Reviewer.permits(Capability::Sign));
        assert!(!Role::Auditor.permits(Capability::Sign));
    }

    #[test]
    fn require_returns_ok_when_permitted() -> Result<()> {
        let svc = service();
        let user = chisel_kernel::UserId::try_from("ed").map_err(Error::Token)?;
        let tokens = svc.issue(&user, Role::Editor)?;
        let claims = svc.validate(&tokens.access)?;
        claims.require(Capability::Edit)?;
        claims.require(Capability::Read)?;
        Ok(())
    }

    #[test]
    fn debug_never_prints_the_signing_secret() {
        let dbg = format!("{svc:?}", svc = service());
        assert!(dbg.contains("SessionService"), "{dbg}");
        assert!(!dbg.contains(SECRET), "the secret must not appear in Debug");
    }

    #[test]
    fn login_start_wait_times_out_loudly() -> Result<()> {
        let provider = OidcProviderConfig {
            issuer: "https://id.example.test".into(),
            authorization_url: "https://id.example.test/authorize".into(),
            token_url: "https://id.example.test/token".into(),
            client_id: "chisel-desktop".into(),
            scopes: vec!["openid".into()],
        };
        let start = start_login(
            &provider,
            &provider.scopes,
            std::time::Duration::from_millis(1),
        )?;
        let outcome = start.wait();
        assert!(matches!(outcome, Err(Error::Kit(_))), "{outcome:?}");
        Ok(())
    }

    #[test]
    fn the_token_exchanger_trait_runs_closures() -> Result<()> {
        let exchange = |token_url: &str, _code: &str, _verifier: &str, _client: &str| {
            Ok(serde_json::json!({ "token_url": token_url }))
        };
        let v = exchange.exchange("https://token", "code", "verifier", "client")?;
        assert_eq!(
            v.get("token_url"),
            Some(&serde_json::json!("https://token"))
        );
        Ok(())
    }
}