OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Redact selected configuration assignment values with Python

Python

Replace every value assigned to an explicit selected key while preserving the order and literal values of unselected assignments.

Python code excerpt: Redact selected configuration assignment values with Python. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Replace every value assigned to an explicit selected key while preserving the order and literal values of unselected assignments. Uses saved stdin text; never reads the real process environment.

Before you start

  • Save the code as redact.py and run with Python 3.12 using no CLI arguments: python3.12 redact.py. Supply the protocol text through standard input.
  • Uses only sys and json. Performs one bounded stdin read of 65537 bytes, rejects input exceeding 65536 bytes, and strictly decodes UTF-8.
  • Requires exactly one literal --- separator line. Rejects a leading BOM and prohibited controls anywhere. Ignores only empty lines and lines starting with #; whitespace is not trimmed.
  • Validates ASCII key syntax, unique selectors, at most 100 selectors, at most 100 assignment records, and at most 1024 total UTF-8 bytes across original assignment values, including duplicates and selected values.
  • Preserves assignment order, duplicate assignments, and all unselected values. Replaces every selected assignment value, including an empty value, with [REDACTED].
  • Validates the complete input before producing successful stdout. Success writes exactly one JSON object followed by LF using ensure_ascii=True, exits 0, and leaves stderr empty. Invalid input, arguments, UTF-8, or stdin read failure produces only error: invalid input followed by LF on stderr and exits 2.
  • No output key-name arrays are produced; assignment records remain in input order.

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

  • This is a literal LF-only assignment protocol, not a general dotenv parser. Quotes, backslashes, spaces, # characters within values, and additional = characters are preserved literally.
  • Only explicitly selected keys are redacted. Unselected values remain visible; this is neither automatic secret detection nor certification that output is safe to publish.
  • The CLI reads no files, environment variables, credentials, or host configuration and performs no network access, subprocess execution, or dynamic execution.
  • 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.
  • Unselected assignment values are emitted unchanged. Review output before sharing.
  • 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

TOKEN
---
TOKEN=secret-one
HOST=localhost
TOKEN=secret-two

Expected output

{"assignments":[{"key":"TOKEN","value":"[REDACTED]"},{"key":"HOST","value":"localhost"},{"key":"TOKEN","value":"[REDACTED]"}]}
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
    return all(
        'A' <= ch <= 'Z' or 'a' <= ch <= 'z' or
        '0' <= ch <= '9' or ch == '_'
        for ch in key[1:]
    )


def parse(data):
    if len(data) > 65536:
        raise ValueError
    text = data.decode('utf-8', errors='strict')
    if text.startswith('\ufeff'):
        raise ValueError
    for ch in text:
        number = ord(ch)
        if (number < 32 and ch != '\n') or number == 127:
            raise ValueError

    selectors = set()
    assignments = []
    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 selectors:
                raise ValueError
            selectors.add(line)
            if len(selectors) > 100:
                raise ValueError
            continue

        assignment_count += 1
        if assignment_count > 100 or '=' not in line:
            raise ValueError
        key, value = line.split('=', 1)
        if not valid_key(key):
            raise ValueError
        value_bytes += len(value.encode('utf-8'))
        if value_bytes > 1024:
            raise ValueError
        assignments.append({
            'key': key,
            'value': '[REDACTED]' if key in selectors else value
        })

    if not separator_seen:
        raise ValueError
    return {'assignments': assignments}


def main():
    try:
        if len(sys.argv) != 1:
            raise ValueError
        data = sys.stdin.buffer.read(65537)
        result = parse(data)
    except Exception:
        sys.stderr.write('error: invalid input\n')
        return 2

    output = json.dumps(result, ensure_ascii=True) + '\n'
    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.
  • Check all selected duplicate values are replaced; review unselected values before sharing.
  • 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.