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