ic_auth/
session_request.rs1use 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
23pub enum SessionRequestError {
24 InvalidRequest,
26 Scope(ScopeLabelError),
28 Grants(ClaimsError),
30 ScopeRejected,
32 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
70pub struct SessionTtlPolicy {
71 default_secs: u64,
72 maximum_secs: u64,
73}
74
75impl Default for SessionTtlPolicy {
76 fn default() -> Self {
78 Self {
79 default_secs: 900,
80 maximum_secs: MAX_SESSION_SECONDS,
81 }
82 }
83}
84
85impl SessionTtlPolicy {
86 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 #[must_use]
99 pub const fn default_secs(self) -> u64 {
100 self.default_secs
101 }
102
103 #[must_use]
105 pub const fn maximum_secs(self) -> u64 {
106 self.maximum_secs
107 }
108}
109
110#[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 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 #[must_use]
152 pub fn scopes(&self) -> &[ScopeLabel] {
153 &self.scopes
154 }
155
156 #[must_use]
158 pub const fn ttl_secs(&self) -> Option<u64> {
159 self.ttl_secs
160 }
161
162 #[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 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 now_ns
200 .checked_add(seconds * NANOS_PER_SECOND)
201 .ok_or(SessionRequestError::InvalidLifetime)
202 }
203
204 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}