CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

trysac/openapi-diff

Compare two OpenAPI 3.0/3.1 JSON specs and classify each change as breaking, warning or info with ten rules. Use when reviewing an API contract change, checking for breaking changes before a release, or gating CI on API compatibility.

Quality

95%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Low

Low-risk findings worth noting

Overview
Quality
Evals
Security
Files

openapi_diff.pyscripts/

#!/usr/bin/env python3
"""Classify the differences between two OpenAPI 3.0/3.1 JSON documents.

Standard library only, no network, no environment access. Reads the two files
named on the command line and prints one line per change, or JSON.

Usage:
    python3 openapi_diff.py BASE.json HEAD.json [--format text|json]
                            [--fail-on breaking|warning|none]

Exit codes: 0 no change reaches --fail-on, 1 at least one does, 2 usage or input error.
"""

import argparse
import json
import re
import sys

MAX_BYTES = 10_485_760
MAX_SCHEMA_DEPTH = 64
MAX_REF_HOPS = 64
MAX_COMPARISONS = 100_000
VERSION_RE = re.compile(r"^3\.[01]\.\d+(?:[-+][0-9A-Za-z.+-]*)?$")
METHODS = ("get", "put", "post", "delete", "options", "head", "patch", "trace")
COMPOSITION = ("allOf", "oneOf", "anyOf", "not")


class DiffError(Exception):
    """Input problem with a stable code."""

    def __init__(self, code, message):
        super().__init__(message[:200])
        self.code = code


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


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


def rec(value):
    return value if is_obj(value) else {}


def canon(value):
    """Canonical JSON text so that 1 equals 1.0 and true differs from 1."""
    if isinstance(value, bool):
        return "true" if value else "false"
    if isinstance(value, float) and value.is_integer():
        return str(int(value))
    if isinstance(value, list):
        return "[" + ",".join(canon(v) for v in value) + "]"
    if is_obj(value):
        return "{" + ",".join(json.dumps(k) + ":" + canon(value[k]) for k in sorted(value)) + "}"
    return json.dumps(value)


def load_spec(path):
    try:
        with open(path, "rb") as handle:
            raw = handle.read(MAX_BYTES + 1)
    except OSError as exc:
        raise DiffError("io_error", "cannot read %s: %s" % (path, exc.strerror))
    if len(raw) > MAX_BYTES:
        raise DiffError("too_large", "%s exceeds %d bytes" % (path, MAX_BYTES))
    try:
        doc = json.loads(raw.decode("utf-8-sig"))
    except (ValueError, UnicodeDecodeError) as exc:
        raise DiffError(
            "parse_error",
            "%s is not valid JSON (convert YAML to JSON first): %s" % (path, str(exc)[:100]),
        )
    if not is_obj(doc):
        raise DiffError("parse_error", "%s must contain a JSON object" % path)
    version = doc.get("openapi")
    if not isinstance(version, str) or not VERSION_RE.match(version):
        raise DiffError(
            "unsupported_version",
            "unsupported version %r in %s; expected 3.0.x or 3.1.x" % (version, path),
        )
    check_refs(doc, path)
    return doc


def check_refs(doc, path):
    stack = [(doc, 0)]
    while stack:
        value, depth = stack.pop()
        if depth > 256:
            raise DiffError("too_deep", "%s is nested too deeply" % path)
        children = value if isinstance(value, list) else value.values() if is_obj(value) else ()
        if is_obj(value):
            ref = value.get("$ref")
            if isinstance(ref, str) and ref != "#" and not ref.startswith("#/"):
                raise DiffError("unresolved_ref", "non-local reference %r in %s" % (ref[:100], path))
        for child in children:
            if isinstance(child, (dict, list)):
                stack.append((child, depth + 1))


def lookup(doc, ref):
    if ref != "#" and not ref.startswith("#/"):
        raise DiffError("unresolved_ref", "unresolved reference %r" % ref[:100])
    pointer = ref[1:]
    value = doc
    if pointer:
        for raw in pointer[1:].split("/"):
            token = raw.replace("~1", "/").replace("~0", "~")
            if isinstance(value, list) and token.isdigit() and int(token) < len(value):
                value = value[int(token)]
            elif is_obj(value) and token in value:
                value = value[token]
            else:
                raise DiffError("unresolved_ref", "unresolved reference %r" % ref[:100])
    return value, pointer


def deref(doc, loc):
    value, pointer = loc
    for _ in range(MAX_REF_HOPS + 1):
        if not is_obj(value) or not isinstance(value.get("$ref"), str):
            return value, pointer
        value, pointer = lookup(doc, value["$ref"])
    raise DiffError("too_deep", "reference chain is too long")


def at(doc, parent, key):
    items = rec(parent[0])
    if key not in items:
        return None
    return deref(doc, (items[key], "%s/%s" % (parent[1], esc(key))))


def type_set(schema):
    raw = schema.get("type")
    result = None
    if isinstance(raw, str):
        result = {raw}
    elif isinstance(raw, list):
        result = {t for t in raw if isinstance(t, str)}
    if result is not None and schema.get("nullable") is True:
        result.add("null")
    return result


def covers(types, kind):
    return kind in types or (kind == "integer" and "number" in types)


def lost_types(src, dst):
    if dst is None:
        return []
    if src is None:
        return ["any"]
    return [t for t in src if not covers(dst, t)]


def fmt_types(types):
    return "any" if types is None else "|".join(sorted(types))


def short(text, limit=100):
    return text if len(text) <= limit else text[: limit - 1] + "..."


class Ctx:
    def __init__(self, base, head):
        self.base = base
        self.head = head
        self.count = 0
        self.active = set()


def finding(rule, severity, pointer, message):
    return {"rule": rule, "severity": severity, "pointer": pointer, "message": message}


def compare_schemas(ctx, direction, base, head, depth):
    b = deref(ctx.base, base)
    h = deref(ctx.head, head)
    key = (direction, b[1], h[1])
    if key in ctx.active:
        return []
    if depth > MAX_SCHEMA_DEPTH:
        raise DiffError("too_deep", "schema nesting exceeds %d levels" % MAX_SCHEMA_DEPTH)
    ctx.count += 1
    if ctx.count > MAX_COMPARISONS:
        raise DiffError("too_large", "more than %d schema comparisons" % MAX_COMPARISONS)
    ctx.active.add(key)
    try:
        return analyse(ctx, direction, b, h, depth)
    finally:
        ctx.active.discard(key)


def analyse(ctx, direction, b, h, depth):
    out = []
    bs, hs = rec(b[0]), rec(h[0])
    bt, ht = type_set(bs), type_set(hs)
    lost = lost_types(bt, ht) if direction == "request" else lost_types(ht, bt)
    if lost:
        out.append(finding("type-changed", "breaking", h[1],
                           "Type changed from %s to %s" % (fmt_types(bt), fmt_types(ht))))
    if [canon(bs[k]) if k in bs else "-" for k in COMPOSITION] != [
        canon(hs[k]) if k in hs else "-" for k in COMPOSITION
    ]:
        out.append(finding("type-changed", "warning", h[1], "composition changed, not analysed"))
    out.extend(diff_enum(direction, bs, hs, h[1]))
    out.extend(diff_properties(ctx, direction, b, h, depth))
    if is_obj(bs.get("items")) and is_obj(hs.get("items")):
        out.extend(compare_schemas(ctx, direction, (bs["items"], b[1] + "/items"),
                                   (hs["items"], h[1] + "/items"), depth + 1))
    return out


def diff_enum(direction, bs, hs, pointer):
    benum, henum = bs.get("enum"), hs.get("enum")
    if not isinstance(benum, list) or not isinstance(henum, list):
        return []
    bkeys = [canon(v) for v in benum]
    hkeys = [canon(v) for v in henum]
    out = []
    if direction == "request":
        for key in dict.fromkeys(bkeys):
            if key not in hkeys:
                out.append(finding("request-enum-value-removed", "breaking", pointer + "/enum",
                                   "Enum value %s removed" % short(key)))
    else:
        for key in dict.fromkeys(hkeys):
            if key not in bkeys:
                out.append(finding("response-enum-value-added", "warning", pointer + "/enum",
                                   "Enum value %s added" % short(key)))
    return out


def ignored(direction, schema):
    flag = "readOnly" if direction == "request" else "writeOnly"
    return rec(schema).get(flag) is True


def diff_properties(ctx, direction, b, h, depth):
    out = []
    bprops = rec(rec(b[0]).get("properties"))
    hprops = rec(rec(h[0]).get("properties"))
    for name in bprops:
        braw = (bprops[name], "%s/properties/%s" % (b[1], esc(name)))
        bloc = deref(ctx.base, braw)
        if name not in hprops:
            if direction == "response" and not ignored(direction, bloc[0]):
                out.append(finding("response-property-removed", "breaking", braw[1],
                                   "Property %s removed" % json.dumps(short(name))))
            continue
        hloc = deref(ctx.head, (hprops[name], "%s/properties/%s" % (h[1], esc(name))))
        if ignored(direction, bloc[0]) or ignored(direction, hloc[0]):
            continue
        out.extend(compare_schemas(ctx, direction, bloc, hloc, depth + 1))
    if direction == "request":
        breq = {x for x in rec(b[0]).get("required", []) if isinstance(x, str)} \
            if isinstance(rec(b[0]).get("required"), list) else set()
        hreq_raw = rec(h[0]).get("required")
        hreq = [x for x in hreq_raw if isinstance(x, str)] if isinstance(hreq_raw, list) else []
        for name in dict.fromkeys(hreq):
            if name in breq:
                continue
            if name in hprops:
                hloc = deref(ctx.head, (hprops[name], "%s/properties/%s" % (h[1], esc(name))))
                if ignored(direction, hloc[0]):
                    continue
            out.append(finding("request-property-became-required", "breaking", h[1] + "/required",
                               "Property %s is now required" % json.dumps(short(name))))
    return out


def parse_template(path):
    normalized, names, i = "", [], 0
    while i < len(path):
        opn = path.find("{", i)
        if opn < 0:
            break
        cls = path.find("}", opn + 1)
        if cls < 0:
            break
        normalized += path[i:opn] + "{}"
        names.append(path[opn + 1:cls])
        i = cls + 1
    return normalized + path[i:], names


def collect_ops(doc):
    ops = {}
    for path, raw in rec(doc.get("paths")).items():
        if not path.startswith("/"):
            continue
        normalized, names = parse_template(path)
        item = deref(doc, (raw, "/paths/" + esc(path)))
        for method in METHODS:
            value = rec(item[0]).get(method)
            key = (method, normalized)
            if not is_obj(value) or key in ops:
                continue
            ops[key] = {"method": method, "path": path, "names": names, "item": item,
                        "op": (value, "%s/%s" % (item[1], method))}
    return ops


def param_key(location, name, names):
    if location == "header":
        return "header:" + name.lower()
    if location == "path":
        return "pathpos:%d" % names.index(name) if name in names else "path:" + name
    return "%s:%s" % (location, name)


def collect_params(doc, entry):
    params = {}
    for owner in (entry["item"], entry["op"]):
        listing = rec(owner[0]).get("parameters")
        if not isinstance(listing, list):
            continue
        for i, raw in enumerate(listing):
            loc = deref(doc, (raw, "%s/parameters/%d" % (owner[1], i)))
            p = rec(loc[0])
            name, where = p.get("name"), p.get("in")
            if not isinstance(name, str) or not isinstance(where, str):
                continue
            schema = (p["schema"], loc[1] + "/schema") if is_obj(p.get("schema")) else None
            params[param_key(where, name, entry["names"])] = {
                "label": "%s in %s" % (json.dumps(short(name)), where[:20]),
                "required": where == "path" or p.get("required") is True,
                "pointer": loc[1], "schema": schema}
    return params


def diff_params(ctx, b, h):
    out = []
    bp, hp = collect_params(ctx.base, b), collect_params(ctx.head, h)
    for key, old in bp.items():
        new = hp.get(key)
        if new is None:
            out.append(finding("param-removed", "warning", old["pointer"],
                               "Parameter %s removed" % old["label"]))
            continue
        if not old["required"] and new["required"]:
            out.append(finding("param-became-required", "breaking", new["pointer"],
                               "Parameter %s became required" % new["label"]))
        if old["schema"] and new["schema"]:
            out.extend(compare_schemas(ctx, "request", old["schema"], new["schema"], 0))
    for key, new in hp.items():
        if key in bp:
            continue
        if new["required"]:
            out.append(finding("param-added", "breaking", new["pointer"],
                               "Required parameter %s added" % new["label"]))
        else:
            out.append(finding("param-added", "info", new["pointer"],
                               "Optional parameter %s added" % new["label"]))
    return out


def json_media(content):
    media = {}
    for name, entry in rec(content[0]).items():
        norm = name.split(";")[0].strip().lower()
        if not (norm == "application/json" or norm.endswith("+json")) or norm in media:
            continue
        if not is_obj(entry) or "schema" not in entry:
            continue
        media[norm] = (entry["schema"], "%s/%s/schema" % (content[1], esc(name)))
    return media


def compare_content(ctx, direction, base, head):
    bc, hc = at(ctx.base, base, "content"), at(ctx.head, head, "content")
    if bc is None or hc is None:
        return []
    out, hmedia = [], json_media(hc)
    for name, bschema in json_media(bc).items():
        if name in hmedia:
            out.extend(compare_schemas(ctx, direction, bschema, hmedia[name], 0))
    return out


def diff_body(ctx, b, h):
    hbody = at(ctx.head, h["op"], "requestBody")
    if hbody is None:
        return []
    bbody = at(ctx.base, b["op"], "requestBody")
    out = []
    was = rec(bbody[0] if bbody else None).get("required") is True
    if rec(hbody[0]).get("required") is True and not was:
        out.append(finding("request-property-became-required", "breaking",
                           hbody[1] + "/required", "Request body became required"))
    if bbody is not None:
        out.extend(compare_content(ctx, "request", bbody, hbody))
    return out


def diff_responses(ctx, b, h):
    bres, hres = at(ctx.base, b["op"], "responses"), at(ctx.head, h["op"], "responses")
    if bres is None or hres is None:
        return []
    out = []
    for status in rec(bres[0]):
        if status not in rec(hres[0]):
            continue
        bresp, hresp = at(ctx.base, bres, status), at(ctx.head, hres, status)
        if bresp is not None and hresp is not None:
            out.extend(compare_content(ctx, "response", bresp, hresp))
    return out


def op_label(entry):
    return "%s %s" % (entry["method"].upper(), short(entry["path"]))


def diff_specs(base, head):
    ctx = Ctx(base, head)
    bops, hops = collect_ops(base), collect_ops(head)
    changes = []
    for key, old in bops.items():
        new = hops.get(key)
        if new is None:
            changes.append(dict(finding("operation-removed", "breaking", old["op"][1],
                                        "Operation %s removed" % op_label(old)),
                                method=old["method"], path=old["path"]))
            continue
        found = diff_params(ctx, old, new) + diff_body(ctx, old, new) + diff_responses(ctx, old, new)
        for item in found:
            changes.append(dict(item, method=new["method"], path=new["path"]))
    for key, new in hops.items():
        if key not in bops:
            changes.append(dict(finding("operation-added", "info", new["op"][1],
                                        "Operation %s added" % op_label(new)),
                                method=new["method"], path=new["path"]))
    unique = {}
    for c in changes:
        unique.setdefault((c["path"], c["method"], c["pointer"], c["rule"], c["message"]), c)
    ordered = sorted(unique.values(), key=lambda c: (c["path"], c["method"], c["pointer"]))
    summary = {"breaking": 0, "warning": 0, "info": 0}
    for c in ordered:
        summary[c["severity"]] += 1
    return {"changes": ordered, "summary": summary}


def format_report(report, fmt):
    if fmt == "json":
        return json.dumps(report, indent=2)
    lines = []
    for c in report["changes"]:
        subject = " ".join([c["rule"], c["method"].upper(), c["path"]])
        lines.append("[%s] %s: %s (%s)" % (c["severity"], subject, c["message"], c["pointer"]))
    s = report["summary"]
    lines.append("%d breaking, %d warning, %d info" % (s["breaking"], s["warning"], s["info"]))
    return "\n".join(lines)


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("base")
    parser.add_argument("head")
    parser.add_argument("--format", choices=("text", "json"), default="text")
    parser.add_argument("--fail-on", choices=("breaking", "warning", "none"), default="breaking")
    args = parser.parse_args(argv)
    try:
        report = diff_specs(load_spec(args.base), load_spec(args.head))
    except DiffError as exc:
        print("error (%s): %s" % (exc.code, exc), file=sys.stderr)
        return 2
    print(format_report(report, args.format))
    s = report["summary"]
    if args.fail_on == "breaking" and s["breaking"]:
        return 1
    if args.fail_on == "warning" and (s["breaking"] or s["warning"]):
        return 1
    return 0


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

SKILL.md

tile.json