Skip to main content

ic_auth/
session_request.rs

1//! Canonical unsigned request identity and host-selected lifetime bounds.
2//!
3//! Sorting here is specific to unsigned requests. Signed grant lists must retain
4//! their separate strict-order admission; they must never be sorted into validity.
5
6use crate::claims::{ClaimsError, validate_grants};
7use ic_auth_protocol_types::{AuthRole, DelegatedRoleGrant, ScopeLabel, ScopeLabelError};
8use sha2::{Digest, Sha256};
9use std::{error::Error, fmt};
10
11const MAX_SCOPES: usize = 16;
12const MAX_SESSION_SECONDS: u64 = 1800;
13const NANOS_PER_SECOND: u64 = 1_000_000_000;
14const REQUEST_DOMAIN: &[u8] = b"canic-application-session-request-v1";
15
16///
17/// SessionRequestError
18///
19/// Shape or lifetime refusal. None of these results authenticate a request.
20///
21
22#[derive(Clone, Copy, Debug, Eq, PartialEq)]
23pub enum SessionRequestError {
24    /// Scope count, uniqueness or nonzero TTL was violated.
25    InvalidRequest,
26    /// A label violates the canonical scope grammar.
27    Scope(ScopeLabelError),
28    /// Submitted grants failed bounded canonical shape/order admission.
29    Grants(ClaimsError),
30    /// The protected role is absent or does not contain every requested scope.
31    ScopeRejected,
32    /// Host policy, requested TTL or deadline arithmetic is invalid.
33    InvalidLifetime,
34}
35
36impl fmt::Display for SessionRequestError {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self {
39            Self::InvalidRequest => f.write_str(
40                "session request has invalid scope bounds, duplicate scopes or zero TTL",
41            ),
42            Self::Scope(error) => error.fmt(f),
43            Self::Grants(error) => error.fmt(f),
44            Self::ScopeRejected => f.write_str("requested scopes exceed the selected role"),
45            Self::InvalidLifetime => {
46                f.write_str("invalid session TTL policy, requested lifetime or expiry overflow")
47            }
48        }
49    }
50}
51
52impl Error for SessionRequestError {
53    fn source(&self) -> Option<&(dyn Error + 'static)> {
54        match self {
55            Self::Scope(error) => Some(error),
56            Self::Grants(error) => Some(error),
57            _ => None,
58        }
59    }
60}
61
62///
63/// SessionTtlPolicy
64///
65/// Host-supplied default and ceiling, with `1 <= default <= maximum <= 1800`.
66/// Construction validates numeric bounds, not the provenance of host policy.
67///
68
69#[derive(Clone, Copy, Debug, Eq, PartialEq)]
70pub struct SessionTtlPolicy {
71    default_secs: u64,
72    maximum_secs: u64,
73}
74
75impl Default for SessionTtlPolicy {
76    /// Fifteen-minute leases with a 30-minute request ceiling.
77    fn default() -> Self {
78        Self {
79            default_secs: 900,
80            maximum_secs: MAX_SESSION_SECONDS,
81        }
82    }
83}
84
85impl SessionTtlPolicy {
86    /// Validate the host's default and maximum in seconds.
87    pub fn new(default_secs: u64, maximum_secs: u64) -> Result<Self, SessionRequestError> {
88        if default_secs == 0 || default_secs > maximum_secs || maximum_secs > MAX_SESSION_SECONDS {
89            return Err(SessionRequestError::InvalidLifetime);
90        }
91        Ok(Self {
92            default_secs,
93            maximum_secs,
94        })
95    }
96
97    /// Duration selected when the request omits a TTL.
98    #[must_use]
99    pub const fn default_secs(self) -> u64 {
100        self.default_secs
101    }
102
103    /// Inclusive maximum duration accepted by this host policy.
104    #[must_use]
105    pub const fn maximum_secs(self) -> u64 {
106        self.maximum_secs
107    }
108}
109
110///
111/// SessionRequest
112///
113/// An unsigned request with 1–16 unique sorted scopes and an optional nonzero TTL.
114/// The scope bound implies at most 1024 label bytes. Constructing or hashing this
115/// value does not grant scopes, authenticate a credential or admit its lifetime.
116///
117
118#[derive(Clone, Debug, Eq, PartialEq)]
119pub struct SessionRequest {
120    scopes: Vec<ScopeLabel>,
121    ttl_secs: Option<u64>,
122}
123
124impl SessionRequest {
125    #[cfg(feature = "receiver-stable")]
126    pub(crate) fn into_scopes(self) -> Vec<ScopeLabel> {
127        self.scopes
128    }
129
130    /// Admit count, then grammar in input order, then duplicates and nonzero TTL.
131    ///
132    /// Scope order is normalized. Positive TTLs, including those above the
133    /// protocol ceiling, retain their exact identity until host-policy evaluation.
134    pub fn new(scopes: Vec<String>, ttl_secs: Option<u64>) -> Result<Self, SessionRequestError> {
135        if !(1..=MAX_SCOPES).contains(&scopes.len()) {
136            return Err(SessionRequestError::InvalidRequest);
137        }
138        let mut scopes = scopes
139            .into_iter()
140            .map(ScopeLabel::try_from)
141            .collect::<Result<Vec<_>, _>>()
142            .map_err(SessionRequestError::Scope)?;
143        scopes.sort_unstable();
144        if scopes.windows(2).any(|pair| pair[0] == pair[1]) || ttl_secs == Some(0) {
145            return Err(SessionRequestError::InvalidRequest);
146        }
147        Ok(Self { scopes, ttl_secs })
148    }
149
150    /// Borrow normalized scopes; their inclusion still needs a verified grant.
151    #[must_use]
152    pub fn scopes(&self) -> &[ScopeLabel] {
153        &self.scopes
154    }
155
156    /// Exact submitted lifetime, preserving absence independently of host defaults.
157    #[must_use]
158    pub const fn ttl_secs(&self) -> Option<u64> {
159        self.ttl_secs
160    }
161
162    /// Compute the existing V1 request identity without allocating encoded bytes.
163    ///
164    /// Domain bytes have no terminator. Counts, label lengths and the optional TTL
165    /// use big-endian u64; the TTL presence tag is one byte. This is a request
166    /// fingerprint, never a signed credential or authorization token.
167    #[must_use]
168    pub fn hash(&self) -> [u8; 32] {
169        let mut digest = Sha256::new();
170        digest.update(REQUEST_DOMAIN);
171        digest.update((self.scopes.len() as u64).to_be_bytes());
172        for scope in &self.scopes {
173            let bytes = scope.as_str().as_bytes();
174            digest.update((bytes.len() as u64).to_be_bytes());
175            digest.update(bytes);
176        }
177        digest.update([u8::from(self.ttl_secs.is_some())]);
178        if let Some(seconds) = self.ttl_secs {
179            digest.update(seconds.to_be_bytes());
180        }
181        digest.finalize().into()
182    }
183
184    /// Compute the requested deadline from a trusted host time and policy.
185    ///
186    /// Reject over-limit TTLs and overflow. The receiver must additionally cap
187    /// this deadline by login and authority expiry. Current enrollment is
188    /// independently required for using the session.
189    pub fn expires_at_ns(
190        &self,
191        now_ns: u64,
192        policy: SessionTtlPolicy,
193    ) -> Result<u64, SessionRequestError> {
194        let seconds = self.ttl_secs.unwrap_or(policy.default_secs);
195        if seconds > policy.maximum_secs {
196            return Err(SessionRequestError::InvalidLifetime);
197        }
198        // Policy admission bounds multiplication to 1800 seconds before it runs.
199        now_ns
200            .checked_add(seconds * NANOS_PER_SECOND)
201            .ok_or(SessionRequestError::InvalidLifetime)
202    }
203
204    /// Check narrowing to one protected role, then calculate the requested deadline.
205    ///
206    /// This is cheap request preflight, not proof verification or session admission.
207    /// Grants must be bounded, strictly ordered and unique; they are never sorted.
208    /// Other roles cannot supply missing scopes. The host owns `role`, time and
209    /// TTL policy. Signature, fresh-claims aggregate bounds, current authority,
210    /// replay, revocation, enrollment freshness and the login and authority lease caps remain separate.
211    pub fn evaluate_grants(
212        &self,
213        grants: &[DelegatedRoleGrant],
214        role: &AuthRole,
215        now_ns: u64,
216        policy: SessionTtlPolicy,
217    ) -> Result<u64, SessionRequestError> {
218        validate_grants(grants).map_err(SessionRequestError::Grants)?;
219        let selected = crate::grant_policy::for_role(grants, role)
220            .ok_or(SessionRequestError::ScopeRejected)?;
221        if !crate::grant_policy::scopes_subset(&self.scopes, &selected.scopes) {
222            return Err(SessionRequestError::ScopeRejected);
223        }
224        self.expires_at_ns(now_ns, policy)
225    }
226}