CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

trysac/openapi-style-lint

Lint an OpenAPI 3.0/3.1 JSON document against ten style rules (operationId, kebab-case paths, tags, summaries, response descriptions) and apply safe idempotent autofixes. Use when reviewing or cleaning an API spec or enforcing naming conventions.

Quality

95%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Passed

No findings from the security scan

Overview
Quality
Evals
Security
Files

openapi_style_lint.pyscripts/

#!/usr/bin/env python3
"""Style-lint and safe-autofix an OpenAPI 3.0/3.1 JSON document (rules OAS001-OAS010).

Standard library only, no network, no environment access.

Usage:
    python3 openapi_style_lint.py lint FILE.json [--rule OAS005=off ...] [--format text|json]
    python3 openapi_style_lint.py fix  FILE.json [--rule OAS005=off ...]

`lint` prints one line per finding: RULE SEVERITY POINTER MESSAGE.
`fix` prints the fixed document to stdout and the applied fixes to stderr; FILE is never modified.

Exit codes: 0 clean (or fix done), 1 at least one error-level finding, 2 usage or input error.
"""

import argparse
import copy
import json
import re
import sys

MAX_BYTES = 10 * 1024 * 1024
MAX_DEPTH = 128
HTTP_OPERATIONS = ("get", "put", "post", "delete", "options", "head", "patch", "trace")
DEFAULT_SEVERITY = {
    "OAS001": "error", "OAS002": "error", "OAS003": "warn", "OAS004": "error", "OAS005": "warn",
    "OAS006": "warn", "OAS007": "error", "OAS008": "error", "OAS009": "error", "OAS010": "warn",
}
REASON_PHRASES = {
    "200": "OK", "201": "Created", "202": "Accepted", "204": "No Content", "400": "Bad Request",
    "401": "Unauthorized", "403": "Forbidden", "404": "Not Found", "409": "Conflict",
    "422": "Unprocessable Content", "429": "Too Many Requests", "500": "Internal Server Error",
    "503": "Service Unavailable", "default": "Unexpected error",
}
CAMEL_RE = re.compile(r"[a-z][a-zA-Z0-9]*")
KEBAB_RE = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")


class LintError(Exception):
    def __init__(self, code, message):
        super().__init__(message)
        self.code = code


def esc(token):
    return token.replace("~", "~0").replace("/", "~1")


def is_obj(value):
    return isinstance(value, dict)


def is_camel(text):
    return CAMEL_RE.fullmatch(text) is not None


def is_kebab(text):
    return KEBAB_RE.fullmatch(text) is not None


def to_camel(text):
    spaced = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", text)
    words = [w.lower() for w in re.split(r"[^a-zA-Z0-9]+", spaced) if w]
    if not words:
        return ""
    return words[0] + "".join(w[:1].upper() + w[1:] for w in words[1:])


def validate(doc):
    if not is_obj(doc):
        raise LintError("invalid_document", "document must be a JSON object")
    version = doc.get("openapi")
    if not isinstance(version, str) or not (version.startswith("3.0.") or version.startswith("3.1.")):
        raise LintError("unsupported_version", "unsupported OpenAPI version: %s" % version)
    if "paths" in doc and not is_obj(doc["paths"]):
        raise LintError("invalid_document", "'paths' must be an object if present")
    stack = [(doc, 1)]
    while stack:
        value, depth = stack.pop()
        if depth > MAX_DEPTH:
            raise LintError("too_deep", "nesting exceeds %d levels" % MAX_DEPTH)
        for child in (value.values() if is_obj(value) else value):
            if isinstance(child, (dict, list)):
                stack.append((child, depth + 1))


def operations(doc):
    """Yield (path, method, operation, path_item, pointer) like the library does."""
    result = []
    for path, item in (doc.get("paths") or {}).items():
        if not is_obj(item):
            continue
        for key, op in item.items():
            if key.lower() in HTTP_OPERATIONS and is_obj(op):
                result.append((path, key.lower(), op, item, "/paths/%s/%s" % (esc(path), esc(key))))
    return result


def template_params(path):
    return [m.strip() for m in re.findall(r"\{([^}]+)\}", path) if m.strip()]


def declared_path_params(params):
    names = set()
    if isinstance(params, list):
        for p in params:
            if is_obj(p) and p.get("in") == "path" and isinstance(p.get("name"), str):
                names.add(p["name"])
    return names


def lint(doc, severities=None):
    validate(doc)
    severities = severities or {}
    findings = []

    def emit(rule, pointer, message, fixable):
        sev = severities.get(rule, DEFAULT_SEVERITY[rule])
        if sev != "off":
            findings.append({"rule": rule, "severity": sev, "pointer": pointer,
                             "message": message, "fixable": fixable})

    paths = doc.get("paths") or {}
    ops = operations(doc)
    for key in paths:
        pointer = "/paths/" + esc(key)
        if len(key) > 1 and key.endswith("/"):
            trimmed = key.rstrip("/")
            target = trimmed if trimmed else "/"
            emit("OAS004", pointer, "Path '%s' has a trailing slash" % key, target not in paths)
        for seg in key.split("/"):
            if not seg or (seg.startswith("{") and seg.endswith("}")):
                continue
            if not is_kebab(seg):
                emit("OAS003", pointer, "Literal path segment '%s' is not kebab-case" % seg, False)

    top_tags = {t["name"] for t in doc.get("tags", []) if is_obj(t) and isinstance(t.get("name"), str)} \
        if isinstance(doc.get("tags"), list) else set()
    existing = {op["operationId"] for _, _, op, _, _ in ops if isinstance(op.get("operationId"), str)}
    seen = set()
    for path, _method, op, item, pointer in ops:
        op_id = op.get("operationId")
        if not isinstance(op_id, str) or not op_id:
            emit("OAS001", pointer, "missing operationId", False)
        else:
            if op_id in seen:
                emit("OAS009", pointer + "/operationId", "Duplicate operationId '%s'" % op_id, False)
            else:
                seen.add(op_id)
            if not is_camel(op_id):
                camel = to_camel(op_id)
                can_fix = bool(camel) and camel != op_id and camel not in existing
                emit("OAS002", pointer + "/operationId", "operationId '%s' is not camelCase" % op_id, can_fix)
        summary = op.get("summary")
        if not isinstance(summary, str) or not summary.strip():
            emit("OAS005", pointer, "Operation missing summary", False)
        if isinstance(op.get("tags"), list):
            for i, tag in enumerate(op["tags"]):
                if isinstance(tag, str) and tag not in top_tags:
                    emit("OAS006", "%s/tags/%d" % (pointer, i), "Tag '%s' missing from top-level tags" % tag, True)
        names = template_params(path)
        if names:
            have = declared_path_params(item.get("parameters")) | declared_path_params(op.get("parameters"))
            for name in names:
                if name not in have:
                    emit("OAS007", pointer,
                         "Path template parameter '%s' missing matching 'in: path' parameter" % name, False)
        responses = op.get("responses")
        if is_obj(responses):
            for code, resp in responses.items():
                if is_obj(resp):
                    desc = resp.get("description")
                    if not isinstance(desc, str) or not desc.strip():
                        emit("OAS008", "%s/responses/%s" % (pointer, esc(code)),
                             "Response '%s' missing description" % code, True)

    schemas = (doc.get("components") or {}).get("schemas") if is_obj(doc.get("components")) else None
    if is_obj(schemas):
        for name, schema in schemas.items():
            if is_obj(schema):
                check_properties(schema, "/components/schemas/" + esc(name), emit)
    findings.sort(key=lambda f: (f["pointer"], f["rule"]))
    return findings


def check_properties(schema, pointer, emit):
    props = schema.get("properties")
    if is_obj(props):
        for name, value in props.items():
            ptr = "%s/properties/%s" % (pointer, esc(name))
            if not is_camel(name):
                emit("OAS010", ptr, "Property '%s' in schema is not camelCase" % name, False)
            if is_obj(value):
                check_properties(value, ptr, emit)
    if is_obj(schema.get("items")):
        check_properties(schema["items"], pointer + "/items", emit)
    for comb in ("allOf", "anyOf", "oneOf"):
        if isinstance(schema.get(comb), list):
            for i, sub in enumerate(schema[comb]):
                if is_obj(sub):
                    check_properties(sub, "%s/%s/%d" % (pointer, comb, i), emit)


def reason(code):
    return REASON_PHRASES.get(code, "Response")


def fix(doc, severities=None):
    """Apply OAS004, OAS002, OAS006 and OAS008 fixes to a deep copy; return (doc, applied)."""
    lint(doc, severities)
    out = copy.deepcopy(doc)
    applied = []
    paths = out.get("paths") if is_obj(out.get("paths")) else {}

    def each_op():
        for path_key, item in paths.items():
            if is_obj(item):
                for m, op in item.items():
                    if m.lower() in HTTP_OPERATIONS and is_obj(op):
                        yield path_key, m, op

    for key in list(paths):
        if len(key) > 1 and key.endswith("/"):
            target = key.rstrip("/") or "/"
            if target not in paths:
                content = paths.pop(key)
                paths[target] = content
                applied.append({"rule": "OAS004", "pointer": "/paths/" + esc(key), "before": key, "after": target})

    existing = {op["operationId"] for _, _, op in each_op() if isinstance(op.get("operationId"), str)}
    for path_key, m, op in each_op():
        op_id = op.get("operationId")
        if isinstance(op_id, str) and not is_camel(op_id):
            camel = to_camel(op_id)
            if camel and camel not in existing:
                existing.discard(op_id)
                existing.add(camel)
                op["operationId"] = camel
                applied.append({"rule": "OAS002",
                                "pointer": "/paths/%s/%s/operationId" % (esc(path_key), esc(m)),
                                "before": op_id, "after": camel})

    tags = [t for t in out["tags"] if is_obj(t)] if isinstance(out.get("tags"), list) else []
    known = {t["name"] for t in tags if isinstance(t.get("name"), str)}
    missing = []
    for path_key, m, op in each_op():
        if isinstance(op.get("tags"), list):
            for i, name in enumerate(op["tags"]):
                if isinstance(name, str) and name not in known:
                    if name not in missing:
                        missing.append(name)
                    applied.append({"rule": "OAS006",
                                    "pointer": "/paths/%s/%s/tags/%d" % (esc(path_key), esc(m), i),
                                    "before": None, "after": name})
    if missing:
        tags.extend({"name": name} for name in missing)
        tags.sort(key=lambda t: (str(t.get("name", "")).casefold(), str(t.get("name", ""))))
        out["tags"] = tags

    for path_key, m, op in each_op():
        responses = op.get("responses")
        if is_obj(responses):
            for code, resp in responses.items():
                if is_obj(resp):
                    desc = resp.get("description")
                    if not isinstance(desc, str) or not desc.strip():
                        resp["description"] = reason(code)
                        applied.append({"rule": "OAS008",
                                        "pointer": "/paths/%s/%s/responses/%s" % (esc(path_key), esc(m), esc(code)),
                                        "before": desc, "after": reason(code)})
    lint(out, severities)
    return out, applied


def read_doc(path):
    try:
        with open(path, "rb") as handle:
            raw = handle.read(MAX_BYTES + 1)
    except OSError as exc:
        raise LintError("io_error", "cannot read %s: %s" % (path, exc.strerror))
    if len(raw) > MAX_BYTES:
        raise LintError("too_large", "%s exceeds %d bytes" % (path, MAX_BYTES))
    try:
        return json.loads(raw.decode("utf-8-sig"))
    except (ValueError, UnicodeDecodeError) as exc:
        raise LintError("parse_error", "invalid JSON in %s (convert YAML to JSON first): %s" % (path, str(exc)[:100]))


def parse_rules(items):
    severities = {}
    for item in items:
        rule, _, level = item.partition("=")
        if rule not in DEFAULT_SEVERITY or level not in ("error", "warn", "off"):
            raise LintError("usage", "--rule expects OASnnn=error|warn|off, got %r" % item)
        severities[rule] = level
    return severities


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("command", choices=("lint", "fix"))
    parser.add_argument("file")
    parser.add_argument("--rule", action="append", default=[], help="OASnnn=error|warn|off (repeatable)")
    parser.add_argument("--format", choices=("text", "json"), default="text")
    args = parser.parse_args(argv)
    try:
        severities = parse_rules(args.rule)
        doc = read_doc(args.file)
        if args.command == "lint":
            findings = lint(doc, severities)
            if args.format == "json":
                print(json.dumps(findings, indent=2))
            else:
                for f in findings:
                    print("%s %s %s %s" % (f["rule"], f["severity"], f["pointer"], f["message"]))
            return 1 if any(f["severity"] == "error" for f in findings) else 0
        fixed, applied = fix(doc, severities)
        print(json.dumps(fixed, indent=2, ensure_ascii=False))
        for a in applied:
            print("fixed %s %s: %s -> %s" % (a["rule"], a["pointer"], a["before"], a["after"]), file=sys.stderr)
        return 0
    except LintError as exc:
        print("error (%s): %s" % (exc.code, exc), file=sys.stderr)
        return 2


if __name__ == "__main__":
    sys.exit(main())

SKILL.md

tile.json