1use std::fmt;
21
22use base64::Engine;
23use serde::{Deserialize, Serialize};
24use serde_json::Value;
25use subc_protocol::scope::ScopeStamp;
26
27pub const COVERAGE_SCOPE: &str = "scope";
29pub const COVERAGE_AGENT_AND_WORKERS: &str = "agent_and_workers";
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum Coverage {
36 Scope,
38 AgentAndWorkers,
40}
41
42impl Coverage {
43 pub fn as_str(&self) -> &'static str {
45 match self {
46 Coverage::Scope => COVERAGE_SCOPE,
47 Coverage::AgentAndWorkers => COVERAGE_AGENT_AND_WORKERS,
48 }
49 }
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct ApiKeyTarget {
59 pub scheme: String,
61 pub host: String,
63 #[serde(
65 default,
66 skip_serializing_if = "Option::is_none",
67 deserialize_with = "present_option"
68 )]
69 pub port: Option<u16>,
70 pub path: String,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(deny_unknown_fields)]
77pub struct LoginTarget {
78 pub origin: String,
80}
81
82#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
84#[serde(untagged)]
85pub enum Target {
86 ApiKey(ApiKeyTarget),
88 Login(LoginTarget),
90}
91
92impl Serialize for Target {
93 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
94 match self {
95 Target::ApiKey(target) => target.serialize(serializer),
96 Target::Login(target) => target.serialize(serializer),
97 }
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107#[serde(deny_unknown_fields)]
108pub struct SecretUseRequest {
109 pub name: String,
111 #[serde(
113 default,
114 skip_serializing_if = "Option::is_none",
115 deserialize_with = "present_option"
116 )]
117 pub coverage: Option<Coverage>,
118 pub stamp: ScopeStamp,
120 pub target: Target,
122}
123
124fn present_option<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
125 deserializer: D,
126) -> Result<Option<T>, D::Error> {
127 T::deserialize(deserializer).map(Some)
128}
129
130impl SecretUseRequest {
131 pub fn new(name: &str, stamp: &ScopeStamp, target: Target) -> Self {
136 Self {
137 name: name.to_string(),
138 coverage: None,
139 stamp: stamp.clone(),
140 target,
141 }
142 }
143
144 pub fn with_coverage(mut self, coverage: Coverage) -> Self {
146 self.coverage = Some(coverage);
147 self
148 }
149
150 pub fn to_params(&self) -> Value {
152 serde_json::to_value(self).expect("a secret.use request serializes")
153 }
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
158pub enum ReplyError {
159 Malformed {
162 detail: String,
164 },
165 BadKeyEncoding,
167}
168
169impl fmt::Display for ReplyError {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 match self {
172 ReplyError::Malformed { detail } => write!(f, "malformed reply: {detail}"),
173 ReplyError::BadKeyEncoding => {
174 f.write_str("key_b64url is not strict unpadded base64url")
175 }
176 }
177 }
178}
179
180pub struct ReleasedApiKey {
182 pub location: String,
185 bytes: crate::secret::vault::Material,
187}
188
189impl ReleasedApiKey {
190 pub fn new(location: String, bytes: crate::secret::vault::Material) -> Self {
191 Self { location, bytes }
192 }
193
194 pub fn into_parts(self) -> (String, crate::secret::vault::Material) {
195 (self.location, self.bytes)
196 }
197 pub fn material(&self) -> &[u8] {
199 self.bytes.expose()
200 }
201}
202
203impl fmt::Debug for ReleasedApiKey {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 f.debug_struct("ReleasedApiKey")
206 .field("location", &self.location)
207 .field("key_len", &self.bytes.len())
208 .finish()
209 }
210}
211
212pub struct ReleasedLogin {
214 pub username: String,
216 pub(super) password: crate::secret::vault::Material,
218 pub totp: Option<zeroize::Zeroizing<String>>,
221}
222
223impl ReleasedLogin {
224 pub fn password(&self) -> &[u8] {
226 self.password.expose()
227 }
228}
229
230impl fmt::Debug for ReleasedLogin {
231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232 f.debug_struct("ReleasedLogin")
233 .field("username_len", &self.username.len())
234 .field("password_len", &self.password.len())
235 .field("totp", &self.totp.is_some())
236 .finish()
237 }
238}
239
240#[derive(Debug)]
242pub enum SecretUseReply {
243 ReleasedApiKey(ReleasedApiKey),
245 ReleasedLogin(ReleasedLogin),
247 ApprovalRequired(ApprovalRequest),
252}
253
254#[derive(Clone, PartialEq, Eq, Serialize)]
256pub struct ApprovalRequest {
257 pub request_id: String,
259 pub statement_b64url: String,
261 pub expires_at_ms: u64,
263}
264
265impl fmt::Debug for ApprovalRequest {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 f.debug_struct("ApprovalRequest")
268 .field("request_id", &self.request_id)
269 .field("statement_b64url_len", &self.statement_b64url.len())
270 .field("expires_at_ms", &self.expires_at_ms)
271 .finish()
272 }
273}
274
275#[derive(Debug, Clone, PartialEq, Eq)]
277pub struct VaultError {
278 pub code: String,
281 pub class: Option<String>,
283}
284
285impl VaultError {
286 pub fn is_transient(&self) -> bool {
288 matches!(self.class.as_deref(), Some("transient"))
289 }
290}
291
292#[derive(Debug, Clone, PartialEq, Eq)]
294pub struct VaultTransportError {
295 pub code: String,
297 pub message: String,
299}
300
301#[derive(Debug)]
303pub enum SecretUseAnswer {
304 Reply(SecretUseReply),
306 Refused(VaultError),
308 Rejected(VaultTransportError),
310}
311
312#[derive(Debug, Clone, Copy, PartialEq, Eq)]
315pub enum SecretUseRefusal {
316 NotFound,
317 InvalidParams,
318 LimitExceeded,
319 SetupIncomplete,
320 PendingLimit,
321 StoreError,
322}
323
324impl SecretUseAnswer {
325 pub fn refusal(&self) -> Option<SecretUseRefusal> {
328 use SecretUseRefusal::*;
329 match self {
330 Self::Rejected(error) if error.code == "invalid_params" => Some(InvalidParams),
331 Self::Refused(error) => match error.code.as_str() {
332 "not_found" => Some(NotFound),
333 "limit_exceeded" => Some(LimitExceeded),
334 "secret_setup_incomplete" => Some(SetupIncomplete),
335 "pending_limit" => Some(PendingLimit),
336 "store_error" => Some(StoreError),
337 _ => None,
338 },
339 _ => None,
340 }
341 }
342}
343
344impl Serialize for SecretUseReply {
345 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
346 use serde::ser::SerializeMap;
347 let mut map = serializer.serialize_map(None)?;
348 match self {
349 Self::ReleasedApiKey(key) => {
350 let encoded = zeroize::Zeroizing::new(b64url().encode(key.material()));
351 map.serialize_entry("status", "released")?;
352 map.serialize_entry("kind", "agent_api_key")?;
353 map.serialize_entry("key_b64url", encoded.as_str())?;
354 map.serialize_entry("location", &key.location)?;
355 }
356 Self::ReleasedLogin(login) => {
357 let password = std::str::from_utf8(login.password())
358 .map_err(|_| serde::ser::Error::custom("login password is not UTF-8"))?;
359 map.serialize_entry("status", "released")?;
360 map.serialize_entry("kind", "site_login")?;
361 map.serialize_entry("username", &login.username)?;
362 map.serialize_entry("password", password)?;
363 if let Some(totp) = &login.totp {
364 map.serialize_entry("totp", totp.as_str())?;
365 }
366 }
367 Self::ApprovalRequired(request) => {
368 map.serialize_entry("status", "approval_required")?;
369 map.serialize_entry("request_id", &request.request_id)?;
370 map.serialize_entry("statement_b64url", &request.statement_b64url)?;
371 map.serialize_entry("expires_at_ms", &request.expires_at_ms)?;
372 }
373 }
374 map.end()
375 }
376}
377
378fn b64url() -> base64::engine::general_purpose::GeneralPurpose {
380 base64::engine::general_purpose::URL_SAFE_NO_PAD
381}
382
383pub(super) fn decode_key(text: &str) -> Result<Vec<u8>, ReplyError> {
386 let mut decoded = zeroize::Zeroizing::new(vec![0u8; base64::decoded_len_estimate(text.len())]);
387 let length = b64url()
388 .decode_slice(text, &mut decoded)
389 .map_err(|_| ReplyError::BadKeyEncoding)?;
390 crate::secret::vault::zeroize(&mut decoded[length..]);
391 decoded.truncate(length);
392 Ok(std::mem::take(&mut *decoded))
393}
394
395pub(super) fn is_ulid(text: &str) -> bool {
400 const CROCKFORD: &[u8] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
401 let bytes = text.as_bytes();
402 bytes.len() == 26
403 && matches!(bytes[0], b'0'..=b'7')
404 && bytes.iter().all(|byte| CROCKFORD.contains(byte))
405}
406
407pub fn parse_reply(value: &Value) -> Result<SecretUseReply, ReplyError> {
414 let object = value.as_object().ok_or_else(|| ReplyError::Malformed {
415 detail: "the reply is not an object".into(),
416 })?;
417 let status = object
418 .get("status")
419 .and_then(Value::as_str)
420 .ok_or_else(|| ReplyError::Malformed {
421 detail: "the reply has no status".into(),
422 })?;
423 match status {
424 "released" => parse_released(object),
425 "approval_required" => {
426 expect_keys(
427 object,
428 &["status", "request_id", "statement_b64url", "expires_at_ms"],
429 )?;
430 let request_id = object
431 .get("request_id")
432 .and_then(Value::as_str)
433 .filter(|id| is_ulid(id))
434 .ok_or_else(|| ReplyError::Malformed {
435 detail: "request_id is not a ULID".into(),
436 })?;
437 let statement_b64url = object
438 .get("statement_b64url")
439 .and_then(Value::as_str)
440 .ok_or_else(|| ReplyError::Malformed {
441 detail: "statement_b64url is missing".into(),
442 })?;
443 b64url()
446 .decode(statement_b64url)
447 .map_err(|_| ReplyError::Malformed {
448 detail: "statement_b64url is not strict unpadded base64url".into(),
449 })?;
450 let expires_at_ms = object
451 .get("expires_at_ms")
452 .and_then(Value::as_u64)
453 .ok_or_else(|| ReplyError::Malformed {
454 detail: "expires_at_ms is not an unsigned integer".into(),
455 })?;
456 Ok(SecretUseReply::ApprovalRequired(ApprovalRequest {
457 request_id: request_id.to_string(),
458 statement_b64url: statement_b64url.to_string(),
459 expires_at_ms,
460 }))
461 }
462 other => Err(ReplyError::Malformed {
463 detail: format!("unknown status {}", other.len()),
464 }),
465 }
466}
467
468fn expect_keys(object: &serde_json::Map<String, Value>, keys: &[&str]) -> Result<(), ReplyError> {
471 for key in keys {
472 if !object.contains_key(*key) {
473 return Err(ReplyError::Malformed {
474 detail: "a documented reply key is missing".into(),
475 });
476 }
477 }
478 if object.len() != keys.len() {
479 return Err(ReplyError::Malformed {
480 detail: "the reply carries a key the contract does not show".into(),
481 });
482 }
483 Ok(())
484}
485
486fn parse_released(object: &serde_json::Map<String, Value>) -> Result<SecretUseReply, ReplyError> {
488 match object.get("kind").and_then(Value::as_str) {
489 Some("agent_api_key") => {
490 expect_keys(object, &["status", "kind", "key_b64url", "location"])?;
491 let location = object
492 .get("location")
493 .and_then(Value::as_str)
494 .ok_or_else(|| ReplyError::Malformed {
495 detail: "location is missing".into(),
496 })?;
497 let key_b64url = object
498 .get("key_b64url")
499 .and_then(Value::as_str)
500 .ok_or_else(|| ReplyError::Malformed {
501 detail: "key_b64url is missing".into(),
502 })?;
503 Ok(SecretUseReply::ReleasedApiKey(ReleasedApiKey {
504 location: location.to_string(),
505 bytes: crate::secret::vault::Material::new(decode_key(key_b64url)?),
506 }))
507 }
508 Some("site_login") => {
509 let totp = object.get("totp").cloned();
510 let keys: Vec<&str> = match &totp {
511 Some(_) => vec!["status", "kind", "username", "password", "totp"],
512 None => vec!["status", "kind", "username", "password"],
513 };
514 expect_keys(object, &keys)?;
515 let username = object
516 .get("username")
517 .and_then(Value::as_str)
518 .ok_or_else(|| ReplyError::Malformed {
519 detail: "username is missing".into(),
520 })?;
521 let password = object
522 .get("password")
523 .and_then(Value::as_str)
524 .ok_or_else(|| ReplyError::Malformed {
525 detail: "password is missing".into(),
526 })?;
527 let totp = match totp {
528 None | Some(Value::Null) => None,
529 Some(Value::String(code)) => Some(zeroize::Zeroizing::new(code)),
530 Some(_) => {
531 return Err(ReplyError::Malformed {
532 detail: "totp is not a string".into(),
533 })
534 }
535 };
536 Ok(SecretUseReply::ReleasedLogin(ReleasedLogin {
537 username: username.to_string(),
538 password: crate::secret::vault::Material::new(password.as_bytes().to_vec()),
539 totp,
540 }))
541 }
542 Some(other) => Err(ReplyError::Malformed {
543 detail: format!("released reply kind {}", other.len()),
544 }),
545 None => Err(ReplyError::Malformed {
546 detail: "a released reply carries no kind".into(),
547 }),
548 }
549}
550
551#[derive(Debug, Deserialize)]
554struct ResultError {
555 error: ResultErrorBody,
556}
557
558#[derive(Debug, Deserialize)]
559struct ResultErrorBody {
560 code: String,
561 #[serde(default)]
562 class: Option<String>,
563}
564
565#[derive(Debug, Deserialize)]
567struct TransportError {
568 code: String,
569 message: String,
570}
571
572pub fn parse_answer(body: &Value) -> Result<SecretUseAnswer, ReplyError> {
577 if let Some(result) = body.get("result") {
578 expect_keys(
579 body.as_object().ok_or_else(|| ReplyError::Malformed {
580 detail: "the reply is not an object".into(),
581 })?,
582 &["result"],
583 )?;
584 if result.get("error").is_some() {
585 let error: ResultError =
586 serde_json::from_value(result.clone()).map_err(|_| ReplyError::Malformed {
587 detail: "the result error does not match the contract".into(),
588 })?;
589 return Ok(SecretUseAnswer::Refused(VaultError {
590 code: error.error.code,
591 class: error.error.class,
592 }));
593 }
594 return parse_reply(result).map(SecretUseAnswer::Reply);
595 }
596 if let Ok(error) = serde_json::from_value::<TransportError>(body.clone()) {
597 return Ok(SecretUseAnswer::Rejected(VaultTransportError {
598 code: error.code,
599 message: error.message,
600 }));
601 }
602 Err(ReplyError::Malformed {
603 detail: "the body is neither a result nor a transport error".into(),
604 })
605}