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            _ => false,
95        }
96    }
97}
98
99#[derive(Debug, Serialize, Deserialize, Clone, Default, ToSchema)]
100#[serde(rename_all = "lowercase")]
101pub enum ApiTokenPurpose {
102    #[default]
103    ReadOnly,
104    ReadWrite,
105    Synchronise,
106}
107
108#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
109#[serde(rename_all = "lowercase")]
110pub struct ApiToken {
111    // The account this is associated with.
112    pub account_id: Uuid,
113    pub token_id: Uuid,
114    pub label: String,
115    #[serde(with = "time::serde::timestamp::option")]
116    pub expiry: Option<time::OffsetDateTime>,
117    #[serde(with = "time::serde::timestamp")]
118    pub issued_at: time::OffsetDateTime,
119    // Defaults to ReadOnly if not present
120    #[serde(default)]
121    pub purpose: ApiTokenPurpose,
122}
123
124impl fmt::Display for ApiToken {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        writeln!(f, "account_id: {}", self.account_id)?;
127        writeln!(f, "token_id: {}", self.token_id)?;
128        writeln!(f, "label: {}", self.label)?;
129        writeln!(f, "issued at: {}", self.issued_at)?;
130        if let Some(expiry) = self.expiry {
131            // if this fails we're in trouble!
132            #[allow(clippy::expect_used)]
133            let expiry_str = expiry
134                .to_offset(
135                    time::UtcOffset::local_offset_at(OffsetDateTime::UNIX_EPOCH)
136                        .unwrap_or(time::UtcOffset::UTC),
137                )
138                .format(&time::format_description::well_known::Rfc3339)
139                .expect("Failed to format timestamp to RFC3339");
140            writeln!(f, "token expiry: {}", expiry_str)
141        } else {
142            writeln!(f, "token expiry: never")
143        }
144    }
145}
146
147impl PartialEq for ApiToken {
148    fn eq(&self, other: &Self) -> bool {
149        self.token_id == other.token_id
150    }
151}
152
153impl Eq for ApiToken {}
154
155// This is similar to uat, but omits claims (they have no role in radius), and adds
156// the radius secret field.
157#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
158pub struct RadiusAuthToken {
159    pub name: String,
160    pub displayname: String,
161    pub uuid: String,
162    pub secret: String,
163    pub groups: Vec<Group>,
164}
165
166impl fmt::Display for RadiusAuthToken {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        writeln!(f, "name: {}", self.name)?;
169        writeln!(f, "displayname: {}", self.displayname)?;
170        writeln!(f, "uuid: {}", self.uuid)?;
171        writeln!(f, "secret: {}", self.secret)?;
172        self.groups
173            .iter()
174            .try_for_each(|g| writeln!(f, "group: {}", g))
175    }
176}
177
178#[derive(Debug, Serialize, Deserialize, Clone)]
179#[serde(rename_all = "lowercase")]
180pub struct ScimSyncToken {
181    // uuid of the token?
182    pub token_id: Uuid,
183    #[serde(with = "time::serde::timestamp")]
184    pub issued_at: time::OffsetDateTime,
185    #[serde(default)]
186    pub purpose: ApiTokenPurpose,
187}
188
189#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
190pub struct Group {
191    pub spn: String,
192    pub uuid: String,
193}
194
195impl fmt::Display for Group {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        write!(f, "[ spn: {}, ", self.spn)?;
198        write!(f, "uuid: {} ]", self.uuid)
199    }
200}