string.Formatter Subclass Enforces Template Keys

Subclass string.Formatter to allowlist lookup keys, block attribute traversal in format strings, and mask sensitive values automatically.

PythonSecurity Boundaries

Code

pythonsnippet
39 lines
import string

class SafeAuditFormatter(string.Formatter):
    def __init__(self, allowed_keys: set[str], masked_keys: set[str]) -> None:
        self.allowed_keys = allowed_keys
        self.masked_keys = masked_keys

    def get_field(self, field_name: str, args, kwargs):
        # Reject attribute (.attr) or index ([0]) traversal in user templates
        if "." in field_name or "[" in field_name:
            raise ValueError(f"traversal blocked: {field_name!r}")
        if field_name not in self.allowed_keys:
            raise KeyError(f"key not allowlisted: {field_name!r}")
        return kwargs[field_name], field_name

    def format_field(self, value, format_spec: str) -> str:
        return super().format_field(value, format_spec)

    def convert_field(self, value, conversion: str | None):
        return super().convert_field(value, conversion)

    def get_value(self, key, args, kwargs):
        return super().get_value(key, args, kwargs)

    def render(self, template: str, **fields: object) -> str:
        safe_fields = {
            k: (f"{str(v)[:2]}***" if k in self.masked_keys else v)
            for k, v in fields.items()
        }
        return self.vformat(template, (), safe_fields)

fmt = SafeAuditFormatter(allowed_keys={"user", "token", "action"}, masked_keys={"token"})
print(fmt.render("{user} ran {action} with {token}", user="ada", action="deploy", token="sk_9921a"))

for bad_tpl in ("{user.__class__}", "{secret}"):
    try:
        fmt.render(bad_tpl, user="ada", secret="hidden")
    except (ValueError, KeyError) as exc:
        print("blocked:", exc)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ada ran deploy with sk***
blocked: traversal blocked: 'user.__class__'
blocked: "key not allowlisted: 'secret'"

Behavior overview — string.Formatter Subclass Enforces Template Keys

The moving parts are the class SafeAuditFormatter and the functions __init__, get_field, format_field and convert_field.

Repetition is confined to for k, v in fields.items() — the rest of the file is straight-line. Failure is loud: ValueError and KeyError aborts the current operation instead of degrading it.

What to watch for

  • Nothing external is listed; stock language tooling covers all functionality.
  • The guard "." in field_name or "[" in field_name breaks out ahead of time using a defensive raise when its condition holds.

Putting it to use

Signature: def get_field(self, field_name: str, args, kwargs)

The run emits 1 labeled section — blocked: — one per step.

Callers only need get_field — everything else stays internal.

Core lines

def __init__(self, allowed_keys: set[str], masked_keys: set[str]) -> None:
    self.allowed_keys = allowed_keys
    self.masked_keys = masked_keys
def convert_field(self, value, conversion: str | None):
    return super().convert_field(value, conversion)
def render(self, template: str, **fields: object) -> str:
    safe_fields = {
        k: (f"{str(v)[:2]}***" if k in self.masked_keys else v)
        for k, v in fields.items()
    }
    return self.vformat(template, (), safe_fields)

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
Validation comes first — `ValueError` and `KeyError` marks the failure at `"." in field_name or "[" in field_name`, before any partial work happens.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `__init__`, `get_field`, `format_field` at load time.