Skip to main content

kanidm_proto/internal/
mod.rs

1//! Kanidm internal elements
2//!
3//! Items defined in this module *may* change between releases without notice.
4
5use crate::constants::{
6    CONTENT_TYPE_GIF, CONTENT_TYPE_JPG, CONTENT_TYPE_PNG, CONTENT_TYPE_SVG, CONTENT_TYPE_WEBP,
7};
8use clap::ValueEnum;
9use serde::{Deserialize, Serialize};
10use std::{fmt, str::FromStr};
11use url::Url;
12use utoipa::ToSchema;
13use uuid::Uuid;
14
15use num_enum::TryFromPrimitive;
16
17mod credupdate;
18mod error;
19mod raw;
20mod token;
21
22pub use self::{credupdate::*, error::*, raw::*, token::*};
23
24pub const COOKIE_CSRF_NONCE: &str = "csrf-nonce";
25pub const COOKIE_AUTH_SESSION_ID: &str = "auth-session-id";
26pub const COOKIE_BEARER_TOKEN: &str = "bearer";
27pub const COOKIE_CU_SESSION_TOKEN: &str = "cu-session-token";
28pub const COOKIE_USERNAME: &str = "username";
29pub const COOKIE_OAUTH2_REQ: &str = "o2-authreq";
30
31#[derive(Debug, Serialize, Deserialize, Clone, ToSchema)]
32/// This is a description of a linked or connected application for a user. This is
33/// used in the UI to render applications on the dashboard for a user to access.
34pub enum AppLink {
35    Oauth2 {
36        name: String,
37        display_name: String,
38        redirect_url: Url,
39        // Whether this oauth2 resource has an image.
40        has_image: bool,
41    },
42}
43
44#[derive(
45    Debug, Serialize, Deserialize, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, ToSchema,
46)]
47#[serde(rename_all = "lowercase")]
48#[derive(TryFromPrimitive)]
49#[repr(u16)]
50pub enum UiHint {
51    ExperimentalFeatures = 0,
52    PosixAccount = 1,
53    CredentialUpdate = 2,
54    SynchronisedAccount = 3,
55}
56
57impl fmt::Display for UiHint {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        write!(f, "{}", self.as_ref())
60    }
61}
62
63impl AsRef<str> for UiHint {
64    fn as_ref(&self) -> &str {
65        match self {
66            UiHint::PosixAccount => "PosixAccount",
67            UiHint::CredentialUpdate => "CredentialUpdate",
68            UiHint::ExperimentalFeatures => "ExperimentalFeatures",
69            UiHint::SynchronisedAccount => "SynchronisedAccount",
70        }
71    }
72}
73
74impl FromStr for UiHint {
75    type Err = ();
76
77    fn from_str(s: &str) -> Result<Self, Self::Err> {
78        match s {
79            "CredentialUpdate" => Ok(UiHint::CredentialUpdate),
80            "PosixAccount" => Ok(UiHint::PosixAccount),
81            "ExperimentalFeatures" => Ok(UiHint::ExperimentalFeatures),
82            "SynchronisedAccount" => Ok(UiHint::SynchronisedAccount),
83            _ => Err(()),
84        }
85    }
86}
87
88// State machine states and transitions for the identity verification system feature!
89#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, ToSchema)]
90pub enum IdentifyUserRequest {
91    Start,
92    SubmitCode { other_totp: u32 },
93    DisplayCode,
94}
95
96#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, ToSchema)]
97pub enum IdentifyUserResponse {
98    IdentityVerificationUnavailable,
99    IdentityVerificationAvailable,
100    ProvideCode { step: u32, totp: u32 },
101    WaitForCode,
102    Success,
103    CodeFailure,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash, Ord, PartialOrd, ValueEnum)]
107#[serde(rename_all = "lowercase")]
108pub enum ImageType {
109    Png,
110    Jpg,
111    Gif,
112    Svg,
113    Webp,
114}
115
116impl TryFrom<&str> for ImageType {
117    type Error = &'static str;
118    /// ```
119    /// use kanidm_proto::internal::ImageType;
120    /// assert_eq!(ImageType::try_from("png").unwrap(), ImageType::Png);
121    /// assert!(ImageType::try_from("krabs").is_err());
122    /// ```
123    fn try_from(value: &str) -> Result<Self, &'static str> {
124        #[allow(clippy::panic)]
125        match value {
126            "png" => Ok(Self::Png),
127            "jpg" => Ok(Self::Jpg),
128            "jpeg" => Ok(Self::Jpg), // ugh I hate this
129            "gif" => Ok(Self::Gif),
130            "svg" => Ok(Self::Svg),
131            "webp" => Ok(Self::Webp),
132            _ => Err("Invalid image type!"),
133        }
134    }
135}
136
137impl ImageType {
138    pub fn try_from_content_type(content_type: &str) -> Result<Self, String> {
139        let content_type = content_type.to_lowercase();
140        match content_type.as_str() {
141            CONTENT_TYPE_JPG => Ok(ImageType::Jpg),
142            CONTENT_TYPE_PNG => Ok(ImageType::Png),
143            CONTENT_TYPE_GIF => Ok(ImageType::Gif),
144            CONTENT_TYPE_WEBP => Ok(ImageType::Webp),
145            CONTENT_TYPE_SVG => Ok(ImageType::Svg),
146            _ => Err(format!("Invalid content type: {content_type}")),
147        }
148    }
149
150    pub fn as_content_type_str(&self) -> &'static str {
151        match &self {
152            ImageType::Jpg => CONTENT_TYPE_JPG,
153            ImageType::Png => CONTENT_TYPE_PNG,
154            ImageType::Gif => CONTENT_TYPE_GIF,
155            ImageType::Webp => CONTENT_TYPE_WEBP,
156            ImageType::Svg => CONTENT_TYPE_SVG,
157        }
158    }
159}
160
161#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Debug, PartialOrd, Ord, Hash)]
162pub struct ImageValue {
163    pub filename: String,
164    pub filetype: ImageType,
165    pub contents: Vec<u8>,
166}
167
168impl TryFrom<&str> for ImageValue {
169    type Error = String;
170    fn try_from(s: &str) -> Result<Self, String> {
171        serde_json::from_str(s).map_err(|e| format!("Failed to decode ImageValue from {s} - {e:?}"))
172    }
173}
174
175impl ImageValue {
176    pub fn new(filename: String, filetype: ImageType, contents: Vec<u8>) -> Self {
177        Self {
178            filename,
179            filetype,
180            contents,
181        }
182    }
183}
184
185#[repr(u32)]
186#[derive(Debug, Copy, Clone, Deserialize, Default, Eq, PartialEq)]
187#[serde(rename_all = "lowercase")]
188/// Filesystem type object, used for tuning database parameters.
189pub enum FsType {
190    Zfs = 65536,
191    #[default]
192    #[serde(other)]
193    /// The default setting, if not set to "zfs"
194    Generic = 4096,
195}
196
197impl FsType {
198    pub fn checkpoint_pages(&self) -> u32 {
199        match self {
200            FsType::Generic => 2048,
201            FsType::Zfs => 256,
202        }
203    }
204}
205
206impl TryFrom<&str> for FsType {
207    type Error = ();
208
209    fn try_from(s: &str) -> Result<Self, Self::Error> {
210        match s {
211            "zfs" => Ok(FsType::Zfs),
212            "generic" => Ok(FsType::Generic),
213            _ => Err(()),
214        }
215    }
216}
217
218impl FromStr for FsType {
219    type Err = &'static str;
220
221    fn from_str(s: &str) -> Result<Self, Self::Err> {
222        FsType::try_from(s).map_err(|_| "Invalid FsType, must be either 'zfs' or 'generic'")
223    }
224}
225
226#[derive(Debug, Serialize, Deserialize, Clone, Copy, ToSchema)]
227pub enum Oauth2ClaimMapJoin {
228    #[serde(rename = "csv")]
229    Csv,
230    #[serde(rename = "ssv")]
231    Ssv,
232    #[serde(rename = "array")]
233    Array,
234}
235
236#[derive(Debug, Serialize, Deserialize, Clone)]
237pub struct DomainInfo {
238    pub name: String,
239    pub displayname: String,
240    pub uuid: Uuid,
241    pub level: u32,
242}
243
244#[derive(Debug, Serialize, Deserialize, Clone)]
245pub struct DomainUpgradeCheckReport {
246    pub name: String,
247    pub uuid: Uuid,
248    pub current_level: u32,
249    pub upgrade_level: u32,
250    pub report_items: Vec<DomainUpgradeCheckItem>,
251}
252
253#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
254pub enum DomainUpgradeCheckStatus {
255    Pass6To7Gidnumber,
256    Fail6To7Gidnumber,
257
258    Pass7To8SecurityKeys,
259    Fail7To8SecurityKeys,
260
261    Pass7To8Oauth2StrictRedirectUri,
262    Fail7To8Oauth2StrictRedirectUri,
263}
264
265#[derive(Debug, Serialize, Deserialize, Clone)]
266pub struct DomainUpgradeCheckItem {
267    pub from_level: u32,
268    pub to_level: u32,
269    pub status: DomainUpgradeCheckStatus,
270    pub affected_entries: Vec<String>,
271}
272
273#[test]
274fn test_fstype_deser() {
275    assert_eq!(FsType::try_from("zfs"), Ok(FsType::Zfs));
276    assert_eq!(FsType::try_from("generic"), Ok(FsType::Generic));
277    assert_eq!(FsType::try_from(" "), Err(()));
278    assert_eq!(FsType::try_from("crab🦀"), Err(()));
279}