use std::fmt;
use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use subc_protocol::scope::ScopeStamp;
pub const COVERAGE_SCOPE: &str = "scope";
pub const COVERAGE_AGENT_AND_WORKERS: &str = "agent_and_workers";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Coverage {
Scope,
AgentAndWorkers,
}
impl Coverage {
pub fn as_str(&self) -> &'static str {
match self {
Coverage::Scope => COVERAGE_SCOPE,
Coverage::AgentAndWorkers => COVERAGE_AGENT_AND_WORKERS,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ApiKeyTarget {
pub scheme: String,
pub host: String,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "present_option"
)]
pub port: Option<u16>,
pub path: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LoginTarget {
pub origin: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(untagged)]
pub enum Target {
ApiKey(ApiKeyTarget),
Login(LoginTarget),
}
impl Serialize for Target {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Target::ApiKey(target) => target.serialize(serializer),
Target::Login(target) => target.serialize(serializer),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SecretUseRequest {
pub name: String,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "present_option"
)]
pub coverage: Option<Coverage>,
pub stamp: ScopeStamp,
pub target: Target,
}
fn present_option<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
deserializer: D,
) -> Result<Option<T>, D::Error> {
T::deserialize(deserializer).map(Some)
}
impl SecretUseRequest {
pub fn new(name: &str, stamp: &ScopeStamp, target: Target) -> Self {
Self {
name: name.to_string(),
coverage: None,
stamp: stamp.clone(),
target,
}
}
pub fn with_coverage(mut self, coverage: Coverage) -> Self {
self.coverage = Some(coverage);
self
}
pub fn to_params(&self) -> Value {
serde_json::to_value(self).expect("a secret.use request serializes")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReplyError {
Malformed {
detail: String,
},
BadKeyEncoding,
}
impl fmt::Display for ReplyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ReplyError::Malformed { detail } => write!(f, "malformed reply: {detail}"),
ReplyError::BadKeyEncoding => {
f.write_str("key_b64url is not strict unpadded base64url")
}
}
}
}
pub struct ReleasedApiKey {
pub location: String,
bytes: crate::secret::vault::Material,
}
impl ReleasedApiKey {
pub fn new(location: String, bytes: crate::secret::vault::Material) -> Self {
Self { location, bytes }
}
pub fn into_parts(self) -> (String, crate::secret::vault::Material) {
(self.location, self.bytes)
}
pub fn material(&self) -> &[u8] {
self.bytes.expose()
}
}
impl fmt::Debug for ReleasedApiKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ReleasedApiKey")
.field("location", &self.location)
.field("key_len", &self.bytes.len())
.finish()
}
}
pub struct ReleasedLogin {
pub username: String,
pub(super) password: crate::secret::vault::Material,
pub totp: Option<zeroize::Zeroizing<String>>,
}
impl ReleasedLogin {
pub fn password(&self) -> &[u8] {
self.password.expose()
}
}
impl fmt::Debug for ReleasedLogin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ReleasedLogin")
.field("username_len", &self.username.len())
.field("password_len", &self.password.len())
.field("totp", &self.totp.is_some())
.finish()
}
}
#[derive(Debug)]
pub enum SecretUseReply {
ReleasedApiKey(ReleasedApiKey),
ReleasedLogin(ReleasedLogin),
ApprovalRequired(ApprovalRequest),
}
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct ApprovalRequest {
pub request_id: String,
pub statement_b64url: String,
pub expires_at_ms: u64,
}
impl fmt::Debug for ApprovalRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ApprovalRequest")
.field("request_id", &self.request_id)
.field("statement_b64url_len", &self.statement_b64url.len())
.field("expires_at_ms", &self.expires_at_ms)
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VaultError {
pub code: String,
pub class: Option<String>,
}
impl VaultError {
pub fn is_transient(&self) -> bool {
matches!(self.class.as_deref(), Some("transient"))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VaultTransportError {
pub code: String,
pub message: String,
}
#[derive(Debug)]
pub enum SecretUseAnswer {
Reply(SecretUseReply),
Refused(VaultError),
Rejected(VaultTransportError),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SecretUseRefusal {
NotFound,
InvalidParams,
LimitExceeded,
SetupIncomplete,
PendingLimit,
StoreError,
}
impl SecretUseAnswer {
pub fn refusal(&self) -> Option<SecretUseRefusal> {
use SecretUseRefusal::*;
match self {
Self::Rejected(error) if error.code == "invalid_params" => Some(InvalidParams),
Self::Refused(error) => match error.code.as_str() {
"not_found" => Some(NotFound),
"limit_exceeded" => Some(LimitExceeded),
"secret_setup_incomplete" => Some(SetupIncomplete),
"pending_limit" => Some(PendingLimit),
"store_error" => Some(StoreError),
_ => None,
},
_ => None,
}
}
}
impl Serialize for SecretUseReply {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
let mut map = serializer.serialize_map(None)?;
match self {
Self::ReleasedApiKey(key) => {
let encoded = zeroize::Zeroizing::new(b64url().encode(key.material()));
map.serialize_entry("status", "released")?;
map.serialize_entry("kind", "agent_api_key")?;
map.serialize_entry("key_b64url", encoded.as_str())?;
map.serialize_entry("location", &key.location)?;
}
Self::ReleasedLogin(login) => {
let password = std::str::from_utf8(login.password())
.map_err(|_| serde::ser::Error::custom("login password is not UTF-8"))?;
map.serialize_entry("status", "released")?;
map.serialize_entry("kind", "site_login")?;
map.serialize_entry("username", &login.username)?;
map.serialize_entry("password", password)?;
if let Some(totp) = &login.totp {
map.serialize_entry("totp", totp.as_str())?;
}
}
Self::ApprovalRequired(request) => {
map.serialize_entry("status", "approval_required")?;
map.serialize_entry("request_id", &request.request_id)?;
map.serialize_entry("statement_b64url", &request.statement_b64url)?;
map.serialize_entry("expires_at_ms", &request.expires_at_ms)?;
}
}
map.end()
}
}
fn b64url() -> base64::engine::general_purpose::GeneralPurpose {
base64::engine::general_purpose::URL_SAFE_NO_PAD
}
pub(super) fn decode_key(text: &str) -> Result<Vec<u8>, ReplyError> {
let mut decoded = zeroize::Zeroizing::new(vec![0u8; base64::decoded_len_estimate(text.len())]);
let length = b64url()
.decode_slice(text, &mut decoded)
.map_err(|_| ReplyError::BadKeyEncoding)?;
crate::secret::vault::zeroize(&mut decoded[length..]);
decoded.truncate(length);
Ok(std::mem::take(&mut *decoded))
}
pub(super) fn is_ulid(text: &str) -> bool {
const CROCKFORD: &[u8] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
let bytes = text.as_bytes();
bytes.len() == 26
&& matches!(bytes[0], b'0'..=b'7')
&& bytes.iter().all(|byte| CROCKFORD.contains(byte))
}
pub fn parse_reply(value: &Value) -> Result<SecretUseReply, ReplyError> {
let object = value.as_object().ok_or_else(|| ReplyError::Malformed {
detail: "the reply is not an object".into(),
})?;
let status = object
.get("status")
.and_then(Value::as_str)
.ok_or_else(|| ReplyError::Malformed {
detail: "the reply has no status".into(),
})?;
match status {
"released" => parse_released(object),
"approval_required" => {
expect_keys(
object,
&["status", "request_id", "statement_b64url", "expires_at_ms"],
)?;
let request_id = object
.get("request_id")
.and_then(Value::as_str)
.filter(|id| is_ulid(id))
.ok_or_else(|| ReplyError::Malformed {
detail: "request_id is not a ULID".into(),
})?;
let statement_b64url = object
.get("statement_b64url")
.and_then(Value::as_str)
.ok_or_else(|| ReplyError::Malformed {
detail: "statement_b64url is missing".into(),
})?;
b64url()
.decode(statement_b64url)
.map_err(|_| ReplyError::Malformed {
detail: "statement_b64url is not strict unpadded base64url".into(),
})?;
let expires_at_ms = object
.get("expires_at_ms")
.and_then(Value::as_u64)
.ok_or_else(|| ReplyError::Malformed {
detail: "expires_at_ms is not an unsigned integer".into(),
})?;
Ok(SecretUseReply::ApprovalRequired(ApprovalRequest {
request_id: request_id.to_string(),
statement_b64url: statement_b64url.to_string(),
expires_at_ms,
}))
}
other => Err(ReplyError::Malformed {
detail: format!("unknown status {}", other.len()),
}),
}
}
fn expect_keys(object: &serde_json::Map<String, Value>, keys: &[&str]) -> Result<(), ReplyError> {
for key in keys {
if !object.contains_key(*key) {
return Err(ReplyError::Malformed {
detail: "a documented reply key is missing".into(),
});
}
}
if object.len() != keys.len() {
return Err(ReplyError::Malformed {
detail: "the reply carries a key the contract does not show".into(),
});
}
Ok(())
}
fn parse_released(object: &serde_json::Map<String, Value>) -> Result<SecretUseReply, ReplyError> {
match object.get("kind").and_then(Value::as_str) {
Some("agent_api_key") => {
expect_keys(object, &["status", "kind", "key_b64url", "location"])?;
let location = object
.get("location")
.and_then(Value::as_str)
.ok_or_else(|| ReplyError::Malformed {
detail: "location is missing".into(),
})?;
let key_b64url = object
.get("key_b64url")
.and_then(Value::as_str)
.ok_or_else(|| ReplyError::Malformed {
detail: "key_b64url is missing".into(),
})?;
Ok(SecretUseReply::ReleasedApiKey(ReleasedApiKey {
location: location.to_string(),
bytes: crate::secret::vault::Material::new(decode_key(key_b64url)?),
}))
}
Some("site_login") => {
let totp = object.get("totp").cloned();
let keys: Vec<&str> = match &totp {
Some(_) => vec!["status", "kind", "username", "password", "totp"],
None => vec!["status", "kind", "username", "password"],
};
expect_keys(object, &keys)?;
let username = object
.get("username")
.and_then(Value::as_str)
.ok_or_else(|| ReplyError::Malformed {
detail: "username is missing".into(),
})?;
let password = object
.get("password")
.and_then(Value::as_str)
.ok_or_else(|| ReplyError::Malformed {
detail: "password is missing".into(),
})?;
let totp = match totp {
None | Some(Value::Null) => None,
Some(Value::String(code)) => Some(zeroize::Zeroizing::new(code)),
Some(_) => {
return Err(ReplyError::Malformed {
detail: "totp is not a string".into(),
})
}
};
Ok(SecretUseReply::ReleasedLogin(ReleasedLogin {
username: username.to_string(),
password: crate::secret::vault::Material::new(password.as_bytes().to_vec()),
totp,
}))
}
Some(other) => Err(ReplyError::Malformed {
detail: format!("released reply kind {}", other.len()),
}),
None => Err(ReplyError::Malformed {
detail: "a released reply carries no kind".into(),
}),
}
}
#[derive(Debug, Deserialize)]
struct ResultError {
error: ResultErrorBody,
}
#[derive(Debug, Deserialize)]
struct ResultErrorBody {
code: String,
#[serde(default)]
class: Option<String>,
}
#[derive(Debug, Deserialize)]
struct TransportError {
code: String,
message: String,
}
pub fn parse_answer(body: &Value) -> Result<SecretUseAnswer, ReplyError> {
if let Some(result) = body.get("result") {
expect_keys(
body.as_object().ok_or_else(|| ReplyError::Malformed {
detail: "the reply is not an object".into(),
})?,
&["result"],
)?;
if result.get("error").is_some() {
let error: ResultError =
serde_json::from_value(result.clone()).map_err(|_| ReplyError::Malformed {
detail: "the result error does not match the contract".into(),
})?;
return Ok(SecretUseAnswer::Refused(VaultError {
code: error.error.code,
class: error.error.class,
}));
}
return parse_reply(result).map(SecretUseAnswer::Reply);
}
if let Ok(error) = serde_json::from_value::<TransportError>(body.clone()) {
return Ok(SecretUseAnswer::Rejected(VaultTransportError {
code: error.code,
message: error.message,
}));
}
Err(ReplyError::Malformed {
detail: "the body is neither a result nor a transport error".into(),
})
}