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};
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    /// Set the landing page (home page) of the client. The landing page is where users will be
62    /// redirected to from the Kanidm application portal.
63    pub origin: String,
64
65    /// Set the URL where the application expects OAuth2 requests to be sent.
66    pub redirect_url: Vec<String>,
67
68    /// Create a new OAuth2 public client that requires PKCE. You should prefer using confidential
69    /// client types if possible over public ones.
70    ///
71    /// Public clients have many limitations and can not access all API's of OAuth2. For example
72    /// rfc7662 token introspection requires client authentication.
73    ///
74    /// This cannot be changed after creation. Default value is false.
75    /// This field is immutable.
76    /// If public is false, the operator will create a secret containing the client secret with
77    /// the name `<oauth2-client-name>-kanidm-oauth2-credentials` in the same namespace as the OAuth2 client.
78    #[schemars(extend("x-kubernetes-validations" = [{"message": "Public cannot be changed.", "rule": "self == oldSelf"}]))]
79    #[serde(default)]
80    pub public: bool,
81
82    /// Main scope map for the OAuth2 client. For an authorization to proceed, all scopes requested
83    /// by the client must be available in the final scope set that is granted to the account.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub scope_map: Option<BTreeSet<KanidmScopeMap>>,
86
87    /// Supplementary scope maps for the OAuth2 client. These function the same as scope maps where
88    /// membership of a group provides a set of scopes to the account.
89    /// However these scopes are NOT consulted during authorization decisions made by Kanidm.
90    /// These scopes exist to allow optional properties to be provided (such as personal
91    /// information about a subset of accounts to be revealed) or so that the service may make its
92    /// own authorization decisions based on the provided scopes.
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub sup_scope_map: Option<BTreeSet<KanidmScopeMap>>,
95
96    /// Mapping from a group to a custom claims that it provides to members.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub claim_map: Option<BTreeSet<KanidmClaimMap>>,
99
100    /// Enable strict validation of redirect URLs. Previously redirect URLs only validated the
101    /// origin of the URL matched. When enabled, redirect URLs must match exactly.
102    ///
103    /// Enabled by default.
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub strict_redirect_url: Option<bool>,
106
107    /// Use the 'name' attribute instead of 'spn' for the preferred_username.
108    ///
109    /// Disabled by default.
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub prefer_short_username: Option<bool>,
112
113    /// Allow public clients to redirect to localhost.
114    ///
115    /// Just public clients can allow localhost redirect.
116    /// Disabled by default.
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub allow_localhost_redirect: Option<bool>,
119
120    /// Disable PKCE on this oauth2 client to work around insecure clients that may not support it.
121    /// You should request the client to enable PKCE!
122    ///
123    /// Public clients cannot disable PKCE.
124    /// PKCE is enabled by default.
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub allow_insecure_client_disable_pkce: Option<bool>,
127
128    /// Enable legacy signing crypto on this oauth2 client. This defaults to being disabled.
129    /// You only need to enable this for openid clients that do not support modern cryptographic
130    /// operations.
131    ///
132    /// Disabled by default.
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub jwt_legacy_crypto_enable: Option<bool>,
135
136    /// Automatic rotation configuration for the OAuth2 client secret. Only applies to confidential
137    /// clients (public: false). When enabled, the operator will regenerate the client secret
138    /// periodically based on the configured rotation period.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub secret_rotation: Option<SecretRotation>,
141
142    /// Optional URL to an image for the OAuth2 client application.
143    /// The image will be downloaded and set in Kanidm for display in the application portal.
144    /// Constraints:
145    /// - Maximum size: 256 KB
146    /// - Maximum dimensions: 1024 x 1024 pixels
147    /// - Supported formats: png, jpg, gif, svg, webp
148    #[serde(skip_serializing_if = "Option::is_none")]
149    pub image: Option<OAuth2ClientImageSpec>,
150}
151
152#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
153#[cfg_attr(feature = "schemars", derive(JsonSchema))]
154#[serde(rename_all = "camelCase")]
155pub struct OAuth2ClientImageSpec {
156    /// URL to fetch the image from (HTTP/HTTPS only).
157    /// The operator will periodically check this URL for changes using HEAD requests
158    /// and re-download the image when changes are detected.
159    pub url: String,
160}
161
162impl KanidmResource for KanidmOAuth2Client {
163    #[inline]
164    fn kanidm_ref_spec(&self) -> &KanidmRef {
165        &self.spec.kanidm_ref
166    }
167
168    #[inline]
169    fn get_namespace_selector(kanidm: &Kanidm) -> &Option<LabelSelector> {
170        &kanidm.spec.oauth2_client_namespace_selector
171    }
172
173    #[inline]
174    fn kanidm_name_override(&self) -> Option<&str> {
175        self.spec.kanidm_name.as_deref()
176    }
177}
178
179/// The `KanidmScopeMap` struct represents a mapping of a group to a set of OAuth2 scopes in Kanidm.
180///
181/// Scope maps in Kanidm are used to define the permissions that a client application can request on
182/// behalf of a user. These scopes determine what resources the client can access and what
183/// operations it can perform.
184///
185/// These provide a set of scopes if a user is a member of a specific group within Kanidm. This
186/// allows you to create a relationship between the scopes of a service, and the groups/roles in
187/// Kanidm which can be specific to that service.
188#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
189#[cfg_attr(feature = "schemars", derive(JsonSchema))]
190#[serde(rename_all = "camelCase")]
191pub struct KanidmScopeMap {
192    /// Group name or SPN. Members of this group will be granted the scopes defined in the `scopes` field.
193    pub group: String,
194
195    /// A scope is a string that represents a specific permission or set of permissions that a
196    /// client application can request from an authorization server. Scopes define the level of
197    /// access that the client application is granted to the user's resources.
198    ///
199    /// OpenID Connect allows a number of scopes that affect the content of the resulting authorization
200    /// token. If one of the following scopes is requested by the OpenID client, then the associated
201    /// claims may be added to the authorization token. It is not guaranteed that all of the associated
202    /// claims will be added.
203    ///
204    /// - `profile`: name, family_name, given_name, middle_name, nickname, preferred_username, profile,
205    ///    picture, website, gender, birthdate, zoneinfo, locale, and updated_at
206    /// - `email`: email, email_verified
207    /// - `address`: address
208    /// - `phone`: phone_number, phone_number_verified
209    /// - `groups`: groups
210    ///
211    /// If you are creating an OpenID Connect (OIDC) client, you MUST provide a scope map containing `openid`.
212    /// Without this, OpenID Connect clients WILL NOT WORK!
213    #[allow(clippy::doc_overindented_list_items)]
214    pub scopes: Vec<String>,
215}
216
217impl KanidmScopeMap {
218    pub fn normalize(self) -> Self {
219        let mut scopes = self.scopes;
220        scopes.sort();
221        Self {
222            group: normalize_spn(&self.group),
223            scopes,
224        }
225    }
226    pub fn from(s: &str) -> Option<Self> {
227        let parts = s.split(':').collect::<Vec<_>>();
228        if parts.len() != 2 {
229            return None;
230        }
231        let group = parts[0].to_string();
232        let proto_scopes = parts[1];
233        if proto_scopes.starts_with(" {").not() || proto_scopes.ends_with('}').not() {
234            return None;
235        }
236
237        let scopes = proto_scopes[2..proto_scopes.len() - 1]
238            .split(", ")
239            .map(|s| s.replace('"', ""))
240            .collect();
241        Some(Self { group, scopes })
242    }
243}
244
245/// Some OAuth2 services may consume custom claims from an id token for access control or other
246/// policy decisions. Each custom claim is a key:values set, where there can be many values
247/// associated to a claim name. Different applications may expect these values to be formatted
248/// (joined) in different ways.
249///
250/// Claim values are mapped based on membership to groups. When an account is a member of multiple
251/// groups that would receive the same claim, the values of these maps are merged.
252#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
253#[cfg_attr(feature = "schemars", derive(JsonSchema))]
254#[serde(rename_all = "camelCase")]
255pub struct KanidmClaimMap {
256    /// The name of the claim that will be provided to the client.
257    pub name: String,
258
259    pub values_map: BTreeSet<KanidmClaimsValuesMap>,
260
261    /// The strategy to join the values together.
262    /// Possible strategies to join the values of a claim map:
263    /// `csv` -> "value_a,value_b"
264    /// `ssv` -> "value_a value_b"
265    /// `array` -> ["value_a", "value_b"]
266    #[serde(default)]
267    pub join_strategy: KanidmClaimMapJoinStrategy,
268}
269
270impl KanidmClaimMap {
271    pub fn normalize(self) -> Self {
272        Self {
273            values_map: self
274                .values_map
275                .iter()
276                .map(|vm| vm.clone().normalize())
277                .collect(),
278            ..self
279        }
280    }
281
282    pub fn from(s: &str) -> Option<Self> {
283        let parts = s.split(':').collect::<Vec<_>>();
284        if parts.len() != 4 {
285            return None;
286        }
287        let name = parts[0].to_string();
288        let group = parts[1].to_string();
289        let join_strategy = match parts[2] {
290            "," => KanidmClaimMapJoinStrategy::Csv,
291            " " => KanidmClaimMapJoinStrategy::Ssv,
292            ";" => KanidmClaimMapJoinStrategy::Array,
293            _ => return None,
294        };
295        let proto_values = parts[3];
296        if proto_values.starts_with('"').not() || proto_values.ends_with('"').not() {
297            return None;
298        }
299        let values = proto_values[1..proto_values.len() - 1]
300            .split(",")
301            .map(|s| s.to_string())
302            .collect();
303        Some(Self {
304            name,
305            join_strategy,
306            values_map: BTreeSet::from([KanidmClaimsValuesMap { group, values }]),
307        })
308    }
309
310    pub fn group(v: &[KanidmClaimMap]) -> BTreeSet<KanidmClaimMap> {
311        let mut map: HashMap<String, KanidmClaimMap> = HashMap::new();
312
313        for claim in v {
314            if let Some(existing) = map.get_mut(&claim.name) {
315                existing.values_map.extend(claim.values_map.clone());
316            } else {
317                map.insert(claim.name.clone(), claim.clone());
318            }
319        }
320
321        map.into_values().collect()
322    }
323}
324
325#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
326#[cfg_attr(feature = "schemars", derive(JsonSchema))]
327#[serde(rename_all = "camelCase")]
328pub struct KanidmClaimsValuesMap {
329    /// The group name or SPN that will provide the claim.
330    pub group: String,
331
332    /// The values that will be provided to the client.
333    pub values: Vec<String>,
334}
335
336impl KanidmClaimsValuesMap {
337    pub fn normalize(self) -> Self {
338        let mut values = self.values;
339        values.sort();
340        Self {
341            group: normalize_spn(&self.group),
342            values,
343        }
344    }
345}
346
347#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
348#[cfg_attr(feature = "schemars", derive(JsonSchema))]
349#[serde(rename_all = "snake_case")]
350pub enum KanidmClaimMapJoinStrategy {
351    /// Comma-separated values: "value_a,value_b"
352    Csv,
353    /// Space-separated values: "value_a value_b"
354    Ssv,
355    /// Array format: ["value_a", "value_b"]
356    #[default]
357    Array,
358}
359
360impl KanidmClaimMapJoinStrategy {
361    pub fn to_oauth2_claim_map_join(&self) -> Oauth2ClaimMapJoin {
362        match self {
363            KanidmClaimMapJoinStrategy::Csv => Oauth2ClaimMapJoin::Csv,
364            KanidmClaimMapJoinStrategy::Ssv => Oauth2ClaimMapJoin::Ssv,
365            KanidmClaimMapJoinStrategy::Array => Oauth2ClaimMapJoin::Array,
366        }
367    }
368}
369
370/// Most recent observed status of the Kanidm Group. Read-only.
371/// More info:
372/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
373#[derive(Serialize, Deserialize, Clone, Debug, Default)]
374#[cfg_attr(feature = "schemars", derive(JsonSchema))]
375#[serde(rename_all = "camelCase")]
376pub struct KanidmOAuth2ClientStatus {
377    #[serde(skip_serializing_if = "Option::is_none")]
378    pub conditions: Option<Vec<Condition>>,
379
380    #[serde(skip_serializing_if = "Option::is_none")]
381    pub origin: Option<Vec<String>>,
382
383    #[serde(skip_serializing_if = "Option::is_none")]
384    pub scope_map: Option<Vec<String>>,
385
386    #[serde(skip_serializing_if = "Option::is_none")]
387    pub sup_scope_map: Option<Vec<String>>,
388
389    #[serde(skip_serializing_if = "Option::is_none")]
390    pub claims_map: Option<Vec<String>>,
391
392    pub ready: bool,
393
394    #[serde(skip_serializing_if = "Option::is_none")]
395    pub secret_name: Option<String>,
396
397    pub kanidm_ref: String,
398
399    /// Status of the OAuth2 client image.
400    #[serde(skip_serializing_if = "Option::is_none")]
401    pub image: Option<OAuth2ClientImageStatus>,
402}
403
404#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
405#[cfg_attr(feature = "schemars", derive(JsonSchema))]
406#[serde(rename_all = "camelCase")]
407pub struct OAuth2ClientImageStatus {
408    /// The URL from which the image was last fetched.
409    pub url: String,
410    /// ETag header from the last fetch (for change detection).
411    #[serde(skip_serializing_if = "Option::is_none")]
412    pub etag: Option<String>,
413    /// Last-Modified header from the last fetch.
414    #[serde(skip_serializing_if = "Option::is_none")]
415    pub last_modified: Option<String>,
416    /// Content-Length from the last fetch.
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub content_length: Option<u64>,
419    /// Hash of the image content (SHA-256, for validation).
420    #[serde(skip_serializing_if = "Option::is_none")]
421    pub content_hash: Option<String>,
422}
423
424#[cfg(test)]
425mod tests {
426    use super::{
427        KanidmClaimMap, KanidmClaimMapJoinStrategy, KanidmClaimsValuesMap, KanidmScopeMap,
428    };
429
430    use std::collections::BTreeSet;
431
432    #[test]
433    fn test_kanidm_scope_map_from() {
434        let scope_map = KanidmScopeMap {
435            group: "test_group".to_string(),
436            scopes: vec!["scope1".to_string(), "scope2".to_string()],
437        };
438
439        assert_eq!(
440            KanidmScopeMap::from(r#"test_group@test.example.com: {"scope1", "scope2"}"#)
441                .unwrap()
442                .normalize(),
443            scope_map,
444        );
445
446        assert_eq!(
447            KanidmScopeMap::from(r#"test_group: {"scope1", "scope2"}"#)
448                .unwrap()
449                .normalize(),
450            scope_map,
451        );
452
453        assert!(KanidmScopeMap::from(r#"test_group:{"scope1", "scope2"}"#).is_none(),);
454        assert_eq!(
455            KanidmScopeMap::from(r#"test_group: {"scope1"}"#)
456                .unwrap()
457                .normalize(),
458            KanidmScopeMap {
459                group: "test_group".to_string(),
460                scopes: vec!["scope1".to_string()],
461            }
462        );
463    }
464
465    #[test]
466    fn test_group_kanidm_claims_map() {
467        let claim1 = KanidmClaimMap {
468            name: "claim1".to_string(),
469            values_map: BTreeSet::from([KanidmClaimsValuesMap {
470                group: "group1".to_string(),
471                values: vec!["value1".to_string()],
472            }]),
473            join_strategy: KanidmClaimMapJoinStrategy::Array,
474        };
475
476        let claim2 = KanidmClaimMap {
477            name: "claim1".to_string(),
478            values_map: BTreeSet::from([KanidmClaimsValuesMap {
479                group: "group2".to_string(),
480                values: vec!["value2".to_string()],
481            }]),
482            join_strategy: KanidmClaimMapJoinStrategy::Array,
483        };
484
485        let claim3 = KanidmClaimMap {
486            name: "claim2".to_string(),
487            values_map: BTreeSet::from([KanidmClaimsValuesMap {
488                group: "group3".to_string(),
489                values: vec!["value3".to_string()],
490            }]),
491            join_strategy: KanidmClaimMapJoinStrategy::Array,
492        };
493
494        let claims = vec![claim1.clone(), claim2.clone(), claim3.clone()];
495
496        let grouped_claims = KanidmClaimMap::group(&claims);
497
498        assert_eq!(grouped_claims.len(), 2);
499
500        let grouped_claim1 = grouped_claims.iter().find(|c| c.name == "claim1").unwrap();
501        assert_eq!(grouped_claim1.values_map.len(), 2);
502        assert!(grouped_claim1.values_map.contains(&KanidmClaimsValuesMap {
503            group: "group1".to_string(),
504            values: vec!["value1".to_string()],
505        }));
506        assert!(grouped_claim1.values_map.contains(&KanidmClaimsValuesMap {
507            group: "group2".to_string(),
508            values: vec!["value2".to_string()],
509        }));
510
511        let grouped_claim2 = grouped_claims.iter().find(|c| c.name == "claim2").unwrap();
512        assert_eq!(grouped_claim2.values_map.len(), 1);
513        assert!(grouped_claim2.values_map.contains(&KanidmClaimsValuesMap {
514            group: "group3".to_string(),
515            values: vec!["value3".to_string()],
516        }));
517    }
518
519    #[test]
520    fn test_kanidm_claim_map_from() {
521        let mut claim_map = KanidmClaimMap {
522            name: "claim_name".to_string(),
523            join_strategy: KanidmClaimMapJoinStrategy::Array,
524            values_map: BTreeSet::from([KanidmClaimsValuesMap {
525                group: "group_name".to_string(),
526                // Sorted values after normalization
527                values: vec!["boo".to_string(), "foo".to_string()],
528            }]),
529        };
530
531        assert_eq!(
532            KanidmClaimMap::from(r#"claim_name:group_name@test.example.com:;:"foo,boo""#)
533                .unwrap()
534                .normalize(),
535            claim_map,
536        );
537        assert_eq!(
538            KanidmClaimMap::from(r#"claim_name:group_name:;:"foo,boo""#)
539                .unwrap()
540                .normalize(),
541            claim_map,
542        );
543
544        claim_map.join_strategy = KanidmClaimMapJoinStrategy::Csv;
545        assert_eq!(
546            KanidmClaimMap::from(r#"claim_name:group_name:,:"foo,boo""#)
547                .unwrap()
548                .normalize(),
549            claim_map,
550        );
551
552        claim_map.join_strategy = KanidmClaimMapJoinStrategy::Ssv;
553        assert_eq!(
554            KanidmClaimMap::from(r#"claim_name:group_name: :"foo,boo""#)
555                .unwrap()
556                .normalize(),
557            claim_map,
558        );
559    }
560}