redact-secret 0.1.0-beta.15

Deterministic secret detection and redaction for runtime data and AI context: scans text locally before it reaches logs, storage, telemetry, tools, or model context. Side-effect free: no runtime network, filesystem, environment, telemetry, secret storage, or UI.
Documentation
//! The default policy: maps finalized safe metadata to an [`Action`] without
//! inspecting the input or any matched value.

use crate::error::PolicyFailure;
use crate::types::{Action, Confidence, DetectedFinding, Policy, PolicyContext};

/// Finding types that are always redacted regardless of confidence, because
/// their format alone is specific enough to be actionable.
///
/// Not every [`Specificity::Provider`](crate::types::Specificity) type is
/// here: `twilio_auth_token`, `twilio_api_key_secret`, `datadog_api_key`,
/// `datadog_application_key_legacy`, `new_relic_license_key`,
/// `mailchimp_api_key`, `mailgun_api_key`, `okta_api_token`,
/// `confluent_cloud_api_secret_legacy`, `heroku_api_key_legacy`,
/// and `travisci_api_token` are deliberately left confidence-gated
/// (redact at [`Confidence::High`], warn otherwise) even though that is a
/// weaker action than their specificity alone would suggest — each has a
/// documented `decision-freeze-*` grammar record (or, for
/// `datadog_application_key_legacy`, `confluent_cloud_api_secret_legacy`,
/// `heroku_api_key_legacy`, `mailchimp_api_key`, `mailgun_api_key`,
/// `okta_api_token` and `travisci_api_token`, its own module doc in
/// `detectors::datadog`, `detectors::confluent`, `detectors::heroku`,
/// `detectors::mailchimp`, `detectors::mailgun`, `detectors::okta` or
/// `detectors::travisci`) explaining why a bare
/// keyword-cooccurrence match at medium confidence is too weak (an opaque
/// bare value sharing a line with a vendor keyword) to redact by default.
/// A keyword elsewhere on the line reports [`Confidence::Medium`] and warns.
/// A value assigned to a key that names the provider reports
/// [`Confidence::High`] (issue #702,
/// `decision-redact-provider-named-credential-assignments`), and so do
/// `okta_api_token` under a same-line `SSWS` scheme and, since issue #936,
/// a value whose structure names its credential slot and binds the provider:
/// the complete `mailchimp_api_key` shape outside a hostname or path, the
/// `heroku_api_key_legacy` `.netrc`/`auth:token`/`authorizations` layouts,
/// the `twilio_auth_token` CLI-table column, the
/// `confluent_cloud_api_secret_legacy` `basic.auth.user.info` property, and
/// a `deepgram_api_key` `Token` header on a request to the Deepgram API
/// host. This default policy already redacts every high finding without
/// needing a carve-out here. Overlap resolution's resolved-action
/// severity ranking
/// (`decision-resolve-overlap-precedence-by-resolved-action-severity`)
/// exists precisely so this list does not have to be exhaustive over every
/// `Provider`/`Structural`/`PrivateKey` type for overlap resolution to stay
/// correct: a confidence-gated type here can still lose an overlap to a
/// stricter-resolving lower-specificity candidate, without needing to be
/// added to this list.
const ALWAYS_REDACT_TYPES: [&str; 143] = [
    "anthropic_admin_api_key",
    "anthropic_api_key",
    "anthropic_enterprise_api_key",
    "apify_api_token",
    "atlassian_api_token",
    "authorization_credential",
    "aws_access_key_id",
    "aws_bedrock_long_term_api_key",
    "aws_bedrock_short_term_api_key",
    "aws_secret_access_key",
    "axiom_api_token",
    "axiom_personal_token",
    "azure_devops_personal_access_token",
    "baseten_api_key",
    "bearer_token",
    "bitwarden_secrets_manager_access_token",
    "browserbase_api_key",
    "buildkite_agent_token",
    "buildkite_api_access_token",
    "buildkite_job_token",
    "buildkite_oauth_token",
    "buildkite_packages_token",
    "buildkite_pipeline_token",
    "buildkite_portal_token",
    "cerebras_api_key",
    "clickhouse_cloud_api_secret",
    "clojars_deploy_token",
    "cloudflare_api_token",
    "composio_org_api_key",
    "composio_project_api_key",
    "composio_user_api_key",
    "confluent_cloud_api_secret",
    "connection_string_password",
    "convex_deployment_key",
    "crates_io_api_token",
    "crates_io_trusted_publishing_token",
    "databricks_personal_access_token",
    "datadog_application_key",
    "daytona_api_key",
    "digitalocean_token",
    "discord_bot_token",
    "docker_token",
    "doppler_audit_token",
    "doppler_cli_token",
    "doppler_personal_token",
    "doppler_scim_token",
    "doppler_service_account_identity_token",
    "doppler_service_account_token",
    "doppler_service_token",
    "dynatrace_token",
    "e2b_api_key",
    "elevenlabs_api_key",
    "firebase_server_key",
    "firecrawl_api_key",
    "fireworks_ai_api_key",
    "fly_access_token",
    "github_app_installation_token",
    "github_app_refresh_token",
    "github_app_user_to_server_token",
    "github_fine_grained_personal_access_token",
    "github_oauth_token",
    "github_token",
    "gitlab_runner_authentication_token",
    "gitlab_token",
    "google_api_key",
    "google_oauth_client_secret",
    "grafana_cloud_access_policy_token",
    "grafana_service_account_token",
    "groq_api_key",
    "helicone_api_key",
    "helicone_write_api_key",
    "heroku_api_key",
    "honeycomb_ingest_key",
    "huggingface_token",
    "inngest_signing_key",
    "jwt",
    "langfuse_secret_key",
    "langsmith_api_key",
    "linear_token",
    "mapbox_secret_access_token",
    "microsoft_entra_client_secret",
    "neon_api_key",
    "netlify_personal_access_token",
    "new_relic_user_api_key",
    "notion_integration_token",
    "npm_access_token",
    "nvidia_api_key",
    "onepassword_service_account_token",
    "openai_admin_api_key",
    "openai_api_key",
    "openrouter_api_key",
    "ory_oauth2_token",
    "ory_session_token",
    "otpauth_secret",
    "paddle_api_key",
    "perplexity_api_key",
    "pinecone_api_key",
    "polar_api_credential",
    "polar_organization_access_token",
    "posthog_personal_api_key",
    "posthog_project_secret_api_key",
    "postman_api_key",
    "postman_collection_access_key",
    "pulumi_access_token",
    "pydantic_logfire_token",
    "pypi_api_token",
    "replicate_api_token",
    "resend_api_key",
    "rubygems_api_key",
    "runpod_api_key",
    "sendgrid_api_key",
    "sentry_org_auth_token",
    "sentry_user_auth_token",
    "shopify_access_token",
    "slack_app_level_token",
    "slack_token",
    "slack_user_token",
    "sonarqube_analysis_token",
    "sonarqube_user_token",
    "sourcegraph_access_token",
    "square_access_token",
    "square_oauth_application_secret",
    "stripe_credential",
    "stripe_webhook_signing_secret",
    "supabase_personal_access_token",
    "supabase_secret_key",
    "tavily_api_key",
    "telegram_bot_token",
    "terraform_cloud_token",
    "together_ai_api_key",
    "trigger_dev_personal_access_token",
    "trigger_dev_secret_api_key",
    "unkey_root_key",
    "vault_token",
    "vendor_prefixed_credential",
    "vercel_app_access_token",
    "vercel_app_refresh_token",
    "vercel_personal_access_token",
    "vercel_token",
    "wandb_api_key",
    "xai_api_key",
    "xata_organization_api_key",
    "xata_user_api_key",
];

/// Chooses the default action for a candidate identified only by `type_name`
/// and `confidence` — the metadata overlap resolution already holds before a
/// [`DetectedFinding`] exists. [`default_action`] is this crate's only other
/// caller; `crate::pipeline` calls this directly so ranking never has to
/// fabricate a placeholder finding just to read a resolved action back out
/// of one.
///
/// - `private_key` always blocks.
/// - Every type in [`ALWAYS_REDACT_TYPES`] always redacts.
/// - Everything else redacts at [`Confidence::High`] and warns otherwise.
#[must_use]
pub(crate) fn default_action_for(type_name: &str, confidence: Confidence) -> Action {
    if type_name == "private_key" {
        return Action::Block;
    }
    if ALWAYS_REDACT_TYPES.contains(&type_name) {
        return Action::Redact;
    }
    if confidence == Confidence::High {
        Action::Redact
    } else {
        Action::Warn
    }
}

#[cfg(test)]
mod pii_policy_tests {
    use super::*;

    #[test]
    fn pii_types_remain_confidence_gated() {
        assert_eq!(
            default_action_for("pii_global_synthetic_identity", Confidence::High),
            Action::Redact
        );
        for confidence in [Confidence::Medium, Confidence::Low] {
            assert_eq!(
                default_action_for("pii_global_synthetic_identity", confidence),
                Action::Warn
            );
        }
    }
}

/// Chooses the default action for `finding`. See [`default_action_for`].
#[must_use]
fn default_action(finding: &DetectedFinding) -> Action {
    default_action_for(finding.type_name(), finding.confidence())
}

/// The default [`Policy`]: deterministic, infallible, and independent of
/// [`PolicyContext`].
///
/// A private key is blocked, a known credential type is redacted at any
/// confidence, and anything else is redacted only at high confidence and
/// warned about otherwise. Because it ignores [`PolicyContext`], it is also
/// a valid [`IncrementalPolicy`](crate::IncrementalPolicy), which cannot
/// know the whole-session finding count.
///
/// # Examples
///
/// ```
/// use redact_secret::{Action, DefaultPolicy, DetectorRegistry, scan};
///
/// let registry = DetectorRegistry::with_built_in([])?;
/// let findings = scan("API_KEY=ghp_SYNTHETICREVOKED00000000000000000000", &registry, &DefaultPolicy)?;
/// assert_eq!(findings[0].action(), Action::Redact);
///
/// // Any `Fn(&DetectedFinding, &PolicyContext) -> Result<Action, _>` is a policy.
/// let block_all = |_: &redact_secret::DetectedFinding, _: &redact_secret::PolicyContext| {
///     Ok(Action::Block)
/// };
/// let findings = scan("API_KEY=ghp_SYNTHETICREVOKED00000000000000000000", &registry, &block_all)?;
/// assert_eq!(findings[0].action(), Action::Block);
/// # Ok::<(), redact_secret::SecretScanError>(())
/// ```
#[derive(Clone, Copy, Debug, Default)]
pub struct DefaultPolicy;

impl Policy for DefaultPolicy {
    fn evaluate(
        &self,
        finding: &DetectedFinding,
        _context: &PolicyContext,
    ) -> Result<Action, PolicyFailure> {
        Ok(default_action(finding))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::ByteRange;

    fn finding(type_name: &str, confidence: Confidence) -> DetectedFinding {
        DetectedFinding::new(
            "finding-1",
            type_name,
            "fixture",
            confidence,
            ByteRange::new(0, 1).unwrap(),
        )
        .unwrap()
    }

    #[test]
    fn blocks_private_keys() {
        let context = PolicyContext::new(0, 1);
        let action = DefaultPolicy
            .evaluate(&finding("private_key", Confidence::Low), &context)
            .unwrap();
        assert_eq!(action, Action::Block);
    }

    #[test]
    fn always_redacts_known_types_at_any_confidence() {
        let context = PolicyContext::new(0, 1);
        for type_name in ALWAYS_REDACT_TYPES {
            let action = DefaultPolicy
                .evaluate(&finding(type_name, Confidence::Low), &context)
                .unwrap();
            assert_eq!(action, Action::Redact, "{type_name}");
        }
    }

    #[test]
    fn redacts_high_confidence_and_warns_otherwise() {
        let context = PolicyContext::new(0, 1);
        assert_eq!(
            DefaultPolicy
                .evaluate(&finding("contextual-secret", Confidence::High), &context)
                .unwrap(),
            Action::Redact
        );
        assert_eq!(
            DefaultPolicy
                .evaluate(&finding("contextual-secret", Confidence::Medium), &context)
                .unwrap(),
            Action::Warn
        );
        assert_eq!(
            DefaultPolicy
                .evaluate(&finding("contextual-secret", Confidence::Low), &context)
                .unwrap(),
            Action::Warn
        );
    }

    #[test]
    fn is_independent_of_policy_context() {
        let finding = finding("contextual-secret", Confidence::High);
        assert_eq!(
            DefaultPolicy
                .evaluate(&finding, &PolicyContext::new(0, 5))
                .unwrap(),
            DefaultPolicy
                .evaluate(&finding, &PolicyContext::new(4, 5))
                .unwrap()
        );
    }
}