artifactize-core 0.27.2

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! Protected local credential storage, Codex sign-in, Claude Code's own sign-in (run, never
//! read), saved provider API keys and custom providers, and the remote review store's
//! configuration and token.

pub mod claude_agent;
pub mod codex;
pub mod providers;
pub mod remote;
pub(crate) mod storage;
#[cfg(test)]
mod tests;

use std::path::Path;

use artifactize_provider::auth::Location as CredentialLocation;
use storage::{Location, Tokens};

/// Locate the provider-owned sibling store. This compatibility edge alone knows about the
/// old credential filenames under the engine state; provider never opens that directory.
pub(crate) fn credential_location(
    state: Option<&Path>,
    repo: Option<&Path>,
    tokens: Tokens,
) -> Result<CredentialLocation, String> {
    locate_credential(state, repo, tokens, CredentialAccess::Read)
}

pub(crate) fn writable_credential_location(
    state: Option<&Path>,
    repo: Option<&Path>,
    tokens: Tokens,
) -> Result<CredentialLocation, String> {
    locate_credential(state, repo, tokens, CredentialAccess::Write)
}

#[derive(Clone, Copy)]
enum CredentialAccess {
    Read,
    Write,
}

fn locate_credential(
    state: Option<&Path>,
    repo: Option<&Path>,
    tokens: Tokens,
    access: CredentialAccess,
) -> Result<CredentialLocation, String> {
    let (name, lock) = match tokens {
        Tokens::Providers => ("providers.json", "providers.lock"),
        Tokens::Codex => ("codex.json", "codex.lock"),
        _ => unreachable!("only provider-owned credentials move to the sibling store"),
    };
    let state = crate::store::state_dir(state)?;
    let location = CredentialLocation::beside(&state)?;
    let old = Location::find_in(Some(&state), repo, "auth")?;
    if let Some(refusal) = old.refusal(tokens) {
        return if crate::platform::entry_exists(&old.directory.join(name))
            .map_err(|error| error.to_string())?
        {
            Err(refusal)
        } else {
            Ok(location.refuse(refusal))
        };
    }
    let proposed = Location::at(location.path().to_owned(), repo)?;
    if let Some(refusal) = proposed.refusal(tokens) {
        return Ok(location.refuse(refusal));
    }
    match access {
        CredentialAccess::Write => migrate_credential(&old.directory, location.path(), name, lock)?,
        CredentialAccess::Read => {
            if let Some(bytes) = legacy_snapshot(&old.directory, location.path(), name, lock)? {
                return Ok(location.with_snapshot(name, bytes));
            }
        }
    }
    Ok(location)
}

fn legacy_snapshot(
    old: &Path,
    new: &Path,
    name: &str,
    lock: &str,
) -> Result<Option<Vec<u8>>, String> {
    use std::io::Read;
    let snapshot = || -> std::io::Result<Option<Vec<u8>>> {
        // Once the provider has taken the write lock, that store stays authoritative even
        // after removal. A stale process writing the old path must not restore a sign-in.
        if crate::platform::entry_exists(&new.join(lock))?
            || crate::platform::entry_exists(&new.join(name))?
            || !crate::platform::entry_exists(&old.join(name))?
        {
            return Ok(None);
        }
        let Some(file) = open_legacy_credential(old, name)? else {
            return Ok(None);
        };
        // Same credential-format bound as the provider reader, plus one sentinel byte.
        const SNAPSHOT_BOUND: u64 = 1024 * 1024 + 1;
        let mut bytes = Vec::new();
        file.take(SNAPSHOT_BOUND).read_to_end(&mut bytes)?;
        Ok(Some(bytes))
    };
    snapshot().map_err(|error| error.to_string())
}

fn open_legacy_credential(old: &Path, name: &str) -> std::io::Result<Option<std::fs::File>> {
    use crate::platform;
    if !platform::is_private_dir(old)? {
        return Err(std::io::Error::other(format!(
            "Auth directory must be {}.",
            platform::PRIVATE_DIRECTORY
        )));
    }
    let file = match platform::open_regular(&old.join(name)) {
        Ok(file) => file,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(error) => return Err(error),
    };
    if !platform::is_private_file(&file)? {
        return Err(std::io::Error::other(format!(
            "Auth files must be regular, single-link files {}.",
            platform::PRIVATE_FILE
        )));
    }
    Ok(Some(file))
}

fn migrate_credential(old: &Path, new: &Path, name: &str, lock: &str) -> Result<(), String> {
    use crate::platform;
    let migrate = || -> std::io::Result<()> {
        let source = old.join(name);
        if !platform::entry_exists(&source)? {
            return Ok(());
        }
        if platform::entry_exists(&new.join(lock))? || platform::entry_exists(&new.join(name))? {
            return Ok(());
        }
        let Some(file) = open_legacy_credential(old, name)? else {
            return Ok(());
        };
        drop(file);
        let _legacy = platform::paths::lock_file(&old.join(lock))?;
        let Some(file) = open_legacy_credential(old, name)? else {
            return Ok(());
        };
        platform::create_private_dir_all(new)?;
        if !platform::is_private_dir(new)? {
            return Err(std::io::Error::other(format!(
                "Auth directory must be {}.",
                platform::PRIVATE_DIRECTORY
            )));
        }
        let _new = platform::paths::lock_file(&new.join(lock))?;
        let destination = new.join(name);
        drop(file);
        if !platform::entry_exists(&destination)? {
            platform::paths::rename_open_file(&source, &destination)?;
            platform::sync_dir(new)?;
            platform::sync_dir(old)?;
        }
        Ok(())
    };
    migrate().map_err(|error| error.to_string())
}

pub use artifactize_provider::secret::Inventory as ManagedSecrets;

/// Managed credentials for boundary scrubbing; their values never leave the inventory.
pub fn managed_secrets(
    state: Option<&Path>,
    repo: Option<&Path>,
) -> Result<ManagedSecrets, String> {
    let providers = credential_location(state, repo, Tokens::Providers)?;
    let codex = credential_location(state, repo, Tokens::Codex)?;
    ManagedSecrets::try_read(Some(&providers), Some(&codex))
}