#![forbid(unsafe_code)]
use std::collections::BTreeMap;
#[cfg(all(test, feature = "transport"))]
use std::collections::VecDeque;
use std::future::Future;
#[cfg(any(feature = "transport", test))]
use std::path::Path;
#[cfg(feature = "transport")]
use std::path::PathBuf;
use std::pin::Pin;
#[cfg(feature = "transport")]
use std::sync::Arc;
#[cfg(all(test, feature = "transport"))]
use std::sync::Mutex;
#[cfg(feature = "transport")]
use std::time::Duration;
use base64::Engine;
#[cfg(any(feature = "transport", test))]
use serde_json::json;
use serde_json::Value;
use sha2::{Digest, Sha256};
#[cfg(feature = "transport")]
use subc_protocol::{Flags, Frame, FrameType, Priority};
#[cfg(feature = "transport")]
use subc_transport::{authenticate_client, connection_file, read_frame, write_frame};
#[cfg(feature = "transport")]
use tokio::net::TcpStream;
#[cfg(feature = "transport")]
use tokio::sync::Mutex as AsyncMutex;
#[cfg(feature = "transport")]
use tokio::time::Instant;
#[cfg(feature = "consumer")]
mod consumer;
mod fleet_epoch;
mod module_secret;
mod policy;
#[cfg(any(feature = "transport", test))]
mod sensitive_wire;
#[cfg(feature = "transport")]
mod transport;
mod watch;
pub use fleet_epoch::{
decode_fleet_epoch_open_batch_reply, decode_fleet_epoch_open_reply,
decode_fleet_epoch_seal_batch_reply, decode_fleet_epoch_seal_reply, FleetEpochOpenRequest,
FleetEpochOpenResult, FleetEpochSeal, FleetEpochSealRequest,
};
pub use module_secret::{
ModuleSecret, ModuleSecretError, ModuleSecretState, ModuleSecretSummary, ModuleSecretWritten,
Secret,
};
pub use policy::{
decode_policy_active_reply, decode_policy_token_reply, ActivePolicy, PolicyToken,
PolicyTokenRequest,
};
#[cfg(feature = "transport")]
pub use watch::{PolicyWatch, ScopedWatch};
pub use watch::{
PolicyWatchNotice, ScopedWatchKind, ScopedWatchNotice, ScopedWatchOutcome, WatchAction,
WatchNotice, WatchTracker,
};
#[cfg(feature = "transport")]
const CREDENTIAL_MODULE_ID: &str = "claustrum";
#[cfg(any(feature = "transport", test))]
const CREDENTIAL_GET_OP: &str = "credential.get";
#[cfg(any(feature = "transport", test))]
const CREDENTIAL_GET_SCOPED_OP: &str = "credential.get_scoped";
#[cfg(any(feature = "transport", test))]
const CREDENTIAL_REPORT_AUTH_FAILURE_OP: &str = "credential.report_auth_failure";
#[cfg(feature = "transport")]
const CREDENTIAL_REPORT_CONDITION_OP: &str = "credential.report_condition";
#[cfg(feature = "transport")]
const CREDENTIAL_CLEAR_CONDITION_OP: &str = "credential.clear_condition";
#[cfg(any(feature = "transport", test))]
const CREDENTIAL_STATUS_OP: &str = "credential.status";
#[cfg(any(feature = "transport", test))]
const CREDENTIAL_SIGN_OP: &str = "credential.sign";
#[cfg(any(feature = "transport", test))]
const CREDENTIAL_PUBLIC_KEY_OP: &str = "credential.public_key";
#[cfg(any(feature = "transport", test))]
const CREDENTIAL_SEAL_OP: &str = "credential.seal";
#[cfg(any(feature = "transport", test))]
const CREDENTIAL_LIST_SCOPED_OP: &str = "credential.list_scoped";
#[cfg(feature = "transport")]
const CREDENTIAL_READ_TIMEOUT: Duration = Duration::from_secs(3);
#[cfg(feature = "transport")]
const CREDENTIAL_CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
#[cfg(feature = "transport")]
const CREDENTIAL_CALL_DEADLINE: Duration = Duration::from_secs(10);
#[cfg(feature = "transport")]
const DEFAULT_TRANSIENT_RETRIES: usize = 2;
const MAX_SCOPED_CONDITION_SINCE_MS: u64 = (1 << 53) - 1;
pub type CredentialResolverFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CredentialErrorClass {
AuthRequired,
CredentialAbsent,
Unauthorized,
Permanent,
Transient,
ContextOverflow,
InvalidResponse,
Transport,
Unavailable,
Unclassified,
}
impl CredentialErrorClass {
pub fn classifier_code(self) -> &'static str {
match self {
Self::AuthRequired => "credential_auth_required",
Self::CredentialAbsent => "credential_absent",
Self::Unauthorized => "unauthorized",
Self::Permanent => "credential_permanent",
Self::Transient => "credential_transient",
Self::ContextOverflow => "credential_context_overflow",
Self::InvalidResponse => "credential_invalid_response",
Self::Transport => "credential_transport",
Self::Unavailable => "credential_resolver_unavailable",
Self::Unclassified => "credential_unclassified",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CredentialResolverError {
pub class: CredentialErrorClass,
code: String,
safe_message: String,
}
impl CredentialResolverError {
pub fn new(class: CredentialErrorClass, safe_message: impl Into<String>) -> Self {
let code = class.classifier_code();
Self {
class,
code: code.to_owned(),
safe_message: safe_message.into(),
}
}
pub fn unavailable() -> Self {
Self::new(
CredentialErrorClass::Unavailable,
"campaign credential resolver is unavailable",
)
}
pub fn transport(message: impl Into<String>) -> Self {
Self::new(CredentialErrorClass::Transport, message)
}
fn unclassified(code: impl Into<String>, message: impl Into<String>) -> Self {
Self {
class: CredentialErrorClass::Unclassified,
code: code.into(),
safe_message: message.into(),
}
}
pub fn code(&self) -> &str {
&self.code
}
pub fn retryable(&self) -> bool {
matches!(
self.class,
CredentialErrorClass::Transient | CredentialErrorClass::Transport
)
}
pub fn is_transport(&self) -> bool {
matches!(
self.class,
CredentialErrorClass::Transport | CredentialErrorClass::Unavailable
)
}
}
impl std::fmt::Display for CredentialResolverError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{}: {}", self.code(), self.safe_message)
}
}
impl std::error::Error for CredentialResolverError {}
pub struct ResolvedCredential {
payload: Vec<u8>,
pub record_version: String,
pub expires_at_ms: Option<i64>,
pub account_id: Option<String>,
pub email: Option<String>,
pub org_name: Option<String>,
pub auth: Option<AuthDescriptor>,
pub hosts: Option<Vec<String>>,
pub invalid_key: Option<InvalidKeyEvidence>,
pub base_url: Option<String>,
pub headers: Option<BTreeMap<String, String>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthDescriptor {
pub header: String,
pub scheme: AuthScheme,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthScheme {
Bearer,
Raw,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidKeyEvidence {
pub status: u16,
pub error_code: Option<String>,
pub error_code_field: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CredentialStatus {
pub ready: bool,
pub record_version: Option<String>,
pub stale_pending: bool,
pub last_error_code: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CredentialSignature {
pub signature_hex: String,
pub key_id: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PublicKeyAlgorithm {
Ed25519,
X25519,
}
impl PublicKeyAlgorithm {
pub fn as_str(self) -> &'static str {
match self {
Self::Ed25519 => "ed25519",
Self::X25519 => "x25519",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CredentialPublicKey {
pub public_key_hex: String,
pub key_id: String,
pub algorithm: PublicKeyAlgorithm,
}
#[derive(Clone, Copy)]
pub struct SealRequest<'a> {
pub credential_id: &'a str,
pub recipient_public_key: &'a [u8; 32],
pub info: &'a [u8],
pub aad: &'a [u8],
pub plaintext: &'a [u8],
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CredentialSeal {
pub enc: Vec<u8>,
pub ciphertext: Vec<u8>,
pub key_id: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScopedCredentialListing {
pub credentials: Vec<ListedCredential>,
pub undecodable_credentials: Vec<String>,
pub grant_tuples: Vec<ListedGrant>,
pub undecodable_grants: Vec<String>,
pub view: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ListedCredential {
pub provider: Option<String>,
pub fusiform_provider_id: Option<String>,
pub hosts: Option<Vec<String>>,
pub incarnation: Option<String>,
pub plan_tier_observed_at_ms: Option<i64>,
pub plan_tier_since_ms: Option<u64>,
pub id: String,
pub categories: Vec<String>,
pub credential_type: String,
pub serves: Vec<String>,
pub provider_ids: Vec<String>,
pub auth_method: Option<String>,
pub refresh_adapter: Option<String>,
pub state: String,
pub record_version: u64,
pub operations: Vec<String>,
pub account_id: Option<String>,
pub email: Option<String>,
pub org_name: Option<String>,
pub org_id: Option<String>,
pub plan_tier: Option<String>,
pub plan_tier_source: Option<String>,
pub condition: Option<ListedCredentialCondition>,
pub github_app: Option<ListedGitHubApp>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListedGitHubApp {
pub app_id: String,
pub slug: String,
pub created_by: Option<String>,
pub created_at_ms: Option<u64>,
pub agent: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListedCredentialCondition {
pub reason: String,
pub since_ms: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListedGrant {
pub selector_kind: String,
pub selector: String,
pub operation: String,
}
impl ResolvedCredential {
pub fn new(payload: Vec<u8>, record_version: String, expires_at_ms: Option<i64>) -> Self {
Self::new_with_identity(payload, record_version, expires_at_ms, None, None, None)
}
fn new_with_identity(
payload: Vec<u8>,
record_version: String,
expires_at_ms: Option<i64>,
account_id: Option<String>,
email: Option<String>,
org_name: Option<String>,
) -> Self {
Self {
payload,
record_version,
expires_at_ms,
account_id,
email,
org_name,
auth: None,
hosts: None,
invalid_key: None,
base_url: None,
headers: None,
}
}
pub fn expose(&self) -> &[u8] {
&self.payload
}
}
impl std::fmt::Debug for ResolvedCredential {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ResolvedCredential")
.field("payload", &"[REDACTED]")
.field("record_version", &self.record_version)
.field("expires_at_ms", &self.expires_at_ms)
.field("account_id", &self.account_id)
.field("email", &self.email)
.field("org_name", &self.org_name)
.field("auth", &self.auth)
.field("hosts", &self.hosts)
.field("invalid_key", &self.invalid_key)
.field("base_url", &self.base_url)
.field(
"headers",
&self
.headers
.as_ref()
.map(|headers| headers.keys().collect::<Vec<_>>()),
)
.finish()
}
}
impl Drop for ResolvedCredential {
fn drop(&mut self) {
self.payload.fill(0);
}
}
pub trait CredentialResolver: Send + Sync {
fn resolve<'a>(
&'a self,
raw_handle: &'a str,
min_ttl_ms: Option<u64>,
force_refresh: bool,
) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>>;
fn get_scoped<'a>(
&'a self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>>;
fn get_scoped_with_min_ttl<'a>(
&'a self,
_credential_id: &'a str,
_min_ttl_ms: u64,
) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn report_auth_failure<'a>(
&'a self,
_credential_id: &'a str,
_record_version: u64,
_provider_status: u16,
) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn report_condition<'a>(
&'a self,
_credential_id: &'a str,
_record_version: u64,
_reason: &'a str,
_provider_status: u16,
_action_url: Option<&'a str>,
_enrollment_token: Option<&'a str>,
) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn clear_condition<'a>(
&'a self,
_credential_id: &'a str,
_record_version: u64,
_enrollment_token: Option<&'a str>,
) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn status_scoped<'a>(
&'a self,
_credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<CredentialStatus, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn sign<'a>(
&'a self,
_credential_id: &'a str,
_payload: &'a [u8],
) -> CredentialResolverFuture<'a, Result<CredentialSignature, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn public_key<'a>(
&'a self,
_credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<CredentialPublicKey, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn seal<'a>(
&'a self,
_request: SealRequest<'a>,
) -> CredentialResolverFuture<'a, Result<CredentialSeal, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
#[cfg(feature = "transport")]
fn watch_scoped<'a>(
&'a self,
_enrollment_token: Option<&'a str>,
) -> CredentialResolverFuture<'a, Result<ScopedWatch, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn list_scoped(
&self,
) -> CredentialResolverFuture<'_, Result<ScopedCredentialListing, CredentialResolverError>>
{
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
}
#[derive(Debug, Default)]
pub struct UnavailableCredentialResolver;
impl CredentialResolver for UnavailableCredentialResolver {
fn resolve<'a>(
&'a self,
_raw_handle: &'a str,
_min_ttl_ms: Option<u64>,
_force_refresh: bool,
) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn get_scoped<'a>(
&'a self,
_credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
}
#[doc(hidden)]
pub trait CredentialGetTarget: Send + Sync {
fn credential_get<'a>(
&'a self,
raw_handle: &'a str,
min_ttl_ms: Option<u64>,
force_refresh: bool,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>>;
fn credential_get_scoped<'a>(
&'a self,
_credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async {
Err(CredentialResolverError::new(
CredentialErrorClass::Permanent,
"credential scoped reads are unavailable",
))
})
}
fn credential_get_scoped_with_min_ttl<'a>(
&'a self,
_credential_id: &'a str,
_min_ttl_ms: u64,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async {
Err(CredentialResolverError::new(
CredentialErrorClass::Unavailable,
"credential scoped reads with a minimum TTL are unavailable",
))
})
}
fn credential_report_auth_failure<'a>(
&'a self,
_credential_id: &'a str,
_record_version: u64,
_provider_status: u16,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async {
Err(CredentialResolverError::new(
CredentialErrorClass::Unavailable,
"credential auth-failure reports are unavailable",
))
})
}
fn credential_report_condition<'a>(
&'a self,
_credential_id: &'a str,
_record_version: u64,
_reason: &'a str,
_provider_status: u16,
_action_url: Option<&'a str>,
_enrollment_token: Option<&'a str>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn credential_clear_condition<'a>(
&'a self,
_credential_id: &'a str,
_record_version: u64,
_enrollment_token: Option<&'a str>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn credential_status<'a>(
&'a self,
_credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async {
Err(CredentialResolverError::new(
CredentialErrorClass::Permanent,
"credential status reads are unavailable",
))
})
}
fn credential_sign<'a>(
&'a self,
_credential_id: &'a str,
_payload: &'a [u8],
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async {
Err(CredentialResolverError::new(
CredentialErrorClass::Permanent,
"credential signing is unavailable",
))
})
}
fn credential_public_key<'a>(
&'a self,
_credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async {
Err(CredentialResolverError::new(
CredentialErrorClass::Permanent,
"credential public-key reads are unavailable",
))
})
}
fn credential_seal<'a>(
&'a self,
_request: SealRequest<'a>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async {
Err(CredentialResolverError::new(
CredentialErrorClass::Permanent,
"credential sealing is unavailable",
))
})
}
#[cfg(feature = "transport")]
fn credential_watch_scoped<'a>(
&'a self,
_enrollment_token: Option<&'a str>,
) -> CredentialResolverFuture<'a, Result<ScopedWatch, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn credential_list_scoped(
&self,
) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
Box::pin(async {
Err(CredentialResolverError::new(
CredentialErrorClass::Permanent,
"credential listing is unavailable",
))
})
}
}
#[cfg(feature = "transport")]
pub struct ClaustrumCredentialResolver {
target: Arc<dyn CredentialGetTarget>,
live_target: Option<Arc<LiveCredentialGetTarget>>,
module_secret_target: Option<Arc<LiveCredentialGetTarget>>,
transient_retries: usize,
}
#[cfg(feature = "transport")]
impl std::fmt::Debug for ClaustrumCredentialResolver {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ClaustrumCredentialResolver")
.field("target", &CREDENTIAL_MODULE_ID)
.field("transient_retries", &self.transient_retries)
.finish()
}
}
#[cfg(feature = "transport")]
impl ClaustrumCredentialResolver {
pub fn new(connection_file_path: PathBuf, consumer_module_id: impl Into<String>) -> Self {
let target = Arc::new(LiveCredentialGetTarget::new(
Arc::new(LiveCredentialConnector {
connection_file_path,
consumer_module_id: consumer_module_id.into(),
}),
CREDENTIAL_CALL_DEADLINE,
));
Self {
target: target.clone(),
live_target: Some(target.clone()),
module_secret_target: Some(target),
transient_retries: DEFAULT_TRANSIENT_RETRIES,
}
}
#[doc(hidden)]
pub fn with_live_consumer_identity(
connection_file_path: PathBuf,
consumer_module_id: String,
) -> Self {
Self::new(connection_file_path, consumer_module_id)
}
#[cfg(feature = "consumer")]
pub fn with_consumer(consumer: Arc<subc_client_rs::SubcConsumer>) -> Self {
let target = Arc::new(LiveCredentialGetTarget::new(
Arc::new(consumer::ConsumerConnector(consumer.clone())),
CREDENTIAL_CALL_DEADLINE,
));
Self {
module_secret_target: Some(Arc::new(LiveCredentialGetTarget::new(
Arc::new(consumer::ModuleSecretConnector(consumer)),
CREDENTIAL_CALL_DEADLINE,
))),
target: target.clone(),
live_target: Some(target),
transient_retries: DEFAULT_TRANSIENT_RETRIES,
}
}
#[doc(hidden)]
async fn retry_call<T, F: Future<Output = Result<T, CredentialResolverError>>>(
&self,
should_retry: impl Fn(&CredentialResolverError) -> bool,
mut attempt: impl FnMut() -> F,
) -> Result<T, CredentialResolverError> {
for _ in 0..self.transient_retries {
match attempt().await {
Err(error) if should_retry(&error) => {
tokio::time::sleep(Duration::from_millis(100)).await;
}
result => return result,
}
}
attempt().await
}
pub fn with_target(target: Arc<dyn CredentialGetTarget>, transient_retries: usize) -> Self {
Self {
target,
live_target: None,
module_secret_target: None,
transient_retries,
}
}
}
#[cfg(feature = "transport")]
impl CredentialResolver for ClaustrumCredentialResolver {
fn watch_scoped<'a>(
&'a self,
enrollment_token: Option<&'a str>,
) -> CredentialResolverFuture<'a, Result<ScopedWatch, CredentialResolverError>> {
self.target.credential_watch_scoped(enrollment_token)
}
fn resolve<'a>(
&'a self,
raw_handle: &'a str,
min_ttl_ms: Option<u64>,
force_refresh: bool,
) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
Box::pin(self.retry_call(
|error| error.class == CredentialErrorClass::Transport,
move || async move {
self.target
.credential_get(raw_handle, min_ttl_ms, force_refresh)
.await
.and_then(decode_credential_reply)
},
))
}
fn get_scoped<'a>(
&'a self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
Box::pin(async move {
self.target
.credential_get_scoped(credential_id)
.await
.and_then(decode_credential_reply)
})
}
fn get_scoped_with_min_ttl<'a>(
&'a self,
credential_id: &'a str,
min_ttl_ms: u64,
) -> CredentialResolverFuture<'a, Result<ResolvedCredential, CredentialResolverError>> {
Box::pin(async move {
self.target
.credential_get_scoped_with_min_ttl(credential_id, min_ttl_ms)
.await
.and_then(decode_credential_reply)
})
}
fn report_auth_failure<'a>(
&'a self,
credential_id: &'a str,
record_version: u64,
provider_status: u16,
) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
Box::pin(async move {
if !matches!(provider_status, 401 | 403) {
return Err(CredentialResolverError::new(
CredentialErrorClass::Permanent,
"provider status must be 401 or 403",
));
}
self.target
.credential_report_auth_failure(credential_id, record_version, provider_status)
.await
.and_then(decode_report_auth_failure_reply)
})
}
fn report_condition<'a>(
&'a self,
credential_id: &'a str,
record_version: u64,
reason: &'a str,
provider_status: u16,
action_url: Option<&'a str>,
enrollment_token: Option<&'a str>,
) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
Box::pin(async move {
self.target
.credential_report_condition(
credential_id,
record_version,
reason,
provider_status,
action_url,
enrollment_token,
)
.await
.and_then(decode_report_condition_reply)
})
}
fn clear_condition<'a>(
&'a self,
credential_id: &'a str,
record_version: u64,
enrollment_token: Option<&'a str>,
) -> CredentialResolverFuture<'a, Result<bool, CredentialResolverError>> {
Box::pin(async move {
self.target
.credential_clear_condition(credential_id, record_version, enrollment_token)
.await
.and_then(decode_clear_condition_reply)
})
}
fn status_scoped<'a>(
&'a self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<CredentialStatus, CredentialResolverError>> {
Box::pin(async move {
self.target
.credential_status(credential_id)
.await
.and_then(decode_credential_status_reply)
})
}
fn sign<'a>(
&'a self,
credential_id: &'a str,
payload: &'a [u8],
) -> CredentialResolverFuture<'a, Result<CredentialSignature, CredentialResolverError>> {
Box::pin(
self.retry_call(CredentialResolverError::retryable, || async {
self.target
.credential_sign(credential_id, payload)
.await
.and_then(decode_signature_reply)
}),
)
}
fn public_key<'a>(
&'a self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<CredentialPublicKey, CredentialResolverError>> {
Box::pin(
self.retry_call(CredentialResolverError::retryable, || async {
self.target
.credential_public_key(credential_id)
.await
.and_then(decode_public_key_reply)
}),
)
}
fn seal<'a>(
&'a self,
request: SealRequest<'a>,
) -> CredentialResolverFuture<'a, Result<CredentialSeal, CredentialResolverError>> {
Box::pin(async move {
self.target
.credential_seal(request)
.await
.and_then(decode_seal_reply)
})
}
fn list_scoped(
&self,
) -> CredentialResolverFuture<'_, Result<ScopedCredentialListing, CredentialResolverError>>
{
Box::pin(async move {
self.target
.credential_list_scoped()
.await
.and_then(decode_list_scoped_reply)
})
}
}
#[cfg(feature = "transport")]
trait CredentialConsumerConnection: Send {
fn sensitive_request(
&mut self,
_request: Secret<Vec<u8>>,
) -> CredentialResolverFuture<'_, Result<Secret<Vec<u8>>, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn into_scoped_watch(
self: Box<Self>,
_enrollment_token: Option<String>,
) -> CredentialResolverFuture<'static, Result<ScopedWatch, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn into_policy_watch(
self: Box<Self>,
) -> CredentialResolverFuture<'static, Result<PolicyWatch, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn credential_get<'a>(
&'a mut self,
raw_handle: &'a str,
min_ttl_ms: Option<u64>,
force_refresh: bool,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.credential_request(
credential_get_request(raw_handle, min_ttl_ms, force_refresh),
"credential.get",
)
.await
})
}
fn credential_get_scoped<'a>(
&'a mut self,
credential_id: &'a str,
min_ttl_ms: Option<u64>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.credential_request(
credential_get_scoped_request(credential_id, min_ttl_ms),
CREDENTIAL_GET_SCOPED_OP,
)
.await
})
}
fn credential_report_auth_failure<'a>(
&'a mut self,
credential_id: &'a str,
record_version: u64,
provider_status: u16,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.credential_request(
credential_report_auth_failure_request(
credential_id,
record_version,
provider_status,
),
CREDENTIAL_REPORT_AUTH_FAILURE_OP,
)
.await
})
}
fn credential_status<'a>(
&'a mut self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.credential_request(
credential_status_request(credential_id),
CREDENTIAL_STATUS_OP,
)
.await
})
}
fn credential_sign<'a>(
&'a mut self,
credential_id: &'a str,
payload: &'a [u8],
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.credential_request(
credential_sign_request(credential_id, payload),
CREDENTIAL_SIGN_OP,
)
.await
})
}
fn credential_public_key<'a>(
&'a mut self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.credential_request(
credential_public_key_request(credential_id),
CREDENTIAL_PUBLIC_KEY_OP,
)
.await
})
}
fn credential_seal<'a>(
&'a mut self,
request: SealRequest<'a>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.credential_request(credential_seal_request(request), CREDENTIAL_SEAL_OP)
.await
})
}
fn credential_list_scoped(
&mut self,
) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
self.credential_request(credential_list_scoped_request(), CREDENTIAL_LIST_SCOPED_OP)
}
fn credential_request<'a>(
&'a mut self,
_request: Value,
_operation: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
}
#[cfg(feature = "transport")]
trait CredentialConsumerConnector: Send + Sync {
fn connect<'a>(
&'a self,
) -> CredentialResolverFuture<
'a,
Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
>;
fn connect_policy_watch(
&self,
) -> CredentialResolverFuture<
'_,
Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
> {
self.connect()
}
}
#[cfg(feature = "transport")]
struct LiveCredentialConnector {
connection_file_path: PathBuf,
consumer_module_id: String,
}
#[cfg(feature = "transport")]
impl CredentialConsumerConnector for LiveCredentialConnector {
fn connect<'a>(
&'a self,
) -> CredentialResolverFuture<
'a,
Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
> {
Box::pin(async move {
ClaustrumConsumer::connect(&self.connection_file_path, &self.consumer_module_id)
.await
.map(|consumer| Box::new(consumer) as Box<dyn CredentialConsumerConnection>)
})
}
}
#[cfg(feature = "transport")]
struct LiveCredentialGetTarget {
connector: Arc<dyn CredentialConsumerConnector>,
call_deadline: Duration,
consumer: AsyncMutex<Option<Box<dyn CredentialConsumerConnection>>>,
}
#[cfg(feature = "transport")]
impl LiveCredentialGetTarget {
fn new(connector: Arc<dyn CredentialConsumerConnector>, call_deadline: Duration) -> Self {
Self {
connector,
call_deadline,
consumer: AsyncMutex::new(None),
}
}
async fn connect_if_needed(
&self,
consumer: &mut Option<Box<dyn CredentialConsumerConnection>>,
) -> Result<(), CredentialResolverError> {
if consumer.is_none() {
*consumer = Some(self.connector.connect().await?);
}
Ok(())
}
async fn unary_call<P, T>(
&self,
operation: &str,
params: P,
send: impl for<'a> FnOnce(
&'a mut dyn CredentialConsumerConnection,
&'a P,
)
-> CredentialResolverFuture<'a, Result<T, CredentialResolverError>>,
) -> Result<T, CredentialResolverError> {
let deadline = Instant::now() + self.call_deadline;
let mut consumer = tokio::time::timeout_at(deadline, self.consumer.lock())
.await
.map_err(|_| Self::deadline_error(operation))?;
if Instant::now() >= deadline {
return Err(Self::deadline_error(operation));
}
let result = tokio::time::timeout_at(deadline, async {
self.connect_if_needed(&mut consumer).await?;
if Instant::now() >= deadline {
return Err(Self::deadline_error(operation));
}
let result = send(
consumer
.as_deref_mut()
.expect("credential consumer initialized"),
¶ms,
)
.await;
if Instant::now() >= deadline {
Err(Self::deadline_error(operation))
} else {
result
}
})
.await
.unwrap_or_else(|_| Err(Self::deadline_error(operation)));
Self::clear_failed_transport(&mut consumer, &result);
result
}
async fn get_scoped(
&self,
credential_id: &str,
min_ttl_ms: Option<u64>,
) -> Result<Value, CredentialResolverError> {
self.unary_call(
CREDENTIAL_GET_SCOPED_OP,
(credential_id, min_ttl_ms),
|consumer, &(id, ttl)| consumer.credential_get_scoped(id, ttl),
)
.await
}
async fn sensitive_request(
&self,
request: Secret<Vec<u8>>,
operation: &str,
) -> Result<Secret<Vec<u8>>, CredentialResolverError> {
self.unary_call(operation, (), move |consumer, &()| {
consumer.sensitive_request(request)
})
.await
}
async fn condition_request(
&self,
operation: &str,
params: Value,
) -> Result<Value, CredentialResolverError> {
self.unary_call(operation, operation, move |consumer, &op| {
consumer.credential_request(json!({ "method": op, "params": params }), op)
})
.await
}
fn deadline_error(operation: &str) -> CredentialResolverError {
CredentialResolverError::transport(format!(
"{operation} timed out waiting for the credential route"
))
}
fn clear_failed_transport<T>(
consumer: &mut Option<Box<dyn CredentialConsumerConnection>>,
result: &Result<T, CredentialResolverError>,
) {
if result
.as_ref()
.is_err_and(CredentialResolverError::is_transport)
{
*consumer = None;
}
}
}
#[cfg(feature = "transport")]
impl CredentialGetTarget for LiveCredentialGetTarget {
fn credential_watch_scoped<'a>(
&'a self,
enrollment_token: Option<&'a str>,
) -> CredentialResolverFuture<'a, Result<ScopedWatch, CredentialResolverError>> {
Box::pin(async move {
tokio::time::timeout(self.call_deadline, async {
self.connector
.connect()
.await?
.into_scoped_watch(enrollment_token.map(str::to_owned))
.await
})
.await
.unwrap_or_else(|_| Err(Self::deadline_error("auth.watch_scoped")))
})
}
fn credential_get<'a>(
&'a self,
raw_handle: &'a str,
min_ttl_ms: Option<u64>,
force_refresh: bool,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(self.unary_call(
CREDENTIAL_GET_OP,
(raw_handle, min_ttl_ms, force_refresh),
|consumer, &(handle, ttl, force)| consumer.credential_get(handle, ttl, force),
))
}
fn credential_get_scoped<'a>(
&'a self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(self.get_scoped(credential_id, None))
}
fn credential_get_scoped_with_min_ttl<'a>(
&'a self,
credential_id: &'a str,
min_ttl_ms: u64,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(self.get_scoped(credential_id, Some(min_ttl_ms)))
}
fn credential_report_auth_failure<'a>(
&'a self,
credential_id: &'a str,
record_version: u64,
provider_status: u16,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(self.unary_call(
CREDENTIAL_REPORT_AUTH_FAILURE_OP,
(credential_id, record_version, provider_status),
|consumer, &(id, version, status)| {
consumer.credential_report_auth_failure(id, version, status)
},
))
}
fn credential_report_condition<'a>(
&'a self,
credential_id: &'a str,
record_version: u64,
reason: &'a str,
provider_status: u16,
action_url: Option<&'a str>,
enrollment_token: Option<&'a str>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
let mut params = condition_params(credential_id, record_version, enrollment_token);
params["reason"] = json!(reason);
params["provider_status"] = json!(provider_status);
if let Some(action_url) = action_url {
params["action_url"] = json!(action_url);
}
self.condition_request(CREDENTIAL_REPORT_CONDITION_OP, params)
.await
})
}
fn credential_clear_condition<'a>(
&'a self,
credential_id: &'a str,
record_version: u64,
enrollment_token: Option<&'a str>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.condition_request(
CREDENTIAL_CLEAR_CONDITION_OP,
condition_params(credential_id, record_version, enrollment_token),
)
.await
})
}
fn credential_status<'a>(
&'a self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(
self.unary_call(CREDENTIAL_STATUS_OP, credential_id, |consumer, &id| {
consumer.credential_status(id)
}),
)
}
fn credential_sign<'a>(
&'a self,
credential_id: &'a str,
payload: &'a [u8],
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(self.unary_call(
CREDENTIAL_SIGN_OP,
(credential_id, payload),
|consumer, &(id, payload)| consumer.credential_sign(id, payload),
))
}
fn credential_public_key<'a>(
&'a self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(
self.unary_call(CREDENTIAL_PUBLIC_KEY_OP, credential_id, |consumer, &id| {
consumer.credential_public_key(id)
}),
)
}
fn credential_seal<'a>(
&'a self,
request: SealRequest<'a>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(
self.unary_call(CREDENTIAL_SEAL_OP, request, |consumer, &request| {
consumer.credential_seal(request)
}),
)
}
fn credential_list_scoped(
&self,
) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
Box::pin(
self.unary_call(CREDENTIAL_LIST_SCOPED_OP, (), |consumer, &()| {
consumer.credential_list_scoped()
}),
)
}
}
#[cfg(feature = "transport")]
struct ClaustrumConsumer {
stream: TcpStream,
route_channel: u16,
route_epoch: u32,
next_corr: u64,
}
#[cfg(feature = "transport")]
impl ClaustrumConsumer {
async fn connect(
connection_file_path: &Path,
consumer_module_id: &str,
) -> Result<Self, CredentialResolverError> {
let connection = connection_file::read(connection_file_path).map_err(|error| {
CredentialResolverError::transport(format!(
"credential route connection metadata is unavailable: {error}"
))
})?;
let endpoint = connection.endpoints.first().ok_or_else(|| {
CredentialResolverError::transport("credential route has no daemon endpoint")
})?;
let address = format!("{}:{}", endpoint.host, endpoint.port);
let mut stream =
tokio::time::timeout(CREDENTIAL_CONNECT_TIMEOUT, TcpStream::connect(address))
.await
.map_err(|error| {
CredentialResolverError::transport(format!(
"credential route connection timed out: {error}"
))
})?
.map_err(|error| {
CredentialResolverError::transport(format!(
"credential route connection failed: {error}"
))
})?;
authenticate_client(&mut stream, &connection, CREDENTIAL_READ_TIMEOUT)
.await
.map_err(|_| {
CredentialResolverError::new(
CredentialErrorClass::AuthRequired,
"credential route authentication failed",
)
})?;
let mut consumer = Self {
stream,
route_channel: 0,
route_epoch: 0,
next_corr: 1,
};
(consumer.route_channel, consumer.route_epoch) =
consumer.route_open(consumer_module_id).await?;
Ok(consumer)
}
fn next_correlation(&mut self) -> u64 {
let correlation = self.next_corr;
self.next_corr += 1;
correlation
}
async fn route_open(
&mut self,
consumer_module_id: &str,
) -> Result<(u16, u32), CredentialResolverError> {
let correlation = self.next_correlation();
let body = route_open_body(consumer_module_id)?;
let reply = tokio::time::timeout(CREDENTIAL_READ_TIMEOUT, async {
self.write_request(0, 0, correlation, Priority::Passive, body)
.await?;
self.read_reply(0, 0, correlation).await
})
.await
.map_err(|_| CredentialResolverError::transport("credential route open timed out"))??;
if reply.header.ty == FrameType::Error {
return Err(decode_wire_error(&reply.body));
}
let value: Value = serde_json::from_slice(&reply.body).map_err(|_| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential route-open reply is not valid JSON",
)
})?;
let channel = value
.get("route_channel")
.and_then(Value::as_u64)
.and_then(|value| u16::try_from(value).ok())
.ok_or_else(|| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential route-open reply has no valid channel",
)
})?;
let epoch = value
.get("route_epoch")
.and_then(Value::as_u64)
.and_then(|value| u32::try_from(value).ok())
.ok_or_else(|| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential route-open reply has no valid epoch",
)
})?;
Ok((channel, epoch))
}
async fn write_request(
&mut self,
channel: u16,
epoch: u32,
correlation: u64,
priority: Priority,
body: Value,
) -> Result<(), CredentialResolverError> {
self.write_bytes(
channel,
epoch,
correlation,
priority,
transport::encode_request(&body)?,
)
.await
}
async fn write_bytes(
&mut self,
channel: u16,
epoch: u32,
correlation: u64,
priority: Priority,
bytes: Vec<u8>,
) -> Result<(), CredentialResolverError> {
let frame = Frame::build(
FrameType::Request,
Flags::new(false, priority, false),
channel,
epoch,
correlation,
bytes,
)
.map_err(|_| {
CredentialResolverError::new(
CredentialErrorClass::Permanent,
"credential request framing failed",
)
})?;
write_frame(&mut self.stream, &frame)
.await
.map_err(|error| {
CredentialResolverError::transport(format!(
"credential route write failed: {error}"
))
})
}
async fn read_reply(
&mut self,
channel: u16,
epoch: u32,
correlation: u64,
) -> Result<Frame, CredentialResolverError> {
loop {
let frame = read_frame(&mut self.stream)
.await
.map_err(|error| {
CredentialResolverError::transport(format!(
"credential route read failed: {error}"
))
})?
.ok_or_else(|| {
CredentialResolverError::transport("credential route closed before replying")
})?;
if frame.header.channel == channel
&& frame.header.epoch == epoch
&& frame.header.corr == correlation
&& matches!(frame.header.ty, FrameType::Response | FrameType::Error)
{
return Ok(frame);
}
}
}
}
#[cfg(feature = "transport")]
impl CredentialConsumerConnection for ClaustrumConsumer {
fn sensitive_request(
&mut self,
request: Secret<Vec<u8>>,
) -> CredentialResolverFuture<'_, Result<Secret<Vec<u8>>, CredentialResolverError>> {
Box::pin(transport::sensitive_request(self, request))
}
fn into_scoped_watch(
self: Box<Self>,
enrollment_token: Option<String>,
) -> CredentialResolverFuture<'static, Result<ScopedWatch, CredentialResolverError>> {
Box::pin(async move { (*self).start_scoped_watch(enrollment_token).await })
}
fn into_policy_watch(
self: Box<Self>,
) -> CredentialResolverFuture<'static, Result<PolicyWatch, CredentialResolverError>> {
Box::pin(watch::start_policy_watch(*self))
}
fn credential_request<'a>(
&'a mut self,
request: Value,
operation: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(transport::credential_request(self, request, operation))
}
}
#[cfg(any(feature = "transport", test))]
fn credential_list_scoped_request() -> Value {
json!({
"method": CREDENTIAL_LIST_SCOPED_OP,
"params": {},
})
}
fn optional_string(value: &Value, key: &str) -> Option<String> {
value
.get(key)
.and_then(Value::as_str)
.filter(|text| !text.is_empty())
.map(str::to_owned)
}
fn invalid_listing(detail: &str) -> CredentialResolverError {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
format!("credential.list_scoped reply {detail}"),
)
}
fn listing_strings(row: &Value, key: &str, optional: bool) -> Result<Vec<String>, String> {
if optional && matches!(row.get(key), None | Some(Value::Null)) {
return Ok(Vec::new());
}
let items = row
.get(key)
.and_then(Value::as_array)
.ok_or_else(|| format!("{key} is not an array"))?;
items
.iter()
.map(|item| {
item.as_str()
.map(str::to_owned)
.ok_or_else(|| format!("{key} contains a non-string"))
})
.collect()
}
fn listing_string(row: &Value, key: &str) -> Result<String, String> {
optional_string(row, key).ok_or_else(|| format!("{key} is not a non-empty string"))
}
fn decode_optional_string(row: &Value, key: &str) -> Result<Option<String>, String> {
match row.get(key) {
None | Some(Value::Null) => Ok(None),
Some(value) => value
.as_str()
.map(|s| Some(s.to_owned()))
.ok_or_else(|| format!("{key} is not a string")),
}
}
fn decode_optional_hosts(row: &Value) -> Result<Option<Vec<String>>, String> {
match row.get("hosts") {
None | Some(Value::Null) => Ok(None),
Some(_) => listing_strings(row, "hosts", false).map(Some),
}
}
fn decode_optional_headers(row: &Value) -> Result<Option<BTreeMap<String, String>>, String> {
let headers = match row.get("headers") {
None | Some(Value::Null) => return Ok(None),
Some(Value::Object(headers)) => headers,
Some(_) => return Err("headers is not an object".into()),
};
headers
.iter()
.map(|(name, value)| {
value
.as_str()
.map(|value| (name.clone(), value.to_owned()))
.ok_or_else(|| "headers contains a non-string value".to_string())
})
.collect::<Result<BTreeMap<_, _>, _>>()
.map(Some)
}
fn decode_optional_auth(row: &Value) -> Result<Option<AuthDescriptor>, String> {
let auth = match row.get("auth") {
None | Some(Value::Null) => return Ok(None),
Some(auth) if auth.is_object() => auth,
Some(_) => return Err("auth is not an object".into()),
};
let header = auth
.get("header")
.and_then(Value::as_str)
.ok_or_else(|| "auth.header is not a string".to_string())?
.to_owned();
let scheme = match auth.get("scheme").and_then(Value::as_str) {
Some("bearer") => AuthScheme::Bearer,
Some("raw") => AuthScheme::Raw,
_ => return Err("auth.scheme is not bearer or raw".into()),
};
Ok(Some(AuthDescriptor { header, scheme }))
}
fn decode_optional_invalid_key(row: &Value) -> Result<Option<InvalidKeyEvidence>, String> {
let evidence = match row.get("invalid_key") {
None | Some(Value::Null) => return Ok(None),
Some(evidence) if evidence.is_object() => evidence,
Some(_) => return Err("invalid_key is not an object".into()),
};
let status = evidence
.get("status")
.and_then(Value::as_u64)
.and_then(|status| u16::try_from(status).ok())
.ok_or_else(|| "invalid_key.status is not a u16".to_string())?;
let error_code = decode_optional_string(evidence, "error_code")
.map_err(|error| format!("invalid_key.{error}"))?;
let error_code_field = decode_optional_string(evidence, "error_code_field")
.map_err(|error| format!("invalid_key.{error}"))?;
if error_code.is_some() != error_code_field.is_some() {
return Err("invalid_key error_code and error_code_field must be present together".into());
}
Ok(Some(InvalidKeyEvidence {
status,
error_code,
error_code_field,
}))
}
fn decode_optional_condition(row: &Value) -> Result<Option<ListedCredentialCondition>, String> {
let condition = match row.get("condition") {
None | Some(Value::Null) => return Ok(None),
Some(condition) if condition.is_object() => condition,
Some(_) => return Err("condition is not an object".into()),
};
let reason = condition
.get("reason")
.and_then(Value::as_str)
.ok_or_else(|| "condition.reason is not a string".to_string())?;
let since_ms = condition
.get("since_ms")
.and_then(Value::as_u64)
.filter(|&since_ms| since_ms <= MAX_SCOPED_CONDITION_SINCE_MS)
.ok_or_else(|| "condition.since_ms is not a non-negative safe integer".to_string())?;
Ok(Some(ListedCredentialCondition {
reason: reason.to_owned(),
since_ms,
}))
}
fn decode_optional_github_app(row: &Value) -> Result<Option<ListedGitHubApp>, String> {
let app = match row.get("github_app") {
None | Some(Value::Null) => return Ok(None),
Some(app) => app,
};
if !app.is_object() {
return Err("github_app is not an object".into());
}
let (created_by, created_at_ms, agent) = match (
app.get("created_by"),
app.get("created_at_ms"),
app.get("agent"),
) {
(None, None, None) => (None, None, None),
(Some(created_by), Some(created_at_ms), Some(agent)) => (
Some(
created_by
.as_str()
.filter(|&s| s == "vault")
.ok_or("github_app.created_by is not the string vault")?
.to_owned(),
),
Some(
created_at_ms
.as_u64()
.ok_or("github_app.created_at_ms is not a non-negative integer")?,
),
Some(
agent
.as_str()
.ok_or("github_app.agent is not a string")?
.to_owned(),
),
),
_ => return Err("github_app attestation is incomplete".into()),
};
Ok(Some(ListedGitHubApp {
app_id: listing_string(app, "app_id").map_err(|error| format!("github_app.{error}"))?,
slug: listing_string(app, "slug").map_err(|error| format!("github_app.{error}"))?,
created_by,
created_at_ms,
agent,
}))
}
const MAX_LISTED_ORG_ID_BYTES: usize = 128;
fn is_valid_listed_org_id(value: &str) -> bool {
!value.is_empty()
&& value.len() <= MAX_LISTED_ORG_ID_BYTES
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
}
fn decode_listed_credential(row: &Value) -> Result<ListedCredential, String> {
Ok(ListedCredential {
plan_tier_since_ms: row
.get("plan_tier_since_ms")
.filter(|value| !value.is_null())
.map(|value| {
value
.as_u64()
.ok_or_else(|| "plan_tier_since_ms is not a non-negative integer".to_string())
})
.transpose()?,
provider: decode_optional_string(row, "provider")?,
fusiform_provider_id: decode_optional_string(row, "fusiform_provider_id")?,
hosts: decode_optional_hosts(row)?,
incarnation: decode_optional_string(row, "incarnation")?,
plan_tier_observed_at_ms: match row.get("plan_tier_observed_at_ms") {
None | Some(Value::Null) => None,
Some(value) => Some(
value
.as_i64()
.ok_or_else(|| "plan_tier_observed_at_ms is not an integer".to_string())?,
),
},
id: listing_string(row, "id")?,
categories: listing_strings(row, "categories", false)?,
credential_type: listing_string(row, "type")?,
serves: listing_strings(row, "serves", false)?,
provider_ids: listing_strings(row, "provider_ids", true)?,
auth_method: decode_optional_string(row, "auth_method")?,
refresh_adapter: decode_optional_string(row, "refresh_adapter")?,
state: listing_string(row, "state")?,
record_version: row
.get("record_version")
.and_then(Value::as_u64)
.ok_or_else(|| "record_version is not an unsigned integer".to_string())?,
operations: listing_strings(row, "operations", false)?,
account_id: decode_optional_string(row, "account_id")?,
email: decode_optional_string(row, "email")?,
org_name: decode_optional_string(row, "org_name")?,
org_id: row
.get("org_id")
.filter(|value| !value.is_null())
.map(|value| {
value
.as_str()
.filter(|value| is_valid_listed_org_id(value))
.map(str::to_owned)
.ok_or_else(|| "org_id is not a valid organization id".to_string())
})
.transpose()?,
plan_tier: decode_optional_string(row, "plan_tier")?,
plan_tier_source: decode_optional_string(row, "plan_tier_source")?,
condition: decode_optional_condition(row)?,
github_app: decode_optional_github_app(row)?,
})
}
fn decode_listed_grant(tuple: &Value) -> Result<ListedGrant, String> {
Ok(ListedGrant {
selector_kind: listing_string(tuple, "selector_kind")?,
selector: listing_string(tuple, "selector")?,
operation: listing_string(tuple, "operation")?,
})
}
pub fn decode_list_scoped_reply(
value: Value,
) -> Result<ScopedCredentialListing, CredentialResolverError> {
let result = reply_result(value)?;
let view = result
.get("view")
.and_then(Value::as_str)
.ok_or_else(|| invalid_listing("has no view digest"))?
.to_owned();
let rows = result
.get("credentials")
.and_then(Value::as_array)
.ok_or_else(|| invalid_listing("has no credentials array"))?;
let mut credentials = Vec::with_capacity(rows.len());
let mut undecodable_credentials = Vec::new();
for (index, row) in rows.iter().enumerate() {
match decode_listed_credential(row) {
Ok(credential) => credentials.push(credential),
Err(error) => {
let id = optional_string(row, "id").unwrap_or_else(|| format!("row {index}"));
let detail = format!("{id}: {error}");
undecodable_credentials.push(detail);
}
}
}
let mut grant_tuples = Vec::new();
let mut undecodable_grants = Vec::new();
if let Some(tuples) = result.get("grant_tuples") {
let tuples = tuples
.as_array()
.ok_or_else(|| invalid_listing("grant_tuples is not an array"))?;
for (index, tuple) in tuples.iter().enumerate() {
match decode_listed_grant(tuple) {
Ok(grant) => grant_tuples.push(grant),
Err(error) => undecodable_grants.push(format!("grant tuple {index}: {error}")),
}
}
}
Ok(ScopedCredentialListing {
credentials,
undecodable_credentials,
grant_tuples,
undecodable_grants,
view,
})
}
#[cfg(any(feature = "transport", test))]
fn credential_get_request(raw_handle: &str, min_ttl_ms: Option<u64>, force_refresh: bool) -> Value {
let mut params =
serde_json::Map::from_iter([("handle".to_owned(), Value::String(raw_handle.to_owned()))]);
if let Some(min_ttl_ms) = min_ttl_ms {
params.insert("min_ttl_ms".to_owned(), Value::from(min_ttl_ms));
}
if force_refresh {
params.insert("force_refresh".to_owned(), Value::Bool(true));
}
json!({
"method": CREDENTIAL_GET_OP,
"params": params,
})
}
#[cfg(any(feature = "transport", test))]
fn credential_get_scoped_request(credential_id: &str, min_ttl_ms: Option<u64>) -> Value {
let mut params = json!({ "credential_id": credential_id });
if let Some(min_ttl_ms) = min_ttl_ms {
params["min_ttl_ms"] = json!(min_ttl_ms);
}
json!({
"method": CREDENTIAL_GET_SCOPED_OP,
"params": params,
})
}
#[cfg(any(feature = "transport", test))]
fn credential_report_auth_failure_request(
credential_id: &str,
record_version: u64,
provider_status: u16,
) -> Value {
json!({
"method": CREDENTIAL_REPORT_AUTH_FAILURE_OP,
"params": {
"credential_id": credential_id,
"provider_status": provider_status,
"record_version": record_version,
},
})
}
#[cfg(feature = "transport")]
fn condition_params(
credential_id: &str,
record_version: u64,
enrollment_token: Option<&str>,
) -> Value {
let mut params = json!({ "credential_id": credential_id, "record_version": record_version });
if let Some(enrollment_token) = enrollment_token {
params["enrollment_token"] = json!(enrollment_token);
}
params
}
#[cfg(any(feature = "transport", test))]
fn credential_status_request(credential_id: &str) -> Value {
json!({
"method": CREDENTIAL_STATUS_OP,
"params": { "credential_id": credential_id },
})
}
#[cfg(any(feature = "transport", test))]
fn credential_sign_request(credential_id: &str, payload: &[u8]) -> Value {
json!({
"method": CREDENTIAL_SIGN_OP,
"params": {
"credential_id": credential_id,
"payload_b64": base64::engine::general_purpose::STANDARD.encode(payload),
},
})
}
#[cfg(any(feature = "transport", test))]
fn credential_public_key_request(credential_id: &str) -> Value {
json!({
"method": CREDENTIAL_PUBLIC_KEY_OP,
"params": { "credential_id": credential_id },
})
}
#[cfg(any(feature = "transport", test))]
fn credential_seal_request(request: SealRequest<'_>) -> Value {
let encode = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes);
json!({
"method": CREDENTIAL_SEAL_OP,
"params": {
"credential_id": request.credential_id,
"recipient_public_key_b64": encode(request.recipient_public_key),
"info_b64": encode(request.info),
"aad_b64": encode(request.aad),
"plaintext_b64": encode(request.plaintext),
},
})
}
pub fn decode_wire_error(bytes: &[u8]) -> CredentialResolverError {
let value = serde_json::from_slice::<Value>(bytes).unwrap_or(Value::Null);
let Some(code) = value.get("code").and_then(Value::as_str) else {
return CredentialResolverError::transport(
"credential service returned an invalid error frame",
);
};
let body = subc_protocol::ErrorBody {
code: code.to_owned(),
message: value
.get("message")
.and_then(Value::as_str)
.unwrap_or("credential route refused the request")
.to_owned(),
detail: value.get("detail").cloned(),
};
if subc_protocol::error_codes::is_retryable_route_open_refusal(&body) {
CredentialResolverError {
class: CredentialErrorClass::Transport,
code: body.code,
safe_message: body.message,
}
} else {
CredentialResolverError::unclassified(body.code, body.message)
}
}
fn classify_error_value(value: &Value) -> CredentialResolverError {
let class = value
.get("class")
.or_else(|| value.pointer("/error/class"))
.or_else(|| value.pointer("/error/data/class"))
.and_then(Value::as_str);
let class = match class {
Some("auth_required") => Some(CredentialErrorClass::AuthRequired),
Some("credential_absent") => Some(CredentialErrorClass::CredentialAbsent),
Some("unauthorized") => Some(CredentialErrorClass::Unauthorized),
Some("permanent") => Some(CredentialErrorClass::Permanent),
Some("transient") => Some(CredentialErrorClass::Transient),
Some("context_overflow") => Some(CredentialErrorClass::ContextOverflow),
_ => None,
};
let code_field = value
.get("code")
.or_else(|| value.pointer("/error/code"))
.and_then(Value::as_str);
let class = match code_field {
Some("not_found") => Some(CredentialErrorClass::CredentialAbsent),
Some("auth_required") => Some(CredentialErrorClass::AuthRequired),
_ => class,
};
if let Some(class) = class {
let message = match code_field {
Some(code) => format!("credential service rejected the request: {code}"),
None => "credential service rejected the request".to_string(),
};
return CredentialResolverError::new(class, message);
}
let code = value
.get("code")
.or_else(|| value.pointer("/error/code"))
.and_then(Value::as_str)
.unwrap_or("credential_unclassified");
let message = value
.get("message")
.or_else(|| value.pointer("/error/message"))
.and_then(Value::as_str)
.unwrap_or("credential service returned an unclassified error");
CredentialResolverError::unclassified(code, message)
}
#[cfg(feature = "transport")]
fn route_open_body(consumer_module_id: &str) -> Result<Value, CredentialResolverError> {
let read = subc_os::launch_nonce()
.map(|nonce| nonce.map(|nonce| nonce.value().to_owned()))
.map_err(|error| error.to_string());
Ok(route_open_body_with_nonce(
consumer_module_id,
&required_launch_nonce(read)?,
))
}
#[cfg(feature = "transport")]
fn required_launch_nonce(
read: Result<Option<String>, String>,
) -> Result<String, CredentialResolverError> {
match read {
Ok(Some(nonce)) if !nonce.trim().is_empty() => Ok(nonce),
Ok(_) => Err(CredentialResolverError::new(
CredentialErrorClass::AuthRequired,
"credential consumer requires a non-empty launch nonce for the reserved principal",
)),
Err(error) => Err(CredentialResolverError::new(
CredentialErrorClass::AuthRequired,
format!(
"credential consumer could not read the launch nonce for the reserved principal: {error}"
),
)),
}
}
#[cfg(feature = "transport")]
fn route_open_body_with_nonce(consumer_module_id: &str, launch_nonce: &str) -> Value {
json!({
"op": "route.open",
"target": {
"kind": "management_surface",
"module_id": CREDENTIAL_MODULE_ID,
},
"identity": {
"harness": consumer_module_id,
"session": "campaign-credential-consumer",
},
"consumer_identity": {
"module_id": consumer_module_id,
"launch_nonce": launch_nonce,
},
"config": [],
})
}
fn reply_result(value: Value) -> Result<Value, CredentialResolverError> {
let result = value.get("result").cloned().unwrap_or(value);
if result.get("error").is_some() {
return Err(classify_error_value(&result));
}
Ok(result)
}
fn valid_lower_hex(value: &str, length: usize) -> bool {
value.len() == length
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
fn hex_bytes(bytes: &[u8]) -> String {
let mut encoded = String::with_capacity(bytes.len() * 2);
for byte in bytes {
encoded.push_str(&format!("{byte:02x}"));
}
encoded
}
pub fn decode_signature_reply(
value: Value,
) -> Result<CredentialSignature, CredentialResolverError> {
let result = reply_result(value)?;
let signature_b64 = result
.get("signature_b64")
.and_then(Value::as_str)
.ok_or_else(|| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential signing reply has no signature_b64",
)
})?;
let signature = base64::engine::general_purpose::STANDARD
.decode(signature_b64)
.map_err(|_| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential signing reply has invalid base64",
)
})?;
if signature.len() != 64 {
return Err(CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential signing reply has a non-Ed25519 signature length",
));
}
let key_id = result
.get("key_id")
.and_then(Value::as_str)
.filter(|value| valid_lower_hex(value, 16))
.ok_or_else(|| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential signing reply has no valid key_id",
)
})?;
Ok(CredentialSignature {
signature_hex: hex_bytes(&signature),
key_id: key_id.to_owned(),
})
}
pub fn decode_public_key_reply(
value: Value,
) -> Result<CredentialPublicKey, CredentialResolverError> {
let result = reply_result(value)?;
let public_key_hex = result
.get("public_key_hex")
.and_then(Value::as_str)
.filter(|value| valid_lower_hex(value, 64))
.ok_or_else(|| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential public-key reply has no valid public_key_hex",
)
})?;
let key_id = result
.get("key_id")
.and_then(Value::as_str)
.filter(|value| valid_lower_hex(value, 16))
.ok_or_else(|| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential public-key reply has no valid key_id",
)
})?;
let public_key_bytes = (0..public_key_hex.len())
.step_by(2)
.map(|index| u8::from_str_radix(&public_key_hex[index..index + 2], 16))
.collect::<Result<Vec<_>, _>>()
.expect("validated lowercase hex decodes");
let expected_key_id = hex_bytes(&Sha256::digest(&public_key_bytes)[..8]);
if key_id != expected_key_id {
return Err(CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential public-key reply key_id does not identify public_key_hex",
));
}
let algorithm = match result.get("algorithm").and_then(Value::as_str) {
Some("ed25519") => PublicKeyAlgorithm::Ed25519,
Some("x25519") => PublicKeyAlgorithm::X25519,
_ => {
return Err(CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential public-key reply is neither Ed25519 nor X25519",
))
}
};
Ok(CredentialPublicKey {
public_key_hex: public_key_hex.to_owned(),
key_id: key_id.to_owned(),
algorithm,
})
}
pub fn decode_seal_reply(value: Value) -> Result<CredentialSeal, CredentialResolverError> {
let result = reply_result(value)?;
let invalid = |detail: &str| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
format!("credential seal reply {detail}"),
)
};
let bytes = |field: &str| {
let text = result
.get(field)
.and_then(Value::as_str)
.ok_or_else(|| invalid(&format!("has no {field}")))?;
base64::engine::general_purpose::STANDARD
.decode(text)
.map_err(|_| invalid(&format!("has invalid base64 in {field}")))
};
let enc = bytes("enc_b64")?;
if enc.len() != 32 {
return Err(invalid("has a non-X25519 encapsulated key length"));
}
let ciphertext = bytes("ciphertext_b64")?;
if ciphertext.len() < 16 {
return Err(invalid("has a ciphertext shorter than the AEAD tag"));
}
let key_id = result
.get("key_id")
.and_then(Value::as_str)
.filter(|value| valid_lower_hex(value, 16))
.ok_or_else(|| invalid("has no valid key_id"))?;
Ok(CredentialSeal {
enc,
ciphertext,
key_id: key_id.to_owned(),
})
}
pub fn decode_credential_status_reply(
value: Value,
) -> Result<CredentialStatus, CredentialResolverError> {
let result = reply_result(value)?;
let ready = result
.get("ready")
.and_then(Value::as_bool)
.ok_or_else(|| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential status reply has no ready flag",
)
})?;
let record_version = result
.get("record_version")
.map(decode_record_version)
.transpose()?;
Ok(CredentialStatus {
ready,
record_version,
stale_pending: result
.get("stale_pending")
.map(|value| {
value
.as_bool()
.ok_or_else(|| invalid_metadata("stale_pending is not a boolean"))
})
.transpose()?
.unwrap_or(false),
last_error_code: decode_optional_string(&result, "last_error_code")
.map_err(invalid_metadata)?,
})
}
fn invalid_metadata(detail: impl Into<String>) -> CredentialResolverError {
CredentialResolverError::new(CredentialErrorClass::InvalidResponse, detail)
}
fn decode_record_version(value: &Value) -> Result<String, CredentialResolverError> {
value
.as_u64()
.map(|version| version.to_string())
.ok_or_else(|| invalid_metadata("record_version is not an unsigned integer"))
}
pub fn decode_credential_reply(
value: Value,
) -> Result<ResolvedCredential, CredentialResolverError> {
let result = reply_result(value)?;
let payload = match result.get("payload") {
Some(Value::Array(payload)) => payload
.iter()
.map(|byte| {
byte.as_u64()
.and_then(|byte| u8::try_from(byte).ok())
.ok_or_else(|| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential payload contains a non-byte value",
)
})
})
.collect::<Result<Vec<_>, _>>()?,
_ => {
return Err(CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential reply has no opaque payload",
));
}
};
let version = result
.get("record_version")
.ok_or_else(|| invalid_metadata("credential reply has no record version"))
.and_then(decode_record_version)?;
let expires_at_ms = match result.get("expires_at_ms") {
None | Some(Value::Null) => None,
Some(value) => Some(
value
.as_i64()
.ok_or_else(|| invalid_metadata("expires_at_ms is not an integer"))?,
),
};
let mut credential = ResolvedCredential::new_with_identity(
payload,
version,
expires_at_ms,
decode_optional_string(&result, "account_id").map_err(invalid_metadata)?,
decode_optional_string(&result, "email").map_err(invalid_metadata)?,
decode_optional_string(&result, "org_name").map_err(invalid_metadata)?,
);
credential.auth = decode_optional_auth(&result).map_err(invalid_metadata)?;
credential.hosts = decode_optional_hosts(&result).map_err(invalid_metadata)?;
credential.invalid_key = decode_optional_invalid_key(&result).map_err(invalid_metadata)?;
credential.base_url = decode_optional_string(&result, "base_url").map_err(invalid_metadata)?;
credential.headers = decode_optional_headers(&result).map_err(invalid_metadata)?;
Ok(credential)
}
pub fn decode_report_auth_failure_reply(value: Value) -> Result<bool, CredentialResolverError> {
let result = value.get("result").unwrap_or(&value);
if result.get("error").is_some() {
return Err(classify_error_value(result));
}
result
.get("accepted")
.and_then(Value::as_bool)
.ok_or_else(|| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"auth-failure report reply has no accepted value",
)
})
}
pub fn decode_report_condition_reply(value: Value) -> Result<bool, CredentialResolverError> {
decode_condition_reply(value, "accepted")
}
pub fn decode_clear_condition_reply(value: Value) -> Result<bool, CredentialResolverError> {
decode_condition_reply(value, "cleared")
}
fn decode_condition_reply(value: Value, field: &str) -> Result<bool, CredentialResolverError> {
reply_result(value)?
.get(field)
.and_then(Value::as_bool)
.ok_or_else(|| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
format!("credential condition reply has no boolean {field} value"),
)
})
}
#[cfg(test)]
mod contract_tests;
#[cfg(test)]
mod client_regressions;
#[cfg(test)]
mod condition_tests;
#[cfg(test)]
mod tests {
#[cfg(feature = "transport")]
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
#[cfg(feature = "transport")]
#[derive(Debug)]
struct FakeCkcredTarget {
script: Mutex<VecDeque<Result<Value, CredentialResolverError>>>,
requests: Mutex<Vec<(String, Option<u64>, bool)>>,
reports: Mutex<Vec<(String, u64, u16)>>,
}
#[cfg(feature = "transport")]
impl CredentialGetTarget for FakeCkcredTarget {
fn credential_get<'a>(
&'a self,
raw_handle: &'a str,
min_ttl_ms: Option<u64>,
force_refresh: bool,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.requests
.lock()
.expect("fake CKCRED target poisoned")
.push((raw_handle.to_owned(), min_ttl_ms, force_refresh));
self.script
.lock()
.expect("fake CKCRED target poisoned")
.pop_front()
.expect("fake CKCRED target script exhausted")
})
}
fn credential_get_scoped<'a>(
&'a self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.requests
.lock()
.expect("fake CKCRED target poisoned")
.push((credential_id.to_owned(), None, false));
self.script
.lock()
.expect("fake CKCRED target poisoned")
.pop_front()
.expect("fake CKCRED target script exhausted")
})
}
fn credential_get_scoped_with_min_ttl<'a>(
&'a self,
credential_id: &'a str,
min_ttl_ms: u64,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.requests
.lock()
.expect("fake CKCRED target poisoned")
.push((credential_id.to_owned(), Some(min_ttl_ms), false));
self.script
.lock()
.expect("fake CKCRED target script exhausted")
.pop_front()
.expect("fake CKCRED target script exhausted")
})
}
fn credential_report_auth_failure<'a>(
&'a self,
credential_id: &'a str,
record_version: u64,
provider_status: u16,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.reports
.lock()
.expect("fake CKCRED target poisoned")
.push((credential_id.to_owned(), record_version, provider_status));
self.script
.lock()
.expect("fake CKCRED target script exhausted")
.pop_front()
.expect("fake CKCRED target script exhausted")
})
}
}
#[cfg(feature = "transport")]
#[derive(Debug)]
struct DeadlineConnector {
dials: Arc<AtomicUsize>,
}
#[cfg(feature = "transport")]
impl CredentialConsumerConnector for DeadlineConnector {
fn connect<'a>(
&'a self,
) -> CredentialResolverFuture<
'a,
Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
> {
Box::pin(async move {
let dial = self.dials.fetch_add(1, Ordering::SeqCst);
Ok(Box::new(DeadlineConsumer { hangs: dial == 0 })
as Box<dyn CredentialConsumerConnection>)
})
}
}
#[cfg(feature = "transport")]
struct DeadlineConsumer {
hangs: bool,
}
#[cfg(feature = "transport")]
impl CredentialConsumerConnection for DeadlineConsumer {
fn credential_get<'a>(
&'a mut self,
_raw_handle: &'a str,
_min_ttl_ms: Option<u64>,
_force_refresh: bool,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async { panic!("deadline fixture only supports scoped reads") })
}
fn credential_get_scoped<'a>(
&'a mut self,
_credential_id: &'a str,
_min_ttl_ms: Option<u64>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
if self.hangs {
std::future::pending().await
} else {
Ok(json!({
"payload": b"reconnected-secret".to_vec(),
"record_version": 2,
}))
}
})
}
fn credential_sign<'a>(
&'a mut self,
_credential_id: &'a str,
_payload: &'a [u8],
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async { panic!("deadline fixture only supports scoped reads") })
}
fn credential_public_key<'a>(
&'a mut self,
_credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async { panic!("deadline fixture only supports scoped reads") })
}
}
#[cfg(feature = "transport")]
#[tokio::test(start_paused = true)]
async fn silent_call_deadline_is_transport_rebuilds_and_releases_mutex_mutation_proof() {
let dials = Arc::new(AtomicUsize::new(0));
let deadline = Duration::from_millis(20);
let target = Arc::new(LiveCredentialGetTarget::new(
Arc::new(DeadlineConnector {
dials: Arc::clone(&dials),
}),
deadline,
));
let first_error = tokio::time::timeout(
deadline.saturating_mul(3),
target.credential_get_scoped("github_app:first"),
)
.await
.expect("the scoped call's own timeout must fire")
.expect_err("the silent first consumer must reach the whole-call deadline");
assert_eq!(dials.load(Ordering::SeqCst), 1);
let second = tokio::time::timeout(
deadline.saturating_mul(3),
target.credential_get_scoped("github_app:second"),
)
.await
.expect("a timed-out holder must release the consumer mutex")
.expect("the rebuilt consumer must serve the second caller");
assert_eq!(first_error.class, CredentialErrorClass::Transport);
assert!(first_error.retryable());
assert_eq!(
first_error.to_string(),
"credential_transport: credential.get_scoped timed out waiting for the credential route"
);
assert_eq!(second["payload"], json!(b"reconnected-secret".to_vec()));
assert_eq!(
dials.load(Ordering::SeqCst),
2,
"the deadline must clear the stale cached consumer before the next call"
);
}
#[cfg(feature = "transport")]
#[tokio::test(start_paused = true)]
async fn handle_and_seal_deadlines_include_the_queue_without_dialing() {
let dials = Arc::new(AtomicUsize::new(0));
let deadline = Duration::from_secs(5);
let target = LiveCredentialGetTarget::new(
Arc::new(DeadlineConnector {
dials: dials.clone(),
}),
deadline,
);
let mut holder = target.consumer.lock().await;
*holder = Some(Box::new(DeadlineConsumer { hangs: false }));
let (get, seal) = tokio::time::timeout(deadline + Duration::from_millis(1), async {
tokio::join!(
target.credential_get("fixture-handle", None, false),
target.credential_seal(SealRequest {
credential_id: "kem:fixture",
recipient_public_key: &[1; 32],
info: b"",
aad: b"",
plaintext: b"fixture",
}),
)
})
.await
.expect("handle and seal must time out while the route is held");
assert!(get.unwrap_err().is_transport());
assert!(seal.unwrap_err().is_transport());
assert!(holder.is_some());
assert_eq!(dials.load(Ordering::SeqCst), 0);
}
#[cfg(feature = "transport")]
#[tokio::test(start_paused = true)]
async fn scoped_read_deadlines_expire_in_the_queue_without_clearing_the_held_route() {
let dials = Arc::new(AtomicUsize::new(0));
let deadline = Duration::from_secs(5);
let target = LiveCredentialGetTarget::new(
Arc::new(DeadlineConnector {
dials: dials.clone(),
}),
deadline,
);
let mut holder = target.consumer.lock().await;
*holder = Some(Box::new(DeadlineConsumer { hangs: false }));
let results = tokio::time::timeout(deadline + Duration::from_millis(1), async {
tokio::join!(
target.credential_get_scoped("github_app:queued"),
target.credential_get_scoped_with_min_ttl("github_app:queued", 1),
target.credential_status("github_app:queued"),
target.credential_list_scoped(),
)
})
.await
.expect("queued reads must time out while another caller still holds the route");
for result in [results.0, results.1, results.2, results.3] {
assert!(result.unwrap_err().is_transport());
}
assert!(holder.is_some());
drop(holder);
target
.credential_get_scoped("github_app:later")
.await
.unwrap();
assert_eq!(
dials.load(Ordering::SeqCst),
0,
"the holder's route must be reused"
);
}
#[cfg(feature = "transport")]
#[tokio::test(start_paused = true)]
async fn scoped_read_shares_one_deadline_between_connecting_and_calling() {
#[derive(Debug)]
struct SlowConnector(Duration);
impl CredentialConsumerConnector for SlowConnector {
fn connect(
&self,
) -> CredentialResolverFuture<
'_,
Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
> {
Box::pin(async move {
tokio::time::sleep(self.0).await;
Ok(Box::new(DeadlineConsumer { hangs: true })
as Box<dyn CredentialConsumerConnection>)
})
}
}
let deadline = Duration::from_secs(5);
for dial_time in [Duration::from_secs(3), Duration::from_secs(6)] {
let target = LiveCredentialGetTarget::new(Arc::new(SlowConnector(dial_time)), deadline);
let error = tokio::time::timeout(
deadline + Duration::from_millis(1),
target.credential_get_scoped("github_app:slow"),
)
.await
.expect("dial and request must share one deadline")
.unwrap_err();
assert!(error.is_transport());
assert!(target.consumer.lock().await.is_none());
}
}
#[cfg(feature = "transport")]
#[tokio::test]
async fn live_shape_red_proof_retry_class_and_capability_redaction() {
let raw_handle = "capability-handle-must-never-leak";
let target = Arc::new(FakeCkcredTarget {
script: Mutex::new(VecDeque::from([
Err(CredentialResolverError::new(
CredentialErrorClass::Transport,
"credential service is temporarily unavailable",
)),
Ok(json!({
"result": {
"payload": b"api-secret".to_vec(),
"record_version": 7,
"expires_at_ms": 1234,
}
})),
])),
requests: Mutex::new(Vec::new()),
reports: Mutex::new(Vec::new()),
});
let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 2);
let credential = resolver.resolve(raw_handle, Some(500), true).await.unwrap();
assert_eq!(credential.expose(), b"api-secret");
assert_eq!(credential.record_version, "7");
assert_eq!(target.requests.lock().unwrap().len(), 2);
assert!(!format!("{credential:?}").contains(raw_handle));
let permanent = CredentialResolverError::new(
CredentialErrorClass::Permanent,
"credential service rejected the request",
);
assert!(!permanent.retryable());
assert!(!permanent.to_string().contains(raw_handle));
}
#[test]
fn wire_refusals_follow_the_daemon_recovery_verdict() {
for (code, expected_back, retryable) in [
("unknown_module", None, false),
("missing_identity", None, false),
("future_refusal", None, false),
("module_warming", None, true),
("module_reloading", None, true),
("target_unavailable", Some(true), true),
("target_unavailable", Some(false), false),
("module_timeout", None, true),
] {
let error = decode_wire_error(
&serde_json::to_vec(&json!({
"code": code,
"message": format!("{code} 1"),
"detail": { "expected_back": expected_back },
}))
.unwrap(),
);
assert_eq!(error.retryable(), retryable, "{code} {expected_back:?}");
assert!(error.to_string().contains(code), "verbatim code preserved");
}
let other = classify_error_value(&json!({"code": "weird_new_code"}));
assert!(!other.is_transport());
}
#[test]
fn ckcred_contract_red_proof_request_shape_and_error_capability_redaction() {
let raw_handle = "raw-capability-token";
assert_eq!(
credential_get_request(raw_handle, Some(250), true),
json!({
"method": "credential.get",
"params": {
"handle": raw_handle,
"min_ttl_ms": 250,
"force_refresh": true,
}
})
);
let credential_id = "github_app:scoped-agent";
assert_eq!(
credential_get_scoped_request(credential_id, None),
json!({
"method": "credential.get_scoped",
"params": { "credential_id": credential_id },
})
);
assert_eq!(
credential_get_scoped_request(credential_id, Some(500)),
json!({
"method": "credential.get_scoped",
"params": {
"credential_id": credential_id,
"min_ttl_ms": 500,
},
})
);
assert_eq!(
credential_report_auth_failure_request(credential_id, 7, 401),
json!({
"method": "credential.report_auth_failure",
"params": {
"credential_id": credential_id,
"provider_status": 401,
"record_version": 7,
},
})
);
assert_eq!(
credential_status_request(credential_id),
json!({
"method": "credential.status",
"params": { "credential_id": credential_id },
})
);
let signing_credential = "signing:agent-assertion:1";
assert_eq!(
credential_sign_request(signing_credential, b"abc"),
json!({
"method": "credential.sign",
"params": {
"credential_id": signing_credential,
"payload_b64": "YWJj",
},
})
);
assert_eq!(
credential_public_key_request(signing_credential),
json!({
"method": "credential.public_key",
"params": { "credential_id": signing_credential },
})
);
let error = decode_credential_reply(json!({"result": {"error": {
"class": "auth_required",
"code": "needs_login",
"message": format!("unknown handle {raw_handle}"),
}}}))
.unwrap_err();
assert_eq!(error.class, CredentialErrorClass::AuthRequired);
assert_eq!(error.code(), "credential_auth_required");
assert!(!error.to_string().contains(raw_handle));
}
#[test]
fn signing_replies_decode_exact_ed25519_material_and_reject_wrong_algorithm() {
let signature = decode_signature_reply(json!({
"result": {
"signature_b64": base64::engine::general_purpose::STANDARD.encode([7_u8; 64]),
"key_id": "0123456789abcdef",
}
}))
.unwrap();
assert_eq!(signature.signature_hex, "07".repeat(64));
assert_eq!(signature.key_id, "0123456789abcdef");
let public_key_hex = "ab".repeat(32);
let public_key_bytes = [0xab_u8; 32];
let key_id = hex_bytes(&Sha256::digest(public_key_bytes)[..8]);
let public_key = decode_public_key_reply(json!({
"result": {
"public_key_hex": public_key_hex,
"key_id": key_id,
"algorithm": "ed25519",
}
}))
.unwrap();
assert_eq!(public_key.public_key_hex, "ab".repeat(32));
assert_eq!(public_key.algorithm, PublicKeyAlgorithm::Ed25519);
let error = decode_public_key_reply(json!({
"result": {
"public_key_hex": "ab".repeat(32),
"key_id": hex_bytes(&Sha256::digest(public_key_bytes)[..8]),
"algorithm": "rsa",
}
}))
.unwrap_err();
assert_eq!(error.class, CredentialErrorClass::InvalidResponse);
}
#[test]
fn public_key_replies_type_x25519_and_refuse_unknown_algorithms_and_wrong_key_ids() {
let public_key_bytes = [0xcd_u8; 32];
let key_id = hex_bytes(&Sha256::digest(public_key_bytes)[..8]);
let reply = |algorithm: &str, key_id: &str| {
json!({
"result": {
"public_key_hex": "cd".repeat(32),
"key_id": key_id,
"algorithm": algorithm,
}
})
};
let x25519 = decode_public_key_reply(reply("x25519", &key_id)).unwrap();
assert_eq!(x25519.algorithm, PublicKeyAlgorithm::X25519);
assert_eq!(x25519.algorithm.as_str(), "x25519");
assert_eq!(x25519.public_key_hex, "cd".repeat(32));
assert_eq!(x25519.key_id, key_id);
let ed25519 = decode_public_key_reply(reply("ed25519", &key_id)).unwrap();
assert_eq!(ed25519.algorithm, PublicKeyAlgorithm::Ed25519);
for algorithm in ["rsa", "X25519", "Ed25519", ""] {
assert_eq!(
decode_public_key_reply(reply(algorithm, &key_id))
.unwrap_err()
.class,
CredentialErrorClass::InvalidResponse,
"{algorithm:?}"
);
}
let wrong_key_id = hex_bytes(&Sha256::digest([0xab_u8; 32])[..8]);
for algorithm in ["x25519", "ed25519"] {
let error = decode_public_key_reply(reply(algorithm, &wrong_key_id)).unwrap_err();
assert_eq!(error.class, CredentialErrorClass::InvalidResponse);
assert!(
error.to_string().contains("key_id does not identify"),
"{algorithm}: {error}"
);
}
}
#[test]
fn unknown_method_without_a_class_remains_unclassified_and_preserves_producer_details() {
let error = decode_wire_error(
br#"{"code":"unknown_method","message":"unknown method 'credential.put'"}"#,
);
assert_eq!(error.class, CredentialErrorClass::Unclassified);
assert_eq!(error.code(), "unknown_method");
assert!(!error.retryable());
assert_ne!(error.class, CredentialErrorClass::Permanent);
assert_eq!(
error.to_string(),
"unknown_method: unknown method 'credential.put'"
);
}
#[test]
fn error_shaped_success_reply_surfaces_the_typed_class_and_code() {
let error = decode_credential_reply(json!({
"result": { "error": { "class": "permanent", "code": "not_found" } }
}))
.expect_err("an error reply must not decode as a credential");
assert_eq!(error.class, CredentialErrorClass::CredentialAbsent);
assert!(
error.to_string().contains("not_found"),
"the producer's code must survive classification: {error}"
);
assert!(
!error.to_string().contains("opaque payload"),
"a typed refusal must never render as invalid_response: {error}"
);
}
#[cfg(feature = "transport")]
#[tokio::test]
async fn scoped_transport_failure_returns_without_internal_retry_ladder_mutation_proof() {
let credential_id = "github_app:bounded-agent";
let target = Arc::new(FakeCkcredTarget {
script: Mutex::new(VecDeque::from([
Err(CredentialResolverError::transport(
"connection reset by peer",
)),
Ok(json!({
"payload": b"must-not-be-reached".to_vec(),
"record_version": 2,
})),
])),
requests: Mutex::new(Vec::new()),
reports: Mutex::new(Vec::new()),
});
let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 2);
let error = resolver
.get_scoped(credential_id)
.await
.expect_err("caller owns the scoped redial");
assert_eq!(error.class, CredentialErrorClass::Transport);
assert_eq!(target.requests.lock().unwrap().len(), 1);
}
#[cfg(feature = "transport")]
#[tokio::test]
async fn scoped_get_with_min_ttl_forwards_the_requested_bound() {
let credential_id = "oauth:anthropic";
let target = Arc::new(FakeCkcredTarget {
script: Mutex::new(VecDeque::from([Ok(json!({
"payload": b"served-token".to_vec(),
"record_version": 4,
"expires_at_ms": 1_900_000_000_000_i64,
}))])),
requests: Mutex::new(Vec::new()),
reports: Mutex::new(Vec::new()),
});
let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 0);
let credential = resolver
.get_scoped_with_min_ttl(credential_id, 300_000)
.await
.unwrap();
assert_eq!(credential.expose(), b"served-token");
assert_eq!(
target.requests.lock().unwrap().as_slice(),
&[(credential_id.to_owned(), Some(300_000), false)]
);
}
#[cfg(feature = "transport")]
#[tokio::test]
async fn report_auth_failure_rejects_unsupported_status_before_sending() {
let credential_id = "apikey:openrouter";
let target = Arc::new(FakeCkcredTarget {
script: Mutex::new(VecDeque::from([Ok(json!({
"result": { "accepted": true }
}))])),
requests: Mutex::new(Vec::new()),
reports: Mutex::new(Vec::new()),
});
let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 0);
let error = resolver
.report_auth_failure(credential_id, 12, 429)
.await
.expect_err("only provider 401 and 403 statuses are sent");
assert_eq!(error.class, CredentialErrorClass::Permanent);
assert!(target.reports.lock().unwrap().is_empty());
}
#[cfg(feature = "transport")]
#[tokio::test]
async fn scoped_reads_use_the_credential_id_and_decode_the_record_directly() {
let credential_id = "github_app:scoped-agent";
let target = Arc::new(FakeCkcredTarget {
script: Mutex::new(VecDeque::from([Ok(json!({
"payload": b"-----BEGIN PRIVATE KEY-----\nscoped PEM\n-----END PRIVATE KEY-----".to_vec(),
"record_version": 7,
}))])),
requests: Mutex::new(Vec::new()),
reports: Mutex::new(Vec::new()),
});
let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 0);
let credential = resolver.get_scoped(credential_id).await.unwrap();
assert_eq!(
credential.expose(),
b"-----BEGIN PRIVATE KEY-----\nscoped PEM\n-----END PRIVATE KEY-----"
);
assert_eq!(credential.record_version, "7");
assert_eq!(
target.requests.lock().unwrap().as_slice(),
&[(credential_id.to_owned(), None, false)]
);
}
#[cfg(feature = "transport")]
#[test]
fn route_open_body_omits_project_fields() {
let body = route_open_body_with_nonce("prefrontal-core", "nonce-under-test");
assert_eq!(
body["identity"],
json!({
"harness": "prefrontal-core",
"session": "campaign-credential-consumer",
})
);
assert!(body.get("project_root").is_none());
assert!(body.get("project_id").is_none());
}
#[cfg(feature = "transport")]
#[test]
fn route_open_body_carries_the_reserved_consumer_identity_when_the_nonce_is_present() {
let body = route_open_body_with_nonce("prefrontal-core", "nonce-under-test");
assert_eq!(
body.pointer("/consumer_identity/module_id")
.and_then(Value::as_str),
Some("prefrontal-core"),
"a supervised launch must ride the reserved principal"
);
assert_eq!(
body.pointer("/consumer_identity/launch_nonce")
.and_then(Value::as_str),
Some("nonce-under-test")
);
}
#[cfg(feature = "transport")]
#[test]
fn motor_credential_route_presents_its_launch_nonce() {
let body = route_open_body_with_nonce("ck-motor", "motor-nonce");
assert_eq!(body["op"], "route.open");
assert_eq!(body["target"]["module_id"], "claustrum");
assert_eq!(
body["consumer_identity"],
json!({"module_id":"ck-motor", "launch_nonce":"motor-nonce"})
);
}
#[cfg(feature = "transport")]
#[tokio::test]
async fn signing_not_found_and_auth_required_are_terminal_without_retries() {
struct TerminalTarget {
code: &'static str,
calls: AtomicUsize,
}
impl CredentialGetTarget for TerminalTarget {
fn credential_get<'a>(
&'a self,
_: &'a str,
_: Option<u64>,
_: bool,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
panic!("signing must not read private credentials")
}
fn credential_sign<'a>(
&'a self,
_: &'a str,
_: &'a [u8],
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
self.calls.fetch_add(1, Ordering::SeqCst);
Err(classify_error_value(
&json!({"code":self.code, "class":"transient", "message":"do not log vault material"}),
))
})
}
fn credential_public_key<'a>(
&'a self,
_: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
self.credential_sign("unused", b"")
}
}
for (code, class) in [
("not_found", CredentialErrorClass::CredentialAbsent),
("auth_required", CredentialErrorClass::AuthRequired),
] {
let target = Arc::new(TerminalTarget {
code,
calls: AtomicUsize::new(0),
});
let resolver = ClaustrumCredentialResolver::with_target(target.clone(), 2);
assert_eq!(
resolver
.sign("signing:ck-motor-ssh:1", b"challenge")
.await
.unwrap_err()
.class,
class
);
assert_eq!(
resolver
.public_key("signing:ck-motor-ssh:1")
.await
.unwrap_err()
.class,
class
);
assert_eq!(target.calls.load(Ordering::SeqCst), 2);
for wire in [
json!({"code":code}),
json!({"error":{"code":code}}),
json!({"error":{"code":code,"class":"transient"}}),
] {
let error = classify_error_value(&wire);
assert_eq!(error.class, class);
assert!(!error.retryable());
assert!(!error.is_transport());
assert!(!error.to_string().contains("do not log vault material"));
}
}
}
#[cfg(feature = "transport")]
#[test]
fn route_open_body_carries_prefrontal_routing_as_consumer_id() {
let body = route_open_body_with_nonce("prefrontal-routing", "routing-nonce-under-test");
assert_eq!(
body.pointer("/consumer_identity/module_id")
.and_then(Value::as_str),
Some("prefrontal-routing")
);
assert_eq!(
body.pointer("/identity/harness").and_then(Value::as_str),
Some("prefrontal-routing")
);
}
#[cfg(feature = "transport")]
#[test]
fn route_open_body_requires_the_launch_nonce_for_the_reserved_principal() {
assert_eq!(
required_launch_nonce(Ok(Some("nonce".to_string()))).unwrap(),
"nonce"
);
for read in [
Ok(None),
Ok(Some(" ".to_string())),
Err("descriptor 3 is not open".to_string()),
] {
let result = std::panic::catch_unwind(|| required_launch_nonce(read.clone()));
let refusal = result
.unwrap_or_else(|_| panic!("{read:?} panicked instead of refusing"))
.expect_err("a missing nonce must not yield one");
assert_eq!(
refusal.class,
CredentialErrorClass::AuthRequired,
"{read:?}"
);
assert!(!refusal.retryable(), "{read:?}");
}
}
#[test]
fn list_scoped_request_sends_no_enrollment_token() {
assert_eq!(
credential_list_scoped_request(),
json!({ "method": "credential.list_scoped", "params": {} })
);
}
#[test]
fn list_scoped_reply_decodes_identity_rows_grants_and_view() {
let listing = decode_list_scoped_reply(json!({
"result": {
"credentials": [
{
"id": "oauth:anthropic:yiyi",
"categories": ["anthropic-native", "llm-provider"],
"type": "oauth",
"serves": ["anthropic"],
"refresh_adapter": "anthropic",
"state": "active",
"record_version": 227,
"operations": ["list"],
"account_id": "acct-1",
"email": "a@example.test"
},
{
"id": "apikey:artificial-analysis",
"categories": [],
"type": "apikey",
"serves": [],
"state": "active",
"record_version": 1,
"operations": ["read"]
}
],
"grants": 1,
"grant_tuples": [
{"selector_kind": "category", "selector": "anthropic-native", "operation": "list"}
],
"view": "digest"
}
}))
.expect("listing decodes");
assert_eq!(listing.view, "digest");
assert_eq!(listing.credentials.len(), 2);
let claude = &listing.credentials[0];
assert_eq!(claude.id, "oauth:anthropic:yiyi");
assert_eq!(claude.refresh_adapter.as_deref(), Some("anthropic"));
assert_eq!(claude.account_id.as_deref(), Some("acct-1"));
assert_eq!(claude.record_version, 227);
assert_eq!(listing.credentials[1].account_id, None);
assert_eq!(listing.credentials[1].refresh_adapter, None);
assert_eq!(
listing.grant_tuples,
vec![ListedGrant {
selector_kind: "category".into(),
selector: "anthropic-native".into(),
operation: "list".into(),
}]
);
}
#[test]
fn list_scoped_reply_without_view_is_invalid_and_unreadable_rows_are_local() {
let no_view = decode_list_scoped_reply(json!({ "result": { "credentials": [] } }))
.expect_err("no view");
assert_eq!(no_view.class, CredentialErrorClass::InvalidResponse);
let no_id = decode_list_scoped_reply(json!({
"result": { "credentials": [{ "state": "active" }], "view": "v" }
}))
.expect("row without id does not reject the listing");
assert!(no_id.credentials.is_empty());
assert_eq!(
no_id.undecodable_credentials,
["row 0: id is not a non-empty string"]
);
}
#[test]
fn list_scoped_reply_treats_explicit_null_optional_fields_as_absent() {
let row = |extra: Value| {
let mut row = json!({
"id": "oauth:anthropic",
"categories": ["llm-provider"],
"type": "oauth",
"serves": ["anthropic"],
"state": "active",
"record_version": 3,
"operations": ["read"],
});
row.as_object_mut()
.unwrap()
.extend(extra.as_object().unwrap().clone());
row
};
let listing = decode_list_scoped_reply(json!({
"result": {
"credentials": [
row(json!({
"provider_ids": null,
"auth_method": null,
"refresh_adapter": null,
"account_id": null,
"email": null,
"org_name": null,
"plan_tier": null,
"plan_tier_source": null,
"plan_tier_since_ms": null,
"org_id": null,
"github_app": null,
})),
row(json!({ "plan_tier": 20 })),
],
"view": "v",
}
}))
.expect("listing");
assert_eq!(
listing.credentials.len(),
1,
"{:?}",
listing.undecodable_credentials
);
let listed = &listing.credentials[0];
assert!(listed.provider_ids.is_empty());
assert!(listed.plan_tier_since_ms.is_none());
assert!(listed.org_id.is_none());
assert!(listed.github_app.is_none());
assert_eq!(
(
&listed.auth_method,
&listed.refresh_adapter,
&listed.account_id,
&listed.email,
&listed.org_name,
&listed.plan_tier,
&listed.plan_tier_source,
),
(&None, &None, &None, &None, &None, &None, &None)
);
assert_eq!(
listing.undecodable_credentials,
["oauth:anthropic: plan_tier is not a string"]
);
}
}