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