Skip to main content

vela_protocol/kernel/
authentication.rs

1//! Bearer-free observations of standard authentication ceremonies.
2//!
3//! Runtime credentials, cookies, assertions, and tokens remain with their
4//! providers. Canonical history retains only facts the repository authority
5//! validated at transaction time.
6
7use std::collections::BTreeSet;
8
9use chrono::{DateTime, SecondsFormat};
10use serde::{Deserialize, Serialize};
11
12use super::principal_capability::PrincipalClass;
13
14pub const AUTHENTICATION_OBSERVATION_SCHEMA_V1: &str = "vela.authentication-observation.v1";
15pub const MAX_AUTHENTICATION_AGE_SECONDS: i64 = 24 * 60 * 60;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum AuthenticationMethod {
20    LocalOsSession,
21    PlatformUserPresence,
22    AgentEventSignature,
23    AgentRecordSignature,
24    Passkey,
25    Oidc,
26    WorkloadOidc,
27    GithubApp,
28    SciTokens,
29    Spiffe,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34pub enum AuthenticationAssurance {
35    LocalSession,
36    SingleFactor,
37    MultiFactor,
38    PhishingResistant,
39    WorkloadAttested,
40}
41
42/// `session_root` commits to a provider-side session or assertion record. It
43/// is never the session identifier or bearer credential itself.
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(deny_unknown_fields)]
46pub struct AuthenticationObservationV1 {
47    pub schema: String,
48    pub principal_id: String,
49    pub principal_class: PrincipalClass,
50    pub issuer: String,
51    pub subject: String,
52    pub method: AuthenticationMethod,
53    pub assurance: AuthenticationAssurance,
54    pub session_root: String,
55    pub authenticated_at: String,
56    pub observed_at: String,
57    pub expires_at: String,
58    pub user_presence: bool,
59    pub user_verification: bool,
60    pub recovery_recent: bool,
61    pub revocation_ref: Option<String>,
62}
63
64impl AuthenticationObservationV1 {
65    pub fn validate(&self) -> Result<(), String> {
66        if self.schema != AUTHENTICATION_OBSERVATION_SCHEMA_V1 {
67            return Err(format!(
68                "authentication schema must be {AUTHENTICATION_OBSERVATION_SCHEMA_V1}"
69            ));
70        }
71        require_text("authentication principal", &self.principal_id, 2048)?;
72        require_text("authentication issuer", &self.issuer, 1024)?;
73        require_text("authentication subject", &self.subject, 1024)?;
74        require_sha256("authentication session_root", &self.session_root)?;
75        if let Some(root) = &self.revocation_ref {
76            require_sha256("authentication revocation_ref", root)?;
77        }
78
79        let authenticated_at =
80            parse_canonical_time("authentication authenticated_at", &self.authenticated_at)?;
81        let observed_at = parse_canonical_time("authentication observed_at", &self.observed_at)?;
82        let expires_at = parse_canonical_time("authentication expires_at", &self.expires_at)?;
83        if observed_at < authenticated_at
84            || observed_at >= expires_at
85            || (expires_at - authenticated_at).num_seconds() > MAX_AUTHENTICATION_AGE_SECONDS
86        {
87            return Err("authentication observation is stale or exceeds 24 hours".into());
88        }
89
90        match self.principal_class {
91            PrincipalClass::Human => {
92                let identifiers = [
93                    format!("local:{}|{}", self.issuer, self.subject),
94                    format!("oidc:{}|{}", self.issuer, self.subject),
95                    format!("orcid:{}|{}", self.issuer, self.subject),
96                ];
97                if !identifiers.contains(&self.principal_id) {
98                    return Err(
99                        "human authentication must bind the exact principal issuer-subject".into(),
100                    );
101                }
102                if !matches!(
103                    self.method,
104                    AuthenticationMethod::LocalOsSession
105                        | AuthenticationMethod::PlatformUserPresence
106                        | AuthenticationMethod::Passkey
107                        | AuthenticationMethod::Oidc
108                ) {
109                    return Err("human authentication method is not supported".into());
110                }
111                if self.method == AuthenticationMethod::Passkey
112                    && (!self.user_presence
113                        || !self.user_verification
114                        || self.assurance != AuthenticationAssurance::PhishingResistant)
115                {
116                    return Err(
117                        "passkey authentication requires presence, verification, and phishing resistance"
118                            .into(),
119                    );
120                }
121                if self.method == AuthenticationMethod::PlatformUserPresence
122                    && (!self.user_presence
123                        || !self.user_verification
124                        || self.assurance < AuthenticationAssurance::MultiFactor)
125                {
126                    return Err(
127                        "platform user-presence authentication requires presence and verification"
128                            .into(),
129                    );
130                }
131            }
132            PrincipalClass::Agent => {
133                let locally_signed = matches!(
134                    self.method,
135                    AuthenticationMethod::AgentEventSignature
136                        | AuthenticationMethod::AgentRecordSignature
137                ) && self.assurance == AuthenticationAssurance::SingleFactor;
138                let externally_attested = matches!(
139                    self.method,
140                    AuthenticationMethod::WorkloadOidc
141                        | AuthenticationMethod::GithubApp
142                        | AuthenticationMethod::SciTokens
143                        | AuthenticationMethod::Spiffe
144                ) && self.assurance
145                    == AuthenticationAssurance::WorkloadAttested;
146                if (!locally_signed && !externally_attested)
147                    || self.user_presence
148                    || self.user_verification
149                {
150                    return Err("agent authentication facts are invalid".into());
151                }
152            }
153            PrincipalClass::Workload => {
154                if !matches!(
155                    self.method,
156                    AuthenticationMethod::WorkloadOidc
157                        | AuthenticationMethod::GithubApp
158                        | AuthenticationMethod::SciTokens
159                        | AuthenticationMethod::Spiffe
160                ) || self.assurance != AuthenticationAssurance::WorkloadAttested
161                    || self.user_presence
162                    || self.user_verification
163                {
164                    return Err("workload authentication facts are invalid".into());
165                }
166            }
167            PrincipalClass::Service | PrincipalClass::Institution => {
168                return Err(
169                    "service and institution entities do not authenticate as transaction principals"
170                        .into(),
171                );
172            }
173        }
174        Ok(())
175    }
176
177    pub fn validate_at(
178        &self,
179        transaction_at: &str,
180        revoked_session_roots: &BTreeSet<String>,
181    ) -> Result<(), String> {
182        self.validate()?;
183        if transaction_at != self.observed_at {
184            return Err("authentication observation time differs from the authority record".into());
185        }
186        if revoked_session_roots.contains(&self.session_root) {
187            return Err("authentication session was revoked before transaction use".into());
188        }
189        Ok(())
190    }
191}
192
193fn require_text(name: &str, value: &str, maximum: usize) -> Result<(), String> {
194    if value.is_empty()
195        || value.len() > maximum
196        || value.chars().any(|character| character.is_control())
197    {
198        return Err(format!(
199            "{name} is empty, oversized, or contains control text"
200        ));
201    }
202    Ok(())
203}
204
205fn require_sha256(name: &str, value: &str) -> Result<(), String> {
206    let Some(hex) = value.strip_prefix("sha256:") else {
207        return Err(format!("{name} must use a full sha256: digest"));
208    };
209    if hex.len() != 64
210        || !hex
211            .bytes()
212            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
213    {
214        return Err(format!(
215            "{name} must contain 64 lowercase hexadecimal characters"
216        ));
217    }
218    Ok(())
219}
220
221fn parse_canonical_time(name: &str, value: &str) -> Result<DateTime<chrono::FixedOffset>, String> {
222    let parsed = DateTime::parse_from_rfc3339(value)
223        .map_err(|error| format!("{name} is not RFC3339: {error}"))?;
224    if parsed.to_rfc3339_opts(SecondsFormat::Secs, true) != value {
225        return Err(format!(
226            "{name} must use canonical whole-second UTC RFC3339"
227        ));
228    }
229    Ok(parsed)
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235
236    fn root(character: char) -> String {
237        format!("sha256:{}", character.to_string().repeat(64))
238    }
239
240    fn human() -> AuthenticationObservationV1 {
241        AuthenticationObservationV1 {
242            schema: AUTHENTICATION_OBSERVATION_SCHEMA_V1.into(),
243            principal_id: "oidc:https://github.com|1234567".into(),
244            principal_class: PrincipalClass::Human,
245            issuer: "https://github.com".into(),
246            subject: "1234567".into(),
247            method: AuthenticationMethod::Passkey,
248            assurance: AuthenticationAssurance::PhishingResistant,
249            session_root: root('a'),
250            authenticated_at: "2026-07-24T12:00:00Z".into(),
251            observed_at: "2026-07-24T12:05:00Z".into(),
252            expires_at: "2026-07-24T13:00:00Z".into(),
253            user_presence: true,
254            user_verification: true,
255            recovery_recent: false,
256            revocation_ref: Some(root('b')),
257        }
258    }
259
260    #[test]
261    fn exact_human_observation_is_bearer_free() {
262        let observation = human();
263        observation.validate().unwrap();
264        let encoded = serde_json::to_string(&observation).unwrap();
265        assert!(!encoded.contains("bearer"));
266        assert!(!encoded.contains("session_id"));
267        assert!(!encoded.contains("cookie"));
268    }
269
270    #[test]
271    fn passkey_requires_exact_identity_presence_and_verification() {
272        let mut wrong_identity = human();
273        wrong_identity.principal_id = "someone@example.com".into();
274        assert!(wrong_identity.validate().is_err());
275
276        let mut no_verification = human();
277        no_verification.user_verification = false;
278        assert!(no_verification.validate().is_err());
279    }
280
281    #[test]
282    fn signed_agent_record_is_a_single_factor_agent_observation() {
283        let observation = AuthenticationObservationV1 {
284            schema: AUTHENTICATION_OBSERVATION_SCHEMA_V1.into(),
285            principal_id: "agent:fixture".into(),
286            principal_class: PrincipalClass::Agent,
287            issuer: "vela.activity-record.v1".into(),
288            subject: "agent:fixture".into(),
289            method: AuthenticationMethod::AgentRecordSignature,
290            assurance: AuthenticationAssurance::SingleFactor,
291            session_root: root('c'),
292            authenticated_at: "2026-07-24T12:00:00Z".into(),
293            observed_at: "2026-07-24T12:01:00Z".into(),
294            expires_at: "2026-07-24T12:05:00Z".into(),
295            user_presence: false,
296            user_verification: false,
297            recovery_recent: false,
298            revocation_ref: None,
299        };
300        observation.validate().unwrap();
301
302        let mut wrong_assurance = observation.clone();
303        wrong_assurance.assurance = AuthenticationAssurance::MultiFactor;
304        assert!(wrong_assurance.validate().is_err());
305
306        let mut fabricated_presence = observation;
307        fabricated_presence.user_presence = true;
308        assert!(fabricated_presence.validate().is_err());
309    }
310
311    #[test]
312    fn expiry_and_revocation_fail_closed() {
313        let observation = human();
314        assert!(
315            observation
316                .validate_at(&observation.observed_at, &BTreeSet::new())
317                .is_ok()
318        );
319        assert!(
320            observation
321                .validate_at(
322                    &observation.observed_at,
323                    &BTreeSet::from([observation.session_root.clone()])
324                )
325                .is_err()
326        );
327
328        let mut stale = human();
329        stale.expires_at = "2026-07-26T12:00:00Z".into();
330        assert!(stale.validate().is_err());
331    }
332
333    #[test]
334    fn recovery_is_retained_policy_context_not_hidden_state() {
335        let mut observation = human();
336        observation.recovery_recent = true;
337        observation.validate().unwrap();
338        assert_eq!(
339            serde_json::to_value(observation).unwrap()["recovery_recent"],
340            true
341        );
342    }
343}