1#![doc = include_str!("../README.md")]
11#![deny(unsafe_code)]
12#![warn(missing_docs)]
13
14ai6::guatiao::providers!(SystemSecrets);
15
16#[cfg(target_os = "linux")]
17mod linux;
18#[cfg(target_os = "linux")]
19mod proc;
20#[cfg(windows)]
21mod windows;
22
23use std::fmt;
24use std::sync::Arc;
25
26use ai6::directorates::q::secret_kind::{
27 SecretAsk, SecretProvider, SecretRead, SecretStore, SecretStored,
28};
29use ai6::guatiao::library::ProviderError;
30use ai6::guatiao::{Alloc, FromValue, Schema, Secret, Status, ToValue, Value};
31use zeroize::Zeroizing;
32
33pub const PROVIDER_ID: &str = "system";
35
36#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq)]
38#[map(crate = ::ai6::guatiao, deny_unknown_fields)]
39pub struct SystemConfig {
40 #[schema(title = "Service")]
44 #[map(default = "ai6".to_owned())]
45 pub service: String,
46 #[schema(title = "Secret Service client")]
49 pub program: Option<String>,
50 #[schema(title = "A call may take", format = "seconds")]
52 #[map(default = 30)]
53 pub timeout_secs: u64,
54}
55
56impl Default for SystemConfig {
57 fn default() -> Self {
58 Self {
59 service: "ai6".to_owned(),
60 program: None,
61 timeout_secs: 30,
62 }
63 }
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct StoreError(pub String);
69
70impl fmt::Display for StoreError {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.write_str(&self.0)
73 }
74}
75
76impl std::error::Error for StoreError {}
77
78pub trait Store: Send + Sync {
80 fn get(&self, service: &str, key: &str) -> Result<Option<Zeroizing<String>>, StoreError>;
86
87 fn put(&self, service: &str, key: &str, value: &str) -> Result<(), StoreError>;
93}
94
95#[derive(ai6::guatiao::Provider)]
97#[provider(
98 SecretProvider,
99 id = "system",
100 name = "System secret store",
101 config = SystemConfig,
102 crate = ::ai6::guatiao
103)]
104pub struct SystemSecrets {
105 service: String,
106 store: Arc<dyn Store>,
107}
108
109impl fmt::Debug for SystemSecrets {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111 f.debug_struct("SystemSecrets")
112 .field("service", &self.service)
113 .finish_non_exhaustive()
114 }
115}
116
117impl SystemSecrets {
118 pub fn new(config: SystemConfig) -> Result<Self, String> {
125 check(&config)?;
126 let store = platform(&config)?;
127 Ok(Self {
128 service: config.service,
129 store,
130 })
131 }
132
133 pub fn with_store(service: &str, store: Arc<dyn Store>) -> Result<Self, String> {
139 if service.trim().is_empty() {
140 return Err("service must name a namespace".to_owned());
141 }
142 Ok(Self {
143 service: service.to_owned(),
144 store,
145 })
146 }
147}
148
149impl TryFrom<SystemConfig> for SystemSecrets {
150 type Error = ProviderError;
151
152 fn try_from(config: SystemConfig) -> Result<Self, Self::Error> {
153 Self::new(config).map_err(|why| ProviderError::new(Status::GUATIAO_ERR_BAD_VALUE, &why))
154 }
155}
156
157fn check(config: &SystemConfig) -> Result<(), String> {
158 if config.service.trim().is_empty() {
159 return Err("service must name a namespace".to_owned());
160 }
161 if config.timeout_secs == 0 {
162 return Err("timeout_secs must be at least 1".to_owned());
163 }
164 if config
165 .program
166 .as_deref()
167 .is_some_and(|p| p.trim().is_empty())
168 {
169 return Err("program must name the secret-tool program".to_owned());
170 }
171 Ok(())
172}
173
174#[cfg(target_os = "linux")]
175fn platform(config: &SystemConfig) -> Result<Arc<dyn Store>, String> {
176 Ok(Arc::new(linux::SecretTool::new(
177 config.program.as_deref().unwrap_or("secret-tool"),
178 std::time::Duration::from_secs(config.timeout_secs),
179 )))
180}
181
182#[cfg(windows)]
183fn platform(config: &SystemConfig) -> Result<Arc<dyn Store>, String> {
184 if config.program.is_some() {
185 return Err("program is a Linux setting: Windows has no client program".to_owned());
186 }
187 Ok(Arc::new(windows::CredentialManager))
188}
189
190#[cfg(not(any(target_os = "linux", windows)))]
191fn platform(config: &SystemConfig) -> Result<Arc<dyn Store>, String> {
192 let _ = config;
193 Err(
194 "the system store is implemented for Windows and Linux only; this platform has not \
195 been reproduced"
196 .to_owned(),
197 )
198}
199
200fn failure(status: Status, message: &str) -> ProviderError {
201 ProviderError::new(status, message)
202}
203
204fn ask_of(value: &Value) -> Result<SecretAsk, ProviderError> {
205 let ask = SecretAsk::from_value(value)
206 .map_err(|error| failure(Status::GUATIAO_ERR_BAD_VALUE, &error.to_string()))?;
207 if let Some(name) = ask.fields.keys().next() {
208 return Err(failure(
209 Status::GUATIAO_ERR_BAD_VALUE,
210 &format!("the system provider takes no field `{name}`"),
211 ));
212 }
213 check_key(&ask.key)?;
214 Ok(ask)
215}
216
217fn check_key(key: &str) -> Result<(), ProviderError> {
218 if key.trim().is_empty() || key.chars().any(char::is_control) {
219 return Err(failure(
220 Status::GUATIAO_ERR_BAD_VALUE,
221 "a secret of the system provider names its entry in `key`, as text with no control \
222 character",
223 ));
224 }
225 Ok(())
226}
227
228impl SecretProvider for SystemSecrets {
229 fn read(&self, ask: &Value) -> Result<Value, ProviderError> {
230 self.read_in(ask, Alloc::wiping())
231 }
232
233 fn read_in(&self, ask: &Value, alloc: Alloc) -> Result<Value, ProviderError> {
234 let ask = ask_of(ask)?;
235 let value = self
236 .store
237 .get(&self.service, &ask.key)
238 .map_err(|error| failure(Status::GUATIAO_ERR_INTERNAL, &error.0))?
239 .ok_or_else(|| {
240 failure(
241 Status::GUATIAO_ERR_NOT_FOUND,
242 &format!("the system store has no entry {:?}", ask.key),
243 )
244 })?;
245 if value.is_empty() {
246 return Err(failure(
247 Status::GUATIAO_ERR_BAD_VALUE,
248 &format!("the system store's entry {:?} is empty", ask.key),
249 ));
250 }
251 SecretRead {
252 value: Secret::new(value.as_str().to_owned()),
253 revision: None,
254 }
255 .to_value_in(alloc)
256 .map_err(|error| failure(Status::GUATIAO_ERR_ALLOC, &error.to_string()))
257 }
258
259 fn fields(&self) -> Result<Value, ProviderError> {
260 let mut schema = ai6::guatiao::Map::new();
261 schema.set("type", "object");
262 schema.set("properties", ai6::guatiao::Map::new());
263 schema.set("additionalProperties", false);
264 Ok(schema.into())
265 }
266
267 fn store(&self, request: &Value) -> Result<Value, ProviderError> {
268 let request = SecretStore::from_value(request)
269 .map_err(|error| failure(Status::GUATIAO_ERR_BAD_VALUE, &error.to_string()))?;
270 if let Some(name) = request.fields.keys().next() {
271 return Err(failure(
272 Status::GUATIAO_ERR_BAD_VALUE,
273 &format!("the system provider takes no field `{name}`"),
274 ));
275 }
276 check_key(&request.key)?;
277 if request.expect.is_some() {
278 return Err(failure(
279 Status::GUATIAO_ERR_BAD_VALUE,
280 "the system store keeps no revision, so it cannot check one",
281 ));
282 }
283 if request.value.expose().is_empty() {
284 return Err(failure(
285 Status::GUATIAO_ERR_BAD_VALUE,
286 "a secret to keep is not empty",
287 ));
288 }
289 self.store
290 .put(&self.service, &request.key, request.value.expose())
291 .map_err(|error| failure(Status::GUATIAO_ERR_INTERNAL, &error.0))?;
292 SecretStored::default()
293 .to_value_in(Alloc::wiping())
294 .map_err(|error| failure(Status::GUATIAO_ERR_ALLOC, &error.to_string()))
295 }
296}