Skip to main content

oci_api/services/keys/
client.rs

1use reqwest::Method;
2
3use crate::client::Oci;
4use crate::client::request_executor::{RequestPayload, RequestTarget};
5use crate::error::Result;
6use crate::services::keys::models::Key;
7
8#[derive(Clone)]
9pub struct KeysClient {
10    oci_client: Oci,
11    management_endpoint: String,
12}
13
14impl KeysClient {
15    pub fn new(oci_client: &Oci, management_endpoint: impl Into<String>) -> Self {
16        Self {
17            oci_client: oci_client.clone(),
18            management_endpoint: normalize_management_endpoint(&management_endpoint.into()),
19        }
20    }
21
22    pub async fn get_key(&self, key_id: &str) -> Result<Key> {
23        let path = format!("/20180608/keys/{key_id}");
24        let response = self
25            .oci_client
26            .executor()
27            .execute(
28                Method::GET,
29                RequestTarget {
30                    scheme: "https",
31                    host: &self.management_endpoint,
32                    path: &path,
33                },
34                RequestPayload {
35                    body: None,
36                    content_type: None,
37                    extra_headers: Vec::new(),
38                },
39            )
40            .await?;
41        response.json().await.map_err(Into::into)
42    }
43
44    pub async fn rotate_key(&self, key_id: &str) -> Result<Key> {
45        let path = format!("/20180608/keys/{key_id}/actions/rotate");
46        let response = self
47            .oci_client
48            .executor()
49            .execute(
50                Method::POST,
51                RequestTarget {
52                    scheme: "https",
53                    host: &self.management_endpoint,
54                    path: &path,
55                },
56                RequestPayload {
57                    body: Some("{}".to_owned()),
58                    content_type: Some("application/json"),
59                    extra_headers: Vec::new(),
60                },
61            )
62            .await?;
63        response.json().await.map_err(Into::into)
64    }
65}
66
67fn normalize_management_endpoint(management_endpoint: &str) -> String {
68    management_endpoint
69        .trim()
70        .trim_start_matches("https://")
71        .trim_start_matches("http://")
72        .trim_end_matches('/')
73        .to_owned()
74}
75
76#[cfg(test)]
77mod tests {
78    use super::normalize_management_endpoint;
79
80    #[test]
81    fn test_normalize_management_endpoint_strips_scheme_and_trailing_slash() {
82        assert_eq!(
83            normalize_management_endpoint(
84                "https://example-management.kms.ap-chuncheon-1.oci.oraclecloud.com/"
85            ),
86            "example-management.kms.ap-chuncheon-1.oci.oraclecloud.com"
87        );
88    }
89}