Skip to main content

gitfox_client/
spaces.rs

1//! Spaces, and the things that live in them: secrets. Also the caller's own
2//! account resources — SSH keys — and the instance's system configuration.
3//!
4//! Verified against the GitFox API v1.3.0 OpenAPI document:
5//!
6//! | Operation | Endpoint |
7//! |---|---|
8//! | memberships    | `GET /api/v1/user/memberships` |
9//! | root spaces    | `GET /api/v1/spaces` |
10//! | one space      | `GET /api/v1/spaces/{space_ref}` |
11//! | list secrets   | `GET /api/v1/spaces/{space_ref}/secrets` |
12//! | get secret     | `GET /api/v1/secrets/{secret_ref}` |
13//! | create secret  | `POST /api/v1/secrets` |
14//! | update secret  | `PATCH /api/v1/secrets/{secret_ref}` |
15//! | delete secret  | `DELETE /api/v1/secrets/{secret_ref}` |
16//! | SSH keys       | `GET` / `POST /api/v1/user/keys`, `DELETE …/keys/{identifier}` |
17//! | system config  | `GET /api/v1/system/config` |
18//!
19//! `{secret_ref}` is `space/identifier` with the slashes encoded, exactly like
20//! a repository reference — checked against a live instance, where the
21//! unencoded form answers 404.
22
23use serde_json::json;
24
25use crate::client::{GitFoxClient, Method, Query};
26use crate::error::Result;
27use crate::models::{Membership, PublicKey, Space, SpaceSecret, SystemConfig};
28use crate::pipeline::urlencode;
29
30pub struct SpacesApi<'a> {
31    client: &'a GitFoxClient,
32}
33
34impl<'a> SpacesApi<'a> {
35    pub(crate) fn new(client: &'a GitFoxClient) -> Self {
36        Self { client }
37    }
38
39    /// `GET /api/v1/user/memberships` — the spaces the caller belongs to.
40    pub async fn memberships(&self, page: u32, limit: u32) -> Result<Vec<Membership>> {
41        let mut q = Query::new();
42        q.push("sort", "identifier")
43            .push("order", "asc")
44            .push("page", page)
45            .push("limit", limit);
46        self.client
47            .get_json(&q.apply("/api/v1/user/memberships"))
48            .await
49    }
50
51    /// `GET /api/v1/spaces/{space_ref}`
52    pub async fn get(&self, space: &str) -> Result<Space> {
53        self.client
54            .get_json(&format!("/api/v1/spaces/{}", encode_ref(space)))
55            .await
56    }
57
58    /// `GET /api/v1/spaces/{space_ref}/secrets`
59    pub async fn secrets(
60        &self,
61        space: &str,
62        query: Option<&str>,
63        page: u32,
64        limit: u32,
65    ) -> Result<Vec<SpaceSecret>> {
66        let mut q = Query::new();
67        q.push_opt("query", query)
68            .push("page", page)
69            .push("limit", limit);
70        self.client
71            .get_json(&q.apply(&format!("/api/v1/spaces/{}/secrets", encode_ref(space))))
72            .await
73    }
74
75    /// `GET /api/v1/secrets/{secret_ref}`
76    pub async fn secret(&self, space: &str, identifier: &str) -> Result<SpaceSecret> {
77        self.client.get_json(&secret_path(space, identifier)).await
78    }
79
80    /// `POST /api/v1/secrets`
81    pub async fn create_secret(
82        &self,
83        space: &str,
84        identifier: &str,
85        data: &str,
86        description: Option<&str>,
87    ) -> Result<SpaceSecret> {
88        let mut body = json!({ "space_ref": space, "identifier": identifier, "data": data });
89        if let Some(description) = description {
90            body["description"] = json!(description);
91        }
92        self.client
93            .request(Method::POST, "/api/v1/secrets", Some(&body), &[])
94            .await?
95            .deserialize()
96    }
97
98    /// `PATCH /api/v1/secrets/{secret_ref}`
99    pub async fn update_secret(
100        &self,
101        space: &str,
102        identifier: &str,
103        data: &str,
104        description: Option<&str>,
105    ) -> Result<SpaceSecret> {
106        let mut body = json!({ "data": data });
107        if let Some(description) = description {
108            body["description"] = json!(description);
109        }
110        self.client
111            .request(
112                Method::PATCH,
113                &secret_path(space, identifier),
114                Some(&body),
115                &[],
116            )
117            .await?
118            .deserialize()
119    }
120
121    /// `DELETE /api/v1/secrets/{secret_ref}`
122    pub async fn delete_secret(&self, space: &str, identifier: &str) -> Result<()> {
123        self.client
124            .request(Method::DELETE, &secret_path(space, identifier), None, &[])
125            .await
126            .map(|_| ())
127    }
128
129    /// `GET /api/v1/user/keys`
130    pub async fn public_keys(&self, page: u32, limit: u32) -> Result<Vec<PublicKey>> {
131        let mut q = Query::new();
132        q.push("sort", "created")
133            .push("order", "asc")
134            .push("page", page)
135            .push("limit", limit);
136        self.client.get_json(&q.apply("/api/v1/user/keys")).await
137    }
138
139    /// `POST /api/v1/user/keys`
140    pub async fn add_public_key(&self, identifier: &str, content: &str) -> Result<PublicKey> {
141        self.client
142            .request(
143                Method::POST,
144                "/api/v1/user/keys",
145                Some(&json!({ "identifier": identifier, "content": content, "usage": "auth" })),
146                &[],
147            )
148            .await?
149            .deserialize()
150    }
151
152    /// `DELETE /api/v1/user/keys/{public_key_identifier}`
153    pub async fn delete_public_key(&self, identifier: &str) -> Result<()> {
154        self.client
155            .request(
156                Method::DELETE,
157                &format!("/api/v1/user/keys/{}", urlencode(identifier)),
158                None,
159                &[],
160            )
161            .await
162            .map(|_| ())
163    }
164
165    /// `GET /api/v1/system/config`
166    pub async fn system_config(&self) -> Result<SystemConfig> {
167        self.client.get_json("/api/v1/system/config").await
168    }
169}
170
171/// `org/team` → `org%2Fteam`, as a space or secret reference travels in a path.
172pub fn encode_ref(reference: &str) -> String {
173    reference
174        .trim_matches('/')
175        .split('/')
176        .map(urlencode)
177        .collect::<Vec<_>>()
178        .join("%2F")
179}
180
181fn secret_path(space: &str, identifier: &str) -> String {
182    format!(
183        "/api/v1/secrets/{}%2F{}",
184        encode_ref(space),
185        urlencode(identifier)
186    )
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    #[test]
194    fn a_secret_reference_encodes_the_space_and_the_name_as_one_segment() {
195        assert_eq!(
196            secret_path("ai-repos", "deploy-host"),
197            "/api/v1/secrets/ai-repos%2Fdeploy-host"
198        );
199        assert_eq!(
200            secret_path("org/team", "TOKEN"),
201            "/api/v1/secrets/org%2Fteam%2FTOKEN"
202        );
203    }
204}