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 SessionTtlPolicy {
76 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 #[must_use]
89 pub const fn default_secs(self) -> u64 {
90 self.default_secs
91 }
92
93 #[must_use]
95 pub const fn maximum_secs(self) -> u64 {
96 self.maximum_secs
97 }
98}
99
100#[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 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 #[must_use]
142 pub fn scopes(&self) -> &[ScopeLabel] {
143 &self.scopes
144 }
145
146 #[must_use]
148 pub const fn ttl_secs(&self) -> Option<u64> {
149 self.ttl_secs
150 }
151
152 #[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 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 now_ns
190 .checked_add(seconds * NANOS_PER_SECOND)
191 .ok_or(SessionRequestError::InvalidLifetime)
192 }
193
194 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}