Skip to content

Find secrets and confidential data

At the end of this guide you will find API keys, passwords and other credentials in user input, read which rule found them and whether a key is a live or a test key, detect classification markings and confidential document types, switch on extra rule families, and mask findings before a text is written to a log.

The running example: a coding assistant. Developers paste configuration files, stack traces and documents into the chat. The assistant must not send secrets from those pastes to the language model or write them to its logs.

Before you start

  • Install the Python package (pip install patronus-ark) or add the Rust crates patronus-ark and patronus-ark-core; see Installation.
  • Steps 1 to 4, 6 and 7 use only L1: fast rules with validators, no model files and no network. Step 5 downloads a classifier model of about 170 MB from Hugging Face on first use.
  • Two terms used throughout:
    • A category is one kind of risk the scanner checks. This guide uses dlp (data loss prevention: secrets, credentials and classification markings, found by rules) and sensitive_document (what kind of document a text is, found by a model). See Categories.
    • A level is how much work the scanner spends: L1 rules, L2 small classifier models, L3 larger transformer models. dlp runs at L1 only; sensitive_document runs at L2 and L3. See Analysis framework.

All keys and passwords on this page are made up or are publicly documented test values that grant no access.

What dlp finds

By default dlp reports two kinds of findings. The result label is the group of the rule that matched:

Group What it covers
API_KEY Provider-issued API keys, for example of LLM providers.
CLOUD_KEY Cloud access keys and secrets (AWS, Google Cloud, Azure, …).
PAYMENT_KEY Payment provider keys and webhook secrets (Stripe, …).
SECRET_TOKEN OAuth, personal access, bot and bearer tokens, JWTs (GitHub, GitLab, npm, Slack, …).
CREDENTIAL Passwords in assignments, prose and connection strings, URL userinfo, Basic auth, session cookies, signed URLs, OTP seeds.
PASSWORD_HASH Password hashes (bcrypt, Argon2, crypt formats, …).
PRIVATE_KEY PEM private keys and similar key material.
CRYPTO_KEY Wallet private keys and seed phrases (BIP39, Electrum, Monero).
dlp.document.classification_marking Classification markings such as CONFIDENTIAL, STRENG VERTRAULICH or VS-NfD.

Broader families are off by default and switched on one rule at a time: business identifiers (dlp.de.*, dlp.record.*, project and organization IDs), content classes (dlp.content.*: SQL, source code, database dumps, system logs and stack traces) and the other document classes (dlp.document.*: legal, contracts, HR, financials, …). Step 4 shows how.

In total dlp has 176 rules with 34 labels. How the default profile compares with gitleaks, TruffleHog and detect-secrets is on DLP coverage and comparison.

Step 1: Scan a pasted configuration

Create a gateway for the dlp category at max_level l1 and scan what the developer pasted. The gateway is built once and reused for every message.

from patronus_ark import SecurityGateway

scanner = SecurityGateway({"categories": ["dlp"], "max_level": "l1"})

message = (
    "My deploy script fails with 401, here is the config:\n"
    'deploy_token = "7fQ2xLp9Vd4KmZ8rT3wNbH6c"\n'
    'db_password = "Tr0ub4dor&3-horse"\n'
)
for result in scanner.scan_all(message)["native"]:
    print(result["category"], result["level"], result["class_name"], result["confidence"])
    for span in result["evidence_spans"]:
        print("  ", span["label"], "characters", span["start_char"], "to", span["end_char"])
use patronus_ark::{GatewayConfig, SecurityGateway};
use patronus_ark_core::{cascade::SecurityLevel, SecurityCategory};

fn main() {
    let config = GatewayConfig::new(vec![SecurityCategory::Dlp], SecurityLevel::L1);
    let scanner = SecurityGateway::new(config).expect("valid config");

    let message = "My deploy script fails with 401, here is the config:\n\
                   deploy_token = \"7fQ2xLp9Vd4KmZ8rT3wNbH6c\"\n\
                   db_password = \"Tr0ub4dor&3-horse\"\n";
    for result in scanner.scan_all(message).native {
        println!("{} {} {} {}", result.category, result.level, result.class_name, result.confidence);
        for span in &result.evidence_spans {
            println!("   {} bytes {} to {}", span.label, span.start_byte, span.end_byte);
        }
    }
}

Output (Python):

dlp L1 CREDENTIAL 1.0
   CREDENTIAL characters 69 to 93
   CREDENTIAL characters 110 to 127

Output (Rust):

dlp L1 CREDENTIAL 1
   CREDENTIAL bytes 69 to 93
   CREDENTIAL bytes 110 to 127

There is one result for the category. class_name is not safe, so the paste contains a secret; it names one group (CREDENTIAL), and when a text holds findings of several groups it still names only one of them. Read evidence_spans for every finding: each span has the label, the matched text, a score and its position in characters and bytes. Both spans cover only the value between the quotes, not deploy_token = or db_password =. In the default mode strict, every finding scores 1.0.

Step 2: See which rule matched, and whether a key is live

The spans say what was found. The rule details say how: they sit in layers[0]["details"]["matched_rules"], one entry per finding.

from patronus_ark import SecurityGateway

scanner = SecurityGateway({"categories": ["dlp"], "max_level": "l1"})

message = (
    "My deploy script fails with 401, here is the config:\n"
    'deploy_token = "7fQ2xLp9Vd4KmZ8rT3wNbH6c"\n'
    'db_password = "Tr0ub4dor&3-horse"\n'
)
result = scanner.scan_all(message)["native"][0]
for rule in result["layers"][0]["details"]["matched_rules"]:
    print(rule["rule_id"], rule["subtype"], rule.get("provider", "-"), rule["severity"])

Output:

dlp_password_assignment password - live
dlp_generic_credential_assignment generic_secret - live
Field Meaning
rule_id The stable id of the rule. Use it to switch the rule off or on (Step 7).
subtype What the value is within its group: api_key, access_token, secret_key, private_key, password, connection_string, generic_secret, …
provider The provider for provider-bound formats (stripe, github, aws, …); absent for generic rules.
severity test for a provider's publicly documented test key, otherwise live.

Both rules here are generic: they find a secret by the name it is assigned to, not by a provider's key format, so they have no provider. A provider rule names its provider, and a provider's published test key, for example a Stripe test key, is reported with severity test: the assistant can still mask it but does not need to raise an alert. Both values here are live. Each entry also has the byte span, the validator_strength and a source_ref. All subtypes are listed in the DLP taxonomy.

Step 3: Detect classification markings

Developers also paste parts of internal documents. A classification marking (a banner such as CONFIDENTIAL, or a classification field) says the document must not leave the company. Markings are on by default, in English and German.

from patronus_ark import SecurityGateway

scanner = SecurityGateway({"categories": ["dlp"], "max_level": "l1"})

messages = [
    "CONFIDENTIAL\nRelease plan for the new billing service, draft 3.",
    "Einstufung: Streng vertraulich\nMigrationsplan für das Rechenzentrum.",
]
for message in messages:
    for result in scanner.scan_all(message)["native"]:
        print(result["class_name"], [(s["start_char"], s["end_char"]) for s in result["evidence_spans"]])

Output:

dlp.document.classification_marking [(0, 12)]
dlp.document.classification_marking [(12, 30)]

The span is the marking itself (CONFIDENTIAL; Streng vertraulich). A marking counts only where it stands as one: as a banner in capitals on its own line, or as the value of a classification key (Classification:, Einstufung:). The word "confidential" in a normal sentence, a list of levels, or a marking next to words such as "template" or "example" is not reported.

Step 4: Switch on a rule family that is off by default

Content classes such as stack traces, logs, SQL or source code are off by default, because most applications see them all the time. The coding assistant decides that stack traces from its production services should not reach the model, so it switches on the rule dlp_stacktrace_block with the rules key:

from patronus_ark import SecurityGateway

message = """Why does this crash?
Traceback (most recent call last):
  File "/srv/app/billing/invoice.py", line 88, in render
    total = compute(items)
  File "/srv/app/billing/tax.py", line 12, in compute
    raise ValueError("negative amount")
ValueError: negative amount"""

for name, rules in [("default", {}), ("with dlp_stacktrace_block", {"dlp_stacktrace_block": True})]:
    scanner = SecurityGateway({"categories": ["dlp"], "max_level": "l1", "rules": rules})
    for result in scanner.scan_all(message)["native"]:
        print(f"{name}:", result["class_name"], [(s["start_char"], s["end_char"]) for s in result["evidence_spans"]])

Output:

default: safe []
with dlp_stacktrace_block: dlp.content.system_log [(21, 113)]

With the rule on, the trace is reported as dlp.content.system_log. Which families exist, which rules belong to them and a second example (SQL) are in Choose categories & levels: switch on an extra DLP rule; every rule id with its default state is in the L1 rule catalog.

Step 5: Classify confidential documents (sensitive_document)

Rules find secrets and markings, but most confidential documents carry neither: an NDA, an HR review or board minutes are sensitive because of what they are. sensitive_document is a model-backed category: a classifier says which kind of document a text is. Its classes are legal, hr, finance, medical, education, marketing, internal_and_tech, source_code and other.

It has no L1 rules. The L2 model (a small classifier package) answers first; when it is unsure, the text is promoted to the L3 transformer. Allow the download once with "download": "missing" and call warmup().

from patronus_ark import SecurityGateway

scanner = SecurityGateway(
    {"categories": ["sensitive_document"], "max_level": "l3", "download": "missing"}
)
scanner.warmup()

messages = [
    "Can you explain what a for loop does in Python?",
    "Please shorten this: Mutual non-disclosure agreement between Example Corp and Sample Ltd. "
    "The receiving party shall keep all confidential information secret for five years.",
    "Summarise this review: salary adjustment for J. Doe to 68,000 EUR, two warnings for late "
    "attendance, termination to be discussed with HR.",
]
for message in messages:
    print("---")
    for result in scanner.scan_all(message)["native"]:
        print(result["level"], result["model"], result["class_name"], round(result["confidence"], 3))

Output:

---
L2 orca-sonar-document-classifier other 1.0
---
L3 orca-sonar-document-classifier legal 1.0
---
L3 orca-sonar-document-classifier hr 0.993

The question stays at L2 with other. L2 was not sure enough about the NDA and the HR review, so L3 checked them and answered legal and hr. Each category has one final result: when L3 answers, its answer is the result, and level says which level decided. See One result per category.

Use sensitive_document when the question is "may this document leave?" rather than "does it contain a key?", for example to block legal or HR documents from an external model, and combine it with dlp for the secrets inside. It costs model inference on every text (L2 for all, L3 for the unsure ones) and needs its model files: with no cached files and downloads off, it produces no verdict at all. See Manage model assets and Offline & air-gapped scanning.

Step 6: Mask findings before logging

The assistant logs every user message for debugging. Scan with dlp and pii together and log only the masked text. Use character offsets with Python strings and byte offsets with Rust strings. When both categories find something at the same place (a password that looks like part of an e-mail address), the DLP finding owns the range and the overlapping PII span is dropped.

import logging

from patronus_ark import SecurityGateway

logging.basicConfig(format="%(levelname)s %(message)s", level=logging.INFO)
log = logging.getLogger("assistant")


def mask(text, spans):
    """Replace every finding with its label, e.g. [CREDENTIAL]. Overlapping spans are merged."""
    merged = []  # longest span first among those that start together
    for span in sorted(spans, key=lambda s: (s["start_char"], -s["end_char"])):
        if merged and span["start_char"] < merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], span["end_char"])  # overlap: extend
        else:
            merged.append([span["start_char"], span["end_char"], span["label"]])
    out, pos = [], 0
    for start, end, label in merged:
        out.append(text[pos:start])
        out.append(f"[{label}]")
        pos = end
    out.append(text[pos:])
    return "".join(out)


scanner = SecurityGateway({"categories": ["dlp", "pii"], "max_level": "l1"})

message = (
    "Login fails for jane.doe@example.com. "
    "Connection string: postgres://app:Winter-2024-x@db.internal:5432/shop"
)
spans = []
for result in scanner.scan_all(message)["native"]:
    spans.extend(result["evidence_spans"])
log.info("user message: %s", mask(message, spans))
use patronus_ark::{GatewayConfig, SecurityGateway};
use patronus_ark_core::{cascade::SecurityLevel, SecurityCategory};

/// Replace every finding with its label, e.g. `[CREDENTIAL]`. Spans may overlap, so they
/// are sorted and merged first. Rust strings are sliced by byte offsets.
fn mask(text: &str, mut spans: Vec<(usize, usize, String)>) -> String {
    // Longest span first among those that start together.
    spans.sort_by_key(|(start, end, _)| (*start, std::cmp::Reverse(*end)));
    let mut merged: Vec<(usize, usize, String)> = Vec::new();
    for (start, end, label) in spans {
        match merged.last_mut() {
            Some(last) if start < last.1 => last.1 = last.1.max(end), // overlap: extend
            _ => merged.push((start, end, label)),
        }
    }
    let mut out = String::new();
    let mut pos = 0;
    for (start, end, label) in merged {
        out.push_str(&text[pos..start]);
        out.push_str(&format!("[{label}]"));
        pos = end;
    }
    out.push_str(&text[pos..]);
    out
}

fn main() {
    let config = GatewayConfig::new(
        vec![SecurityCategory::Dlp, SecurityCategory::Pii],
        SecurityLevel::L1,
    );
    let scanner = SecurityGateway::new(config).expect("valid config");

    let message = "Login fails for jane.doe@example.com. \
                   Connection string: postgres://app:Winter-2024-x@db.internal:5432/shop";
    let mut spans = Vec::new();
    for result in scanner.scan_all(message).native {
        for span in &result.evidence_spans {
            spans.push((span.start_byte, span.end_byte, span.label.clone()));
        }
    }
    println!("user message: {}", mask(message, spans));
}

Output (Python):

INFO user message: Login fails for [EMAIL]. Connection string: postgres://app:[CREDENTIAL]@db.internal:5432/shop

Output (Rust):

user message: Login fails for [EMAIL]. Connection string: postgres://app:[CREDENTIAL]@db.internal:5432/shop

Only the password inside the connection string is masked; user name, host and database stay readable, which keeps the log useful. Mask before the text reaches any handler, so no log line, trace or error report ever holds the raw value. The personal-data guide uses the same mask function for chat messages.

Step 7: Tune false positives

Values that are not reported on purpose. Documented example values (marked with a word such as EXAMPLE or SAMPLE at the start or end, the way provider documentation marks its sample keys), placeholders and references to an environment variable are not secrets, and the rules leave them out:

from patronus_ark import SecurityGateway

scanner = SecurityGateway({"categories": ["dlp"], "max_level": "l1"})

messages = [
    'deploy_token = "7fQ2xLp9Vd4KmZ8rEXAMPLE"',
    'api_key = "<your-api-key>"',
    "const client = new Client({ password: process.env.DB_PASS });",
]
for message in messages:
    print(scanner.scan_all(message)["native"][0]["class_name"])

Output:

safe
safe
safe

A rule reports values you do not care about. Switch it off by the rule_id from Step 2. For example, if developers paste test fixtures with throw-away passwords all day:

from patronus_ark import SecurityGateway

message = 'In the unit test I use: db_password = "Tr0ub4dor&3-horse"'

for name, rules in [("default", {}), ("rule off", {"dlp_password_assignment": False})]:
    scanner = SecurityGateway({"categories": ["dlp"], "max_level": "l1", "rules": rules})
    print(f"{name}:", scanner.scan_all(message)["native"][0]["class_name"])

Output:

default: CREDENTIAL
rule off: safe

A switched-off rule is off for every text, so prefer narrow switches and keep the provider rules on. Rules can also be switched per request (enqueue(text, execution_gates={"rules": {...}})).

You want scores instead of yes/no. In the default strict mode every finding scores 1.0 so that every match can block. With "dlp_mode": "balanced" (or recall) findings are scored by rule, validator and nearby words, and weak ones without a field name are dropped; see DLP score and modes.

What's next