Skip to main content

kaniop_oauth2/
crd.rs

1use kaniop_k8s_util::types::normalize_spn;
2use kaniop_operator::controller::kanidm::KanidmResource;
3use kaniop_operator::crd::{KanidmRef, SecretRotation, MetadataTemplate};
4use kaniop_operator::kanidm::crd::Kanidm;
5
6use std::{
7    collections::{BTreeSet, HashMap},
8    ops::Not,
9};
10
11use kanidm_proto::internal::Oauth2ClaimMapJoin;
12
13use k8s_openapi::apimachinery::pkg::apis::meta::v1::{Condition, LabelSelector};
14use kube::CustomResource;
15#[cfg(feature = "schemars")]
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18
19/// The KanidmOAuth2Client custom resource definition (CRD) defines an OAuth2 client integration in
20/// Kanidm. This resource allows you to configure OAuth2 clients that can interact with the Kanidm
21/// authorization server. The CRD supports various configurations, including scope maps,
22/// claim maps, and other OAuth2 client settings.
23/// More info:
24/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
25#[derive(CustomResource, Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
26#[cfg_attr(feature = "schemars", derive(JsonSchema))]
27#[kube(
28    category = "kaniop",
29    group = "kaniop.rs",
30    version = "v1beta1",
31    kind = "KanidmOAuth2Client",
32    plural = "kanidmoauth2clients",
33    singular = "kanidmoauth2client",
34    shortname = "oauth2",
35    namespaced,
36    status = "KanidmOAuth2ClientStatus",
37    doc = r#"The Kanidm OAuth2 client custom resource definition (CRD) defines an OAuth2 client
38    integration in Kanidm."#,
39    printcolumn = r#"{"name":"Kanidm","type":"string","jsonPath":".status.kanidmRef"}"#,
40    printcolumn = r#"{"name":"Public","type":"string","jsonPath":".spec.public"}"#,
41    printcolumn = r#"{"name":"Secret","type":"string","jsonPath":".status.secretName"}"#,
42    printcolumn = r#"{"name":"Ready","type":"boolean","jsonPath":".status.ready"}"#,
43    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#,
44    derive = "Default"
45)]
46#[serde(rename_all = "camelCase")]
47pub struct KanidmOAuth2ClientSpec {
48    pub kanidm_ref: KanidmRef,
49
50    /// The name of the entity in Kanidm. If not specified, the Kubernetes resource name is used.
51    /// Use this field to manage Kanidm entities with names that don't conform to Kubernetes naming rules
52    /// (e.g., entities with underscores like `idm_admin` or `idm_all_persons`).
53    /// This field is immutable and cannot be changed after creation.
54    #[schemars(extend("x-kubernetes-validations" = [{"message": "kanidmName cannot be changed.", "rule": "self == oldSelf"}]))]
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub kanidm_name: Option<String>,
57
58    /// Set the display name for the OAuth2 client.
59    pub displayname: String,
60
61    /// Native Kanidm description. Omit to leave unmanaged; use an empty string to clear.
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub description: Option<String>,
64
65    /// Set the landing page (home page) of the client. The landing page is where users will be
66    /// redirected to from the Kanidm application portal.
67    pub origin: String,
68
69    /// Set the URL where the application expects OAuth2 requests to be sent.
70    pub redirect_url: Vec<String>,
71
72    /// Create a new OAuth2 public client that requires PKCE. You should prefer using confidential
73    /// client types if possible over public ones.
74    ///
75    /// Public clients have many limitations and can not access all API's of OAuth2. For example
76    /// rfc7662 token introspection requires client authentication.
77    ///
78    /// This cannot be changed after creation. Default value is false.
79    /// This field is immutable.
80    /// If public is false, the operator will create a secret containing the client secret with
81    /// the name `<oauth2-client-name>-kanidm-oauth2-credentials` in the same namespace as the OAuth2 client.
82    #[schemars(extend("x-kubernetes-validations" = [{"message": "Public cannot be changed.", "rule": "self == oldSelf"}]))]
83    #[serde(default)]
84    pub public: bool,
85
86    /// Main scope map for the OAuth2 client. For an authorization to proceed, all scopes requested
87    /// by the client must be available in the final scope set that is granted to the account.
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub scope_map: Option<BTreeSet<KanidmScopeMap>>,
90
91    /// Supplementary scope maps for the OAuth2 client. These function the same as scope maps where
92    /// membership of a group provides a set of scopes to the account.
93    /// However these scopes are NOT consulted during authorization decisions made by Kanidm.
94    /// These scopes exist to allow optional properties to be provided (such as personal
95    /// information about a subset of accounts to be revealed) or so that the service may make its
96    /// own authorization decisions based on the provided scopes.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub sup_scope_map: Option<BTreeSet<KanidmScopeMap>>,
99
100    /// Mapping from a group to a custom claims that it provides to members.
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub claim_map: Option<BTreeSet<KanidmClaimMap>>,
103
104    /// Enable strict validation of redirect URLs. Previously redirect URLs only validated the
105    /// origin of the URL matched. When enabled, redirect URLs must match exactly.
106    ///
107    /// Enabled by default.
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub strict_redirect_url: Option<bool>,
110
111    /// Use the 'name' attribute instead of 'spn' for the preferred_username.
112    ///
113    /// Disabled by default.
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub prefer_short_username: Option<bool>,
116
117    /// Allow public clients to redirect to localhost.
118    ///
119    /// Just public clients can allow localhost redirect.
120    /// Disabled by default.
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub allow_localhost_redirect: Option<bool>,
123
124    /// Disable PKCE on this oauth2 client to work around insecure clients that may not support it.
125    /// You should request the client to enable PKCE!
126    ///
127    /// Public clients cannot disable PKCE.
128    /// PKCE is enabled by default.
129    #[serde(skip_serializing_if = "Option::is_none")]
130    pub allow_insecure_client_disable_pkce: Option<bool>,
131
132    /// Enable legacy signing crypto on this oauth2 client. This defaults to being disabled.
133    /// You only need to enable this for openid clients that do not support modern cryptographic
134    /// operations.
135    ///
136    /// Disabled by default.
137    #[serde(skip_serializing_if = "Option::is_none")]
138    pub jwt_legacy_crypto_enable: Option<bool>,
139
140    /// Disable the consent prompt for this OAuth2 client. This allows skipping the user
141    /// consent screen for well-known admin-managed applications. When enabled, users will
142    /// not be prompted to grant consent when authorizing with this client.
143    ///
144    /// Disabled by default.
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub disable_consent_prompt: Option<bool>,
147
148    /// Refresh token lifetime in seconds for this OAuth2 client.
149    /// If omitted, Kaniop leaves the Kanidm attribute unchanged (and new clients use
150    /// Kanidm's default of 16 hours). Removing this field does not reset a value
151    /// previously managed by Kaniop. Longer lifetimes increase the impact of token theft.
152    #[schemars(range(min = 1))]
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub refresh_token_expiry: Option<u32>,
155
156    /// Automatic rotation configuration for the OAuth2 client secret. Only applies to confidential
157    /// clients (public: false). When enabled, the operator will regenerate the client secret
158    /// periodically based on the configured rotation period.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub secret_rotation: Option<SecretRotation>,
161
162    /// Template applied to the Secret created for confidential clients (public: false).
163    /// Allows attaching custom annotations and labels to the generated Secret. The operator's own
164    /// labels and annotations take precedence over any conflicting keys in the template.
165    /// Changes to this template are enforced on the next reconciliation, overwriting any manual
166    /// modifications made to the Secret
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub secret_template: Option<MetadataTemplate>,
169
170    /// Aliases for the canonical secret keys (CLIENT_ID and CLIENT_SECRET).
171    /// Allows consumers that require different fixed key names to access the same credentials.
172    /// The canonical keys CLIENT_ID and CLIENT_SECRET are always present.
173    /// Only applies to confidential clients (public: false).
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub secret_key_aliases: Option<SecretKeyAliases>,
176
177    /// Optional URL to an image for the OAuth2 client application.
178    /// The image will be downloaded and set in Kanidm for display in the application portal.
179    /// Constraints:
180    /// - Maximum size: 256 KB
181    /// - Maximum dimensions: 1024 x 1024 pixels
182    /// - Supported formats: png, jpg, gif, svg, webp
183    #[serde(skip_serializing_if = "Option::is_none")]
184    pub image: Option<OAuth2ClientImageSpec>,
185}
186
187#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
188#[cfg_attr(feature = "schemars", derive(JsonSchema))]
189#[serde(rename_all = "camelCase")]
190pub struct OAuth2ClientImageSpec {
191    /// URL to fetch the image from (HTTP/HTTPS only).
192    /// The operator will periodically check this URL for changes using HEAD requests
193    /// and re-download the image when changes are detected.
194    pub url: String,
195}
196
197/// Aliases for canonical secret keys.
198/// Allows specifying additional key names for CLIENT_ID and CLIENT_SECRET values.
199/// Duplicate aliases are deduplicated. Invalid key names are rejected by the webhook.
200#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
201#[cfg_attr(feature = "schemars", derive(JsonSchema))]
202#[serde(rename_all = "camelCase")]
203pub struct SecretKeyAliases {
204    /// Aliases for the CLIENT_ID key.
205    /// Each alias will be added as an additional key containing the same client ID value.
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub client_id: Option<Vec<String>>,
208
209    /// Aliases for the CLIENT_SECRET key.
210    /// Each alias will be added as an additional key containing the same client secret value.
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub client_secret: Option<Vec<String>>,
213}
214
215impl SecretKeyAliases {
216    pub fn collect_aliases(&self) -> (Vec<String>, Vec<String>) {
217        let client_id_aliases = self
218            .client_id
219            .as_ref()
220            .map(|v| {
221                let mut deduped: Vec<String> = v.to_vec();
222                deduped.sort();
223                deduped.dedup();
224                deduped
225            })
226            .unwrap_or_default();
227
228        let client_secret_aliases = self
229            .client_secret
230            .as_ref()
231            .map(|v| {
232                let mut deduped: Vec<String> = v.to_vec();
233                deduped.sort();
234                deduped.dedup();
235                deduped
236            })
237            .unwrap_or_default();
238
239        (client_id_aliases, client_secret_aliases)
240    }
241}
242
243impl KanidmResource for KanidmOAuth2Client {
244    #[inline]
245    fn kanidm_ref_spec(&self) -> &KanidmRef {
246        &self.spec.kanidm_ref
247    }
248
249    #[inline]
250    fn get_namespace_selector(kanidm: &Kanidm) -> &Option<LabelSelector> {
251        &kanidm.spec.oauth2_client_namespace_selector
252    }
253
254    #[inline]
255    fn kanidm_name_override(&self) -> Option<&str> {
256        self.spec.kanidm_name.as_deref()
257    }
258}
259
260/// The `KanidmScopeMap` struct represents a mapping of a group to a set of OAuth2 scopes in Kanidm.
261///
262/// Scope maps in Kanidm are used to define the permissions that a client application can request on
263/// behalf of a user. These scopes determine what resources the client can access and what
264/// operations it can perform.
265///
266/// These provide a set of scopes if a user is a member of a specific group within Kanidm. This
267/// allows you to create a relationship between the scopes of a service, and the groups/roles in
268/// Kanidm which can be specific to that service.
269#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
270#[cfg_attr(feature = "schemars", derive(JsonSchema))]
271#[serde(rename_all = "camelCase")]
272pub struct KanidmScopeMap {
273    /// Group name or SPN. Members of this group will be granted the scopes defined in the `scopes` field.
274    pub group: String,
275
276    /// A scope is a string that represents a specific permission or set of permissions that a
277    /// client application can request from an authorization server. Scopes define the level of
278    /// access that the client application is granted to the user's resources.
279    ///
280    /// OpenID Connect allows a number of scopes that affect the content of the resulting authorization
281    /// token. If one of the following scopes is requested by the OpenID client, then the associated
282    /// claims may be added to the authorization token. It is not guaranteed that all of the associated
283    /// claims will be added.
284    ///
285    /// - `profile`: name, family_name, given_name, middle_name, nickname, preferred_username, profile,
286    ///    picture, website, gender, birthdate, zoneinfo, locale, and updated_at
287    /// - `email`: email, email_verified
288    /// - `address`: address
289    /// - `phone`: phone_number, phone_number_verified
290    /// - `groups`: groups
291    ///
292    /// If you are creating an OpenID Connect (OIDC) client, you MUST provide a scope map containing `openid`.
293    /// Without this, OpenID Connect clients WILL NOT WORK!
294    #[allow(clippy::doc_overindented_list_items)]
295    pub scopes: Vec<String>,
296}
297
298impl KanidmScopeMap {
299    pub fn normalize(self) -> Self {
300        let mut scopes = self.scopes;
301        scopes.sort();
302        Self {
303            group: normalize_spn(&self.group),
304            scopes,
305        }
306    }
307    pub fn from(s: &str) -> Option<Self> {
308        let parts = s.split(':').collect::<Vec<_>>();
309        if parts.len() != 2 {
310            return None;
311        }
312        let group = parts[0].to_string();
313        let proto_scopes = parts[1];
314        if proto_scopes.starts_with(" {").not() || proto_scopes.ends_with('}').not() {
315            return None;
316        }
317
318        let scopes = proto_scopes[2..proto_scopes.len() - 1]
319            .split(", ")
320            .map(|s| s.replace('"', ""))
321            .collect();
322        Some(Self { group, scopes })
323    }
324}
325
326/// Some OAuth2 services may consume custom claims from an id token for access control or other
327/// policy decisions. Each custom claim is a key:values set, where there can be many values
328/// associated to a claim name. Different applications may expect these values to be formatted
329/// (joined) in different ways.
330///
331/// Claim values are mapped based on membership to groups. When an account is a member of multiple
332/// groups that would receive the same claim, the values of these maps are merged.
333#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
334#[cfg_attr(feature = "schemars", derive(JsonSchema))]
335#[serde(rename_all = "camelCase")]
336pub struct KanidmClaimMap {
337    /// The name of the claim that will be provided to the client.
338    pub name: String,
339
340    pub values_map: BTreeSet<KanidmClaimsValuesMap>,
341
342    /// The strategy to join the values together.
343    /// Possible strategies to join the values of a claim map:
344    /// `csv` -> "value_a,value_b"
345    /// `ssv` -> "value_a value_b"
346    /// `array` -> ["value_a", "value_b"]
347    #[serde(default)]
348    pub join_strategy: KanidmClaimMapJoinStrategy,
349}
350
351impl KanidmClaimMap {
352    pub fn normalize(self) -> Self {
353        Self {
354            values_map: self
355                .values_map
356                .iter()
357                .map(|vm| vm.clone().normalize())
358                .collect(),
359            ..self
360        }
361    }
362
363    pub fn from(s: &str) -> Option<Self> {
364        let parts = s.split(':').collect::<Vec<_>>();
365        if parts.len() != 4 {
366            return None;
367        }
368        let name = parts[0].to_string();
369        let group = parts[1].to_string();
370        let join_strategy = match parts[2] {
371            "," => KanidmClaimMapJoinStrategy::Csv,
372            " " => KanidmClaimMapJoinStrategy::Ssv,
373            ";" => KanidmClaimMapJoinStrategy::Array,
374            _ => return None,
375        };
376        let proto_values = parts[3];
377        if proto_values.starts_with('"').not() || proto_values.ends_with('"').not() {
378            return None;
379        }
380        let values = proto_values[1..proto_values.len() - 1]
381            .split(",")
382            .map(|s| s.to_string())
383            .collect();
384        Some(Self {
385            name,
386            join_strategy,
387            values_map: BTreeSet::from([KanidmClaimsValuesMap { group, values }]),
388        })
389    }
390
391    pub fn group(v: &[KanidmClaimMap]) -> BTreeSet<KanidmClaimMap> {
392        let mut map: HashMap<String, KanidmClaimMap> = HashMap::new();
393
394        for claim in v {
395            if let Some(existing) = map.get_mut(&claim.name) {
396                existing.values_map.extend(claim.values_map.clone());
397            } else {
398                map.insert(claim.name.clone(), claim.clone());
399            }
400        }
401
402        map.into_values().collect()
403    }
404}
405
406#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
407#[cfg_attr(feature = "schemars", derive(JsonSchema))]
408#[serde(rename_all = "camelCase")]
409pub struct KanidmClaimsValuesMap {
410    /// The group name or SPN that will provide the claim.
411    pub group: String,
412
413    /// The values that will be provided to the client.
414    pub values: Vec<String>,
415}
416
417impl KanidmClaimsValuesMap {
418    pub fn normalize(self) -> Self {
419        let mut values = self.values;
420        values.sort();
421        Self {
422            group: normalize_spn(&self.group),
423            values,
424        }
425    }
426}
427
428#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
429#[cfg_attr(feature = "schemars", derive(JsonSchema))]
430#[serde(rename_all = "snake_case")]
431pub enum KanidmClaimMapJoinStrategy {
432    /// Comma-separated values: "value_a,value_b"
433    Csv,
434    /// Space-separated values: "value_a value_b"
435    Ssv,
436    /// Array format: ["value_a", "value_b"]
437    #[default]
438    Array,
439}
440
441impl KanidmClaimMapJoinStrategy {
442    pub fn to_oauth2_claim_map_join(&self) -> Oauth2ClaimMapJoin {
443        match self {
444            KanidmClaimMapJoinStrategy::Csv => Oauth2ClaimMapJoin::Csv,
445            KanidmClaimMapJoinStrategy::Ssv => Oauth2ClaimMapJoin::Ssv,
446            KanidmClaimMapJoinStrategy::Array => Oauth2ClaimMapJoin::Array,
447        }
448    }
449}
450
451/// Most recent observed status of the Kanidm Group. Read-only.
452/// More info:
453/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
454#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
455#[cfg_attr(feature = "schemars", derive(JsonSchema))]
456#[serde(rename_all = "camelCase")]
457pub struct KanidmOAuth2ClientStatus {
458    #[serde(skip_serializing_if = "Option::is_none")]
459    #[cfg_attr(
460        feature = "schemars",
461        schemars(extend("x-kubernetes-list-type" = "map", "x-kubernetes-list-map-keys" = ["type"]))
462    )]
463    pub conditions: Option<Vec<Condition>>,
464
465    #[serde(skip_serializing_if = "Option::is_none")]
466    pub origin: Option<Vec<String>>,
467
468    #[serde(skip_serializing_if = "Option::is_none")]
469    pub scope_map: Option<Vec<String>>,
470
471    #[serde(skip_serializing_if = "Option::is_none")]
472    pub sup_scope_map: Option<Vec<String>>,
473
474    #[serde(skip_serializing_if = "Option::is_none")]
475    pub claims_map: Option<Vec<String>>,
476
477    pub ready: bool,
478
479    #[serde(skip_serializing_if = "Option::is_none")]
480    pub secret_name: Option<String>,
481
482    pub kanidm_ref: String,
483
484    /// Status of the OAuth2 client image.
485    #[serde(skip_serializing_if = "Option::is_none")]
486    pub image: Option<OAuth2ClientImageStatus>,
487}
488
489#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
490#[cfg_attr(feature = "schemars", derive(JsonSchema))]
491#[serde(rename_all = "camelCase")]
492pub struct OAuth2ClientImageStatus {
493    /// The URL from which the image was last fetched.
494    pub url: String,
495    /// ETag header from the last fetch (for change detection).
496    #[serde(skip_serializing_if = "Option::is_none")]
497    pub etag: Option<String>,
498    /// Last-Modified header from the last fetch.
499    #[serde(skip_serializing_if = "Option::is_none")]
500    pub last_modified: Option<String>,
501    /// Content-Length from the last fetch.
502    #[serde(skip_serializing_if = "Option::is_none")]
503    pub content_length: Option<u64>,
504    /// Hash of the image content (SHA-256, for validation).
505    #[serde(skip_serializing_if = "Option::is_none")]
506    pub content_hash: Option<String>,
507}
508
509#[cfg(test)]
510mod tests {
511    use super::{
512        KanidmClaimMap, KanidmClaimMapJoinStrategy, KanidmClaimsValuesMap, KanidmOAuth2ClientSpec,
513        KanidmScopeMap,
514    };
515
516    use std::collections::BTreeSet;
517
518    #[test]
519    fn test_refresh_token_expiry_serde() {
520        let base = serde_json::json!({
521            "kanidmRef": {"name": "idm"},
522            "displayname": "Test Client",
523            "origin": "https://example.com",
524            "redirectUrl": [],
525        });
526        let mut configured = base.clone();
527        configured["refreshTokenExpiry"] = serde_json::json!(7_776_000);
528
529        let spec: KanidmOAuth2ClientSpec = serde_json::from_value(configured).unwrap();
530        assert_eq!(spec.refresh_token_expiry, Some(7_776_000));
531        assert_eq!(
532            serde_json::to_value(&spec).unwrap()["refreshTokenExpiry"],
533            serde_json::json!(7_776_000)
534        );
535
536        let unset: KanidmOAuth2ClientSpec = serde_json::from_value(base.clone()).unwrap();
537        assert_eq!(unset.refresh_token_expiry, None);
538        assert!(serde_json::to_value(&unset)
539            .unwrap()
540            .get("refreshTokenExpiry")
541            .is_none());
542
543        for invalid in [serde_json::json!(-1), serde_json::json!(4_294_967_296_u64)] {
544            let mut value = base.clone();
545            value["refreshTokenExpiry"] = invalid;
546            assert!(serde_json::from_value::<KanidmOAuth2ClientSpec>(value).is_err());
547        }
548    }
549
550    #[test]
551    fn test_kanidm_scope_map_from() {
552        let scope_map = KanidmScopeMap {
553            group: "test_group".to_string(),
554            scopes: vec!["scope1".to_string(), "scope2".to_string()],
555        };
556
557        assert_eq!(
558            KanidmScopeMap::from(r#"test_group@test.example.com: {"scope1", "scope2"}"#)
559                .unwrap()
560                .normalize(),
561            scope_map,
562        );
563
564        assert_eq!(
565            KanidmScopeMap::from(r#"test_group: {"scope1", "scope2"}"#)
566                .unwrap()
567                .normalize(),
568            scope_map,
569        );
570
571        assert!(KanidmScopeMap::from(r#"test_group:{"scope1", "scope2"}"#).is_none(),);
572        assert_eq!(
573            KanidmScopeMap::from(r#"test_group: {"scope1"}"#)
574                .unwrap()
575                .normalize(),
576            KanidmScopeMap {
577                group: "test_group".to_string(),
578                scopes: vec!["scope1".to_string()],
579            }
580        );
581    }
582
583    #[test]
584    fn test_group_kanidm_claims_map() {
585        let claim1 = KanidmClaimMap {
586            name: "claim1".to_string(),
587            values_map: BTreeSet::from([KanidmClaimsValuesMap {
588                group: "group1".to_string(),
589                values: vec!["value1".to_string()],
590            }]),
591            join_strategy: KanidmClaimMapJoinStrategy::Array,
592        };
593
594        let claim2 = KanidmClaimMap {
595            name: "claim1".to_string(),
596            values_map: BTreeSet::from([KanidmClaimsValuesMap {
597                group: "group2".to_string(),
598                values: vec!["value2".to_string()],
599            }]),
600            join_strategy: KanidmClaimMapJoinStrategy::Array,
601        };
602
603        let claim3 = KanidmClaimMap {
604            name: "claim2".to_string(),
605            values_map: BTreeSet::from([KanidmClaimsValuesMap {
606                group: "group3".to_string(),
607                values: vec!["value3".to_string()],
608            }]),
609            join_strategy: KanidmClaimMapJoinStrategy::Array,
610        };
611
612        let claims = vec![claim1.clone(), claim2.clone(), claim3.clone()];
613
614        let grouped_claims = KanidmClaimMap::group(&claims);
615
616        assert_eq!(grouped_claims.len(), 2);
617
618        let grouped_claim1 = grouped_claims.iter().find(|c| c.name == "claim1").unwrap();
619        assert_eq!(grouped_claim1.values_map.len(), 2);
620        assert!(grouped_claim1.values_map.contains(&KanidmClaimsValuesMap {
621            group: "group1".to_string(),
622            values: vec!["value1".to_string()],
623        }));
624        assert!(grouped_claim1.values_map.contains(&KanidmClaimsValuesMap {
625            group: "group2".to_string(),
626            values: vec!["value2".to_string()],
627        }));
628
629        let grouped_claim2 = grouped_claims.iter().find(|c| c.name == "claim2").unwrap();
630        assert_eq!(grouped_claim2.values_map.len(), 1);
631        assert!(grouped_claim2.values_map.contains(&KanidmClaimsValuesMap {
632            group: "group3".to_string(),
633            values: vec!["value3".to_string()],
634        }));
635    }
636
637    #[test]
638    fn test_kanidm_claim_map_from() {
639        let mut claim_map = KanidmClaimMap {
640            name: "claim_name".to_string(),
641            join_strategy: KanidmClaimMapJoinStrategy::Array,
642            values_map: BTreeSet::from([KanidmClaimsValuesMap {
643                group: "group_name".to_string(),
644                // Sorted values after normalization
645                values: vec!["boo".to_string(), "foo".to_string()],
646            }]),
647        };
648
649        assert_eq!(
650            KanidmClaimMap::from(r#"claim_name:group_name@test.example.com:;:"foo,boo""#)
651                .unwrap()
652                .normalize(),
653            claim_map,
654        );
655        assert_eq!(
656            KanidmClaimMap::from(r#"claim_name:group_name:;:"foo,boo""#)
657                .unwrap()
658                .normalize(),
659            claim_map,
660        );
661
662        claim_map.join_strategy = KanidmClaimMapJoinStrategy::Csv;
663        assert_eq!(
664            KanidmClaimMap::from(r#"claim_name:group_name:,:"foo,boo""#)
665                .unwrap()
666                .normalize(),
667            claim_map,
668        );
669
670        claim_map.join_strategy = KanidmClaimMapJoinStrategy::Ssv;
671        assert_eq!(
672            KanidmClaimMap::from(r#"claim_name:group_name: :"foo,boo""#)
673                .unwrap()
674                .normalize(),
675            claim_map,
676        );
677    }
678}