kanidm_proto/internal/
token.rs

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