← Configuration contracts in CI: comparing JSON and .env keys without leaking values
Configuration contracts in CI: comparing JSON and .env keys without leaking values
English ↔ Español
The problem is not just an invalid file
A project can compile and still load configuration that is incompatible with the environment where it will run. A variable documented in .env.example is no longer created by the pipeline; a production JSON file gains a key that never reached staging; a configuration template changes silently and deployment discovers the mismatch only when the application starts.
These are forms of configuration drift: two files that should follow the same contract stop agreeing. Traditional syntax validation does not solve this. Two JSON documents can both be valid and still describe different structures. Two .env files can be acceptable as text while declaring incompatible sets of variables.
Resource Contract Checks was built for this narrow space: compare JSON structures and check .env variable-name contracts, both locally and through a GitHub Action. The implementation is also bundled in the portfolio's free tools collection. It is not meant to replace JSON Schema, a complete dotenv parser, or a secret scanner. Its job is to make a configuration difference visible before it slips through review.
Two modes, two kinds of contract
The tool receives two files: a reference and a candidate. The selected mode defines what “compatible” means.
JSON: compare structure, not a schema
The json mode parses both documents and walks their structures recursively. Object keys are compared independently of their textual order; arrays remain order-sensitive. For every difference, the engine records a path and a kind: added, removed, or changed.
An illustrative CLI result can look like this:
{
"changes": [
{ "path": "/service/timeout", "kind": "changed", "before": 3000, "after": 5000 },
{ "path": "/features/retry", "kind": "added", "after": true }
],
"truncated": false
}
Paths follow JSON Pointer: each segment starts with /, ~ becomes ~0, and / inside a key becomes ~1. This matters when property names contain those characters; concatenating keys without escaping would create ambiguous paths. The rule comes from RFC 6901.
There is also a numeric-safety check. The engine verifies whether converting a JSON numeric literal to JavaScript Number loses precision. It rejects non-finite values, integers outside the safe range, and decimals whose normalized representation changes. This avoids presenting a rounded value as a trustworthy equality or difference. RFC 8259 notes that JSON number range and precision depend on implementation capabilities; for identifiers and exact decimal values, strings or an explicit decimal type are often a better choice.
The engine limits each input to 200,000 text units, rejects structures deeper than 100 levels, and stores at most 500 changes. Once the change limit is reached, truncated becomes true; the result is no longer a complete list. These limits are intentional: a configuration comparator should not consume unbounded resources because someone added a huge or deeply nested document.
.env: compare key names, not values
The env mode answers a different question: do both configurations declare the same variables? It ignores blank lines and comments, accepts a basic NAME=... assignment and the export NAME=... form, and collects only the identifier before the equals sign.
It can therefore report missing keys, extra keys, duplicates, and lines that do not follow the expected basic format. Values are not part of the comparison. Two files containing DATABASE_URL and PAYMENT_TOKEN can have completely different values and still satisfy the same key-name contract.
That behavior is deliberate, but it has an important boundary: this is not a full shell parser or a complete implementation of every dotenv convention. It does not expand ${VAR}, evaluate commands, interpret escapes, or validate whether a URL, port, or secret has a correct value. It checks the presence and basic shape of declarations, not the semantics of their values.
The CLI and GitHub Action have different output profiles
The same engine is used by a Node.js CLI and a composite Action. The CLI is suitable for local inspection and custom automation:
node tools/bin/resource-tools.mjs env .env.example .env.ci
node tools/bin/resource-tools.mjs json config/default.json config/ci.json
It can also read one input from stdin by using - once. Files must be regular files, decoding requires valid UTF-8, and the 200,000-byte limit is checked again while reading—not only from the file's initial size. This helps handle a file that grows after stat and avoids blocking indefinitely on a FIFO.
The CLI returns stable exit codes: 0 for equality or a valid contract, 1 for differences, and 2 for invalid input or incorrect usage. In .env mode, the local report may show key names and line numbers, but not values. In JSON mode, the detailed report includes paths and before/after values. The CLI's JSON output can therefore contain sensitive data: do not redirect it to public logs without reviewing the content.
The GitHub Action uses a narrower output policy. Its action.yml defines a composite action with three inputs—tool, reference, and candidate—and passes them to the process through environment variables rather than interpolating them into a shell command. The runner uses Node.js 20 or newer and Bash; the package already includes the CLI and engine, installs no dependencies, and makes no network requests during the check.
The Action runner writes only status and counts to GITHUB_STEP_SUMMARY. For JSON, it reports the number of differences and whether the list was truncated. For .env, it reports counts of missing and extra keys, duplicates, and invalid lines. It does not publish paths, key names, file snippets, or values. The status and exit-code outputs are available to later steps.
This reduces the chance that a CI summary becomes an accidental disclosure channel; it does not turn the runner into a security boundary. The files remain in the workspace, the process must read them, and other steps in the same job may have access to the environment and working directory. Avoid placing real secrets in test files when placeholders are sufficient. Keep the distinction clear: the Action summary is aggregated, but the CLI's JSON report is not redacted.
The Action tests exercise this boundary: an .env case checks that strings used as secrets do not appear in the summary or stdout; another tries to inject arguments as commands; and a JSON case confirms that the summary contains counts rather than values. These tests make the intended guarantees verifiable, but they do not prove total security for the runner or other workflow steps.
Integrating it into a pipeline
A minimal workflow can check the presence of environment keys on every pull request:
name: configuration-contracts
on: [pull_request]
permissions:
contents: read
jobs:
contracts:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check environment key contract
uses: owner/repo@FULL_SHA
with:
tool: env
reference: .env.example
candidate: .env.ci
Replace the owner/repo@FULL_SHA placeholder with YagoLagrottiBracco/resource-contract-checks@44b484f7eba8e5b074713eb753e2ae18db434aa6 to pin this release to a full commit. In production, do the same for actions/checkout and other dependencies: tags are convenient, but a mutable branch or tag does not offer the same reproducibility as a reviewed SHA. GitHub recommends pinning actions to full SHAs when stability and security are priorities; it also recommends auditing third-party action code and granting only the permissions required. See Metadata syntax, Secure use, and Workflow syntax.
To compare JSON, reuse the step and change tool: env to tool: json, with reference: config/default.json and candidate: config/ci.json. Both files must already exist in the workspace; the Action does not download them or discover them automatically. If the candidate is generated during the job, generate it before the comparison step. If the configuration contains credentials, prefer building a synthetic version with dummy values. The .env comparator only needs names, but the entire file still passes through the local process.
The repository's own workflow runs tests in a Node.js 20 and 22 matrix and invokes the Action with synthetic .env files. The public execution recorded on October 17, 2026 completed successfully for the documented CI jobs. This verifies that particular workflow; it is not evidence of tested compatibility on every operating system or adoption by third parties.
What the tool does not promise
A small comparator should not be turned into a universal configuration solution.
- It does not validate JSON Schema. If you need types, required properties, enumerations, limits, or API-version compatibility, use JSON Schema with a validator such as Ajv. Comparing two examples is not a substitute for a formal contract.
- It does not understand every dotenv dialect. For variable expansion, escapes, multiline quoting, or runtime-specific rules, use the parser used by the application itself. This regular expression checks names; it is not a complete grammar.
- It is not a secret scanner. The
.envmode does not inspect values; the JSON mode can show them in local output. Use dedicated credential-detection tools and repository secret policies. - It is not an unlimited diff. There are size, depth, and change-count limits. A truncated result must be treated as a difference, not proof that every change was listed.
- It does not resolve domain semantics. Two URLs may differ and both be valid; two ports may exist but point to the wrong services. That requires contextual validation, not structural comparison.
There is also a common JSON.parse limitation: duplicate keys inside the same object are not reported as an error by this engine. If duplicate properties matter to your contract, add a parsing stage that detects them before comparison. For financial numbers, do not rely on Number as an exact decimal representation; model units and precision explicitly.
Release, supply chain, and actual status
Version 1.0.0 was published on October 17, 2026, with v1 and v1.0.0 tags, an MIT license, and an attached distribution ZIP. The README recommends pinning the reviewed full SHA. A GitHub Marketplace listing is not claimed. The code is available in the repository, and the copy bundled with the portfolio lives in packages/resource-action.
The value of a small Action is not replacing an organization's configuration system. It is putting a low-cost check where drift can still be fixed: before merge. The security boundary, however, must be designed by whoever maintains the workflow. A summary without values is a useful exposure reduction; least-privilege permissions, pinned dependencies, synthetic files, and code review are still necessary.
Sources and implementation
- Resource Contract Checks — source and release 1.0.0
- JSON and
.envengine - CLI and input reading
- Action runner and tests
- RFC 6901 — JSON Pointer and RFC 8259 — JSON
- GitHub Actions: metadata, security, and workflow commands
The release and workflow were checked in the repository on November 12, 2026. This article describes the published code and tests; it makes no claims about adoption metrics, savings, avoided incidents, or validation in customer environments.
El problema no es solo un archivo inválido
Un proyecto puede compilar y aun así cargar una configuración incompatible con el entorno donde se ejecutará. Una variable documentada en .env.example deja de crearse en el pipeline; un archivo JSON de producción incorpora una clave que nunca llegó a staging; una plantilla de configuración cambia en silencio y el despliegue descubre la diferencia cuando la aplicación arranca.
Son formas de configuration drift: dos archivos que deberían respetar el mismo contrato dejan de coincidir. La validación sintáctica tradicional no lo resuelve. Dos documentos JSON pueden ser válidos y describir estructuras distintas. Dos archivos .env pueden tener un formato aceptable como texto, pero declarar conjuntos de variables incompatibles.
Resource Contract Checks se creó para cubrir ese espacio concreto: comparar estructuras JSON y verificar contratos de nombres de variables .env, tanto localmente como mediante una GitHub Action. La implementación también está empaquetada en la colección de herramientas gratuitas del portafolio. No pretende sustituir JSON Schema, un parser completo de dotenv ni un detector de secretos. Su función es hacer visible una diferencia de configuración antes de que pase inadvertida durante la revisión.
Dos modos, dos tipos de contrato
La herramienta recibe dos archivos: una referencia y un candidato. El modo elegido determina qué significa “compatible”.
JSON: comparar estructuras, no validar un schema
El modo json analiza ambos documentos y recorre sus estructuras de forma recursiva. Las claves de los objetos se comparan sin depender de su orden textual; los arrays siguen siendo sensibles al orden. Para cada diferencia, el motor registra una ruta y un tipo: added, removed o changed.
Un resultado ilustrativo de la CLI puede parecerse a este:
{
"changes": [
{ "path": "/service/timeout", "kind": "changed", "before": 3000, "after": 5000 },
{ "path": "/features/retry", "kind": "added", "after": true }
],
"truncated": false
}
Las rutas siguen JSON Pointer: cada segmento comienza con /, ~ se convierte en ~0 y / dentro de una clave se convierte en ~1. Esto importa cuando los nombres de propiedades contienen esos caracteres; concatenar claves sin escape produciría rutas ambiguas. La regla procede de la RFC 6901.
También existe una comprobación de seguridad numérica. El motor verifica si convertir un literal numérico JSON a Number de JavaScript pierde precisión. Rechaza valores no finitos, enteros fuera del rango seguro y decimales cuya representación normalizada cambia. Así evita presentar un valor redondeado como una igualdad o diferencia fiable. La RFC 8259 señala que el rango y la precisión de los números JSON dependen de las capacidades de cada implementación; para identificadores y valores decimales exactos, las cadenas o un tipo decimal explícito suelen ser una opción mejor.
El motor limita cada entrada a 200.000 unidades de texto, rechaza estructuras con más de 100 niveles de profundidad y almacena como máximo 500 diferencias. Al alcanzar el límite de cambios, truncated pasa a true; el resultado deja de ser una lista completa. Son límites intencionales: un comparador de configuración no debería consumir recursos sin control porque alguien añadió un documento enorme o demasiado anidado.
.env: comparar nombres de claves, no valores
El modo env responde a otra pregunta: ¿ambas configuraciones declaran las mismas variables? Ignora líneas vacías y comentarios, acepta una asignación básica NOMBRE=... y la forma export NOMBRE=..., y recoge únicamente el identificador anterior al signo igual.
Por eso puede informar claves ausentes, adicionales, duplicadas y líneas que no siguen el formato básico esperado. Los valores no forman parte de la comparación. Dos archivos que contienen DATABASE_URL y PAYMENT_TOKEN pueden tener valores completamente distintos y aun así cumplir el mismo contrato de nombres.
Ese comportamiento es deliberado, pero tiene un límite importante: no es un parser completo de shell ni una implementación integral de todas las convenciones de dotenv. No expande ${VAR}, no evalúa comandos, no interpreta escapes ni valida si una URL, un puerto o un secreto tienen un valor correcto. Comprueba la presencia y la forma básica de las declaraciones, no la semántica de sus valores.
La CLI y la GitHub Action tienen perfiles de salida distintos
El mismo motor se utiliza desde una CLI de Node.js y una Action compuesta. La CLI sirve para inspección local y automatizaciones propias:
node tools/bin/resource-tools.mjs env .env.example .env.ci
node tools/bin/resource-tools.mjs json config/default.json config/ci.json
También permite leer una entrada desde stdin usando - una sola vez. Los archivos deben ser regulares, la decodificación exige UTF-8 válido y el límite de 200.000 bytes se vuelve a comprobar durante la lectura, no solo a partir del tamaño inicial del archivo. Esto ayuda a manejar un archivo que crece después de stat y evita quedar bloqueado indefinidamente esperando una FIFO.
La CLI devuelve códigos de salida estables: 0 para igualdad o contrato válido, 1 para diferencias y 2 para entrada inválida o uso incorrecto. En el modo .env, el informe local puede mostrar nombres de claves y números de línea, pero no valores. En el modo JSON, el informe detallado incluye rutas y valores before/after. Por tanto, la salida JSON de la CLI puede contener datos sensibles: no la redirijas a logs públicos sin revisar el contenido.
La GitHub Action utiliza una política de salida más limitada. Su action.yml define una composite action con tres entradas —tool, reference y candidate— y las pasa al proceso mediante variables de entorno, sin interpolarlas en un comando de shell. El runner utiliza Node.js 20 o superior y Bash; el paquete ya incluye la CLI y el motor, no instala dependencias y no realiza solicitudes de red durante la comprobación.
El runner de la Action escribe en GITHUB_STEP_SUMMARY únicamente el estado y los recuentos. Para JSON informa la cantidad de diferencias y si la lista quedó truncada. Para .env informa cuántas claves faltan o sobran, cuántos duplicados y cuántas líneas inválidas existen. No publica rutas, nombres de claves, fragmentos de archivos ni valores. Las salidas status y exit-code quedan disponibles para los pasos siguientes.
Esto reduce la posibilidad de que un resumen de CI se convierta en un canal accidental de exposición; no convierte al runner en una frontera de seguridad. Los archivos siguen en el workspace, el proceso debe leerlos y otros pasos del mismo job pueden tener acceso al entorno y al directorio de trabajo. Evita colocar secretos reales en archivos de prueba cuando bastan valores ficticios. Mantén clara la diferencia: el resumen de la Action es agregado, pero el informe JSON de la CLI no está redactado.
Las pruebas de la Action ejercitan esta frontera: un caso .env comprueba que las cadenas usadas como secretos no aparecen en el resumen ni en stdout; otro intenta inyectar argumentos como comandos; y un caso JSON confirma que el resumen muestra recuentos, no valores. Estas pruebas hacen verificables las garantías previstas, pero no demuestran la seguridad total del runner ni de los demás pasos del workflow.
Integrarlo en el pipeline
Un workflow mínimo puede comprobar la presencia de claves de entorno en cada pull request:
name: configuration-contracts
on: [pull_request]
permissions:
contents: read
jobs:
contracts:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check environment key contract
uses: owner/repo@FULL_SHA
with:
tool: env
reference: .env.example
candidate: .env.ci
Sustituye el marcador owner/repo@FULL_SHA por YagoLagrottiBracco/resource-contract-checks@44b484f7eba8e5b074713eb753e2ae18db434aa6 para fijar esta release a un commit completo. En producción, haz lo mismo con actions/checkout y las demás dependencias: las etiquetas son cómodas, pero una rama o etiqueta mutable no ofrece la misma reproducibilidad que un SHA revisado. GitHub recomienda fijar las acciones a SHA completos cuando la estabilidad y la seguridad son prioritarias; también recomienda auditar el código de acciones de terceros y conceder solo los permisos necesarios. Consulta Metadata syntax, Secure use y Workflow syntax.
Para comparar JSON, reutiliza el paso y cambia tool: env por tool: json, con reference: config/default.json y candidate: config/ci.json. Ambos archivos deben existir en el workspace; la Action no los descarga ni los descubre automáticamente. Si el candidato se genera durante el job, créalo antes del paso de comparación. Si la configuración contiene credenciales, es preferible construir una versión sintética con valores ficticios. El comparador .env solo necesita los nombres, pero el archivo completo sigue pasando por el proceso local.
El workflow del propio repositorio ejecuta las pruebas en una matriz de Node.js 20 y 22 y llama a la Action con archivos .env sintéticos. La ejecución pública registrada el 17 de octubre de 2026 terminó correctamente en los trabajos de CI documentados. Esto verifica ese workflow concreto; no demuestra compatibilidad probada en todos los sistemas operativos ni adopción por terceros.
Lo que la herramienta no promete
Un comparador pequeño no debe convertirse en una solución universal de configuración.
- No valida JSON Schema. Si necesitas tipos, propiedades obligatorias, enumeraciones, límites o compatibilidad entre versiones de API, utiliza JSON Schema con un validador como Ajv. Comparar dos ejemplos no sustituye un contrato formal.
- No entiende todos los dialectos dotenv. Para expansión de variables, escapes, comillas multilínea o reglas específicas del runtime, utiliza el parser de la propia aplicación. Esta expresión regular comprueba nombres; no es una gramática completa.
- No es un detector de secretos. El modo
.envno inspecciona los valores; el modo JSON puede mostrarlos en la salida local. Utiliza herramientas específicas de detección de credenciales y políticas de secretos del repositorio. - No es un diff ilimitado. Existen límites de tamaño, profundidad y cantidad de cambios. Un resultado truncado debe tratarse como una diferencia, no como prueba de que se enumeraron todos los cambios.
- No resuelve la semántica del dominio. Dos URL pueden ser diferentes y ambas válidas; dos puertos pueden existir y apuntar a servicios incorrectos. Eso exige validación contextual, no comparación estructural.
También existe una limitación habitual de JSON.parse: este motor no informa como error las claves duplicadas dentro de un mismo objeto. Si la duplicidad de propiedades importa para tu contrato, añade una etapa de análisis que las detecte antes de comparar. Para números financieros, no confíes en Number como representación decimal exacta; modela explícitamente la unidad y la precisión.
Release, cadena de suministro y estado real
La versión 1.0.0 se publicó el 17/10/2026, con las etiquetas v1 y v1.0.0, licencia MIT y un ZIP de distribución adjunto. El README recomienda fijar el SHA completo revisado. No se afirma que exista una ficha en GitHub Marketplace. El código está disponible en el repositorio, y la copia integrada en el portafolio se encuentra en packages/resource-action.
El valor de una Action pequeña no está en sustituir el sistema de configuración de una organización. Está en colocar una comprobación barata donde el drift todavía puede corregirse: antes del merge. Sin embargo, la frontera de seguridad debe diseñarla quien mantiene el workflow. Un resumen sin valores reduce la exposición; los permisos mínimos, las dependencias fijadas, los archivos sintéticos y la revisión del código siguen siendo necesarios.
Fuentes e implementación
- Resource Contract Checks — código y release 1.0.0
- Motor JSON y
.env - CLI y lectura de entradas
- Runner de la Action y pruebas
- RFC 6901 — JSON Pointer y RFC 8259 — JSON
- GitHub Actions: metadata, seguridad y comandos de workflow
La release y el workflow se revisaron en el repositorio el 12/11/2026. Este artículo describe el código y las pruebas publicadas; no afirma métricas de adopción, ahorros, incidentes evitados ni validación en entornos de clientes.