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