Skip to main content

ic_auth/
session_request.rs

1//! Canonical session request identity, independent of proof verification or storage.
2//!
3//! Hashing a request does not authenticate a token, select host TTL policy or
4//! grant scopes. Session admission and replay remain separate engine obligations.
5
6use crate::canonical::CanonicalAuthError;
7use ic_auth_protocol_types::{AuthRole, DelegatedRoleGrant, ScopeLabel};
8use sha2::{Digest, Sha256};
9use thiserror::Error;
10
11/// Request shape, narrowing and lifetime rejection; no cryptographic verification.
12#[derive(Debug, Error, Eq, PartialEq)]
13pub enum SessionRequestError {
14    /// Scope bounds, uniqueness or a nonzero requested lifetime were violated.
15    #[error("session request has invalid scope bounds, duplicate scopes or zero TTL")]
16    InvalidRequest,
17    /// Host TTL policy, requested lifetime or deadline arithmetic is invalid.
18    #[error("invalid session TTL policy, requested lifetime or expiry overflow")]
19    InvalidLifetime,
20    /// The request exceeds the grant for the protected receiver role.
21    #[error("requested scopes are not granted for the protected receiver role")]
22    ScopeRejected,
23    /// A scope label or grant cannot be represented canonically.
24    #[error(transparent)]
25    Canonical(#[from] CanonicalAuthError),
26}
27
28/// Checked current maximum session lifetime, in seconds (1..=1800).
29/// Authorization needs this bound, without an admission default.
30/// Construction cannot bypass range admission:
31/// ```compile_fail
32/// use ic_auth::session_request::SessionTtlLimit;
33/// let invalid = SessionTtlLimit(0);
34/// ```
35#[derive(Clone, Copy, Debug, Eq, PartialEq)]
36pub struct SessionTtlLimit(u64);
37impl SessionTtlLimit {
38    /// Admit a positive maximum no greater than the protocol session ceiling.
39    pub fn new(seconds: u64) -> Result<Self, SessionRequestError> {
40        if seconds == 0 || seconds > crate::limits::MAX_SESSION_SECS {
41            return Err(SessionRequestError::InvalidLifetime);
42        }
43        Ok(Self(seconds))
44    }
45    #[must_use]
46    /// Return the admitted maximum in seconds.
47    pub const fn seconds(self) -> u64 {
48        self.0
49    }
50}
51
52/// Checked default and maximum TTL for fresh admission. Neither value is taken
53/// from a submitted request. Live authorization uses only `maximum()`.
54#[derive(Clone, Copy, Debug, Eq, PartialEq)]
55pub struct SessionTtlPolicy {
56    default_secs: u64,
57    maximum: SessionTtlLimit,
58}
59impl SessionTtlPolicy {
60    /// Admit positive default/maximum lifetimes with default no greater than maximum.
61    pub fn new(default_secs: u64, maximum_secs: u64) -> Result<Self, SessionRequestError> {
62        let maximum = SessionTtlLimit::new(maximum_secs)?;
63        if default_secs == 0 || default_secs > maximum_secs {
64            return Err(SessionRequestError::InvalidLifetime);
65        }
66        Ok(Self {
67            default_secs,
68            maximum,
69        })
70    }
71    #[must_use]
72    /// Lifetime used when a request does not specify one, in seconds.
73    pub const fn default_secs(self) -> u64 {
74        self.default_secs
75    }
76    #[must_use]
77    /// Maximum admitted lifetime for both fresh admission and later authorization.
78    pub const fn maximum(self) -> SessionTtlLimit {
79        self.maximum
80    }
81}
82
83/// Canonical narrowing request: 1..=16 unique scopes, at most 1024 scope bytes.
84/// Input order is normalized before hashing; duplicates are rejected.
85#[derive(Clone, Debug, Eq, PartialEq)]
86pub struct SessionRequest {
87    scopes: Vec<ScopeLabel>,
88    ttl_secs: Option<u64>,
89}
90impl SessionRequest {
91    /// Validate scope bounds and grammar, sort scopes, and reject duplicates or zero TTL.
92    /// This does not grant permissions or admit the TTL against host policy.
93    pub fn new(scopes: Vec<String>, ttl_secs: Option<u64>) -> Result<Self, SessionRequestError> {
94        check_scope_count(scopes.len())?;
95        let mut scopes = ScopeLabel::from_strings(scopes).map_err(CanonicalAuthError::from)?;
96        scopes.sort_unstable();
97        if scopes.windows(2).any(|pair| pair[0] == pair[1]) || ttl_secs == Some(0) {
98            return Err(SessionRequestError::InvalidRequest);
99        }
100        Ok(Self { scopes, ttl_secs })
101    }
102    /// Exact requested TTL in seconds; None leaves selection to protected host policy.
103    #[must_use]
104    pub const fn ttl_secs(&self) -> Option<u64> {
105        self.ttl_secs
106    }
107    #[must_use]
108    /// Borrow the sorted, unique requested scopes.
109    pub fn scopes(&self) -> &[ScopeLabel] {
110        &self.scopes
111    }
112    #[cfg(all(
113        feature = "sessions",
114        any(
115            feature = "portable-signature-verification",
116            feature = "certified-proof-verification"
117        )
118    ))]
119    pub(crate) fn into_scopes(self) -> Vec<ScopeLabel> {
120        self.scopes
121    }
122    /// Calculate a requested lease against protected TTL policy (maximum 1800s).
123    /// This authenticates nothing and does not cap login or authority deadlines.
124    /// The host supplies its clock and default/maximum policy, never the request.
125    pub fn expires_at_ns(
126        &self,
127        now_ns: u64,
128        policy: SessionTtlPolicy,
129    ) -> Result<u64, SessionRequestError> {
130        let ttl = self.ttl_secs.unwrap_or(policy.default_secs());
131        if ttl > policy.maximum().seconds() {
132            return Err(SessionRequestError::InvalidLifetime);
133        }
134        now_ns
135            .checked_add(ttl * crate::limits::NS_PER_SECOND)
136            .ok_or(SessionRequestError::InvalidLifetime)
137    }
138    /// Evaluate narrowing and requested TTL at this caller's protected snapshot.
139    /// Admission and verified claims both use this policy; each retains its own
140    /// authority checks and the verified lease additionally caps signed deadlines.
141    pub(crate) fn evaluate(
142        &self,
143        grants: &[DelegatedRoleGrant],
144        role: &AuthRole,
145        now_ns: u64,
146        policy: SessionTtlPolicy,
147    ) -> Result<u64, SessionRequestError> {
148        let grant = crate::certificate_issuance::grant_for_role(grants, role)
149            .ok_or(SessionRequestError::ScopeRejected)?;
150        if !crate::certificate_issuance::scopes_are_subset(&self.scopes, &grant.scopes) {
151            return Err(SessionRequestError::ScopeRejected);
152        }
153        self.expires_at_ns(now_ns, policy)
154    }
155    /// Exact Canic V1 request hash; None and an explicit default TTL differ.
156    #[must_use]
157    pub fn hash(&self) -> [u8; 32] {
158        let mut hash = Sha256::new();
159        hash.update(b"canic-application-session-request-v1");
160        hash.update((self.scopes.len() as u64).to_be_bytes());
161        for scope in &self.scopes {
162            hash.update((scope.as_str().len() as u64).to_be_bytes());
163            hash.update(scope.as_str().as_bytes());
164        }
165        match self.ttl_secs {
166            None => hash.update([0]),
167            Some(ttl) => {
168                hash.update([1]);
169                hash.update(ttl.to_be_bytes());
170            }
171        }
172        hash.finalize().into()
173    }
174}
175
176pub(crate) fn check_scope_count(count: usize) -> Result<(), SessionRequestError> {
177    if count == 0 || count > crate::limits::MAX_SESSION_SCOPES {
178        return Err(SessionRequestError::InvalidRequest);
179    }
180    Ok(())
181}