#![forbid(unsafe_code)]
#[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;
mod watch;
#[cfg(feature = "transport")]
pub use watch::ScopedWatch;
pub use watch::{
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(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;
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>,
}
#[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 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 plan_tier: Option<String>,
pub plan_tier_source: Option<String>,
}
#[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,
}
}
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)
.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 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,
_handle: &'a str,
_payload: &'a [u8],
) -> CredentialResolverFuture<'a, Result<CredentialSignature, CredentialResolverError>> {
Box::pin(async { Err(CredentialResolverError::unavailable()) })
}
fn public_key<'a>(
&'a self,
_handle: &'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_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,
_handle: &'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,
_handle: &'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>,
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,
project_root: PathBuf,
consumer_module_id: impl Into<String>,
) -> Self {
Self {
target: Arc::new(LiveCredentialGetTarget::new(
Arc::new(LiveCredentialConnector {
connection_file_path,
project_root,
consumer_module_id: consumer_module_id.into(),
}),
CREDENTIAL_CALL_DEADLINE,
)),
transient_retries: DEFAULT_TRANSIENT_RETRIES,
}
}
#[doc(hidden)]
pub fn with_live_consumer_identity(
connection_file_path: PathBuf,
project_root: PathBuf,
consumer_module_id: String,
) -> Self {
Self {
target: Arc::new(LiveCredentialGetTarget::new(
Arc::new(LiveCredentialConnector {
connection_file_path,
project_root,
consumer_module_id,
}),
CREDENTIAL_CALL_DEADLINE,
)),
transient_retries: DEFAULT_TRANSIENT_RETRIES,
}
}
#[doc(hidden)]
pub fn with_target(target: Arc<dyn CredentialGetTarget>, transient_retries: usize) -> Self {
Self {
target,
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(async move {
let mut retries = 0;
loop {
match self
.target
.credential_get(raw_handle, min_ttl_ms, force_refresh)
.await
{
Ok(reply) => return decode_credential_reply(reply),
Err(error) if error.retryable() && retries < self.transient_retries => {
retries += 1;
}
Err(error) => return Err(error),
}
}
})
}
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 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,
handle: &'a str,
payload: &'a [u8],
) -> CredentialResolverFuture<'a, Result<CredentialSignature, CredentialResolverError>> {
Box::pin(async move {
let mut retries = 0;
loop {
match self.target.credential_sign(handle, payload).await {
Ok(reply) => return decode_signature_reply(reply),
Err(error) if error.retryable() && retries < self.transient_retries => {
retries += 1;
}
Err(error) => return Err(error),
}
}
})
}
fn public_key<'a>(
&'a self,
handle: &'a str,
) -> CredentialResolverFuture<'a, Result<CredentialPublicKey, CredentialResolverError>> {
Box::pin(async move {
let mut retries = 0;
loop {
match self.target.credential_public_key(handle).await {
Ok(reply) => return decode_public_key_reply(reply),
Err(error) if error.retryable() && retries < self.transient_retries => {
retries += 1;
}
Err(error) => return Err(error),
}
}
})
}
fn seal<'a>(
&'a self,
request: SealRequest<'a>,
) -> CredentialResolverFuture<'a, Result<CredentialSeal, CredentialResolverError>> {
Box::pin(async move {
let mut retries = 0;
loop {
match self.target.credential_seal(request).await {
Ok(reply) => return decode_seal_reply(reply),
Err(error) if error.retryable() && retries < self.transient_retries => {
retries += 1;
}
Err(error) => return Err(error),
}
}
})
}
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 into_scoped_watch(
self: Box<Self>,
_enrollment_token: Option<String>,
) -> CredentialResolverFuture<'static, Result<ScopedWatch, 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>>;
fn credential_get_scoped<'a>(
&'a mut self,
credential_id: &'a str,
min_ttl_ms: Option<u64>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>>;
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 {
Err(CredentialResolverError::new(
CredentialErrorClass::Unavailable,
"credential auth-failure reports are unavailable",
))
})
}
fn credential_status<'a>(
&'a mut 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 mut self,
credential_id: &'a str,
payload: &'a [u8],
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>>;
fn credential_public_key<'a>(
&'a mut self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>>;
fn credential_seal<'a>(
&'a mut self,
_request: SealRequest<'a>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async {
Err(CredentialResolverError::new(
CredentialErrorClass::Permanent,
"credential sealing is unavailable",
))
})
}
fn credential_list_scoped(
&mut self,
) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
Box::pin(async {
Err(CredentialResolverError::new(
CredentialErrorClass::Permanent,
"credential listing is unavailable",
))
})
}
}
#[cfg(feature = "transport")]
trait CredentialConsumerConnector: Send + Sync {
fn connect<'a>(
&'a self,
) -> CredentialResolverFuture<
'a,
Result<Box<dyn CredentialConsumerConnection>, CredentialResolverError>,
>;
}
#[cfg(feature = "transport")]
struct LiveCredentialConnector {
connection_file_path: PathBuf,
project_root: 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.project_root,
&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(())
}
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(async move {
let mut consumer = self.consumer.lock().await;
self.connect_if_needed(&mut consumer).await?;
let result = tokio::time::timeout(
self.call_deadline,
consumer
.as_mut()
.expect("credential consumer initialized")
.credential_get(raw_handle, min_ttl_ms, force_refresh),
)
.await
.unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_GET_OP)));
Self::clear_failed_transport(&mut consumer, &result);
result
})
}
fn credential_get_scoped<'a>(
&'a self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
let mut consumer = self.consumer.lock().await;
self.connect_if_needed(&mut consumer).await?;
let result = tokio::time::timeout(
self.call_deadline,
consumer
.as_mut()
.expect("credential consumer initialized")
.credential_get_scoped(credential_id, None),
)
.await
.unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_GET_SCOPED_OP)));
Self::clear_failed_transport(&mut consumer, &result);
result
})
}
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 {
let mut consumer = self.consumer.lock().await;
self.connect_if_needed(&mut consumer).await?;
let result = tokio::time::timeout(
self.call_deadline,
consumer
.as_mut()
.expect("credential consumer initialized")
.credential_get_scoped(credential_id, Some(min_ttl_ms)),
)
.await
.unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_GET_SCOPED_OP)));
Self::clear_failed_transport(&mut consumer, &result);
result
})
}
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 {
let mut consumer = self.consumer.lock().await;
self.connect_if_needed(&mut consumer).await?;
let result = tokio::time::timeout(
self.call_deadline,
consumer
.as_mut()
.expect("credential consumer initialized")
.credential_report_auth_failure(credential_id, record_version, provider_status),
)
.await
.unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_REPORT_AUTH_FAILURE_OP)));
Self::clear_failed_transport(&mut consumer, &result);
result
})
}
fn credential_status<'a>(
&'a self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
let mut consumer = self.consumer.lock().await;
self.connect_if_needed(&mut consumer).await?;
let result = tokio::time::timeout(
self.call_deadline,
consumer
.as_mut()
.expect("credential consumer initialized")
.credential_status(credential_id),
)
.await
.unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_STATUS_OP)));
Self::clear_failed_transport(&mut consumer, &result);
result
})
}
fn credential_sign<'a>(
&'a self,
credential_id: &'a str,
payload: &'a [u8],
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
let mut consumer = self.consumer.lock().await;
self.connect_if_needed(&mut consumer).await?;
let result = tokio::time::timeout(
self.call_deadline,
consumer
.as_mut()
.expect("credential consumer initialized")
.credential_sign(credential_id, payload),
)
.await
.unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_SIGN_OP)));
Self::clear_failed_transport(&mut consumer, &result);
result
})
}
fn credential_public_key<'a>(
&'a self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
let mut consumer = self.consumer.lock().await;
self.connect_if_needed(&mut consumer).await?;
let result = tokio::time::timeout(
self.call_deadline,
consumer
.as_mut()
.expect("credential consumer initialized")
.credential_public_key(credential_id),
)
.await
.unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_PUBLIC_KEY_OP)));
Self::clear_failed_transport(&mut consumer, &result);
result
})
}
fn credential_seal<'a>(
&'a self,
request: SealRequest<'a>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(async move {
let mut consumer = self.consumer.lock().await;
self.connect_if_needed(&mut consumer).await?;
let result = tokio::time::timeout(
self.call_deadline,
consumer
.as_mut()
.expect("credential consumer initialized")
.credential_seal(request),
)
.await
.unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_SEAL_OP)));
Self::clear_failed_transport(&mut consumer, &result);
result
})
}
fn credential_list_scoped(
&self,
) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
Box::pin(async move {
let mut consumer = self.consumer.lock().await;
self.connect_if_needed(&mut consumer).await?;
let result = tokio::time::timeout(
self.call_deadline,
consumer
.as_mut()
.expect("credential consumer initialized")
.credential_list_scoped(),
)
.await
.unwrap_or_else(|_| Err(Self::deadline_error(CREDENTIAL_LIST_SCOPED_OP)));
Self::clear_failed_transport(&mut consumer, &result);
result
})
}
}
#[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,
project_root: &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_CONNECT_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(project_root, 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,
project_root: &Path,
consumer_module_id: &str,
) -> Result<(u16, u32), CredentialResolverError> {
let correlation = self.next_correlation();
let body = route_open_body(project_root, consumer_module_id);
self.write_request(0, 0, correlation, Priority::Passive, body)
.await?;
let reply = self.read_reply(0, 0, correlation).await?;
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 credential_get(
&mut self,
raw_handle: &str,
min_ttl_ms: Option<u64>,
force_refresh: bool,
) -> Result<Value, CredentialResolverError> {
self.credential_request(
credential_get_request(raw_handle, min_ttl_ms, force_refresh),
"credential.get",
)
.await
}
async fn credential_get_scoped(
&mut self,
credential_id: &str,
min_ttl_ms: Option<u64>,
) -> Result<Value, CredentialResolverError> {
self.credential_request(
credential_get_scoped_request(credential_id, min_ttl_ms),
CREDENTIAL_GET_SCOPED_OP,
)
.await
}
async fn credential_report_auth_failure(
&mut self,
credential_id: &str,
record_version: u64,
provider_status: u16,
) -> Result<Value, CredentialResolverError> {
self.credential_request(
credential_report_auth_failure_request(credential_id, record_version, provider_status),
CREDENTIAL_REPORT_AUTH_FAILURE_OP,
)
.await
}
async fn credential_status(
&mut self,
credential_id: &str,
) -> Result<Value, CredentialResolverError> {
self.credential_request(
credential_status_request(credential_id),
CREDENTIAL_STATUS_OP,
)
.await
}
async fn credential_sign(
&mut self,
handle: &str,
payload: &[u8],
) -> Result<Value, CredentialResolverError> {
self.credential_request(credential_sign_request(handle, payload), CREDENTIAL_SIGN_OP)
.await
}
async fn credential_public_key(
&mut self,
handle: &str,
) -> Result<Value, CredentialResolverError> {
self.credential_request(
credential_public_key_request(handle),
CREDENTIAL_PUBLIC_KEY_OP,
)
.await
}
async fn credential_seal(
&mut self,
request: SealRequest<'_>,
) -> Result<Value, CredentialResolverError> {
self.credential_request(credential_seal_request(request), CREDENTIAL_SEAL_OP)
.await
}
async fn credential_request(
&mut self,
request: Value,
operation: &str,
) -> Result<Value, CredentialResolverError> {
let correlation = self.next_correlation();
self.write_request(
self.route_channel,
self.route_epoch,
correlation,
Priority::Interactive,
request,
)
.await?;
let reply = self
.read_reply(self.route_channel, self.route_epoch, correlation)
.await?;
if reply.header.ty == FrameType::Error {
return Err(decode_wire_error(&reply.body));
}
serde_json::from_slice(&reply.body).map_err(|_| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
format!("{operation} reply is not valid JSON"),
)
})
}
async fn write_request(
&mut self,
channel: u16,
epoch: u32,
correlation: u64,
priority: Priority,
body: Value,
) -> Result<(), CredentialResolverError> {
let bytes = serde_json::to_vec(&body).map_err(|_| {
CredentialResolverError::new(
CredentialErrorClass::Permanent,
"credential request encoding failed",
)
})?;
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 = tokio::time::timeout(CREDENTIAL_READ_TIMEOUT, read_frame(&mut self.stream))
.await
.map_err(|error| {
CredentialResolverError::transport(format!(
"credential route reply timed out: {error}"
))
})?
.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 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 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(ClaustrumConsumer::credential_get(
self,
raw_handle,
min_ttl_ms,
force_refresh,
))
}
fn credential_get_scoped<'a>(
&'a mut self,
credential_id: &'a str,
min_ttl_ms: Option<u64>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(ClaustrumConsumer::credential_get_scoped(
self,
credential_id,
min_ttl_ms,
))
}
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(ClaustrumConsumer::credential_report_auth_failure(
self,
credential_id,
record_version,
provider_status,
))
}
fn credential_status<'a>(
&'a mut self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(ClaustrumConsumer::credential_status(self, credential_id))
}
fn credential_sign<'a>(
&'a mut self,
credential_id: &'a str,
payload: &'a [u8],
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(ClaustrumConsumer::credential_sign(
self,
credential_id,
payload,
))
}
fn credential_public_key<'a>(
&'a mut self,
credential_id: &'a str,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(ClaustrumConsumer::credential_public_key(
self,
credential_id,
))
}
fn credential_seal<'a>(
&'a mut self,
request: SealRequest<'a>,
) -> CredentialResolverFuture<'a, Result<Value, CredentialResolverError>> {
Box::pin(ClaustrumConsumer::credential_seal(self, request))
}
fn credential_list_scoped(
&mut self,
) -> CredentialResolverFuture<'_, Result<Value, CredentialResolverError>> {
Box::pin(
self.credential_request(credential_list_scoped_request(), CREDENTIAL_LIST_SCOPED_OP),
)
}
}
#[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 && row.get(key).is_none() {
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 listing_optional_string(row: &Value, key: &str) -> Result<Option<String>, String> {
match row.get(key) {
None => Ok(None),
Some(value) => value
.as_str()
.map(|s| Some(s.to_owned()))
.ok_or_else(|| format!("{key} is not a string")),
}
}
fn decode_listed_credential(row: &Value) -> Result<ListedCredential, String> {
Ok(ListedCredential {
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: listing_optional_string(row, "auth_method")?,
refresh_adapter: listing_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: listing_optional_string(row, "account_id")?,
email: listing_optional_string(row, "email")?,
org_name: listing_optional_string(row, "org_name")?,
plan_tier: listing_optional_string(row, "plan_tier")?,
plan_tier_source: listing_optional_string(row, "plan_tier_source")?,
})
}
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").and_then(Value::as_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(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);
classify_error_value(&value)
}
const RELAY_ROUTING_CODES: [&str; 7] = [
subc_protocol::error_codes::UNKNOWN_MODULE,
subc_protocol::error_codes::MODULE_RELOADING,
subc_protocol::error_codes::MODULE_WARMING,
subc_protocol::error_codes::TARGET_UNAVAILABLE,
subc_protocol::error_codes::MODULE_TIMEOUT,
"unknown_channel",
"stale_route_epoch",
];
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");
if RELAY_ROUTING_CODES.contains(&code) {
return CredentialResolverError::new(
CredentialErrorClass::Transport,
format!("{code}: {message}"),
);
}
CredentialResolverError::unclassified(code, message)
}
#[cfg(feature = "transport")]
fn route_open_body(project_root: &Path, consumer_module_id: &str) -> Value {
let read = subc_os::launch_nonce()
.map(|nonce| nonce.map(|nonce| nonce.value().to_owned()))
.map_err(|error| error.to_string());
route_open_body_with_nonce(
project_root,
consumer_module_id,
&required_launch_nonce(read),
)
}
#[cfg(feature = "transport")]
fn required_launch_nonce(read: Result<Option<String>, String>) -> String {
match read {
Ok(Some(nonce)) if !nonce.trim().is_empty() => nonce,
Ok(_) => panic!(
"credential consumer requires a non-empty launch nonce for the reserved principal"
),
Err(error) => panic!(
"credential consumer could not read the launch nonce for the reserved principal: {error}"
),
}
}
#[cfg(feature = "transport")]
fn route_open_body_with_nonce(
project_root: &Path,
consumer_module_id: &str,
launch_nonce: &str,
) -> Value {
json!({
"op": "route.open",
"target": {
"kind": "management_surface",
"module_id": CREDENTIAL_MODULE_ID,
},
"identity": {
"project_root": project_root,
"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").and_then(|value| match value {
Value::String(version) if !version.is_empty() => Some(version.clone()),
Value::Number(version) => Some(version.to_string()),
_ => None,
});
Ok(CredentialStatus {
ready,
record_version,
stale_pending: result
.get("stale_pending")
.and_then(Value::as_bool)
.unwrap_or(false),
last_error_code: result
.get("last_error_code")
.and_then(Value::as_str)
.map(str::to_owned),
})
}
pub fn decode_credential_reply(
value: Value,
) -> Result<ResolvedCredential, CredentialResolverError> {
let result = value.get("result").unwrap_or(&value);
if result.get("error").is_some() {
return Err(classify_error_value(result));
}
let payload = match result.get("payload") {
Some(Value::String(payload)) => payload.as_bytes().to_vec(),
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")
.map(|version| match version {
Value::String(version) => version.clone(),
version => version.to_string(),
})
.filter(|version| !version.is_empty())
.ok_or_else(|| {
CredentialResolverError::new(
CredentialErrorClass::InvalidResponse,
"credential reply has no record version",
)
})?;
let expires_at_ms = result.get("expires_at_ms").and_then(Value::as_i64);
Ok(ResolvedCredential::new_with_identity(
payload,
version,
expires_at_ms,
optional_string(result, "account_id"),
optional_string(result, "email"),
optional_string(result, "org_name"),
))
}
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",
)
})
}
#[cfg(test)]
mod contract_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": "reconnected-secret",
"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]
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 = tokio::spawn({
let target = Arc::clone(&target);
async move { target.credential_get_scoped("github_app:first").await }
});
tokio::time::timeout(deadline, async {
while dials.load(Ordering::SeqCst) == 0 {
tokio::task::yield_now().await;
}
})
.await
.expect("first call must dial before the fixture deadline");
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");
let first_error = first
.await
.expect("deadline task must join")
.expect_err("the silent first consumer must reach the whole-call deadline");
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!("reconnected-secret"));
assert_eq!(
dials.load(Ordering::SeqCst),
2,
"the deadline must clear the stale cached consumer before the next call"
);
}
#[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::Transient,
"credential service is temporarily unavailable",
)),
Ok(json!({
"result": {
"payload": "api-secret",
"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 relay_routing_codes_classify_transport_so_redial_arms_fire() {
for code in [
"unknown_channel",
"stale_route_epoch",
"unknown_module",
"module_warming",
"module_reloading",
"target_unavailable",
"module_timeout",
] {
let error = classify_error_value(&json!({
"code": code,
"message": format!("{code} 1"),
}));
assert!(
error.is_transport(),
"{code} must classify transport (got {:?})",
error.class
);
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_wire_error(
json!({
"class": "auth_required",
"message": format!("unknown handle {raw_handle}"),
})
.to_string()
.as_bytes(),
);
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": "must-not-be-reached",
"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": "served-token",
"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": "-----BEGIN PRIVATE KEY-----\nscoped PEM\n-----END PRIVATE KEY-----",
"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_carries_the_reserved_consumer_identity_when_the_nonce_is_present() {
let root = Path::new("/probe/root");
let body = route_open_body_with_nonce(root, "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(Path::new("/motor-project"), "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(
Path::new("/probe/routing"),
"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()))),
"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()));
assert!(result.is_err(), "{read:?} must not yield a nonce");
}
}
#[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"]
);
}
}