kaniop_oauth2/
crd.rs

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