cortexkit_claustrum_client/
module_secret.rs1use super::*;
4use serde::Deserialize;
5use zeroize::{Zeroize, Zeroizing};
6
7pub struct Secret<T: Zeroize>(Zeroizing<T>);
13
14impl<T: Zeroize> Secret<T> {
15 pub fn new(value: T) -> Self {
16 Self(Zeroizing::new(value))
17 }
18
19 pub fn expose(&self) -> &T {
20 &self.0
21 }
22
23 pub(super) fn expose_mut(&mut self) -> &mut T {
24 &mut self.0
25 }
26}
27
28impl<T: Zeroize> std::fmt::Debug for Secret<T> {
29 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 formatter.write_str("<redacted>")
31 }
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum ModuleSecretError {
36 VersionConflict,
37 Protected,
38 Limit,
39 Other(CredentialResolverError),
40}
41
42impl std::fmt::Display for ModuleSecretError {
43 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 match self {
45 Self::VersionConflict => formatter.write_str("module secret version conflict"),
46 Self::Protected => formatter.write_str("module secret is protected"),
47 Self::Limit => formatter.write_str("module secret item limit reached"),
48 Self::Other(error) => error.fmt(formatter),
49 }
50 }
51}
52
53impl std::error::Error for ModuleSecretError {
54 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
55 match self {
56 Self::Other(error) => Some(error),
57 _ => None,
58 }
59 }
60}
61
62impl From<CredentialResolverError> for ModuleSecretError {
63 fn from(error: CredentialResolverError) -> Self {
64 Self::Other(error)
65 }
66}
67
68#[derive(Debug, Deserialize, PartialEq, Eq)]
69pub struct ModuleSecretWritten {
70 pub name: String,
71 pub version: u64,
72 pub created: bool,
73}
74
75#[derive(Debug)]
76pub struct ModuleSecret {
77 pub name: String,
78 pub version: u64,
79 pub value: Secret<Vec<u8>>,
80 pub protected: bool,
81}
82
83#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
84#[serde(rename_all = "snake_case")]
85pub enum ModuleSecretState {
86 Active,
87 Corrupt,
88}
89
90#[derive(Debug, Deserialize, PartialEq, Eq)]
91pub struct ModuleSecretSummary {
92 pub name: String,
93 pub version: u64,
94 pub protected: bool,
95 pub state: ModuleSecretState,
96 pub updated_at_ms: i64,
97}
98
99#[cfg(any(feature = "transport", test))]
100pub(super) mod wire {
101 use super::*;
102 use serde::Serialize;
103
104 #[derive(Debug, Serialize)]
105 struct Put<'a> {
106 name: &'a str,
107 #[serde(serialize_with = "serialize_value")]
108 value: Secret<String>,
109 #[serde(skip_serializing_if = "Option::is_none")]
110 expected_version: Option<u64>,
111 #[serde(skip_serializing_if = "Option::is_none")]
112 protected: Option<bool>,
113 }
114
115 fn serialize_value<S: serde::Serializer>(
116 value: &Secret<String>,
117 serializer: S,
118 ) -> Result<S::Ok, S::Error> {
119 serializer.serialize_str(value.expose())
120 }
121
122 #[derive(Debug, Serialize)]
123 struct Named<'a> {
124 name: &'a str,
125 #[serde(skip_serializing_if = "Option::is_none")]
126 expected_version: Option<u64>,
127 }
128
129 #[derive(Debug, Serialize)]
130 struct Empty {}
131
132 #[derive(Debug, Deserialize)]
133 struct Reply<T> {
134 result: T,
135 }
136
137 #[derive(Deserialize)]
138 #[serde(transparent)]
139 struct BorrowedValue<'a>(#[serde(borrow)] &'a str);
140
141 impl std::fmt::Debug for BorrowedValue<'_> {
142 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143 formatter.write_str("<redacted>")
144 }
145 }
146
147 #[derive(Debug, Deserialize)]
148 struct Got<'a> {
149 name: String,
150 version: u64,
151 #[serde(borrow)]
152 value: BorrowedValue<'a>,
153 protected: bool,
154 }
155
156 #[derive(Debug, Deserialize)]
157 struct Deleted {
158 deleted: bool,
159 }
160
161 #[derive(Debug, Deserialize)]
162 struct Listed {
163 items: Vec<ModuleSecretSummary>,
164 }
165
166 #[derive(Debug, Deserialize)]
167 struct WireError<'a> {
168 code: &'a str,
169 class: Option<&'a str>,
170 }
171
172 #[derive(Debug, Deserialize)]
173 struct MaybeError<'a> {
174 #[serde(borrow)]
175 error: Option<WireError<'a>>,
176 }
177
178 fn invalid_response() -> ModuleSecretError {
179 CredentialResolverError::new(
180 CredentialErrorClass::InvalidResponse,
181 "invalid module-secret reply",
182 )
183 .into()
184 }
185
186 fn decode<'a, T: Deserialize<'a>>(bytes: &'a Secret<Vec<u8>>) -> Result<T, ModuleSecretError> {
187 let probe: Reply<MaybeError<'_>> =
188 serde_json::from_slice(bytes.expose()).map_err(|_| invalid_response())?;
189 if let Some(error) = probe.result.error {
190 return Err(match error.code {
191 "module_secret_version_conflict" => ModuleSecretError::VersionConflict,
192 "module_secret_protected" => ModuleSecretError::Protected,
193 "module_secret_limit" => ModuleSecretError::Limit,
194 _ => classify_error_value(
195 &serde_json::json!({"code": error.code, "class": error.class}),
196 )
197 .into(),
198 });
199 }
200 let reply: Reply<T> =
201 serde_json::from_slice(bytes.expose()).map_err(|_| invalid_response())?;
202 Ok(reply.result)
203 }
204
205 fn encode(
206 params: impl Serialize,
207 method: &'static str,
208 ) -> Result<Secret<Vec<u8>>, ModuleSecretError> {
209 sensitive_wire::encode_request(method, params).map_err(|_| {
210 ModuleSecretError::Other(CredentialResolverError::new(
211 CredentialErrorClass::Permanent,
212 "module-secret request encoding failed",
213 ))
214 })
215 }
216
217 #[cfg(feature = "transport")]
218 impl ClaustrumCredentialResolver {
219 pub async fn module_secret_put(
222 &self,
223 name: &str,
224 value: Secret<Vec<u8>>,
225 expected_version: Option<u64>,
226 protected: Option<bool>,
227 ) -> Result<ModuleSecretWritten, ModuleSecretError> {
228 let mut encoded = Secret::new(String::with_capacity(
229 base64::encoded_len(value.expose().len(), true).ok_or_else(invalid_response)?,
230 ));
231 base64::engine::general_purpose::STANDARD.encode_string(value.expose(), &mut encoded.0);
232 let reply = self
233 .module_secret_send(encode(
234 Put {
235 name,
236 value: encoded,
237 expected_version,
238 protected,
239 },
240 "module_secret.put",
241 )?)
242 .await?;
243 decode(&reply)
244 }
245
246 pub async fn module_secret_get(
248 &self,
249 name: &str,
250 ) -> Result<ModuleSecret, ModuleSecretError> {
251 let reply = self
252 .module_secret_send(encode(
253 Named {
254 name,
255 expected_version: None,
256 },
257 "module_secret.get",
258 )?)
259 .await?;
260 let got: Got<'_> = decode(&reply)?;
261 let mut value = Secret::new(vec![0; base64::decoded_len_estimate(got.value.0.len())]);
262 let len = base64::engine::general_purpose::STANDARD
263 .decode_slice(got.value.0, &mut value.0)
264 .map_err(|_| invalid_response())?;
265 value.0.truncate(len);
266 Ok(ModuleSecret {
267 name: got.name,
268 version: got.version,
269 value,
270 protected: got.protected,
271 })
272 }
273
274 pub async fn module_secret_delete(
276 &self,
277 name: &str,
278 expected_version: Option<u64>,
279 ) -> Result<(), ModuleSecretError> {
280 let reply = self
281 .module_secret_send(encode(
282 Named {
283 name,
284 expected_version,
285 },
286 "module_secret.delete",
287 )?)
288 .await?;
289 let deleted: Deleted = decode(&reply)?;
290 if !deleted.deleted {
291 return Err(invalid_response());
292 }
293 Ok(())
294 }
295
296 pub async fn module_secret_list(
298 &self,
299 ) -> Result<Vec<ModuleSecretSummary>, ModuleSecretError> {
300 let reply = self
301 .module_secret_send(encode(Empty {}, "module_secret.list")?)
302 .await?;
303 Ok(decode::<Listed>(&reply)?.items)
304 }
305
306 async fn module_secret_send(
307 &self,
308 request: Secret<Vec<u8>>,
309 ) -> Result<Secret<Vec<u8>>, ModuleSecretError> {
310 let target = self
311 .module_secret_target
312 .as_ref()
313 .ok_or_else(CredentialResolverError::unavailable)?;
314 target
315 .sensitive_request(request, "module_secret")
316 .await
317 .map_err(Into::into)
318 }
319 }
320
321 #[cfg(test)]
322 mod tests;
323}