Skip to main content

ruvic-secret-guard

Detecta secretos expuestos (API keys, tokens, contraseñas, llaves privadas, .env…) antes de que salgan: antes de un commit, de construir una imagen Docker, de aceptar una subida o de enviar un texto a otro servicio.

  • Entradas: comprimidos (.zip, .tar, .tar.gz/.tgz, .tar.bz2, .tar.xz, .gz, .bz2, .xz, y derivados de zip como .jar, .whl, .docx), archivos de texto o código, strings de cualquier tamaño, carpetas, bytes y streams.
  • Hecha para hooks: API de Python (ensure_clean, callbacks, fail_fast), CLI con códigos de salida, hook de git pre-commit y soporte para el framework pre-commit.
  • Segura por defecto: nunca devuelve el secreto completo (ghp_************ (40 chars)), no extrae nada a disco y tiene topes contra zip bombs.
  • Sin dependencias: solo la biblioteca estándar. Python 3.10+.

Instalación

pip install ruvic-secret-guard

Se instala como ruvic-secret-guard; en el código se importa como secret_guard y el comando de terminal es secret-guard:

secret-guard --version
python -c "import secret_guard; print(secret_guard.__version__)"

Uso rápido

import secret_guard

# Comprimidos: el formato se detecta por contenido, no por extensión
result = secret_guard.scan_path('build.zip')

# Archivos normales
result = secret_guard.scan_path('src/settings.py')

# Strings (de cualquier tamaño)
result = secret_guard.scan_string(texto)

if not result.is_clean:
    print(result.format_text())
secret-guard: build.zip
2 hallazgo(s) [critical=1, high=1] en 3 elemento(s) escaneado(s); 2 bloqueante(s) (fail_on=high)
  [critical] build.zip!src/app.py:1:10  github-token: Token de GitHub  ghp_************ (40 chars)
  [high] build.zip!.env  dotenv-file: Archivo .env (usa variables de entorno en su lugar)

Todas las entradas

Entrada Función Notas
Ruta (carpeta, archivo o comprimido) scan_path(path) / scan(path) Detecta qué es
Comprimido (obligatorio) scan_archive(path | bytes | stream) UnsupportedFormatError si no lo es
Archivo de texto/código scan_file(path) Se lee en streaming y completo
String scan_string(text, name='<string>') name='app.py' activa heurísticas de ese tipo
Bytes en memoria scan_bytes(data, name='upload.zip') Comprimido o contenido de un archivo
Stream binario scan_stream(fileobj, name=...) Subidas HTTP, sys.stdin.buffer… (sirve aunque no admita seek)
Varios archivos en memoria scan_items({'a.py': b'...', '.env': '...'}) Valores bytes, str o función que devuelva bytes
Varias rutas scan_paths([...]) Un solo resultado

Los comprimidos se recorren sin extraerlos e incluyen comprimidos anidados (release.tar.gz!libs/inner.zip!conf/settings.py), hasta max_archive_depth niveles.


Uso desde hooks

1. Hook de Python: cortar el flujo

from secret_guard import ensure_clean, SecretsDetectedError

def before_docker_build(context_dir: str) -> None:
    ensure_clean(context_dir)          # lanza SecretsDetectedError si hay secretos

try:
    before_docker_build('./app')
except SecretsDetectedError as error:
    print(error)                        # "2 posible(s) secreto(s) ...: src/app.py:1:10, .env"
    for finding in error.result.blocking():
        print(finding.to_dict())        # seguro de registrar o devolver: va enmascarado

Para texto, escanéalo primero: ensure_clean(scan_string(payload)).

2. Hook que recibe una subida

def on_upload(filename: str, payload: bytes):
    result = secret_guard.scan_bytes(payload, name=filename)
    if not result.is_clean:
        return 422, [f.to_dict() for f in result.blocking()]

3. Callback por hallazgo y parada temprana

result = secret_guard.scan_path(
    'dist/',
    on_finding=lambda f: logger.warning(f.format()),   # se llama en cuanto aparece
    fail_fast=True,                                    # se detiene en el primer bloqueante
)

Con fail_fast, el resultado queda truncated=True: solo sabes que hay al menos uno.

4. Hook de git pre-commit

secret-guard install-git-hook          # en la raíz del repo (respeta core.hooksPath)

Escanea lo que está staged (el índice, no la copia de trabajo) y bloquea el commit:

secret-guard: git staged (/ruta/repo)
  [critical] config.py:1:6  github-token: Token de GitHub  ghp_************ (40 chars)
BLOQUEADO: 1 posible(s) secreto(s) con severidad >= high.

Desde Python: secret_guard.scan_git_staged('.').

5. Framework pre-commit

# .pre-commit-config.yaml del proyecto que consume
repos:
  - repo: local
    hooks:
      - id: secret-guard
        name: secret-guard
        entry: secret-guard scan
        language: python
        additional_dependencies: [ruvic-secret-guard]

6. CI o paso previo a docker build

secret-guard scan . --fail-on high || exit 1
docker build -t app .
secret-guard scan build.zip --format json > report.json   # para otras herramientas
cat contexto.tar.gz | secret-guard scan - --name contexto.tar.gz
secret-guard scan --string "$PAYLOAD"

El resultado (ScanResult)

Atributo / método Significado
is_clean No hay hallazgos con severidad ≥ fail_on (default high)
has_secrets Hay al menos un hallazgo, de cualquier severidad
blocking(threshold=None) Hallazgos ≥ umbral
findings Lista de Finding, de más a menos grave
skipped Elementos no escaneados (o no por completo) y su motivo
truncated El escaneo se detuvo antes (fail_fast o límite total)
format_text(), to_dict(), to_json() Salidas listas para usar
ScanResult.merge([...]) Une varios resultados

Cada Finding trae rule_id, severity, source (archivo.zip!ruta/interna), line, column, redacted (enmascarado) y fingerprint (huella estable para allowlists).

Motivos en skipped: binary, too_large, truncated, total_limit, encrypted, unreadable, unsupported_archive:7z|rar, max_depth, too_many_members.

Configuración

from secret_guard import Scanner, ScanConfig, Rule

scanner = Scanner(ScanConfig(
    fail_on='medium',                       # low | medium | high | critical
    max_file_bytes=10 * 1024 * 1024,        # por archivo dentro de carpetas/comprimidos
    max_total_bytes=1024 * 1024 * 1024,     # tope global
    max_archive_depth=3,                    # comprimidos anidados
    ignore_globs=('tests/fixtures/',),
    disabled_rules={'jwt'},
    allowlist={'4ed2f59abee3d436'},         # fingerprints aceptados
    extra_rules=(
        Rule.create('acme-token', r'\b(acme_[A-Za-z0-9]{32})\b',
                    secret_group=1, keywords=['acme_'], severity='critical',
                    description='Token interno ACME'),
    ),
))
scanner.scan_path('build.zip')

Por defecto se omiten node_modules, .venv, venv, __pycache__, .git, entre otros. De .git sí se revisa .git/config, porque suele tener remotes con tokens.

Falsos positivos

  1. En la línea: # secret-guard: ignore (también pragma: allowlist secret y gitleaks:allow).
  2. Archivo .secretguardignore en la raíz de la carpeta, del comprimido o del repo:
    # sin "/": cualquier carpeta o archivo con ese nombre
    fixtures
    # con "/": ruta relativa completa
    docs/examples/*.md
    # terminado en "/": ese directorio entero
    vendor/
    
  3. Por huella: ScanConfig(allowlist={...}) o --allow <fingerprint>.

Qué detecta

secret-guard rules lista todas las reglas. Resumen:

  • critical: llaves privadas PEM/OpenSSH/PGP, AWS Access Key, tokens de GitHub, GitLab, PyPI, llaves live de Stripe, API keys de OpenAI y Anthropic, Azure Storage, llaves SSH (id_rsa).
  • high: Google API/OAuth, Slack, Discord, SendGrid, Twilio, npm, Telegram, Shopify, DigitalOcean, Hugging Face, URLs con usuario y contraseña, cabeceras Authorization, archivos .env, keystores (.p12, .jks, .key), .git-credentials, .netrc, terraform.tfstate.
  • medium: JWT, Mailgun, archivos .pem, .npmrc/.pypirc, y asignaciones genéricas (PASSWORD = "...") con entropía suficiente que no parezcan placeholders.

Las plantillas (.env.example, .env.sample, .env.template) no se marcan. Tampoco valores como changeme, ${VAR}, os.getenv(...), {{ template }} o AKIA...EXAMPLE.

Límites y seguridad

  • No se extrae nada a disco; los miembros se leen en memoria con topes de tamaño. Un tamaño declarado falso (zip/gzip bomb) se corta y queda como truncated.
  • Los symlinks no se siguen.
  • No soporta .7z ni .rar (se reportan como unsupported_archive).
  • Es detección por patrones: no verifica con cada proveedor si el token está activo.
  • Un archivo .secretguardignore dentro del contenido escaneado puede ocultar hallazgos. Los patrones aplicados quedan en result.ignore_patterns; si no confías en quien produce el contenido, usa ScanConfig(use_ignore_file=False).

CLI

secret-guard scan [PATH ...] [--string TEXT] [-]     (o simplemente: secret-guard PATH)
secret-guard git-staged [--repo DIR]
secret-guard install-git-hook [--repo DIR] [--force]
secret-guard rules

Opciones de escaneo: --fail-on, --format text|json, --max-file-size 10MB, --ignore GLOB, --no-ignore-file, --include-dir NAME, --disable-rule ID, --allow FINGERPRINT, --fail-fast, --quiet.

Códigos de salida: 0 limpio · 1 secretos bloqueantes · 2 error.

Desarrollo

python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'
.venv/bin/python -m pytest
.venv/bin/python examples/hooks.py

Metadata

Release files for ruvic-secret-guard 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ruvic-secret-guard 0.1.1
File Size Uploaded Provenance Actions
ruvic_secret_guard-0.1.1.tar.gz 37.5 kB With provenance Details for ruvic_secret_guard-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ruvic-secret-guard 0.1.1
File Interpreter ABI Platform Actions
ruvic_secret_guard-0.1.1-py3-none-any.whl Python 3 none any Details for ruvic_secret_guard-0.1.1-py3-none-any.whl

Total release size: 72.7 kB

Release files / ruvic_secret_guard-0.1.1.tar.gz

Download URL ruvic_secret_guard-0.1.1.tar.gz
Size 37.5 kB
Tags Source
SHA-256 checksum
How to use checksums
affe9785beac9bf7ade096e743751d4806f4289b171ed58140f02ab8c1a09bef
BLAKE2b-256 checksum
How to use checksums
601d6aa0ca1cd6a2cf4d1fac139a2f45be61f115197897030dbeddde64141793
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 12, 2026.

Transparency log

Release files / ruvic_secret_guard-0.1.1-py3-none-any.whl

Download URL ruvic_secret_guard-0.1.1-py3-none-any.whl
Size 35.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5c1ef6a4b035418d4606e04af1dd5b9cbe80fe918722f0ed3ce2c0893ba7dd78
BLAKE2b-256 checksum
How to use checksums
007fea2025afd669609e70ff150a66051b63852c1b095e650d130d8169d87bb4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 12, 2026.

Transparency log

Security for ruvic-secret-guard 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for ruvic_secret_guard-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 12, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page