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)]
18pub enum SessionRequestError {
19 InvalidRequest,
21 Scope(ScopeLabelError),
23 Grants(ClaimsError),
25 ScopeRejected,
27 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
61pub struct SessionTtlPolicy {
62 default_secs: u64,
63 maximum_secs: u64,
64}
65
66impl SessionTtlPolicy {
67 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 #[must_use]
80 pub const fn default_secs(self) -> u64 {
81 self.default_secs
82 }
83
84 #[must_use]
86 pub const fn maximum_secs(self) -> u64 {
87 self.maximum_secs
88 }
89}
90
91#[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 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 #[must_use]
128 pub fn scopes(&self) -> &[ScopeLabel] {
129 &self.scopes
130 }
131
132 #[must_use]
134 pub const fn ttl_secs(&self) -> Option<u64> {
135 self.ttl_secs
136 }
137
138 #[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 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 now_ns
176 .checked_add(seconds * NANOS_PER_SECOND)
177 .ok_or(SessionRequestError::InvalidLifetime)
178 }
179
180 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}