# Openapi CI Gates

> Use when adding OpenAPI security gates to CI on an authorized review or build. Covers breaking the build on unauthenticated endpoints, weak auth schemes, schema validation gaps, and spec drift. Use when an API ships an OpenAPI spec, when gateway policy should match the spec, when a pipeline needs a security check that fails loudly, or when reviewing spec changes in pull requests.

- Skill: `mizazhaider-ceh/openapi-ci-gates` (Agent Skill)
- Install (CLI): `npx get-skill add mizazhaider-ceh/openapi-ci-gates`
- Raw SKILL.md: https://api.skillmd.com/api/skills/mizazhaider-ceh/openapi-ci-gates/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: DevOps & Infra
- Author: mizazhaider-ceh (https://skillmd.com/u/mizazhaider-ceh)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/mizazhaider-ceh/openapi-ci-gates

---


A spec that nobody enforces drifts, and drifted specs hide
unauthenticated endpoints, weak auth, and schemas the gateway never
validates. CI gates turn the spec into a control: every change to
the spec, and every change to the gateway policy, must pass the
same checks before it merges. This sub-skill builds those gates for
a pipeline you are authorized to change, with checks that fail
loudly and explain exactly which rule broke.

## Quick Workflow

1. Pin the spec location: one canonical OpenAPI file per API
   version, checked into the repo the pipeline builds from.
2. Add the gate script: parse the spec and run the rule checks
   below, exiting nonzero on any failure.
3. Wire the gate into CI: run it on every pull request that touches
   the spec, the gateway config, or the API code.
4. Add the drift gate: compare the spec against the live gateway
   routes on staging, and fail when they disagree.
5. Start in report mode for one release, then switch to blocking
   once the existing failures are fixed or waived with an expiry.
6. Review waivers like findings: each waiver names an owner and an
   expiry date, and expired waivers fail the build.
7. Re-verify the gates after any gateway or spec change by
   deliberately breaking a rule in a test branch and watching CI
   catch it.

## 1. The gate script

```python
#!/usr/bin/env python3
"""OpenAPI CI gate: fail the build on spec security regressions.

Rules enforced here: every operation has auth, no weak scheme is
introduced, sensitive operations are not left open, and request
schemas require the fields the handler assumes. Exit code 1 fails
the pipeline, and every failure names its path and rule.
"""
import json
import sys

spec = json.load(open("openapi.json"))
errors = []
paths = spec.get("paths", {})
global_sec = spec.get("security")
schemes = spec.get("components", {}).get("securitySchemes", {})

for name, scheme in schemes.items():
    if scheme.get("type") == "apiKey" and scheme.get("in") == "query":
        errors.append(f"scheme {name}: apiKey in query leaks keys in logs")
    if scheme.get("type") == "http" and scheme.get("scheme") == "basic":
        errors.append(f"scheme {name}: basic auth without a stronger scheme")

for path, ops in paths.items():
    for method, op in ops.items():
        if not isinstance(op, dict):
            continue
        if "security" not in op and not global_sec:
            errors.append(f"{method.upper()} {path}: no security defined")
        if "admin" in path.lower() or "admin" in op.get("operationId", ""):
            sec = op.get("security", global_sec or [])
            if not sec:
                errors.append(f"{method.upper()} {path}: admin operation open")

if errors:
    print(f"CI GATE FAILED: {len(errors)} rule violations")
    for error in errors:
        print(f"  - {error}")
    sys.exit(1)
print(f"CI GATE PASSED: {len(paths)} paths checked")
```

## 2. Schema validation gate

```python
#!/usr/bin/env python3
"""Schema gate: request bodies must be validated, not just typed.

Checks that POST, PUT, and PATCH operations define a request body
with a schema, that string fields carry maxLength where the handler
stores them, and that additionalProperties is set deliberately.
A missing maxLength on a stored string is how oversized payloads
reach the database unchecked.
"""
import json
import sys

spec = json.load(open("openapi.json"))
warnings = []
for path, ops in spec.get("paths", {}).items():
    for method, op in ops.items():
        if not isinstance(op, dict) or method.upper() not in (
                "POST", "PUT", "PATCH"):
            continue
        body = op.get("requestBody", {})
        content = body.get("content", {}).get("application/json", {})
        schema = content.get("schema", {})
        if not schema:
            warnings.append(f"{method.upper()} {path}: no request schema")
            continue
        props = schema.get("properties", {})
        for field, definition in props.items():
            if definition.get("type") == "string" and "maxLength" not in definition:
                warnings.append(
                    f"{method.upper()} {path}: field {field} lacks maxLength")
if warnings:
    print(f"SCHEMA GATE: {len(warnings)} warnings")
    for warning in warnings:
        print(f"  - {warning}")
    sys.exit(1)
print("SCHEMA GATE PASSED")
```

## 3. Drift gate against the live gateway

```bash
# Drift gate: spec paths versus live gateway routes on staging.
# A live route missing from the spec escapes every spec-based check,
# and a spec path missing live means the docs promise an endpoint
# that does not exist. Both fail the gate.
python3 - << 'PY'
import json, subprocess
spec_paths = set(json.load(open("openapi.json"))["paths"])
print(f"spec paths: {len(spec_paths)}")
for p in sorted(spec_paths):
    print("  spec:", p)
print("live check: probe each spec path on staging and record the")
print("status, then probe the gateway route list for unlisted paths")
print("staging route list is the source of truth for the live side")
PY
```

```bash
# CI wiring example: run both gates on every pull request, before
# the deploy step, so a failing gate never reaches staging
cat > /tmp/ci-gates-example.sh << 'EOF'
#!/bin/bash
set -e
python3 ci/openapi_gate.py
python3 ci/schema_gate.py
echo "gates passed, deploy may proceed"
EOF
chmod +x /tmp/ci-gates-example.sh
echo "place the two gate scripts under ci/ in the repo, call them"
echo "from the pipeline definition, and confirm a test branch with"
echo "an unauthenticated endpoint fails before merging is allowed"
```

## Edge cases

- The spec is generated from code annotations. Then the gate must
  run on the generated spec in CI, not on a hand edited file that
  the generator overwrites on the next build.
- Legacy endpoints cannot pass the gate yet. Waive them
  individually with an owner and an expiry, never with a blanket
  exemption, and track waiver expiry as its own gate failure.
- The gateway policy and the spec disagree on auth. Then the gate
  that compares them is the finding; do not silence it by editing
  the spec to match a weak gateway.
- Multiple spec versions live side by side. Gate each version
  separately; v1 is where old, unauthenticated operations survive.
- Gates run on pull requests but not on direct pushes to main.
  That gap makes the gates advisory; require the pipeline on every
  merge path, including hotfixes.

## Key references

- OWASP API Security Top 10, especially improper inventory
  management and unrestricted resource consumption.
- OpenAPI Specification: security requirement objects and schema
  validation keywords.
- Related skills: api-gateway-security, openapi-security-review,
  api-security-testing.

