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 SessionTtlPolicy {
76    /// Validate the host's default and maximum in seconds.
77    pub fn new(default_secs: u64, maximum_secs: u64) -> Result<Self, SessionRequestError> {
78        if default_secs == 0 || default_secs > maximum_secs || maximum_secs > MAX_SESSION_SECONDS {
79            return Err(SessionRequestError::InvalidLifetime);
80        }
81        Ok(Self {
82            default_secs,
83            maximum_secs,
84        })
85    }
86
87    /// Duration selected when the request omits a TTL.
88    #[must_use]
89    pub const fn default_secs(self) -> u64 {
90        self.default_secs
91    }
92
93    /// Inclusive maximum duration accepted by this host policy.
94    #[must_use]
95    pub const fn maximum_secs(self) -> u64 {
96        self.maximum_secs
97    }
98}
99
100///
101/// SessionRequest
102///
103/// An unsigned request with 1–16 unique sorted scopes and an optional nonzero TTL.
104/// The scope bound implies at most 1024 label bytes. Constructing or hashing this
105/// value does not grant scopes, authenticate a credential or admit its lifetime.
106///
107
108#[derive(Clone, Debug, Eq, PartialEq)]
109pub struct SessionRequest {
110    scopes: Vec<ScopeLabel>,
111    ttl_secs: Option<u64>,
112}
113
114impl SessionRequest {
115    #[cfg(feature = "receiver-memory")]
116    pub(crate) fn into_scopes(self) -> Vec<ScopeLabel> {
117        self.scopes
118    }
119
120    /// Admit count, then grammar in input order, then duplicates and nonzero TTL.
121    ///
122    /// Scope order is normalized. Positive TTLs, including those above the
123    /// protocol ceiling, retain their exact identity until host-policy evaluation.
124    pub fn new(scopes: Vec<String>, ttl_secs: Option<u64>) -> Result<Self, SessionRequestError> {
125        if !(1..=MAX_SCOPES).contains(&scopes.len()) {
126            return Err(SessionRequestError::InvalidRequest);
127        }
128        let mut scopes = scopes
129            .into_iter()
130            .map(ScopeLabel::try_from)
131            .collect::<Result<Vec<_>, _>>()
132            .map_err(SessionRequestError::Scope)?;
133        scopes.sort_unstable();
134        if scopes.windows(2).any(|pair| pair[0] == pair[1]) || ttl_secs == Some(0) {
135            return Err(SessionRequestError::InvalidRequest);
136        }
137        Ok(Self { scopes, ttl_secs })
138    }
139
140    /// Borrow normalized scopes; their inclusion still needs a verified grant.
141    #[must_use]
142    pub fn scopes(&self) -> &[ScopeLabel] {
143        &self.scopes
144    }
145
146    /// Exact submitted lifetime, preserving absence independently of host defaults.
147    #[must_use]
148    pub const fn ttl_secs(&self) -> Option<u64> {
149        self.ttl_secs
150    }
151
152    /// Compute the existing V1 request identity without allocating encoded bytes.
153    ///
154    /// Domain bytes have no terminator. Counts, label lengths and the optional TTL
155    /// use big-endian u64; the TTL presence tag is one byte. This is a request
156    /// fingerprint, never a signed credential or authorization token.
157    #[must_use]
158    pub fn hash(&self) -> [u8; 32] {
159        let mut digest = Sha256::new();
160        digest.update(REQUEST_DOMAIN);
161        digest.update((self.scopes.len() as u64).to_be_bytes());
162        for scope in &self.scopes {
163            let bytes = scope.as_str().as_bytes();
164            digest.update((bytes.len() as u64).to_be_bytes());
165            digest.update(bytes);
166        }
167        digest.update([u8::from(self.ttl_secs.is_some())]);
168        if let Some(seconds) = self.ttl_secs {
169            digest.update(seconds.to_be_bytes());
170        }
171        digest.finalize().into()
172    }
173
174    /// Compute the requested deadline from a trusted host time and policy.
175    ///
176    /// Reject over-limit TTLs and overflow. The receiver must additionally cap
177    /// this deadline by login, key and enrollment deadlines; this method alone
178    /// cannot establish a usable session lease.
179    pub fn expires_at_ns(
180        &self,
181        now_ns: u64,
182        policy: SessionTtlPolicy,
183    ) -> Result<u64, SessionRequestError> {
184        let seconds = self.ttl_secs.unwrap_or(policy.default_secs);
185        if seconds > policy.maximum_secs {
186            return Err(SessionRequestError::InvalidLifetime);
187        }
188        // Policy admission bounds multiplication to 1800 seconds before it runs.
189        now_ns
190            .checked_add(seconds * NANOS_PER_SECOND)
191            .ok_or(SessionRequestError::InvalidLifetime)
192    }
193
194    /// Check narrowing to one protected role, then calculate the requested deadline.
195    ///
196    /// This is cheap request preflight, not proof verification or session admission.
197    /// Grants must be bounded, strictly ordered and unique; they are never sorted.
198    /// Other roles cannot supply missing scopes. The host owns `role`, time and
199    /// TTL policy. Signature, fresh-claims aggregate bounds, current authority,
200    /// replay/revocation and login/key/enrollment lease caps remain separate.
201    pub fn evaluate_grants(
202        &self,
203        grants: &[DelegatedRoleGrant],
204        role: &AuthRole,
205        now_ns: u64,
206        policy: SessionTtlPolicy,
207    ) -> Result<u64, SessionRequestError> {
208        validate_grants(grants).map_err(SessionRequestError::Grants)?;
209        let selected = crate::grant_policy::for_role(grants, role)
210            .ok_or(SessionRequestError::ScopeRejected)?;
211        if !crate::grant_policy::scopes_subset(&self.scopes, &selected.scopes) {
212            return Err(SessionRequestError::ScopeRejected);
213        }
214        self.expires_at_ns(now_ns, policy)
215    }
216}