Skip to main content

kanidm_proto/internal/
token.rs

1use super::UiHint;
2use serde::{Deserialize, Serialize};
3use std::{collections::BTreeSet, fmt};
4use time::OffsetDateTime;
5use utoipa::ToSchema;
6use uuid::Uuid;
7
8use serde_with::skip_serializing_none;
9
10#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
11#[serde(rename_all = "lowercase")]
12pub enum UatPurpose {
13    ReadOnly,
14    ReadWrite {
15        /// If none, there is no expiry, and this is always rw. If there is
16        /// an expiry, check that the current time < expiry.
17        #[serde(with = "time::serde::timestamp::option")]
18        expiry: Option<time::OffsetDateTime>,
19    },
20}
21
22/// The currently authenticated user, and any required metadata for them
23/// to properly authorise them. This is similar in nature to oauth and the krb
24/// PAC/PAD structures. This information is transparent to clients and CAN
25/// be parsed by them!
26///
27/// This structure and how it works will *very much* change over time from this
28/// point onward! This means on updates, that sessions will invalidate in many
29/// cases.
30#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
31#[skip_serializing_none]
32#[serde(rename_all = "lowercase")]
33pub struct UserAuthToken {
34    pub session_id: Uuid,
35    #[serde(with = "time::serde::timestamp")]
36    pub issued_at: time::OffsetDateTime,
37    /// If none, there is no expiry, and this is always valid. If there is
38    /// an expiry, check that the current time < expiry.
39    #[serde(with = "time::serde::timestamp::option")]
40    pub expiry: Option<time::OffsetDateTime>,
41    pub purpose: UatPurpose,
42    pub uuid: Uuid,
43    pub displayname: String,
44    pub spn: String,
45    pub mail_primary: Option<String>,
46    pub ui_hints: BTreeSet<UiHint>,
47
48    pub limit_search_max_results: Option<u64>,
49    pub limit_search_max_filter_test: Option<u64>,
50}
51
52impl fmt::Display for UserAuthToken {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        writeln!(f, "spn: {}", self.spn)?;
55        writeln!(f, "uuid: {}", self.uuid)?;
56        writeln!(f, "display: {}", self.displayname)?;
57        if let Some(exp) = self.expiry {
58            writeln!(f, "expiry: {exp}")?;
59        } else {
60            writeln!(f, "expiry: -")?;
61        }
62        match &self.purpose {
63            UatPurpose::ReadOnly => writeln!(f, "purpose: read only")?,
64            UatPurpose::ReadWrite {
65                expiry: Some(expiry),
66            } => writeln!(f, "purpose: read write (expiry: {expiry})")?,
67            UatPurpose::ReadWrite { expiry: None } => {
68                writeln!(f, "purpose: read write (expiry: none)")?
69            }
70        }
71        Ok(())
72    }
73}
74
75impl PartialEq for UserAuthToken {
76    fn eq(&self, other: &Self) -> bool {
77        self.session_id == other.session_id
78    }
79}
80
81impl Eq for UserAuthToken {}
82
83pub enum PrivilegesActive {
84    /// This session has active read write privs.
85    True,
86    /// This session can become read-write, but requires reauth to proceed.
87    ReauthRequired,
88    /// This session has no privileges and is read only
89    False,
90}
91
92impl UserAuthToken {
93    pub fn name(&self) -> &str {
94        self.spn.split_once('@').map(|x| x.0).unwrap_or(&self.spn)
95    }
96
97    /// Show if the uat at a current point in time has active read-write
98    /// capabilities.
99    pub fn purpose_privilege_state(&self, ct: time::OffsetDateTime) -> PrivilegesActive {
100        match self.purpose {
101            UatPurpose::ReadWrite { expiry: Some(exp) } if ct < exp => PrivilegesActive::True,
102            // The privileges have expired, or are not yet activated on this session.
103            UatPurpose::ReadWrite { expiry: Some(_) } | UatPurpose::ReadWrite { expiry: None } => {
104                PrivilegesActive::ReauthRequired
105            }
106            UatPurpose::ReadOnly => PrivilegesActive::False,
107        }
108    }
109}
110
111#[derive(Debug, Serialize, Deserialize, Clone, Default, ToSchema)]
112#[serde(rename_all = "lowercase")]
113pub enum ApiTokenPurpose {
114    #[default]
115    ReadOnly,
116    ReadWrite,
117    Synchronise,
118}
119
120#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
121#[serde(rename_all = "lowercase")]
122pub struct ApiToken {
123    // The account this is associated with.
124    pub account_id: Uuid,
125    pub token_id: Uuid,
126    pub label: String,
127    #[serde(with = "time::serde::timestamp::option")]
128    pub expiry: Option<time::OffsetDateTime>,
129    #[serde(with = "time::serde::timestamp")]
130    pub issued_at: time::OffsetDateTime,
131    // Defaults to ReadOnly if not present
132    #[serde(default)]
133    pub purpose: ApiTokenPurpose,
134}
135
136impl fmt::Display for ApiToken {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        writeln!(f, "account_id: {}", self.account_id)?;
139        writeln!(f, "token_id: {}", self.token_id)?;
140        writeln!(f, "label: {}", self.label)?;
141        writeln!(f, "issued at: {}", self.issued_at)?;
142        if let Some(expiry) = self.expiry {
143            // if this fails we're in trouble!
144            #[allow(clippy::expect_used)]
145            let expiry_str = expiry
146                .to_offset(
147                    time::UtcOffset::local_offset_at(OffsetDateTime::UNIX_EPOCH)
148                        .unwrap_or(time::UtcOffset::UTC),
149                )
150                .format(&time::format_description::well_known::Rfc3339)
151                .expect("Failed to format timestamp to RFC3339");
152            writeln!(f, "token expiry: {expiry_str}")
153        } else {
154            writeln!(f, "token expiry: never")
155        }
156    }
157}
158
159impl PartialEq for ApiToken {
160    fn eq(&self, other: &Self) -> bool {
161        self.token_id == other.token_id
162    }
163}
164
165impl Eq for ApiToken {}
166
167// This is similar to uat, but omits claims (they have no role in radius), and adds
168// the radius secret field.
169#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
170pub struct RadiusAuthToken {
171    pub name: String,
172    pub displayname: String,
173    pub uuid: String,
174    pub secret: String,
175    pub groups: Vec<Group>,
176}
177
178impl fmt::Display for RadiusAuthToken {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        writeln!(f, "name: {}", self.name)?;
181        writeln!(f, "displayname: {}", self.displayname)?;
182        writeln!(f, "uuid: {}", self.uuid)?;
183        writeln!(f, "secret: {}", self.secret)?;
184        self.groups
185            .iter()
186            .try_for_each(|g| writeln!(f, "group: {g}"))
187    }
188}
189
190#[derive(Debug, Serialize, Deserialize, Clone)]
191#[serde(rename_all = "lowercase")]
192pub struct ScimSyncToken {
193    // uuid of the token?
194    pub token_id: Uuid,
195    #[serde(with = "time::serde::timestamp")]
196    pub issued_at: time::OffsetDateTime,
197    #[serde(default)]
198    pub purpose: ApiTokenPurpose,
199}
200
201#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
202pub struct Group {
203    pub spn: String,
204    pub uuid: String,
205}
206
207impl fmt::Display for Group {
208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209        write!(f, "[ spn: {}, ", self.spn)?;
210        write!(f, "uuid: {} ]", self.uuid)
211    }
212}