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    /// Admit count, then grammar in input order, then duplicates and nonzero TTL.
107    ///
108    /// Scope order is normalized. Positive TTLs, including those above the
109    /// protocol ceiling, retain their exact identity until host-policy evaluation.
110    pub fn new(scopes: Vec<String>, ttl_secs: Option<u64>) -> Result<Self, SessionRequestError> {
111        if !(1..=MAX_SCOPES).contains(&scopes.len()) {
112            return Err(SessionRequestError::InvalidRequest);
113        }
114        let mut scopes = scopes
115            .into_iter()
116            .map(ScopeLabel::try_from)
117            .collect::<Result<Vec<_>, _>>()
118            .map_err(SessionRequestError::Scope)?;
119        scopes.sort_unstable();
120        if scopes.windows(2).any(|pair| pair[0] == pair[1]) || ttl_secs == Some(0) {
121            return Err(SessionRequestError::InvalidRequest);
122        }
123        Ok(Self { scopes, ttl_secs })
124    }
125
126    /// Borrow normalized scopes; their inclusion still needs a verified grant.
127    #[must_use]
128    pub fn scopes(&self) -> &[ScopeLabel] {
129        &self.scopes
130    }
131
132    /// Exact submitted lifetime, preserving absence independently of host defaults.
133    #[must_use]
134    pub const fn ttl_secs(&self) -> Option<u64> {
135        self.ttl_secs
136    }
137
138    /// Compute the existing V1 request identity without allocating encoded bytes.
139    ///
140    /// Domain bytes have no terminator. Counts, label lengths and the optional TTL
141    /// use big-endian u64; the TTL presence tag is one byte. This is a request
142    /// fingerprint, never a signed credential or authorization token.
143    #[must_use]
144    pub fn hash(&self) -> [u8; 32] {
145        let mut digest = Sha256::new();
146        digest.update(REQUEST_DOMAIN);
147        digest.update((self.scopes.len() as u64).to_be_bytes());
148        for scope in &self.scopes {
149            let bytes = scope.as_str().as_bytes();
150            digest.update((bytes.len() as u64).to_be_bytes());
151            digest.update(bytes);
152        }
153        digest.update([u8::from(self.ttl_secs.is_some())]);
154        if let Some(seconds) = self.ttl_secs {
155            digest.update(seconds.to_be_bytes());
156        }
157        digest.finalize().into()
158    }
159
160    /// Compute the requested deadline from a trusted host time and policy.
161    ///
162    /// Reject over-limit TTLs and overflow. The receiver must additionally cap
163    /// this deadline by login, key and enrollment deadlines; this method alone
164    /// cannot establish a usable session lease.
165    pub fn expires_at_ns(
166        &self,
167        now_ns: u64,
168        policy: SessionTtlPolicy,
169    ) -> Result<u64, SessionRequestError> {
170        let seconds = self.ttl_secs.unwrap_or(policy.default_secs);
171        if seconds > policy.maximum_secs {
172            return Err(SessionRequestError::InvalidLifetime);
173        }
174        // Policy admission bounds multiplication to 1800 seconds before it runs.
175        now_ns
176            .checked_add(seconds * NANOS_PER_SECOND)
177            .ok_or(SessionRequestError::InvalidLifetime)
178    }
179
180    /// Check narrowing to one protected role, then calculate the requested deadline.
181    ///
182    /// This is cheap request preflight, not proof verification or session admission.
183    /// Grants must be bounded, strictly ordered and unique; they are never sorted.
184    /// Other roles cannot supply missing scopes. The host owns `role`, time and
185    /// TTL policy. Signature, fresh-claims aggregate bounds, current authority,
186    /// replay/revocation and login/key/enrollment lease caps remain separate.
187    pub fn evaluate_grants(
188        &self,
189        grants: &[DelegatedRoleGrant],
190        role: &AuthRole,
191        now_ns: u64,
192        policy: SessionTtlPolicy,
193    ) -> Result<u64, SessionRequestError> {
194        validate_grants(grants).map_err(SessionRequestError::Grants)?;
195        let selected = crate::grant_policy::for_role(grants, role)
196            .ok_or(SessionRequestError::ScopeRejected)?;
197        if !crate::grant_policy::scopes_subset(&self.scopes, &selected.scopes) {
198            return Err(SessionRequestError::ScopeRejected);
199        }
200        self.expires_at_ns(now_ns, policy)
201    }
202}