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