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    /// 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    /// Disable the consent prompt for this OAuth2 client. This allows skipping the user
137    /// consent screen for well-known admin-managed applications. When enabled, users will
138    /// not be prompted to grant consent when authorizing with this client.
139    ///
140    /// Disabled by default.
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub disable_consent_prompt: Option<bool>,
143
144    /// Automatic rotation configuration for the OAuth2 client secret. Only applies to confidential
145    /// clients (public: false). When enabled, the operator will regenerate the client secret
146    /// periodically based on the configured rotation period.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub secret_rotation: Option<SecretRotation>,
149
150    /// Template applied to the Secret created for confidential clients (public: false).
151    /// Allows attaching custom annotations and labels to the generated Secret. The operator's own
152    /// labels and annotations take precedence over any conflicting keys in the template.
153    /// Changes to this template are enforced on the next reconciliation, overwriting any manual
154    /// modifications made to the Secret
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub secret_template: Option<MetadataTemplate>,
157
158    /// Optional URL to an image for the OAuth2 client application.
159    /// The image will be downloaded and set in Kanidm for display in the application portal.
160    /// Constraints:
161    /// - Maximum size: 256 KB
162    /// - Maximum dimensions: 1024 x 1024 pixels
163    /// - Supported formats: png, jpg, gif, svg, webp
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub image: Option<OAuth2ClientImageSpec>,
166}
167
168#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
169#[cfg_attr(feature = "schemars", derive(JsonSchema))]
170#[serde(rename_all = "camelCase")]
171pub struct OAuth2ClientImageSpec {
172    /// URL to fetch the image from (HTTP/HTTPS only).
173    /// The operator will periodically check this URL for changes using HEAD requests
174    /// and re-download the image when changes are detected.
175    pub url: String,
176}
177
178impl KanidmResource for KanidmOAuth2Client {
179    #[inline]
180    fn kanidm_ref_spec(&self) -> &KanidmRef {
181        &self.spec.kanidm_ref
182    }
183
184    #[inline]
185    fn get_namespace_selector(kanidm: &Kanidm) -> &Option<LabelSelector> {
186        &kanidm.spec.oauth2_client_namespace_selector
187    }
188
189    #[inline]
190    fn kanidm_name_override(&self) -> Option<&str> {
191        self.spec.kanidm_name.as_deref()
192    }
193}
194
195/// The `KanidmScopeMap` struct represents a mapping of a group to a set of OAuth2 scopes in Kanidm.
196///
197/// Scope maps in Kanidm are used to define the permissions that a client application can request on
198/// behalf of a user. These scopes determine what resources the client can access and what
199/// operations it can perform.
200///
201/// These provide a set of scopes if a user is a member of a specific group within Kanidm. This
202/// allows you to create a relationship between the scopes of a service, and the groups/roles in
203/// Kanidm which can be specific to that service.
204#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
205#[cfg_attr(feature = "schemars", derive(JsonSchema))]
206#[serde(rename_all = "camelCase")]
207pub struct KanidmScopeMap {
208    /// Group name or SPN. Members of this group will be granted the scopes defined in the `scopes` field.
209    pub group: String,
210
211    /// A scope is a string that represents a specific permission or set of permissions that a
212    /// client application can request from an authorization server. Scopes define the level of
213    /// access that the client application is granted to the user's resources.
214    ///
215    /// OpenID Connect allows a number of scopes that affect the content of the resulting authorization
216    /// token. If one of the following scopes is requested by the OpenID client, then the associated
217    /// claims may be added to the authorization token. It is not guaranteed that all of the associated
218    /// claims will be added.
219    ///
220    /// - `profile`: name, family_name, given_name, middle_name, nickname, preferred_username, profile,
221    ///    picture, website, gender, birthdate, zoneinfo, locale, and updated_at
222    /// - `email`: email, email_verified
223    /// - `address`: address
224    /// - `phone`: phone_number, phone_number_verified
225    /// - `groups`: groups
226    ///
227    /// If you are creating an OpenID Connect (OIDC) client, you MUST provide a scope map containing `openid`.
228    /// Without this, OpenID Connect clients WILL NOT WORK!
229    #[allow(clippy::doc_overindented_list_items)]
230    pub scopes: Vec<String>,
231}
232
233impl KanidmScopeMap {
234    pub fn normalize(self) -> Self {
235        let mut scopes = self.scopes;
236        scopes.sort();
237        Self {
238            group: normalize_spn(&self.group),
239            scopes,
240        }
241    }
242    pub fn from(s: &str) -> Option<Self> {
243        let parts = s.split(':').collect::<Vec<_>>();
244        if parts.len() != 2 {
245            return None;
246        }
247        let group = parts[0].to_string();
248        let proto_scopes = parts[1];
249        if proto_scopes.starts_with(" {").not() || proto_scopes.ends_with('}').not() {
250            return None;
251        }
252
253        let scopes = proto_scopes[2..proto_scopes.len() - 1]
254            .split(", ")
255            .map(|s| s.replace('"', ""))
256            .collect();
257        Some(Self { group, scopes })
258    }
259}
260
261/// Some OAuth2 services may consume custom claims from an id token for access control or other
262/// policy decisions. Each custom claim is a key:values set, where there can be many values
263/// associated to a claim name. Different applications may expect these values to be formatted
264/// (joined) in different ways.
265///
266/// Claim values are mapped based on membership to groups. When an account is a member of multiple
267/// groups that would receive the same claim, the values of these maps are merged.
268#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
269#[cfg_attr(feature = "schemars", derive(JsonSchema))]
270#[serde(rename_all = "camelCase")]
271pub struct KanidmClaimMap {
272    /// The name of the claim that will be provided to the client.
273    pub name: String,
274
275    pub values_map: BTreeSet<KanidmClaimsValuesMap>,
276
277    /// The strategy to join the values together.
278    /// Possible strategies to join the values of a claim map:
279    /// `csv` -> "value_a,value_b"
280    /// `ssv` -> "value_a value_b"
281    /// `array` -> ["value_a", "value_b"]
282    #[serde(default)]
283    pub join_strategy: KanidmClaimMapJoinStrategy,
284}
285
286impl KanidmClaimMap {
287    pub fn normalize(self) -> Self {
288        Self {
289            values_map: self
290                .values_map
291                .iter()
292                .map(|vm| vm.clone().normalize())
293                .collect(),
294            ..self
295        }
296    }
297
298    pub fn from(s: &str) -> Option<Self> {
299        let parts = s.split(':').collect::<Vec<_>>();
300        if parts.len() != 4 {
301            return None;
302        }
303        let name = parts[0].to_string();
304        let group = parts[1].to_string();
305        let join_strategy = match parts[2] {
306            "," => KanidmClaimMapJoinStrategy::Csv,
307            " " => KanidmClaimMapJoinStrategy::Ssv,
308            ";" => KanidmClaimMapJoinStrategy::Array,
309            _ => return None,
310        };
311        let proto_values = parts[3];
312        if proto_values.starts_with('"').not() || proto_values.ends_with('"').not() {
313            return None;
314        }
315        let values = proto_values[1..proto_values.len() - 1]
316            .split(",")
317            .map(|s| s.to_string())
318            .collect();
319        Some(Self {
320            name,
321            join_strategy,
322            values_map: BTreeSet::from([KanidmClaimsValuesMap { group, values }]),
323        })
324    }
325
326    pub fn group(v: &[KanidmClaimMap]) -> BTreeSet<KanidmClaimMap> {
327        let mut map: HashMap<String, KanidmClaimMap> = HashMap::new();
328
329        for claim in v {
330            if let Some(existing) = map.get_mut(&claim.name) {
331                existing.values_map.extend(claim.values_map.clone());
332            } else {
333                map.insert(claim.name.clone(), claim.clone());
334            }
335        }
336
337        map.into_values().collect()
338    }
339}
340
341#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
342#[cfg_attr(feature = "schemars", derive(JsonSchema))]
343#[serde(rename_all = "camelCase")]
344pub struct KanidmClaimsValuesMap {
345    /// The group name or SPN that will provide the claim.
346    pub group: String,
347
348    /// The values that will be provided to the client.
349    pub values: Vec<String>,
350}
351
352impl KanidmClaimsValuesMap {
353    pub fn normalize(self) -> Self {
354        let mut values = self.values;
355        values.sort();
356        Self {
357            group: normalize_spn(&self.group),
358            values,
359        }
360    }
361}
362
363#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
364#[cfg_attr(feature = "schemars", derive(JsonSchema))]
365#[serde(rename_all = "snake_case")]
366pub enum KanidmClaimMapJoinStrategy {
367    /// Comma-separated values: "value_a,value_b"
368    Csv,
369    /// Space-separated values: "value_a value_b"
370    Ssv,
371    /// Array format: ["value_a", "value_b"]
372    #[default]
373    Array,
374}
375
376impl KanidmClaimMapJoinStrategy {
377    pub fn to_oauth2_claim_map_join(&self) -> Oauth2ClaimMapJoin {
378        match self {
379            KanidmClaimMapJoinStrategy::Csv => Oauth2ClaimMapJoin::Csv,
380            KanidmClaimMapJoinStrategy::Ssv => Oauth2ClaimMapJoin::Ssv,
381            KanidmClaimMapJoinStrategy::Array => Oauth2ClaimMapJoin::Array,
382        }
383    }
384}
385
386/// Most recent observed status of the Kanidm Group. Read-only.
387/// More info:
388/// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
389#[derive(Serialize, Deserialize, Clone, Debug, Default)]
390#[cfg_attr(feature = "schemars", derive(JsonSchema))]
391#[serde(rename_all = "camelCase")]
392pub struct KanidmOAuth2ClientStatus {
393    #[serde(skip_serializing_if = "Option::is_none")]
394    pub conditions: Option<Vec<Condition>>,
395
396    #[serde(skip_serializing_if = "Option::is_none")]
397    pub origin: Option<Vec<String>>,
398
399    #[serde(skip_serializing_if = "Option::is_none")]
400    pub scope_map: Option<Vec<String>>,
401
402    #[serde(skip_serializing_if = "Option::is_none")]
403    pub sup_scope_map: Option<Vec<String>>,
404
405    #[serde(skip_serializing_if = "Option::is_none")]
406    pub claims_map: Option<Vec<String>>,
407
408    pub ready: bool,
409
410    #[serde(skip_serializing_if = "Option::is_none")]
411    pub secret_name: Option<String>,
412
413    pub kanidm_ref: String,
414
415    /// Status of the OAuth2 client image.
416    #[serde(skip_serializing_if = "Option::is_none")]
417    pub image: Option<OAuth2ClientImageStatus>,
418}
419
420#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)]
421#[cfg_attr(feature = "schemars", derive(JsonSchema))]
422#[serde(rename_all = "camelCase")]
423pub struct OAuth2ClientImageStatus {
424    /// The URL from which the image was last fetched.
425    pub url: String,
426    /// ETag header from the last fetch (for change detection).
427    #[serde(skip_serializing_if = "Option::is_none")]
428    pub etag: Option<String>,
429    /// Last-Modified header from the last fetch.
430    #[serde(skip_serializing_if = "Option::is_none")]
431    pub last_modified: Option<String>,
432    /// Content-Length from the last fetch.
433    #[serde(skip_serializing_if = "Option::is_none")]
434    pub content_length: Option<u64>,
435    /// Hash of the image content (SHA-256, for validation).
436    #[serde(skip_serializing_if = "Option::is_none")]
437    pub content_hash: Option<String>,
438}
439
440#[cfg(test)]
441mod tests {
442    use super::{
443        KanidmClaimMap, KanidmClaimMapJoinStrategy, KanidmClaimsValuesMap, KanidmScopeMap,
444    };
445
446    use std::collections::BTreeSet;
447
448    #[test]
449    fn test_kanidm_scope_map_from() {
450        let scope_map = KanidmScopeMap {
451            group: "test_group".to_string(),
452            scopes: vec!["scope1".to_string(), "scope2".to_string()],
453        };
454
455        assert_eq!(
456            KanidmScopeMap::from(r#"test_group@test.example.com: {"scope1", "scope2"}"#)
457                .unwrap()
458                .normalize(),
459            scope_map,
460        );
461
462        assert_eq!(
463            KanidmScopeMap::from(r#"test_group: {"scope1", "scope2"}"#)
464                .unwrap()
465                .normalize(),
466            scope_map,
467        );
468
469        assert!(KanidmScopeMap::from(r#"test_group:{"scope1", "scope2"}"#).is_none(),);
470        assert_eq!(
471            KanidmScopeMap::from(r#"test_group: {"scope1"}"#)
472                .unwrap()
473                .normalize(),
474            KanidmScopeMap {
475                group: "test_group".to_string(),
476                scopes: vec!["scope1".to_string()],
477            }
478        );
479    }
480
481    #[test]
482    fn test_group_kanidm_claims_map() {
483        let claim1 = KanidmClaimMap {
484            name: "claim1".to_string(),
485            values_map: BTreeSet::from([KanidmClaimsValuesMap {
486                group: "group1".to_string(),
487                values: vec!["value1".to_string()],
488            }]),
489            join_strategy: KanidmClaimMapJoinStrategy::Array,
490        };
491
492        let claim2 = KanidmClaimMap {
493            name: "claim1".to_string(),
494            values_map: BTreeSet::from([KanidmClaimsValuesMap {
495                group: "group2".to_string(),
496                values: vec!["value2".to_string()],
497            }]),
498            join_strategy: KanidmClaimMapJoinStrategy::Array,
499        };
500
501        let claim3 = KanidmClaimMap {
502            name: "claim2".to_string(),
503            values_map: BTreeSet::from([KanidmClaimsValuesMap {
504                group: "group3".to_string(),
505                values: vec!["value3".to_string()],
506            }]),
507            join_strategy: KanidmClaimMapJoinStrategy::Array,
508        };
509
510        let claims = vec![claim1.clone(), claim2.clone(), claim3.clone()];
511
512        let grouped_claims = KanidmClaimMap::group(&claims);
513
514        assert_eq!(grouped_claims.len(), 2);
515
516        let grouped_claim1 = grouped_claims.iter().find(|c| c.name == "claim1").unwrap();
517        assert_eq!(grouped_claim1.values_map.len(), 2);
518        assert!(grouped_claim1.values_map.contains(&KanidmClaimsValuesMap {
519            group: "group1".to_string(),
520            values: vec!["value1".to_string()],
521        }));
522        assert!(grouped_claim1.values_map.contains(&KanidmClaimsValuesMap {
523            group: "group2".to_string(),
524            values: vec!["value2".to_string()],
525        }));
526
527        let grouped_claim2 = grouped_claims.iter().find(|c| c.name == "claim2").unwrap();
528        assert_eq!(grouped_claim2.values_map.len(), 1);
529        assert!(grouped_claim2.values_map.contains(&KanidmClaimsValuesMap {
530            group: "group3".to_string(),
531            values: vec!["value3".to_string()],
532        }));
533    }
534
535    #[test]
536    fn test_kanidm_claim_map_from() {
537        let mut claim_map = KanidmClaimMap {
538            name: "claim_name".to_string(),
539            join_strategy: KanidmClaimMapJoinStrategy::Array,
540            values_map: BTreeSet::from([KanidmClaimsValuesMap {
541                group: "group_name".to_string(),
542                // Sorted values after normalization
543                values: vec!["boo".to_string(), "foo".to_string()],
544            }]),
545        };
546
547        assert_eq!(
548            KanidmClaimMap::from(r#"claim_name:group_name@test.example.com:;:"foo,boo""#)
549                .unwrap()
550                .normalize(),
551            claim_map,
552        );
553        assert_eq!(
554            KanidmClaimMap::from(r#"claim_name:group_name:;:"foo,boo""#)
555                .unwrap()
556                .normalize(),
557            claim_map,
558        );
559
560        claim_map.join_strategy = KanidmClaimMapJoinStrategy::Csv;
561        assert_eq!(
562            KanidmClaimMap::from(r#"claim_name:group_name:,:"foo,boo""#)
563                .unwrap()
564                .normalize(),
565            claim_map,
566        );
567
568        claim_map.join_strategy = KanidmClaimMapJoinStrategy::Ssv;
569        assert_eq!(
570            KanidmClaimMap::from(r#"claim_name:group_name: :"foo,boo""#)
571                .unwrap()
572                .normalize(),
573            claim_map,
574        );
575    }
576}