OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Audit required configuration keys without exposing values with Python

Python

Report missing and empty required names, duplicate assignment positions and unknown keys under one literal assignment contract.

Python code excerpt: Audit required configuration keys without exposing values with Python. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Report missing and empty required names, duplicate assignment positions and unknown keys under one literal assignment contract. Uses saved stdin text; never reads the real process environment.

Before you start

  • Save the code as recipe.py. Python 3.12 is required: python3 must resolve to Python 3.12 when running python3 recipe.py < input.txt. Pass no CLI arguments; the shell redirects input.txt to standard input. Only sys and json are imported.
  • Write unique required key names before exactly one standalone --- line, then literal KEY=value assignment records. The separator is required even when both sections are empty. Exactly empty lines and lines starting with # are ignored in both sections. Whitespace is never trimmed.
  • Keys must match ASCII [A-Za-z_][A-Za-z0-9_]{0,63}. Assignments split only at the first equals sign; values are neither expanded nor interpreted.
  • Successful execution emits exactly one JSON object with missing, empty, duplicates and unknown fields, followed by LF, exits 0, and writes nothing to stderr. JSON is serialized with ensure_ascii=True after complete input validation. Key-name arrays and duplicate objects are sorted by ASCII key order.
  • Missing keys have no assignment. Empty keys are required keys with at least one exactly empty assignment value, even if another assignment is nonempty. Unknown keys are distinct assigned keys not selected as required. Duplicate reporting includes selected and unselected keys; each object contains key and positions, with ascending one-based assignment-record ordinals excluding selectors, blank lines and comments.
  • Invalid arguments, input, UTF-8, or stdin read failures produce exactly error: invalid input followed by LF on stderr, exit 2, and no stdout. Input values are never included in output or diagnostics. Use synthetic values for examples; no secrets or host configuration are needed.

Build and check

  1. Save the example as recipe.py.
  2. Prepare input.txt with selectors, a --- separator and literal assignments; use synthetic values while learning.
  3. Run the documented command and inspect the JSON output.
  4. Exit 2 indicates rejected input; no successful JSON result is emitted.

Limits to understand

  • The CLI reads stdin once using sys.stdin.buffer.read(65537) and rejects input exceeding 65536 bytes. It performs no file, environment, network or subprocess access and does not execute other scripts on import.
  • Input must be strict UTF-8 without a leading BOM. LF is the only permitted ASCII control character; CR, NUL, other ASCII controls, and DEL are rejected everywhere. Other Unicode scalar values are allowed in values and comments.
  • At most 100 selector records and 100 assignment records are permitted. Selectors must be unique. Duplicate assignments count separately. A final LF creates no record.
  • The combined UTF-8 length of all assignment values, including duplicate assignments, must not exceed 1024 bytes.
  • This is a literal assignment protocol, not a general dotenv parser. Quotes, backslashes, spaces, additional equals signs, and # within values remain literal.
  • Output-write and allocation failures are outside the input-error guarantee.
  • Literal assignment subset only; no quoting rules, export syntax, interpolation, multiline values or general dotenv compatibility.
  • Key names can themselves be sensitive.
  • stdin may block until EOF; input is bounded to 65536 bytes and 100 selector / 100 assignment records. Total assignment-value bytes are limited to 1024.

Run it

python3 recipe.py < input.txt

Example input

API_KEY
HOST
PORT
---
HOST=
API_KEY=first
API_KEY=second
EXTRA=x

Expected output

{"missing":["PORT"],"empty":["HOST"],"duplicates":[{"key":"API_KEY","positions":[2,3]}],"unknown":["EXTRA"]}
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

This browser preview builds code locally. It does not contact an API or run the code.

Default example ready.

Python example
import sys
import json


def valid_key(key):
    if not 1 <= len(key) <= 64:
        return False
    first = key[0]
    if not ('A' <= first <= 'Z' or 'a' <= first <= 'z' or first == '_'):
        return False
    for char in key[1:]:
        if not ('A' <= char <= 'Z' or 'a' <= char <= 'z' or '0' <= char <= '9' or char == '_'):
            return False
    return True


def audit(text):
    if text.startswith('\ufeff'):
        raise ValueError
    for char in text:
        number = ord(char)
        if (number < 32 and number != 10) or number == 127:
            raise ValueError

    required = set()
    positions = {}
    empty_values = set()
    separator_seen = False
    assignment_count = 0
    value_bytes = 0

    for line in text.split('\n'):
        if line == '' or line.startswith('#'):
            continue
        if line == '---':
            if separator_seen:
                raise ValueError
            separator_seen = True
            continue

        if not separator_seen:
            if not valid_key(line) or line in required or len(required) >= 100:
                raise ValueError
            required.add(line)
            continue

        assignment_count += 1
        if assignment_count > 100:
            raise ValueError
        key, delimiter, value = line.partition('=')
        if delimiter != '=' or not valid_key(key):
            raise ValueError
        value_bytes += len(value.encode('utf-8'))
        if value_bytes > 1024:
            raise ValueError
        if key not in positions:
            positions[key] = []
        positions[key].append(assignment_count)
        if value == '':
            empty_values.add(key)

    if not separator_seen:
        raise ValueError

    return {
        'missing': sorted(key for key in required if key not in positions),
        'empty': sorted(required & empty_values),
        'duplicates': [
            {'key': key, 'positions': positions[key]}
            for key in sorted(positions)
            if len(positions[key]) >= 2
        ],
        'unknown': sorted(key for key in positions if key not in required),
    }


def main():
    try:
        if len(sys.argv) != 1:
            raise ValueError
        data = sys.stdin.buffer.read(65537)
        if len(data) > 65536:
            raise ValueError
        text = data.decode('utf-8', errors='strict')
        output = json.dumps(audit(text), ensure_ascii=True) + '\n'
    except Exception:
        sys.stderr.write('error: invalid input\n')
        return 2

    sys.stdout.write(output)
    return 0


if __name__ == '__main__':
    sys.exit(main())
What to verify after running
  • Check the supplied example against its expected output.
  • Inspect missing, empty, duplicate and unknown key findings.
  • Confirm invalid syntax and extra arguments fail without input values in diagnostics.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 0.1.0 · Documentation reviewed 2026-10-16.

    The release gate requires six primary fixtures and 29 supplementary checks in the pinned offline runtime. Review the bound test evidence for the actual release; these checks do not prove exhaustive correctness or compatibility with other versions.