Skip to main content

kanidm_client/
oauth.rs

1use crate::{ClientError, KanidmClient};
2use kanidm_proto::{
3    attribute::Attribute,
4    constants::{
5        ATTR_DISPLAYNAME, ATTR_KEY_ACTION_REVOKE, ATTR_KEY_ACTION_ROTATE, ATTR_NAME,
6        ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE, ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT,
7        ATTR_OAUTH2_CONSENT_PROMPT_ENABLE, ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE,
8        ATTR_OAUTH2_PREFER_SHORT_USERNAME, ATTR_OAUTH2_RS_BASIC_SECRET, ATTR_OAUTH2_RS_ORIGIN,
9        ATTR_OAUTH2_RS_ORIGIN_LANDING, ATTR_OAUTH2_STRICT_REDIRECT_URI,
10    },
11    internal::{ImageValue, Oauth2ClaimMapJoin},
12    v1::Entry,
13};
14use reqwest::multipart;
15use std::collections::BTreeMap;
16use time::{format_description::well_known::Rfc3339, OffsetDateTime};
17use url::Url;
18
19impl KanidmClient {
20    // ==== Oauth2 resource server configuration
21    #[instrument(level = "debug")]
22    pub async fn idm_oauth2_rs_list(&self) -> Result<Vec<Entry>, ClientError> {
23        self.perform_get_request("/v1/oauth2").await
24    }
25
26    pub async fn idm_oauth2_rs_basic_create(
27        &self,
28        name: &str,
29        displayname: &str,
30        origin: &str,
31    ) -> Result<(), ClientError> {
32        let mut new_oauth2_rs = Entry::default();
33        new_oauth2_rs
34            .attrs
35            .insert(ATTR_NAME.to_string(), vec![name.to_string()]);
36        new_oauth2_rs
37            .attrs
38            .insert(ATTR_DISPLAYNAME.to_string(), vec![displayname.to_string()]);
39        new_oauth2_rs.attrs.insert(
40            ATTR_OAUTH2_RS_ORIGIN_LANDING.to_string(),
41            vec![origin.to_string()],
42        );
43        new_oauth2_rs.attrs.insert(
44            ATTR_OAUTH2_STRICT_REDIRECT_URI.to_string(),
45            vec!["true".to_string()],
46        );
47        self.perform_post_request("/v1/oauth2/_basic", new_oauth2_rs)
48            .await
49    }
50
51    pub async fn idm_oauth2_rs_public_create(
52        &self,
53        name: &str,
54        displayname: &str,
55        origin: &str,
56    ) -> Result<(), ClientError> {
57        let mut new_oauth2_rs = Entry::default();
58        new_oauth2_rs
59            .attrs
60            .insert(ATTR_NAME.to_string(), vec![name.to_string()]);
61        new_oauth2_rs
62            .attrs
63            .insert(ATTR_DISPLAYNAME.to_string(), vec![displayname.to_string()]);
64        new_oauth2_rs.attrs.insert(
65            ATTR_OAUTH2_RS_ORIGIN_LANDING.to_string(),
66            vec![origin.to_string()],
67        );
68        new_oauth2_rs.attrs.insert(
69            ATTR_OAUTH2_STRICT_REDIRECT_URI.to_string(),
70            vec!["true".to_string()],
71        );
72        self.perform_post_request("/v1/oauth2/_public", new_oauth2_rs)
73            .await
74    }
75
76    pub async fn idm_oauth2_rs_get(&self, client_name: &str) -> Result<Option<Entry>, ClientError> {
77        self.perform_get_request(format!("/v1/oauth2/{client_name}").as_str())
78            .await
79    }
80
81    pub async fn idm_oauth2_rs_get_basic_secret(
82        &self,
83        client_name: &str,
84    ) -> Result<Option<String>, ClientError> {
85        self.perform_get_request(format!("/v1/oauth2/{client_name}/_basic_secret").as_str())
86            .await
87    }
88
89    pub async fn idm_oauth2_rs_revoke_key(
90        &self,
91        client_name: &str,
92        key_id: &str,
93    ) -> Result<(), ClientError> {
94        self.perform_post_request(
95            &format!("/v1/oauth2/{client_name}/_attr/{ATTR_KEY_ACTION_REVOKE}"),
96            vec![key_id.to_string()],
97        )
98        .await
99    }
100
101    pub async fn idm_oauth2_rs_rotate_keys(
102        &self,
103        client_name: &str,
104        rotate_at_time: OffsetDateTime,
105    ) -> Result<(), ClientError> {
106        let rfc_3339_str = rotate_at_time.format(&Rfc3339).map_err(|_| {
107            ClientError::InvalidRequest("Unable to format rfc 3339 datetime".into())
108        })?;
109
110        self.perform_post_request(
111            &format!("/v1/oauth2/{client_name}/_attr/{ATTR_KEY_ACTION_ROTATE}"),
112            vec![rfc_3339_str],
113        )
114        .await
115    }
116
117    pub async fn idm_oauth2_rs_update(
118        &self,
119        id: &str,
120        name: Option<&str>,
121        displayname: Option<&str>,
122        landing: Option<&str>,
123        reset_secret: bool,
124    ) -> Result<(), ClientError> {
125        let mut update_oauth2_rs = Entry {
126            attrs: BTreeMap::new(),
127        };
128
129        if let Some(newname) = name {
130            update_oauth2_rs
131                .attrs
132                .insert(ATTR_NAME.to_string(), vec![newname.to_string()]);
133        }
134        if let Some(newdisplayname) = displayname {
135            update_oauth2_rs.attrs.insert(
136                ATTR_DISPLAYNAME.to_string(),
137                vec![newdisplayname.to_string()],
138            );
139        }
140        if let Some(newlanding) = landing {
141            update_oauth2_rs.attrs.insert(
142                ATTR_OAUTH2_RS_ORIGIN_LANDING.to_string(),
143                vec![newlanding.to_string()],
144            );
145        }
146        if reset_secret {
147            update_oauth2_rs
148                .attrs
149                .insert(ATTR_OAUTH2_RS_BASIC_SECRET.to_string(), Vec::new());
150        }
151        self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
152            .await
153    }
154
155    pub async fn idm_oauth2_rs_update_scope_map(
156        &self,
157        id: &str,
158        group: &str,
159        scopes: Vec<&str>,
160    ) -> Result<(), ClientError> {
161        let scopes: Vec<String> = scopes.into_iter().map(str::to_string).collect();
162        self.perform_post_request(
163            format!("/v1/oauth2/{id}/_scopemap/{group}").as_str(),
164            scopes,
165        )
166        .await
167    }
168
169    pub async fn idm_oauth2_rs_delete_scope_map(
170        &self,
171        id: &str,
172        group: &str,
173    ) -> Result<(), ClientError> {
174        self.perform_delete_request(format!("/v1/oauth2/{id}/_scopemap/{group}").as_str())
175            .await
176    }
177
178    pub async fn idm_oauth2_rs_update_sup_scope_map(
179        &self,
180        id: &str,
181        group: &str,
182        scopes: Vec<&str>,
183    ) -> Result<(), ClientError> {
184        let scopes: Vec<String> = scopes.into_iter().map(str::to_string).collect();
185        self.perform_post_request(
186            format!("/v1/oauth2/{id}/_sup_scopemap/{group}").as_str(),
187            scopes,
188        )
189        .await
190    }
191
192    pub async fn idm_oauth2_rs_delete_sup_scope_map(
193        &self,
194        id: &str,
195        group: &str,
196    ) -> Result<(), ClientError> {
197        self.perform_delete_request(format!("/v1/oauth2/{id}/_sup_scopemap/{group}").as_str())
198            .await
199    }
200
201    pub async fn idm_oauth2_rs_delete(&self, id: &str) -> Result<(), ClientError> {
202        self.perform_delete_request(["/v1/oauth2/", id].concat().as_str())
203            .await
204    }
205
206    /// Want to delete the image associated with a resource server? Here's your thing!
207    pub async fn idm_oauth2_rs_delete_image(&self, id: &str) -> Result<(), ClientError> {
208        self.perform_delete_request(format!("/v1/oauth2/{id}/_image").as_str())
209            .await
210    }
211
212    /// Want to add/update the image associated with a resource server? Here's your thing!
213    pub async fn idm_oauth2_rs_update_image(
214        &self,
215        id: &str,
216        image: ImageValue,
217    ) -> Result<(), ClientError> {
218        let file_content_type = image.filetype.as_content_type_str();
219
220        let file_data = match multipart::Part::bytes(image.contents.clone())
221            .file_name(image.filename)
222            .mime_str(file_content_type)
223        {
224            Ok(part) => part,
225            Err(err) => {
226                error!(
227                    "Failed to generate multipart body from image data: {:}",
228                    err
229                );
230                return Err(ClientError::SystemError);
231            }
232        };
233
234        let form = multipart::Form::new().part("image", file_data);
235
236        // send it
237        let response = self
238            .client
239            .post(self.make_url(&format!("/v1/oauth2/{id}/_image")))
240            .multipart(form);
241
242        let response = {
243            let tguard = self.bearer_token.read().await;
244            if let Some(token) = &(*tguard) {
245                response.bearer_auth(token)
246            } else {
247                response
248            }
249        };
250        let response = response
251            .send()
252            .await
253            .map_err(|err| self.handle_response_error(err))?;
254        self.expect_version(&response).await;
255
256        let opid = self.get_kopid_from_response(&response);
257
258        self.ok_or_clienterror(&opid, response)
259            .await?
260            .json()
261            .await
262            .map_err(|e| ClientError::JsonDecode(e, opid))
263    }
264
265    pub async fn idm_oauth2_rs_enable_pkce(&self, id: &str) -> Result<(), ClientError> {
266        let mut update_oauth2_rs = Entry {
267            attrs: BTreeMap::new(),
268        };
269        update_oauth2_rs.attrs.insert(
270            ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE.to_string(),
271            Vec::new(),
272        );
273        self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
274            .await
275    }
276
277    pub async fn idm_oauth2_rs_disable_pkce(&self, id: &str) -> Result<(), ClientError> {
278        let mut update_oauth2_rs = Entry {
279            attrs: BTreeMap::new(),
280        };
281        update_oauth2_rs.attrs.insert(
282            ATTR_OAUTH2_ALLOW_INSECURE_CLIENT_DISABLE_PKCE.to_string(),
283            vec!["true".to_string()],
284        );
285        self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
286            .await
287    }
288
289    pub async fn idm_oauth2_rs_enable_legacy_crypto(&self, id: &str) -> Result<(), ClientError> {
290        let mut update_oauth2_rs = Entry {
291            attrs: BTreeMap::new(),
292        };
293        update_oauth2_rs.attrs.insert(
294            ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE.to_string(),
295            vec!["true".to_string()],
296        );
297        self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
298            .await
299    }
300
301    pub async fn idm_oauth2_rs_disable_legacy_crypto(&self, id: &str) -> Result<(), ClientError> {
302        let mut update_oauth2_rs = Entry {
303            attrs: BTreeMap::new(),
304        };
305        update_oauth2_rs.attrs.insert(
306            ATTR_OAUTH2_JWT_LEGACY_CRYPTO_ENABLE.to_string(),
307            vec!["false".to_string()],
308        );
309        self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
310            .await
311    }
312
313    pub async fn idm_oauth2_rs_prefer_short_username(&self, id: &str) -> Result<(), ClientError> {
314        let mut update_oauth2_rs = Entry {
315            attrs: BTreeMap::new(),
316        };
317        update_oauth2_rs.attrs.insert(
318            ATTR_OAUTH2_PREFER_SHORT_USERNAME.to_string(),
319            vec!["true".to_string()],
320        );
321        self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
322            .await
323    }
324
325    pub async fn idm_oauth2_rs_prefer_spn_username(&self, id: &str) -> Result<(), ClientError> {
326        let mut update_oauth2_rs = Entry {
327            attrs: BTreeMap::new(),
328        };
329        update_oauth2_rs.attrs.insert(
330            ATTR_OAUTH2_PREFER_SHORT_USERNAME.to_string(),
331            vec!["false".to_string()],
332        );
333        self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
334            .await
335    }
336
337    pub async fn idm_oauth2_rs_enable_public_localhost_redirect(
338        &self,
339        id: &str,
340    ) -> Result<(), ClientError> {
341        let mut update_oauth2_rs = Entry {
342            attrs: BTreeMap::new(),
343        };
344        update_oauth2_rs.attrs.insert(
345            ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT.to_string(),
346            vec!["true".to_string()],
347        );
348        self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
349            .await
350    }
351
352    pub async fn idm_oauth2_rs_disable_public_localhost_redirect(
353        &self,
354        id: &str,
355    ) -> Result<(), ClientError> {
356        let mut update_oauth2_rs = Entry {
357            attrs: BTreeMap::new(),
358        };
359        update_oauth2_rs.attrs.insert(
360            ATTR_OAUTH2_ALLOW_LOCALHOST_REDIRECT.to_string(),
361            vec!["false".to_string()],
362        );
363        self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
364            .await
365    }
366
367    pub async fn idm_oauth2_rs_enable_strict_redirect_uri(
368        &self,
369        id: &str,
370    ) -> Result<(), ClientError> {
371        let mut update_oauth2_rs = Entry {
372            attrs: BTreeMap::new(),
373        };
374        update_oauth2_rs.attrs.insert(
375            ATTR_OAUTH2_STRICT_REDIRECT_URI.to_string(),
376            vec!["true".to_string()],
377        );
378        self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
379            .await
380    }
381
382    pub async fn idm_oauth2_rs_disable_strict_redirect_uri(
383        &self,
384        id: &str,
385    ) -> Result<(), ClientError> {
386        let mut update_oauth2_rs = Entry {
387            attrs: BTreeMap::new(),
388        };
389        update_oauth2_rs.attrs.insert(
390            ATTR_OAUTH2_STRICT_REDIRECT_URI.to_string(),
391            vec!["false".to_string()],
392        );
393        self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
394            .await
395    }
396
397    pub async fn idm_oauth2_rs_update_claim_map(
398        &self,
399        id: &str,
400        claim_name: &str,
401        group_id: &str,
402        values: &[String],
403    ) -> Result<(), ClientError> {
404        let values: Vec<String> = values.to_vec();
405        self.perform_post_request(
406            format!("/v1/oauth2/{id}/_claimmap/{claim_name}/{group_id}").as_str(),
407            values,
408        )
409        .await
410    }
411
412    pub async fn idm_oauth2_rs_update_claim_map_join(
413        &self,
414        id: &str,
415        claim_name: &str,
416        join: Oauth2ClaimMapJoin,
417    ) -> Result<(), ClientError> {
418        self.perform_post_request(
419            format!("/v1/oauth2/{id}/_claimmap/{claim_name}").as_str(),
420            join,
421        )
422        .await
423    }
424
425    pub async fn idm_oauth2_rs_delete_claim_map(
426        &self,
427        id: &str,
428        claim_name: &str,
429        group_id: &str,
430    ) -> Result<(), ClientError> {
431        self.perform_delete_request(
432            format!("/v1/oauth2/{id}/_claimmap/{claim_name}/{group_id}").as_str(),
433        )
434        .await
435    }
436
437    pub async fn idm_oauth2_client_add_origin(
438        &self,
439        id: &str,
440        origin: &Url,
441    ) -> Result<(), ClientError> {
442        // TODO: should we normalise loopback origins, so when a user specifies `http://localhost/foo` we store it as `http://[::1]/foo`?
443
444        let url_to_add = &[origin.as_str()];
445        self.perform_post_request(
446            format!("/v1/oauth2/{id}/_attr/{ATTR_OAUTH2_RS_ORIGIN}").as_str(),
447            url_to_add,
448        )
449        .await
450    }
451
452    pub async fn idm_oauth2_client_remove_origin(
453        &self,
454        id: &str,
455        origin: &Url,
456    ) -> Result<(), ClientError> {
457        let url_to_remove = &[origin.as_str()];
458        self.perform_delete_request_with_body(
459            format!("/v1/oauth2/{id}/_attr/{ATTR_OAUTH2_RS_ORIGIN}").as_str(),
460            url_to_remove,
461        )
462        .await
463    }
464
465    pub async fn idm_oauth2_client_device_flow_update(
466        &self,
467        id: &str,
468        value: bool,
469    ) -> Result<(), ClientError> {
470        match value {
471            true => {
472                let mut update_oauth2_rs = Entry {
473                    attrs: BTreeMap::new(),
474                };
475                update_oauth2_rs.attrs.insert(
476                    Attribute::OAuth2DeviceFlowEnable.into(),
477                    vec![value.to_string()],
478                );
479                self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
480                    .await
481            }
482            false => {
483                self.perform_delete_request(&format!(
484                    "/v1/oauth2/{}/_attr/{}",
485                    id,
486                    Attribute::OAuth2DeviceFlowEnable.as_str()
487                ))
488                .await
489            }
490        }
491    }
492
493    pub async fn idm_oauth2_rs_set_refresh_token_expiry(
494        &self,
495        id: &str,
496        expiry: Option<u32>,
497    ) -> Result<(), ClientError> {
498        match expiry {
499            Some(exp) => {
500                let mut update_oauth2_rs = Entry {
501                    attrs: BTreeMap::new(),
502                };
503                update_oauth2_rs.attrs.insert(
504                    Attribute::OAuth2RefreshTokenExpiry.into(),
505                    vec![exp.to_string()],
506                );
507                self.perform_patch_request(format!("/v1/oauth2/{id}").as_str(), update_oauth2_rs)
508                    .await
509            }
510            None => {
511                self.perform_delete_request(&format!(
512                    "/v1/oauth2/{}/_attr/{}",
513                    id,
514                    Attribute::OAuth2RefreshTokenExpiry.as_str()
515                ))
516                .await
517            }
518        }
519    }
520
521    pub async fn idm_oauth2_rs_enable_consent_prompt(&self, id: &str) -> Result<(), ClientError> {
522        let mut update_oauth2_rs = Entry {
523            attrs: BTreeMap::new(),
524        };
525        update_oauth2_rs.attrs.insert(
526            ATTR_OAUTH2_CONSENT_PROMPT_ENABLE.to_string(),
527            vec!["true".to_string()],
528        );
529        self.perform_patch_request(format!("/v1/oauth2/{}", id).as_str(), update_oauth2_rs)
530            .await
531    }
532
533    pub async fn idm_oauth2_rs_disable_consent_prompt(&self, id: &str) -> Result<(), ClientError> {
534        let mut update_oauth2_rs = Entry {
535            attrs: BTreeMap::new(),
536        };
537        update_oauth2_rs.attrs.insert(
538            ATTR_OAUTH2_CONSENT_PROMPT_ENABLE.to_string(),
539            vec!["false".to_string()],
540        );
541        self.perform_patch_request(format!("/v1/oauth2/{}", id).as_str(), update_oauth2_rs)
542            .await
543    }
544}