Validate .env files against a JSON schema (string, int, bool, enum, url, duration, pattern) and generate a .env.example. Use when checking a .env file, documenting required variables or catching config drift. Prints key names only, never values.
95%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Passed
No findings from the security scan
#!/usr/bin/env python3
"""Validate .env files against a JSON schema and generate a .env.example.
Standard library only. Reads only the files named on the command line; it never
reads the process environment and never prints a value from a .env file, only
key names, line numbers and issue codes.
Usage:
python3 dotenv_schema.py --schema schema.json .env [more.env ...] [--json]
python3 dotenv_schema.py --schema schema.json --example
Exit codes: 0 valid, 1 issues found, 2 usage, I/O, syntax or schema error.
Issue codes: E001 required, E002 type, E003 range or length, E004 pattern,
E005 enum, E006 unknown key, E007 duplicate key.
"""
import argparse
import json
import re
import sys
from urllib.parse import urlsplit
MAX_ENV_BYTES = 1_048_576
MAX_ENV_LINES = 10_000
MAX_VALUE_BYTES = 65_536
MAX_SCHEMA_BYTES = 1 << 20
MAX_SCHEMA_VARS = 1000
INT64_MIN, INT64_MAX = -(1 << 63), (1 << 63) - 1
KEY_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
INT_RE = re.compile(r"[+-]?[0-9]+")
TYPES = ("string", "int", "bool", "enum", "url", "duration")
VAR_FIELDS = {"type", "required", "secret", "default", "min", "max", "values", "pattern",
"minLength", "maxLength"}
UNITS_NS = {"ns": 1, "us": 1000, "µs": 1000, "μs": 1000, "ms": 10**6, "s": 10**9,
"m": 60 * 10**9, "h": 3600 * 10**9}
class DotenvError(Exception):
"""Syntax, schema or size problem. The message never contains a value."""
def parse_env(text):
"""Return a list of (key, value, line) tuples using the strict dotenv rules."""
if len(text.encode("utf-8")) > MAX_ENV_BYTES:
raise DotenvError("input too large")
text = text[1:] if text.startswith("") else text
lines = text.split("\n")
entries, line_no = [], 0
for i, raw in enumerate(lines):
if i == len(lines) - 1 and raw == "":
continue
line_no += 1
if line_no > MAX_ENV_LINES:
raise DotenvError("input too large")
line = raw[:-1] if raw.endswith("\r") else raw
rest = line.lstrip(" \t")
if rest == "" or rest.startswith("#"):
continue
if rest.startswith("export ") or rest.startswith("export\t"):
after = rest[len("export"):].lstrip(" \t")
if after == "":
raise DotenvError("line %d: expected key after export" % line_no)
rest = after
eq = rest.find("=")
if eq < 0:
raise DotenvError("line %d: missing '='" % line_no)
key = rest[:eq]
if not KEY_RE.fullmatch(key):
raise DotenvError("line %d: invalid key" % line_no)
value = parse_value(rest[eq + 1:], line_no)
if len(value.encode("utf-8")) > MAX_VALUE_BYTES:
raise DotenvError("line %d: value exceeds 65536 bytes" % line_no)
entries.append((key, value, line_no))
return entries
def parse_value(part, line_no):
if part == "":
return ""
if part[0] == "'":
end = part.find("'", 1)
if end < 0:
raise DotenvError("line %d: unterminated single-quoted value" % line_no)
tail = part[end + 1:].lstrip(" \t")
if tail and not tail.startswith("#"):
raise DotenvError("line %d: unexpected content after closing quote" % line_no)
return part[1:end]
if part[0] == '"':
out, i = [], 1
while i < len(part):
c = part[i]
if c == '"':
tail = part[i + 1:].lstrip(" \t")
if tail and not tail.startswith("#"):
raise DotenvError("line %d: unexpected content after closing quote" % line_no)
return "".join(out)
if c in "\r\n":
raise DotenvError("line %d: newline in double-quoted value" % line_no)
if c == "\\":
if i + 1 >= len(part):
raise DotenvError("line %d: unterminated escape" % line_no)
nxt = part[i + 1]
mapped = {"n": "\n", "t": "\t", '"': '"', "\\": "\\"}.get(nxt)
if mapped is None:
raise DotenvError("line %d: invalid escape sequence" % line_no)
out.append(mapped)
i += 2
continue
out.append(c)
i += 1
raise DotenvError("line %d: unterminated double-quoted value" % line_no)
for i in range(1, len(part)):
if part[i] == "#" and part[i - 1] in " \t":
part = part[:i]
break
return part.strip(" \t")
def is_int(value):
return isinstance(value, int) and not isinstance(value, bool)
def load_schema(text):
if len(text.encode("utf-8")) > MAX_SCHEMA_BYTES:
raise DotenvError("schema exceeds 1 MiB")
try:
raw = json.loads(text)
except ValueError as exc:
raise DotenvError("schema is not valid JSON: %s" % str(exc)[:80])
if not isinstance(raw, dict) or set(raw) - {"vars", "allowUnknown"}:
raise DotenvError("schema must be an object with only 'vars' and 'allowUnknown'")
variables = raw.get("vars") or {}
allow = raw.get("allowUnknown", False)
if not isinstance(variables, dict) or not isinstance(allow, bool):
raise DotenvError("schema 'vars' must be an object and 'allowUnknown' a boolean")
if len(variables) > MAX_SCHEMA_VARS:
raise DotenvError("too many variables (max %d)" % MAX_SCHEMA_VARS)
schema = {"vars": {}, "allowUnknown": allow, "compiled": {}}
for key, spec in variables.items():
schema["vars"][key] = check_var(key, spec, schema)
return schema
def check_var(key, spec, schema):
if not isinstance(spec, dict) or set(spec) - VAR_FIELDS:
raise DotenvError("variable %s: must be an object with known fields only" % key)
var = {"type": spec.get("type", ""), "required": spec.get("required", False),
"secret": spec.get("secret", False), "default": spec.get("default"),
"min": spec.get("min"), "max": spec.get("max"), "values": spec.get("values") or [],
"pattern": spec.get("pattern", ""), "minLength": spec.get("minLength"),
"maxLength": spec.get("maxLength")}
ok = (isinstance(var["type"], str) and isinstance(var["required"], bool)
and isinstance(var["secret"], bool)
and (var["default"] is None or isinstance(var["default"], str))
and all(x is None or is_int(x) for x in (var["min"], var["max"], var["minLength"], var["maxLength"]))
and isinstance(var["values"], list) and all(isinstance(v, str) for v in var["values"])
and isinstance(var["pattern"], str))
if not ok:
raise DotenvError("variable %s: a field has the wrong type" % key)
if var["type"] not in TYPES:
raise DotenvError("variable %s: invalid type" % key)
if var["type"] == "enum" and not var["values"]:
raise DotenvError("variable %s: enum requires at least one value" % key)
if var["type"] == "int" and var["min"] is not None and var["max"] is not None and var["min"] > var["max"]:
raise DotenvError("variable %s: min > max" % key)
if var["pattern"]:
try:
schema["compiled"][key] = re.compile(var["pattern"])
except re.error:
raise DotenvError("variable %s: invalid pattern" % key)
if var["default"] is not None:
issues = check_value(key, var, var["default"], 0, schema)
if issues:
raise DotenvError("variable %s: default does not satisfy its own rules (%s)" % (key, issues[0]["code"]))
return var
def parse_duration(text):
"""Accept the same strings as Go's time.ParseDuration (for example 1h30m, 250ms, 0)."""
rest = text[1:] if text[:1] in ("+", "-") else text
if rest == "0":
return True
if rest == "":
return False
total = 0
while rest:
number = re.match(r"[0-9]*(?:\.[0-9]*)?", rest).group(0)
if not re.search(r"[0-9]", number):
return False
rest = rest[len(number):]
unit = re.match(r"[^0-9.]+", rest)
if not unit or unit.group(0) not in UNITS_NS:
return False
whole, _, frac = number.partition(".")
scale = UNITS_NS[unit.group(0)]
total += int(whole or "0") * scale + (int(frac) * scale) // (10 ** len(frac)) if frac else int(whole or "0") * scale
if total > INT64_MAX:
return False
rest = rest[unit.end():]
return True
def valid_url(value):
if any(ord(c) <= 32 or ord(c) == 127 for c in value):
return False
try:
parts = urlsplit(value)
return bool(parts.scheme) and bool(parts.netloc) and bool(parts.hostname)
except ValueError:
return False
def issue(code, key, line, message):
return {"code": code, "key": key, "line": line, "message": message}
def check_value(key, var, val, line, schema):
kind, out = var["type"], []
if kind == "int":
if not INT_RE.fullmatch(val) or not INT64_MIN <= int(val) <= INT64_MAX:
out.append(issue("E002", key, line, key + " must be an int"))
else:
n = int(val)
if var["min"] is not None and n < var["min"]:
out.append(issue("E003", key, line, "%s must be >= %d" % (key, var["min"])))
if var["max"] is not None and n > var["max"]:
out.append(issue("E003", key, line, "%s must be <= %d" % (key, var["max"])))
elif kind == "bool":
if val not in ("true", "false", "1", "0"):
out.append(issue("E002", key, line, key + " must be a bool"))
elif kind == "url":
if not valid_url(val):
out.append(issue("E002", key, line, key + " must be a url"))
elif kind == "duration":
if not parse_duration(val):
out.append(issue("E002", key, line, key + " must be a duration"))
elif kind == "enum":
if val not in var["values"]:
out.append(issue("E005", key, line, "%s must be one of %s" % (key, "|".join(var["values"]))))
elif kind == "string":
size = len(val.encode("utf-8"))
if var["minLength"] is not None and size < var["minLength"]:
out.append(issue("E003", key, line, "%s must be >= %d" % (key, var["minLength"])))
if var["maxLength"] is not None and size > var["maxLength"]:
out.append(issue("E003", key, line, "%s must be <= %d" % (key, var["maxLength"])))
if var["pattern"] and not schema["compiled"][key].search(val):
out.append(issue("E004", key, line, key + " does not match the required pattern"))
return out
def validate(entries, schema):
issues, seen = [], set()
for key, value, line in entries:
known = key in schema["vars"]
if not known and not schema["allowUnknown"]:
issues.append(issue("E006", key, line, key + " is not in the schema"))
if key in seen:
issues.append(issue("E007", key, line, key + " is defined more than once"))
seen.add(key)
if known:
issues.extend(check_value(key, schema["vars"][key], value, line, schema))
for key, var in schema["vars"].items():
if var["required"] and var["default"] is None and key not in seen:
issues.append(issue("E001", key, 0, key + " is required"))
issues.sort(key=lambda i: (i["line"], i["key"], i["code"]))
return issues
def example(schema):
lines = []
for key in sorted(schema["vars"]):
var = schema["vars"][key]
tag = var["type"] + (", required" if var["required"] else "") + (", secret" if var["secret"] else "")
shown = "" if var["secret"] or var["default"] is None else var["default"]
lines.append("# " + tag)
lines.append("%s=%s" % (key, shown))
return "".join(line + "\n" for line in lines)
def read_text(path, limit):
try:
with open(path, "rb") as handle:
raw = handle.read(limit + 1)
return raw.decode("utf-8")
except OSError as exc:
raise DotenvError("%s: %s" % (path, exc.strerror))
except UnicodeDecodeError:
raise DotenvError("%s: not valid UTF-8" % path)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--schema", required=True, help="path to the JSON schema")
parser.add_argument("--json", action="store_true", help="print issues as a JSON array")
parser.add_argument("--example", action="store_true", help="print the generated .env.example and exit")
parser.add_argument("files", nargs="*", help=".env files to validate (paths only)")
args = parser.parse_args(argv)
try:
schema = load_schema(read_text(args.schema, MAX_SCHEMA_BYTES))
if args.example:
sys.stdout.write(example(schema))
return 0
if not args.files:
print("dotenv-schema: give at least one .env file path", file=sys.stderr)
return 2
all_issues = []
for path in args.files:
try:
issues = validate(parse_env(read_text(path, MAX_ENV_BYTES)), schema)
except DotenvError as exc:
raise DotenvError("%s: %s" % (path, exc))
if not args.json:
for i in issues:
print("%s:%d: %s %s" % (path, i["line"], i["code"], i["message"]))
all_issues.extend(issues)
if args.json:
print(json.dumps(all_issues, separators=(",", ":")))
return 1 if all_issues else 0
except DotenvError as exc:
print("dotenv-schema: %s" % exc, file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main())