Skip to main content

oci_api/services/keys/
client.rs

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