use std::collections::{BTreeSet, HashMap};
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::durable::ErrorClass;
use crate::error::{Result, RustyError};
use crate::record::Effect;
use crate::tool::Tool;
fn invalid(message: impl Into<String>) -> RustyError {
RustyError::InvalidUpdate(message.into())
}
pub fn hex_encode(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
use std::fmt::Write as _;
let _ = write!(out, "{byte:02x}");
}
out
}
pub fn hex_decode(hex: &str) -> Option<Vec<u8>> {
if hex.len() % 2 != 0 {
return None;
}
(0..hex.len())
.step_by(2)
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16).ok())
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConnectionProvider {
Oauth2AuthorizationCode,
Oauth2ClientCredentials,
ApiKey,
Basic,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConnectionStatus {
Active,
NeedsReauth,
Revoked,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClassifiedFailure {
pub class: ErrorClass,
pub detail: String,
pub at: DateTime<Utc>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ConnectionHealth {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_refresh_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_failure: Option<ClassifiedFailure>,
#[serde(default)]
pub consecutive_failures: u32,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConnectionRecord {
pub connection_id: String,
pub provider: ConnectionProvider,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
pub scopes: BTreeSet<String>,
pub status: ConnectionStatus,
#[serde(default)]
pub health: ConnectionHealth,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
pub const CONNECTION_ID_PREFIX: &str = "conn-";
pub const HANDLE_ID_PREFIX: &str = "hdl-";
pub fn new_connection_id() -> String {
format!("{}{}", CONNECTION_ID_PREFIX, uuid::Uuid::new_v4().simple())
}
pub fn new_handle_id() -> String {
format!("{}{}", HANDLE_ID_PREFIX, uuid::Uuid::new_v4().simple())
}
fn minted_id_ok(prefix: &str, id: &str) -> bool {
let Some(hex) = id.strip_prefix(prefix) else {
return false;
};
hex.len() == 32
&& hex
.chars()
.all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
}
fn validate_free_text(what: &str, value: &str, max: usize) -> Result<()> {
let ok = !value.is_empty()
&& value.len() <= max
&& !value.contains('/')
&& value.chars().all(|c| !c.is_control());
if !ok {
return Err(invalid(format!(
"invalid {what} `{value}` (non-empty, at most {max} chars, no `/` or control characters)"
)));
}
Ok(())
}
impl ConnectionRecord {
pub fn validate(&self) -> Result<()> {
if !minted_id_ok(CONNECTION_ID_PREFIX, &self.connection_id) {
return Err(invalid(format!(
"connection id `{}` is not a minted id (`{CONNECTION_ID_PREFIX}` + 32 lowercase hex)",
self.connection_id
)));
}
validate_connection_fields(self.subject.as_deref(), &self.scopes)
}
pub fn is_active(&self) -> bool {
self.status == ConnectionStatus::Active
}
}
pub fn scopes_missing(ceiling: &BTreeSet<String>, requested: &BTreeSet<String>) -> Vec<String> {
requested.difference(ceiling).cloned().collect()
}
pub fn validate_connection_fields(subject: Option<&str>, scopes: &BTreeSet<String>) -> Result<()> {
if let Some(subject) = subject {
validate_free_text("connection subject", subject, 256)?;
}
for scope in scopes {
validate_free_text("connection scope", scope, 512)?;
}
Ok(())
}
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct TokenMaterial {
pub access_token: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_secret: Option<String>,
}
impl std::fmt::Debug for TokenMaterial {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TokenMaterial")
.field("access_token", &"[redacted]")
.field(
"refresh_token",
&self.refresh_token.as_ref().map(|_| "[redacted]"),
)
.field("expires_at", &self.expires_at)
.field(
"client_secret",
&self.client_secret.as_ref().map(|_| "[redacted]"),
)
.finish()
}
}
pub const SEALED_FORMAT_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SealedCredential {
pub format_version: u32,
pub key_id: String,
pub wrapped_data_key: String,
pub wrap_nonce: String,
pub nonce: String,
pub ciphertext: String,
pub sealed_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StoredConnection {
pub record: ConnectionRecord,
pub credential: SealedCredential,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HandleClaims {
pub handle_id: String,
pub connection_id: String,
pub tenant: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run_id: Option<String>,
pub scopes: BTreeSet<String>,
pub issued_at: DateTime<Utc>,
pub expires_at: DateTime<Utc>,
}
impl HandleClaims {
pub fn is_expired(&self, now: DateTime<Utc>) -> bool {
now >= self.expires_at
}
}
pub const HANDLE_TOKEN_PREFIX: &str = "v1";
#[derive(Clone, PartialEq)]
pub struct CredentialHandle {
claims: HandleClaims,
signature: String,
}
impl std::fmt::Debug for CredentialHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CredentialHandle")
.field("claims", &self.claims)
.field("signature", &"[redacted]")
.finish()
}
}
impl CredentialHandle {
pub fn from_parts(claims: HandleClaims, signature: String) -> Self {
Self { claims, signature }
}
pub fn claims(&self) -> &HandleClaims {
&self.claims
}
pub fn signature(&self) -> &str {
&self.signature
}
pub fn token(&self) -> String {
let claims = serde_json::to_vec(&self.claims).unwrap_or_default();
format!(
"{}.{}.{}",
HANDLE_TOKEN_PREFIX,
hex_encode(&claims),
self.signature
)
}
#[allow(clippy::result_large_err)]
pub fn parse_token(token: &str) -> std::result::Result<(HandleClaims, String), BrokerDenial> {
let unknown = |detail: &str| BrokerDenial::unknown_handle(detail.to_owned());
let mut parts = token.splitn(3, '.');
if parts.next() != Some(HANDLE_TOKEN_PREFIX) {
return Err(unknown("not a broker handle token"));
}
let claims_hex = parts.next().unwrap_or_default();
let signature = parts.next().unwrap_or_default().to_owned();
let claims_bytes =
hex_decode(claims_hex).ok_or_else(|| unknown("the claims half is not valid hex"))?;
let claims: HandleClaims = serde_json::from_slice(&claims_bytes)
.map_err(|_| unknown("the claims half is not a handle claims document"))?;
if !minted_id_ok(HANDLE_ID_PREFIX, &claims.handle_id)
|| !minted_id_ok(CONNECTION_ID_PREFIX, &claims.connection_id)
|| claims.tenant.is_empty()
|| claims.expires_at <= claims.issued_at
{
return Err(unknown("the claims fail handle grammar"));
}
Ok((claims, signature))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "reason", rename_all = "snake_case")]
pub enum BrokerDenialReason {
UnknownHandle,
HandleExpired {
expires_at: DateTime<Utc>,
},
ScopeNotGranted {
missing: Vec<String>,
},
ConnectionRevoked {
grant: Vec<String>,
},
ConnectionNeedsReauth,
UnknownConnection,
BrokerUnavailable,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BrokerDenial {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub connection_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub handle_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tenant: Option<String>,
#[serde(flatten)]
pub reason: BrokerDenialReason,
pub detail: String,
}
impl BrokerDenial {
pub fn unknown_handle(detail: String) -> Self {
Self {
connection_id: None,
handle_id: None,
tenant: None,
reason: BrokerDenialReason::UnknownHandle,
detail,
}
}
pub fn handle_expired(claims: &HandleClaims) -> Self {
Self {
connection_id: Some(claims.connection_id.clone()),
handle_id: Some(claims.handle_id.clone()),
tenant: Some(claims.tenant.clone()),
reason: BrokerDenialReason::HandleExpired {
expires_at: claims.expires_at,
},
detail: format!(
"handle `{}` expired at {} — handles are short-lived; re-issue at the next use",
claims.handle_id, claims.expires_at
),
}
}
pub fn scope_not_granted(
claims_or_connection: Option<(&str, Option<&str>, &str)>,
missing: Vec<String>,
detail: String,
) -> Self {
let (connection_id, handle_id, tenant) = match claims_or_connection {
Some((connection, handle, tenant)) => (
Some(connection.to_owned()),
handle.map(str::to_owned),
Some(tenant.to_owned()),
),
None => (None, None, None),
};
Self {
connection_id,
handle_id,
tenant,
detail: format!("{detail} — missing scopes: {}", missing.join(", ")),
reason: BrokerDenialReason::ScopeNotGranted { missing },
}
}
pub fn connection_revoked(record: &ConnectionRecord, tenant: &str, handle_id: &str) -> Self {
Self {
connection_id: Some(record.connection_id.clone()),
handle_id: Some(handle_id.to_owned()),
tenant: Some(tenant.to_owned()),
reason: BrokerDenialReason::ConnectionRevoked {
grant: record.scopes.iter().cloned().collect(),
},
detail: format!(
"connection `{}` is revoked — the grant {} no longer holds; the next use fails \
closed, not the next deploy",
record.connection_id,
serde_json::to_string(&record.scopes).unwrap_or_default(),
),
}
}
pub fn connection_needs_reauth(
record: &ConnectionRecord,
tenant: &str,
handle_id: &str,
) -> Self {
Self {
connection_id: Some(record.connection_id.clone()),
handle_id: Some(handle_id.to_owned()),
tenant: Some(tenant.to_owned()),
reason: BrokerDenialReason::ConnectionNeedsReauth,
detail: format!(
"connection `{}` needs re-authentication — a human must record a new consent act",
record.connection_id
),
}
}
pub fn unknown_connection(claims: &HandleClaims) -> Self {
Self {
connection_id: Some(claims.connection_id.clone()),
handle_id: Some(claims.handle_id.clone()),
tenant: Some(claims.tenant.clone()),
reason: BrokerDenialReason::UnknownConnection,
detail: format!(
"connection `{}` is unknown to tenant `{}`",
claims.connection_id, claims.tenant
),
}
}
pub fn unavailable(detail: String) -> Self {
Self {
connection_id: None,
handle_id: None,
tenant: None,
reason: BrokerDenialReason::BrokerUnavailable,
detail,
}
}
}
impl std::fmt::Display for BrokerDenial {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let tag = match &self.reason {
BrokerDenialReason::UnknownHandle => "unknown_handle",
BrokerDenialReason::HandleExpired { .. } => "handle_expired",
BrokerDenialReason::ScopeNotGranted { .. } => "scope_not_granted",
BrokerDenialReason::ConnectionRevoked { .. } => "connection_revoked",
BrokerDenialReason::ConnectionNeedsReauth => "connection_needs_reauth",
BrokerDenialReason::UnknownConnection => "unknown_connection",
BrokerDenialReason::BrokerUnavailable => "broker_unavailable",
};
write!(f, "{tag}: {}", self.detail)
}
}
impl std::error::Error for BrokerDenial {}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConnectionConsent {
pub connection_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
pub scopes: BTreeSet<String>,
pub recorded_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConnectionRefresh {
pub connection_id: String,
pub refreshed_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConnectionRevocation {
pub connection_id: String,
pub grant: BTreeSet<String>,
pub revoked_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConnectionReauthRequired {
pub connection_id: String,
pub failure: ClassifiedFailure,
pub grant: BTreeSet<String>,
pub recorded_at: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HandleIssuance {
pub claims: HandleClaims,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CredentialUse {
pub handle_id: String,
pub connection_id: String,
pub tenant: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run_id: Option<String>,
pub scopes_checked: BTreeSet<String>,
pub used_at: DateTime<Utc>,
}
#[derive(Clone, PartialEq)]
pub struct TokenGrant {
pub access_token: String,
pub refresh_token: Option<String>,
pub expires_at: Option<DateTime<Utc>>,
}
impl std::fmt::Debug for TokenGrant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TokenGrant")
.field("access_token", &"[redacted]")
.field(
"refresh_token",
&self.refresh_token.as_ref().map(|_| "[redacted]"),
)
.field("expires_at", &self.expires_at)
.finish()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct OAuthFailure {
pub class: ErrorClass,
pub permanent: bool,
pub detail: String,
}
impl OAuthFailure {
pub fn permanent(detail: impl Into<String>) -> Self {
Self {
class: ErrorClass::InvalidInput,
permanent: true,
detail: detail.into(),
}
}
pub fn transient(class: ErrorClass, detail: impl Into<String>) -> Self {
Self {
class,
permanent: false,
detail: detail.into(),
}
}
}
impl std::fmt::Display for OAuthFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let kind = if self.permanent {
"permanent"
} else {
"transient"
};
write!(
f,
"{kind} OAuth failure ({:?}): {}",
self.class, self.detail
)
}
}
impl std::error::Error for OAuthFailure {}
impl ConnectionProvider {
pub fn is_oauth(self) -> bool {
matches!(
self,
ConnectionProvider::Oauth2AuthorizationCode
| ConnectionProvider::Oauth2ClientCredentials
)
}
}
#[async_trait]
pub trait OAuthProvider: std::fmt::Debug + Send + Sync {
async fn exchange_code(
&self,
code: &str,
scopes: &BTreeSet<String>,
) -> std::result::Result<TokenGrant, OAuthFailure>;
async fn refresh(
&self,
connection: &ConnectionRecord,
material: &TokenMaterial,
) -> std::result::Result<TokenGrant, OAuthFailure>;
}
#[derive(Debug, Clone)]
enum ScriptedOutcome {
Rotate,
Grant(TokenGrant),
Fail(OAuthFailure),
}
#[derive(Debug)]
pub struct ScriptedOAuthProvider {
codes: Mutex<std::collections::HashMap<String, ScriptedOutcome>>,
refresh_script: Mutex<std::collections::VecDeque<ScriptedOutcome>>,
counter: std::sync::atomic::AtomicU64,
token_prefix: String,
grant_ttl: chrono::Duration,
exchanges: Mutex<Vec<String>>,
refreshes: Mutex<u64>,
}
impl Default for ScriptedOAuthProvider {
fn default() -> Self {
Self::new()
}
}
impl ScriptedOAuthProvider {
pub fn new() -> Self {
Self {
codes: Mutex::new(std::collections::HashMap::new()),
refresh_script: Mutex::new(std::collections::VecDeque::new()),
counter: std::sync::atomic::AtomicU64::new(0),
token_prefix: "scripted-token".to_owned(),
grant_ttl: chrono::Duration::hours(1),
exchanges: Mutex::new(Vec::new()),
refreshes: Mutex::new(0),
}
}
pub fn with_token_prefix(mut self, prefix: impl Into<String>) -> Self {
self.token_prefix = prefix.into();
self
}
pub fn with_grant_ttl(mut self, ttl: chrono::Duration) -> Self {
self.grant_ttl = ttl;
self
}
pub fn with_code(self, code: impl Into<String>, grant: TokenGrant) -> Self {
self.codes
.lock()
.expect("scripted provider lock")
.insert(code.into(), ScriptedOutcome::Grant(grant));
self
}
pub fn with_code_failure(self, code: impl Into<String>, failure: OAuthFailure) -> Self {
self.codes
.lock()
.expect("scripted provider lock")
.insert(code.into(), ScriptedOutcome::Fail(failure));
self
}
pub fn then_refresh_failure(self, failure: OAuthFailure) -> Self {
self.refresh_script
.lock()
.expect("scripted provider lock")
.push_back(ScriptedOutcome::Fail(failure));
self
}
pub fn then_refresh_grant(self, grant: TokenGrant) -> Self {
self.refresh_script
.lock()
.expect("scripted provider lock")
.push_back(ScriptedOutcome::Grant(grant));
self
}
pub fn call_counts(&self) -> (usize, u64) {
(
self.exchanges.lock().expect("scripted provider lock").len(),
*self.refreshes.lock().expect("scripted provider lock"),
)
}
fn mint(&self, refresh_token: Option<String>) -> TokenGrant {
let n = self
.counter
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
TokenGrant {
access_token: format!("{}-{n}", self.token_prefix),
refresh_token,
expires_at: Some(Utc::now() + self.grant_ttl),
}
}
fn resolve(
&self,
outcome: ScriptedOutcome,
material: Option<&TokenMaterial>,
) -> std::result::Result<TokenGrant, OAuthFailure> {
match outcome {
ScriptedOutcome::Rotate => {
Ok(self.mint(material.and_then(|m| m.refresh_token.clone())))
}
ScriptedOutcome::Grant(grant) => Ok(grant),
ScriptedOutcome::Fail(failure) => Err(failure),
}
}
}
#[async_trait]
impl OAuthProvider for ScriptedOAuthProvider {
async fn exchange_code(
&self,
code: &str,
scopes: &BTreeSet<String>,
) -> std::result::Result<TokenGrant, OAuthFailure> {
let _ = scopes;
self.exchanges
.lock()
.expect("scripted provider lock")
.push(code.to_owned());
let outcome = self
.codes
.lock()
.expect("scripted provider lock")
.get(code)
.cloned();
match outcome {
Some(outcome) => self.resolve(outcome, None),
None => Err(OAuthFailure::permanent(format!(
"invalid_grant: unknown authorization code `{code}`"
))),
}
}
async fn refresh(
&self,
connection: &ConnectionRecord,
material: &TokenMaterial,
) -> std::result::Result<TokenGrant, OAuthFailure> {
let _ = connection;
*self.refreshes.lock().expect("scripted provider lock") += 1;
let outcome = self
.refresh_script
.lock()
.expect("scripted provider lock")
.pop_front();
self.resolve(outcome.unwrap_or(ScriptedOutcome::Rotate), Some(material))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CredentialRequirement {
pub connection_id: String,
pub scopes: BTreeSet<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IssueRequest {
pub tenant: String,
pub run_id: Option<String>,
pub requirement: CredentialRequirement,
}
#[derive(Clone)]
pub struct ResolvedCredential {
pub connection_id: String,
pub handle_id: String,
pub scopes: BTreeSet<String>,
pub material: TokenMaterial,
}
impl std::fmt::Debug for ResolvedCredential {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ResolvedCredential")
.field("connection_id", &self.connection_id)
.field("handle_id", &self.handle_id)
.field("scopes", &self.scopes)
.field("material", &"[redacted]")
.finish()
}
}
#[async_trait]
pub trait CredentialBroker: std::fmt::Debug + Send + Sync {
async fn issue(
&self,
request: &IssueRequest,
) -> std::result::Result<CredentialHandle, BrokerDenial>;
async fn resolve(
&self,
token: &str,
scopes: &BTreeSet<String>,
) -> std::result::Result<ResolvedCredential, BrokerDenial>;
}
#[async_trait]
pub trait CredentialTool: Tool {
fn credential_requirement(&self, args: &Value) -> CredentialRequirement;
async fn call_authenticated(&self, args: Value, handle: &CredentialHandle) -> Result<Value>;
}
type HandleCache =
HashMap<(Option<String>, String, BTreeSet<String>), (CredentialHandle, DateTime<Utc>)>;
#[derive(Clone)]
pub struct CredentialMediator {
broker: Arc<dyn CredentialBroker>,
tenant: String,
run_id: Option<String>,
handles: Arc<Mutex<HandleCache>>,
}
impl std::fmt::Debug for CredentialMediator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CredentialMediator")
.field("tenant", &self.tenant)
.field("run_id", &self.run_id)
.finish()
}
}
impl CredentialMediator {
pub fn new(broker: Arc<dyn CredentialBroker>, tenant: impl Into<String>) -> Self {
Self {
broker,
tenant: tenant.into(),
run_id: None,
handles: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn for_run(&self, run_id: Option<String>) -> Self {
Self {
broker: Arc::clone(&self.broker),
tenant: self.tenant.clone(),
run_id,
handles: Arc::clone(&self.handles),
}
}
pub fn run_id(&self) -> Option<&str> {
self.run_id.as_deref()
}
pub fn broker(&self) -> &Arc<dyn CredentialBroker> {
&self.broker
}
pub async fn issue(
&self,
requirement: &CredentialRequirement,
) -> std::result::Result<CredentialHandle, BrokerDenial> {
let key = (
self.run_id.clone(),
requirement.connection_id.clone(),
requirement.scopes.clone(),
);
if let Some((handle, renew_after)) = self
.handles
.lock()
.ok()
.and_then(|cache| cache.get(&key).cloned())
{
if Utc::now() < renew_after {
return Ok(handle);
}
}
let handle = self
.broker
.issue(&IssueRequest {
tenant: self.tenant.clone(),
run_id: self.run_id.clone(),
requirement: requirement.clone(),
})
.await?;
let claims = handle.claims();
let ttl = claims.expires_at - claims.issued_at;
let renew_after = claims.issued_at + ttl * 3 / 4;
if let Ok(mut cache) = self.handles.lock() {
cache.insert(key, (handle.clone(), renew_after));
}
Ok(handle)
}
pub fn mediate(&self, tool: Arc<dyn CredentialTool>) -> MediatedTool {
MediatedTool {
inner: tool,
mediator: self.clone(),
}
}
}
pub struct MediatedTool {
inner: Arc<dyn CredentialTool>,
mediator: CredentialMediator,
}
impl std::fmt::Debug for MediatedTool {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MediatedTool")
.field("tool", &self.inner.name())
.finish()
}
}
#[async_trait]
impl Tool for MediatedTool {
fn name(&self) -> &str {
self.inner.name()
}
fn description(&self) -> &str {
self.inner.description()
}
fn parameters_schema(&self) -> Value {
self.inner.parameters_schema()
}
fn effect(&self) -> Effect {
self.inner.effect()
}
fn effect_kind(&self) -> &str {
self.inner.effect_kind()
}
fn idempotency_key(&self, args: &Value) -> Option<String> {
self.inner.idempotency_key(args)
}
fn effect_request(&self, call: &crate::llm::ToolCall) -> crate::effects::EffectRequest {
self.inner.effect_request(call)
}
async fn call(&self, args: Value) -> Result<Value> {
let requirement = self.inner.credential_requirement(&args);
let handle =
self.mediator.issue(&requirement).await.map_err(|denial| {
RustyError::Tool(format!("credential issuance denied: {denial}"))
})?;
self.inner.call_authenticated(args, &handle).await
}
}
#[cfg(feature = "wasm")]
#[derive(Clone)]
pub struct BrokeredCapsuleHost {
host: crate::capsule_host::CapsuleHost,
mediator: CredentialMediator,
}
#[cfg(feature = "wasm")]
impl std::fmt::Debug for BrokeredCapsuleHost {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BrokeredCapsuleHost")
.field("host", &self.host)
.field("mediator", &self.mediator)
.finish()
}
}
#[cfg(feature = "wasm")]
impl BrokeredCapsuleHost {
pub fn new(host: crate::capsule_host::CapsuleHost, mediator: CredentialMediator) -> Self {
Self { host, mediator }
}
pub fn host(&self) -> &crate::capsule_host::CapsuleHost {
&self.host
}
pub async fn invoke(
&self,
invocation: crate::capsule_host::CapsuleInvocation,
) -> Result<crate::capsule_host::CapsuleOutcome> {
use crate::capsule::CapabilityGrant;
use std::collections::BTreeMap;
let connections: Vec<String> = self
.host
.manifest()
.capabilities
.iter()
.flat_map(|grant| match grant {
CapabilityGrant::Secret { handles } => handles.as_slice(),
_ => &[],
})
.cloned()
.collect();
if connections.is_empty() {
return self.host.invoke(invocation).await;
}
let mut input = invocation.input.clone();
match &input {
Value::Object(map) => {
if map.contains_key("secrets") {
return Err(RustyError::Node(
"capsule input already carries a `secrets` key — the host issues those \
tokens; a guest supplying its own is refused at admission"
.to_owned(),
));
}
}
_ => {
return Err(RustyError::Node(
"capsule input must be a JSON object when the manifest grants secrets — \
the host injects handle tokens under the reserved `secrets` key"
.to_owned(),
));
}
}
let run_id = invocation
.journal
.as_ref()
.map(|journal| journal.run_id().to_owned())
.or_else(|| self.mediator.run_id().map(str::to_owned));
let mediator = self.mediator.for_run(run_id);
let mut tokens = BTreeMap::new();
for connection_id in connections {
let requirement = CredentialRequirement {
connection_id: connection_id.clone(),
scopes: BTreeSet::new(),
};
let handle = mediator.issue(&requirement).await.map_err(|denial| {
RustyError::Node(format!(
"capsule secret grant `{connection_id}` failed at the broker: {denial}"
))
})?;
tokens.insert(connection_id, handle.token());
}
if let Value::Object(map) = &mut input {
let value = serde_json::to_value(&tokens).map_err(RustyError::Serialization)?;
map.insert("secrets".to_owned(), value);
}
self.host
.invoke(crate::capsule_host::CapsuleInvocation {
input,
journal: invocation.journal,
parent: invocation.parent,
budget: invocation.budget,
})
.await
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ts(millis: i64) -> DateTime<Utc> {
DateTime::<Utc>::from_timestamp_millis(millis).unwrap()
}
fn record() -> ConnectionRecord {
ConnectionRecord {
connection_id: format!("{}{}", CONNECTION_ID_PREFIX, "a".repeat(32)),
provider: ConnectionProvider::Oauth2AuthorizationCode,
subject: Some("user-7".into()),
scopes: BTreeSet::from(["drive.readonly".to_owned(), "drive.write".to_owned()]),
status: ConnectionStatus::Active,
health: ConnectionHealth::default(),
created_at: ts(1_800_000_000_000),
updated_at: ts(1_800_000_000_000),
}
}
fn claims() -> HandleClaims {
HandleClaims {
handle_id: format!("{}{}", HANDLE_ID_PREFIX, "b".repeat(32)),
connection_id: format!("{}{}", CONNECTION_ID_PREFIX, "a".repeat(32)),
tenant: "acme".into(),
run_id: Some("run-1".into()),
scopes: BTreeSet::from(["drive.readonly".to_owned()]),
issued_at: ts(1_800_000_000_000),
expires_at: ts(1_800_000_300_000),
}
}
#[test]
fn minted_ids_fit_their_grammar() {
let connection = new_connection_id();
let handle = new_handle_id();
assert!(minted_id_ok(CONNECTION_ID_PREFIX, &connection));
assert!(minted_id_ok(HANDLE_ID_PREFIX, &handle));
assert!(record().validate().is_ok());
let mut bad = record();
bad.connection_id = "conn-XYZ".into();
assert!(bad.validate().is_err());
let mut bad = record();
bad.subject = Some("acme/user".into());
assert!(bad.validate().is_err());
let mut bad = record();
bad.scopes.insert("a/b".into());
assert!(bad.validate().is_err());
}
#[test]
fn scope_narrowing_names_exactly_the_missing() {
let ceiling = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
assert!(scopes_missing(&ceiling, &BTreeSet::new()).is_empty());
assert!(scopes_missing(&ceiling, &BTreeSet::from(["a".to_owned()])).is_empty());
assert_eq!(
scopes_missing(&ceiling, &BTreeSet::from(["a".to_owned(), "c".to_owned()])),
vec!["c".to_owned()]
);
}
#[test]
fn token_material_debug_never_shows_bytes() {
let material = TokenMaterial {
access_token: "sk-live-MARKER".into(),
refresh_token: Some("rt-MARKER".into()),
expires_at: Some(ts(1_800_000_300_000)),
client_secret: Some("cs-MARKER".into()),
};
let rendered = format!("{material:?}");
assert!(!rendered.contains("sk-live-MARKER"), "got: {rendered}");
assert!(!rendered.contains("rt-MARKER"), "got: {rendered}");
assert!(!rendered.contains("cs-MARKER"), "got: {rendered}");
assert!(rendered.contains("[redacted]"));
let without = TokenMaterial {
client_secret: None,
..material.clone()
};
let value = serde_json::to_value(&without).unwrap();
assert!(value.get("client_secret").is_none(), "got: {value}");
let with = serde_json::to_value(&material).unwrap();
assert_eq!(with["client_secret"], serde_json::json!("cs-MARKER"));
}
#[tokio::test]
async fn scripted_provider_exchanges_rotates_and_fails_as_scripted() {
let scopes = BTreeSet::from(["drive.readonly".to_owned()]);
let provider = ScriptedOAuthProvider::new()
.with_token_prefix("proof-token")
.with_code(
"code-1",
TokenGrant {
access_token: "exchanged-1".into(),
refresh_token: Some("rt-1".into()),
expires_at: Some(ts(1_800_003_600_000)),
},
)
.then_refresh_failure(OAuthFailure::transient(
ErrorClass::Transient,
"provider 503",
))
.then_refresh_failure(OAuthFailure::permanent("invalid_grant"));
let grant = provider.exchange_code("code-1", &scopes).await.unwrap();
assert_eq!(grant.access_token, "exchanged-1");
let err = provider
.exchange_code("code-unknown", &scopes)
.await
.unwrap_err();
assert!(err.permanent, "got: {err}");
let record = record();
let material = TokenMaterial {
access_token: "old".into(),
refresh_token: Some("rt-1".into()),
expires_at: None,
client_secret: None,
};
let err = provider.refresh(&record, &material).await.unwrap_err();
assert!(!err.permanent, "got: {err}");
let err = provider.refresh(&record, &material).await.unwrap_err();
assert!(err.permanent, "got: {err}");
let rotated = provider.refresh(&record, &material).await.unwrap();
assert_eq!(rotated.access_token, "proof-token-0");
assert_eq!(rotated.refresh_token.as_deref(), Some("rt-1"));
let rotated = provider.refresh(&record, &material).await.unwrap();
assert_eq!(rotated.access_token, "proof-token-1");
assert_eq!(provider.call_counts(), (2, 4));
let rendered = format!("{rotated:?}");
assert!(!rendered.contains("proof-token-1"), "got: {rendered}");
assert!(rendered.contains("[redacted]"));
}
#[test]
fn handle_token_round_trips_and_refuses_forged_shapes() {
let handle = CredentialHandle::from_parts(claims(), "cd".repeat(32));
let token = handle.token();
let (parsed, signature) = CredentialHandle::parse_token(&token).unwrap();
assert_eq!(parsed, claims());
assert_eq!(signature, "cd".repeat(32));
for bad in [
"",
"v2.whatever.sig",
"v1.zzzz.sig",
"v1.aGV4.sig",
&token.replace("v1.", "v0."),
] {
let err = CredentialHandle::parse_token(bad).unwrap_err();
assert!(
matches!(err.reason, BrokerDenialReason::UnknownHandle),
"{bad:?} -> {err:?}"
);
}
let mut bad_claims = claims();
bad_claims.expires_at = bad_claims.issued_at;
let bad = CredentialHandle::from_parts(bad_claims, "cd".repeat(32)).token();
assert!(CredentialHandle::parse_token(&bad).is_err());
let rendered = format!("{handle:?}");
assert!(rendered.contains("handle_id"));
assert!(!rendered.contains(&"cd".repeat(32)), "got: {rendered}");
}
#[test]
fn expiry_is_at_the_instant() {
let claims = claims();
assert!(!claims.is_expired(ts(1_800_000_299_999)));
assert!(claims.is_expired(ts(1_800_000_300_000)));
}
#[test]
fn denial_payloads_are_attributable_and_byte_free() {
let denial = BrokerDenial::connection_revoked(&record(), "acme", "hdl-x");
match &denial.reason {
BrokerDenialReason::ConnectionRevoked { grant } => {
assert_eq!(
grant,
&vec!["drive.readonly".to_owned(), "drive.write".to_owned()]
)
}
other => panic!("expected revoked, got {other:?}"),
}
let value = serde_json::to_value(&denial).unwrap();
assert_eq!(value["reason"], serde_json::json!("connection_revoked"));
assert_eq!(
value["grant"],
serde_json::json!(["drive.readonly", "drive.write"]),
"the internally-tagged reason flattens the revoked grant beside it"
);
assert_eq!(value["tenant"], serde_json::json!("acme"));
}
}