proofborne-core 0.2.0-alpha.1

Versioned contracts, events, provider types, and proof graph for Proofborne
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
//! Proof-carrying authentication contract.
//!
//! This module defines the secret-free, versioned `proofborne.auth.v1` bindings
//! and receipts that let later surfaces (CLI login, keychain lifecycle, remote
//! OAuth/coding-plan login, and account-aware routing) record an authentication
//! fact as durable, hash-chained evidence without ever persisting credential
//! material. Secret values live only in environment variables and the OS
//! keychain; the public binding records a secret-free identity hash and a
//! resolved token lifecycle state.

use std::collections::BTreeSet;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::canonical::hash_json;
use crate::event::SCHEMA_VERSION;

/// Version of the proof-carrying authentication protocol.
pub const AUTH_PROTOCOL_VERSION: &str = "proofborne.auth.v1";

/// Token lifecycle state visible to routing and evidence.
///
/// This is a lifecycle fact, not the token value. The runtime derives it from
/// the credential store and provider metadata; no secret is ever serialized.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TokenStatus {
    /// The credential is present and not yet expired.
    #[default]
    Active,
    /// A refresh credential is present and a refresh attempt is required.
    NeedsRefresh,
    /// The token is past its recorded expiry.
    Expired,
    /// The credential was locally revoked or the provider reported a revoke.
    Revoked,
}

/// A discrete lifecycle event that moves a token between states.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TokenLifecycleEvent {
    /// A fresh access/refresh pair was obtained.
    Login,
    /// A refresh attempt succeeded with a new token.
    RefreshSucceeded,
    /// The token reached its recorded expiry.
    Expired,
    /// The credential was locally or provider-side revoked.
    Revoked,
    /// A refresh was attempted but no valid refresh credential exists.
    RefreshUnavailable,
}

/// Deterministically advances a token lifecycle on a discrete event.
///
/// The refresh-unavailable guard blocks a `NeedsRefresh` credential from
/// becoming `Active` when no refresh token is present, matching the fail-closed
/// behaviour the routing layer relies on.
pub fn transition_token(
    status: TokenStatus,
    event: TokenLifecycleEvent,
    refresh_available: bool,
) -> TokenStatus {
    match event {
        TokenLifecycleEvent::Login | TokenLifecycleEvent::RefreshSucceeded => TokenStatus::Active,
        TokenLifecycleEvent::Expired => TokenStatus::Expired,
        TokenLifecycleEvent::Revoked => TokenStatus::Revoked,
        TokenLifecycleEvent::RefreshUnavailable => {
            if status == TokenStatus::Revoked {
                TokenStatus::Revoked
            } else if refresh_available {
                TokenStatus::NeedsRefresh
            } else {
                TokenStatus::Expired
            }
        }
    }
}

/// Derives the effective token status from recorded lifecycle facts.
///
/// An `Active` token past `expires_at` becomes `NeedsRefresh` when a refresh
/// credential exists (recoverable) and `Expired` otherwise. A recorded
/// `NeedsRefresh` with no refresh credential is fail-closed to `Expired` rather
/// than presented as usable. Never re-promotes a `Revoked` credential.
pub fn resolve_token_status(
    status: TokenStatus,
    expires_at: Option<DateTime<Utc>>,
    refresh_available: bool,
    now: DateTime<Utc>,
) -> TokenStatus {
    if status == TokenStatus::Revoked {
        return TokenStatus::Revoked;
    }
    if status == TokenStatus::Active && expires_at.is_some_and(|expiry| expiry <= now) {
        return if refresh_available {
            TokenStatus::NeedsRefresh
        } else {
            TokenStatus::Expired
        };
    }
    if status == TokenStatus::NeedsRefresh && !refresh_available {
        return TokenStatus::Expired;
    }
    status
}

/// Terminal authorization outcome of one auth check, as durable evidence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthReceiptOutcome {
    /// The account was authorized for the requested profile/model.
    Authorized,
    /// The required credential could not be resolved.
    CredentialUnavailable,
    /// The token is expired and cannot be refreshed.
    Expired,
    /// The account's token was revoked.
    Revoked,
    /// The claimed scopes are insufficient for the requested route.
    ScopeInsufficient,
    /// Cooperative cancellation interrupted the auth check.
    Cancelled,
}

/// Secret-free identity and token-state binding for one provider account.
///
/// The `credential_identity_hash` is a digest over the public credential
/// identity (for example `keyring:primary` or `env:OPENAI_API_KEY`), never the
/// secret value. It is stable under secret rotation but changes when the
/// credential identity or provider/profile changes, matching the existing
/// routing authority binding.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AuthBindings {
    /// Provider adapter name.
    pub provider: String,
    /// Provider profile name.
    pub profile: String,
    /// Public provider account identifier.
    pub account_id: String,
    /// Secret-free digest of the credential identity.
    pub credential_identity_hash: String,
    /// Canonically ordered granted scopes.
    #[serde(default)]
    pub scopes: BTreeSet<String>,
    /// Resolved token lifecycle state.
    pub token_status: TokenStatus,
    /// Whether a refresh token is present and can be used.
    pub refresh_available: bool,
    /// When the binding was produced.
    pub observed_at: DateTime<Utc>,
}

impl AuthBindings {
    /// Builds a binding after validating every material field.
    pub fn new(
        provider: impl Into<String>,
        profile: impl Into<String>,
        account_id: impl Into<String>,
        credential_identity_hash: impl Into<String>,
        scopes: BTreeSet<String>,
        token_status: TokenStatus,
        refresh_available: bool,
        observed_at: DateTime<Utc>,
    ) -> Result<Self, AuthError> {
        let bindings = Self {
            provider: provider.into(),
            profile: profile.into(),
            account_id: account_id.into(),
            credential_identity_hash: credential_identity_hash.into(),
            scopes,
            token_status,
            refresh_available,
            observed_at,
        };
        bindings.validate()?;
        Ok(bindings)
    }

    /// Validates identity, scope, and digest-length invariants.
    pub fn validate(&self) -> Result<(), AuthError> {
        validate_identifier(&self.provider, "provider")?;
        validate_identifier(&self.profile, "profile")?;
        validate_identifier(&self.account_id, "account id")?;
        validate_digest(&self.credential_identity_hash, "credential identity hash")?;
        for scope in &self.scopes {
            validate_scope(scope)?;
        }
        Ok(())
    }

    /// Computes a canonical BLAKE3 digest over the validated binding JSON.
    pub fn digest(&self) -> Result<String, AuthError> {
        self.validate()?;
        let value = serde_json::to_value(self).map_err(|_| AuthError::Serialization)?;
        Ok(hash_json(&value))
    }
}

/// Proof-carrying auth check bound to one routing step and workspace authority.
///
/// This mirrors the `RoutingReceipt` shape: it is secret-free, versioned, and
/// binds a canonical `AuthBindings` digest to an explicit step and workspace
/// generation so a later offline verifier can reject tampered or replayed auth
/// evidence without any provider access.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AuthReceipt {
    /// Public schemas identifier, matching `SCHEMA_VERSION`.
    pub schema_version: String,
    /// Authentication protocol identifier, matching `AUTH_PROTOCOL_VERSION`.
    pub protocol_version: String,
    /// Content-addressed digest of the bound `AuthBindings`.
    pub bindings_hash: String,
    /// Monotonic routing step this auth check served.
    pub step: u64,
    /// Monotonic workspace generation this auth check served.
    pub workspace_generation: u64,
    /// Terminal authorization outcome.
    pub outcome: AuthReceiptOutcome,
}

impl AuthReceipt {
    /// Constructs a receipt, validating bindings and outcome consistency.
    pub fn new(
        bindings: &AuthBindings,
        step: u64,
        workspace_generation: u64,
        outcome: AuthReceiptOutcome,
    ) -> Result<Self, AuthError> {
        let receipt = Self {
            schema_version: SCHEMA_VERSION.to_owned(),
            protocol_version: AUTH_PROTOCOL_VERSION.to_owned(),
            bindings_hash: bindings.digest()?,
            step,
            workspace_generation,
            outcome,
        };
        receipt.validate_outcome(bindings)?;
        receipt.validate()?;
        Ok(receipt)
    }

    /// Validates that the outcome is consistent with the token lifecycle state.
    fn validate_outcome(&self, bindings: &AuthBindings) -> Result<(), AuthError> {
        match self.outcome {
            AuthReceiptOutcome::Authorized => {
                if bindings.token_status != TokenStatus::Active {
                    return Err(AuthError::OutcomeMismatch);
                }
            }
            AuthReceiptOutcome::Expired => {
                if bindings.token_status != TokenStatus::Expired {
                    return Err(AuthError::OutcomeMismatch);
                }
            }
            AuthReceiptOutcome::Revoked => {
                if bindings.token_status != TokenStatus::Revoked {
                    return Err(AuthError::OutcomeMismatch);
                }
            }
            AuthReceiptOutcome::CredentialUnavailable
            | AuthReceiptOutcome::ScopeInsufficient
            | AuthReceiptOutcome::Cancelled => {}
        }
        Ok(())
    }

    /// Validates versioning and binding digest format.
    pub fn validate(&self) -> Result<(), AuthError> {
        if self.schema_version != SCHEMA_VERSION {
            return Err(AuthError::UnsupportedSchema(self.schema_version.clone()));
        }
        if self.protocol_version != AUTH_PROTOCOL_VERSION {
            return Err(AuthError::UnsupportedProtocol(
                self.protocol_version.clone(),
            ));
        }
        validate_digest(&self.bindings_hash, "bindings hash")
    }

    /// Computes a canonical BLAKE3 digest over the validated receipt JSON.
    pub fn digest(&self) -> Result<String, AuthError> {
        self.validate()?;
        let value = serde_json::to_value(self).map_err(|_| AuthError::Serialization)?;
        Ok(hash_json(&value))
    }
}

/// Authentication contract failures.
#[derive(Debug, Error)]
pub enum AuthError {
    /// An unsupported schema version was supplied.
    #[error("unsupported auth schema version: {0}")]
    UnsupportedSchema(String),
    /// An unsupported protocol version was supplied.
    #[error("unsupported auth protocol version: {0}")]
    UnsupportedProtocol(String),
    /// A material field failed validation.
    #[error("invalid auth binding: {0}")]
    Invalid(String),
    /// The receipt outcome contradicts the token lifecycle state.
    #[error("auth receipt outcome contradicts the token lifecycle state")]
    OutcomeMismatch,
    /// The contract could not be serialized for digesting.
    #[error("auth binding serialization failed")]
    Serialization,
}

fn validate_identifier(value: &str, label: &str) -> Result<(), AuthError> {
    if value.is_empty()
        || value.len() > 128
        || !value
            .chars()
            .all(|character| character.is_ascii_alphanumeric() || "-_./:".contains(character))
    {
        return Err(AuthError::Invalid(format!("{label}: {value}")));
    }
    Ok(())
}

fn validate_digest(value: &str, label: &str) -> Result<(), AuthError> {
    if value.len() != 64 || !value.chars().all(|character| character.is_ascii_hexdigit()) {
        return Err(AuthError::Invalid(format!(
            "{label} must be a 64-hex BLAKE3 digest"
        )));
    }
    Ok(())
}

fn validate_scope(value: &str) -> Result<(), AuthError> {
    if value.is_empty()
        || value.len() > 256
        || value
            .chars()
            .any(|character| character.is_control() || character.is_whitespace())
    {
        return Err(AuthError::Invalid(format!("invalid scope: {value}")));
    }
    Ok(())
}

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

    fn digest(seed: &str) -> String {
        hash_bytes(seed.as_bytes())
    }

    fn bindings() -> AuthBindings {
        AuthBindings::new(
            "openai",
            "primary",
            "acct_123",
            digest("keyring:primary"),
            BTreeSet::from(["models.read".to_owned(), "chat.completions".to_owned()]),
            TokenStatus::Active,
            true,
            Utc::now(),
        )
        .unwrap()
    }

    #[test]
    fn authorized_receipt_is_valid() {
        let receipt = AuthReceipt::new(&bindings(), 0, 0, AuthReceiptOutcome::Authorized).unwrap();
        assert_eq!(receipt.schema_version, SCHEMA_VERSION);
        assert_eq!(receipt.protocol_version, AUTH_PROTOCOL_VERSION);
        assert_eq!(receipt.outcome, AuthReceiptOutcome::Authorized);
        assert!(receipt.digest().is_ok());
    }

    #[test]
    fn authorized_outcome_requires_active_token() {
        let mut bindings = bindings();
        bindings.token_status = TokenStatus::Expired;
        assert!(matches!(
            AuthReceipt::new(&bindings, 0, 0, AuthReceiptOutcome::Authorized),
            Err(AuthError::OutcomeMismatch)
        ));
    }

    #[test]
    fn expired_outcome_requires_expired_token() {
        let mut bindings = bindings();
        bindings.token_status = TokenStatus::Expired;
        assert!(AuthReceipt::new(&bindings, 0, 0, AuthReceiptOutcome::Expired).is_ok());
        bindings.token_status = TokenStatus::Active;
        assert!(matches!(
            AuthReceipt::new(&bindings, 0, 0, AuthReceiptOutcome::Expired),
            Err(AuthError::OutcomeMismatch)
        ));
    }

    #[test]
    fn revoked_outcome_requires_revoked_token() {
        let mut bindings = bindings();
        bindings.token_status = TokenStatus::Revoked;
        assert!(AuthReceipt::new(&bindings, 0, 0, AuthReceiptOutcome::Revoked).is_ok());
    }

    #[test]
    fn protocol_and_schema_versions_are_committed() {
        let mut receipt =
            AuthReceipt::new(&bindings(), 0, 0, AuthReceiptOutcome::Authorized).unwrap();
        receipt.protocol_version = "attacker.v1".to_owned();
        assert!(matches!(
            receipt.validate(),
            Err(AuthError::UnsupportedProtocol(_))
        ));
    }

    #[test]
    fn bindings_canonicalize_scopes_and_digest() {
        let base = bindings();
        let left = base.clone();
        let mut right = base;
        // Scope ordering must not alter the canonical digest.
        right.scopes = BTreeSet::from(["chat.completions".to_owned(), "models.read".to_owned()]);
        assert_eq!(left.digest().unwrap(), right.digest().unwrap());
    }

    #[test]
    fn binding_material_is_committed_to_digest() {
        let before = bindings().digest().unwrap();
        let mut changed = bindings();
        changed.account_id = "acct_other".to_owned();
        let after = changed.digest().unwrap();
        assert_ne!(before, after);
    }

    #[test]
    fn binding_rejects_invalid_identity_hash() {
        let mut bindings = bindings();
        bindings.credential_identity_hash = "not-a-digest".to_owned();
        assert!(matches!(bindings.validate(), Err(AuthError::Invalid(_))));
    }

    #[test]
    fn binding_rejects_whitespace_scope() {
        let mut bindings = bindings();
        bindings.scopes.insert("bad scope".to_owned());
        assert!(matches!(bindings.validate(), Err(AuthError::Invalid(_))));
    }

    #[test]
    fn transition_login_sets_active() {
        assert_eq!(
            transition_token(TokenStatus::Expired, TokenLifecycleEvent::Login, true),
            TokenStatus::Active
        );
    }

    #[test]
    fn transition_refresh_succeeds_to_active_without_refresh() {
        // A fresh access token is usable even when no further refresh is stored.
        assert_eq!(
            transition_token(
                TokenStatus::NeedsRefresh,
                TokenLifecycleEvent::RefreshSucceeded,
                false
            ),
            TokenStatus::Active
        );
    }

    #[test]
    fn transition_refresh_unavailable_fails_closed() {
        assert_eq!(
            transition_token(
                TokenStatus::NeedsRefresh,
                TokenLifecycleEvent::RefreshUnavailable,
                false
            ),
            TokenStatus::Expired
        );
        assert_eq!(
            transition_token(
                TokenStatus::NeedsRefresh,
                TokenLifecycleEvent::RefreshUnavailable,
                true
            ),
            TokenStatus::NeedsRefresh
        );
    }

    #[test]
    fn transition_revoke_is_terminal() {
        assert_eq!(
            transition_token(TokenStatus::Active, TokenLifecycleEvent::Revoked, true),
            TokenStatus::Revoked
        );
        // RefreshUnavailable never re-promotes a revoked credential.
        assert_eq!(
            transition_token(
                TokenStatus::Revoked,
                TokenLifecycleEvent::RefreshUnavailable,
                true
            ),
            TokenStatus::Revoked
        );
    }

    #[test]
    fn resolve_expired_active_with_refresh_becomes_needs_refresh() {
        let now = Utc::now();
        assert_eq!(
            resolve_token_status(
                TokenStatus::Active,
                Some(now - chrono::Duration::seconds(1)),
                true,
                now,
            ),
            TokenStatus::NeedsRefresh
        );
        assert_eq!(
            resolve_token_status(
                TokenStatus::Active,
                Some(now - chrono::Duration::seconds(1)),
                false,
                now,
            ),
            TokenStatus::Expired
        );
    }

    #[test]
    fn resolve_needs_refresh_without_refresh_is_expired() {
        let now = Utc::now();
        assert_eq!(
            resolve_token_status(TokenStatus::NeedsRefresh, None, false, now),
            TokenStatus::Expired
        );
    }

    #[test]
    fn resolve_never_repromotes_revoked() {
        let now = Utc::now();
        assert_eq!(
            resolve_token_status(TokenStatus::Revoked, None, true, now),
            TokenStatus::Revoked
        );
    }
}