aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
Documentation
//! The fake vault tests script.
//!
//! Compiled only under `cfg(test)` or the `secret-test-fake` feature, which no
//! release profile enables (`scripts/check-secret-test-fake.sh` checks that in
//! CI). Nothing in config, an environment variable or a project setting can
//! select it: a caller has to install it explicitly.

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};

use secret_rules::audit::AuditRecordV1;
use secret_rules::location::LabelRule;

use super::{AuditError, Material, SecretVault, UseAnswer};
use crate::secret::wire::ApprovalRequest;
use crate::secret::SecretScope;
use crate::secret::{ApiKeyTarget, ReleasedApiKey};

/// Everything a test makes the fake say, plus the record of what it was asked.
#[derive(Default)]
pub struct FakeVaultScript {
    /// The reply to a secret-use request for this label. Missing entries are unavailable.
    pub answers: HashMap<String, FakeReply>,
    /// Released bytes per label, advancing once per matching request to exercise
    /// key rotation. After the list runs out, repeat its last value.
    pub material: HashMap<String, Vec<Vec<u8>>>,
}

#[derive(Clone, Debug)]
pub enum FakeReply {
    Rule(LabelRule),
    ApprovalRequired(ApprovalRequest),
    NotFound,
    Unavailable,
}

struct FakeVaultState {
    script: FakeVaultScript,
    /// One label per secret-use request, in call order.
    resolves: Vec<String>,
    /// One label per request matching a stored host/path rule, in call order.
    materials: Vec<String>,
    /// Material calls already served per label, so rotation advances.
    served: HashMap<String, usize>,
    /// Audit records the fake collected, in emission order.
    audit: Vec<AuditRecordV1>,
}

impl std::fmt::Debug for FakeVaultState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FakeVaultState")
            .field("resolves", &self.resolves.len())
            .field("materials", &self.materials.len())
            .field("audit_len", &self.audit.len())
            .finish()
    }
}

/// The test-only vault.
#[derive(Debug, Clone)]
pub struct FakeVault {
    state: Arc<Mutex<FakeVaultState>>,
    resolve_count: Arc<AtomicU64>,
    material_count: Arc<AtomicU64>,
    audit_count: Arc<AtomicU64>,
}

impl Default for FakeVault {
    fn default() -> Self {
        Self::new()
    }
}

impl FakeVault {
    /// A vault that answers `Unavailable` to everything.
    pub fn new() -> Self {
        Self::with_script(FakeVaultScript::default())
    }

    /// A vault that answers from `script`.
    pub fn with_script(script: FakeVaultScript) -> Self {
        Self {
            state: Arc::new(Mutex::new(FakeVaultState {
                script,
                resolves: Vec::new(),
                materials: Vec::new(),
                served: HashMap::new(),
                audit: Vec::new(),
            })),
            resolve_count: Arc::new(AtomicU64::new(0)),
            material_count: Arc::new(AtomicU64::new(0)),
            audit_count: Arc::new(AtomicU64::new(0)),
        }
    }

    fn lock(&self) -> MutexGuard<'_, FakeVaultState> {
        self.state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Choose the reply for `label`.
    pub fn set_answer(&self, label: &str, answer: FakeReply) {
        self.lock().script.answers.insert(label.to_string(), answer);
    }

    /// The bytes released for `label`, in call order.
    pub fn set_material(&self, label: &str, values: Vec<Vec<u8>>) {
        self.lock()
            .script
            .material
            .insert(label.to_string(), values);
    }

    /// Labels that reached material release, in order.
    pub fn materials(&self) -> Vec<String> {
        self.lock().materials.clone()
    }

    /// How many secret-use requests were made.
    pub fn use_calls(&self) -> u64 {
        self.resolve_count.load(Ordering::SeqCst)
    }

    /// How many requests matched a stored host/path rule and asked for material.
    pub fn material_calls(&self) -> u64 {
        self.material_count.load(Ordering::SeqCst)
    }

    /// How many times `audit` was called.
    pub fn audit_calls(&self) -> u64 {
        self.audit_count.load(Ordering::SeqCst)
    }

    /// The audit records the fake collected.
    pub fn audit_records(&self) -> Vec<AuditRecordV1> {
        self.lock().audit.clone()
    }

    /// The labels of the collected audit records with their decisions, in
    /// emission order.
    pub fn audit_summary(&self) -> Vec<(String, secret_rules::audit::Decision)> {
        self.lock()
            .audit
            .iter()
            .map(|record| (record.label.clone(), record.decision))
            .collect()
    }

    /// The next bytes for `label`, honouring rotation.
    fn next_material(&self, label: &str) -> Option<Material> {
        let mut state = self.lock();
        state.materials.push(label.to_string());
        let Some(count) = state.script.material.get(label).map(Vec::len) else {
            return None;
        };
        if count == 0 {
            return None;
        }
        let index = {
            // Repeated requests may receive rotated bytes even with the same rule.
            let served = state.served.entry(label.to_string()).or_insert(0);
            let index = (*served).min(count - 1);
            *served += 1;
            index
        };
        let bytes = state.script.material[label][index].clone();
        Some(Material::new(bytes))
    }
}

impl SecretVault for FakeVault {
    fn use_secret(&self, _scope: &SecretScope, label: &str, target: &ApiKeyTarget) -> UseAnswer {
        self.resolve_count.fetch_add(1, Ordering::SeqCst);
        let answer = {
            let mut state = self.lock();
            state.resolves.push(label.to_string());
            state
                .script
                .answers
                .get(label)
                .cloned()
                .unwrap_or(FakeReply::Unavailable)
        };
        match answer {
            FakeReply::Rule(rule) => {
                let request = secret_rules::target::RequestTarget {
                    host: target.host.clone(),
                    port: target.port.unwrap_or(443),
                    scheme: &target.scheme,
                    target: &target.path,
                };
                if request
                    .matches(&secret_rules::target::RuleTarget {
                        host: &rule.host,
                        port: rule.port,
                        path_prefix: &rule.path_prefix,
                    })
                    .is_err()
                {
                    return UseAnswer::NotFound;
                }
                self.material_count.fetch_add(1, Ordering::SeqCst);
                match self.next_material(label) {
                    Some(material) => UseAnswer::Released(ReleasedApiKey::new(
                        location_text(&rule.location),
                        material,
                    )),
                    None => UseAnswer::Unavailable,
                }
            }
            FakeReply::ApprovalRequired(pending) => UseAnswer::ApprovalRequired(pending),
            FakeReply::NotFound => UseAnswer::NotFound,
            FakeReply::Unavailable => UseAnswer::Unavailable,
        }
    }

    fn audit(&self, record: &AuditRecordV1) -> Result<(), AuditError> {
        self.audit_count.fetch_add(1, Ordering::SeqCst);
        // The crate's writer runs the key check, so a record that reaches the
        // fake's collection has passed the same test a production sink would.
        if !record.scope.as_ref().is_none_or(|scope| scope.is_valid()) {
            return Err(AuditError::Invalid {
                detail: "scope is not plain text".into(),
            });
        }
        self.lock().audit.push(record.clone());
        Ok(())
    }
}

/// A matching record for an addressed test call.
pub fn granted(mut rule: LabelRule) -> FakeReply {
    rule.port = 443;
    FakeReply::Rule(rule)
}

pub(crate) fn location_text(location: &secret_rules::location::Location) -> String {
    use secret_rules::location::Location;
    match location {
        Location::Bearer => "authorization_bearer".into(),
        Location::Header(name) => format!("header:{name}"),
        Location::Query(name) => format!("query:{name}"),
        Location::Json(pointer) => format!("json_pointer:{pointer}"),
    }
}

/// A pending approval for tests.
pub fn approval(request_id: &str) -> ApprovalRequest {
    ApprovalRequest {
        request_id: request_id.to_string(),
        statement_b64url: "c3RhdGVtZW50".into(),
        expires_at_ms: 0,
    }
}