kaniop_oauth2/
crd.rs

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