DEV Community

Cover image for 📜 OpenAPI Recon: Find Endpoints That Skip Auth, Then Prove It
Krishna Kumar
Krishna Kumar

Posted on

📜 OpenAPI Recon: Find Endpoints That Skip Auth, Then Prove It

An OpenAPI spec is the closest thing an API has to a map. Every path, every method, and for each one, a line that says which credentials it needs. That last part is the interesting one, because nothing in the spec enforces it. The spec describes what the team intended. The server does whatever its code does.

So the spec gives you two lists worth checking. The endpoints it marks as open, which you should read carefully. And the endpoints it marks as protected, which you should confirm really are. This article shows how to pull both lists out of a spec with a short script, how to probe them with controls so you don't report noise, and how to prove a real gap.

Only test applications you own or are authorized to test. Every example below uses stand-in data and a mock API on 127.0.0.1.

Where the spec comes from

If you're testing your own API, you already have it. On an authorized test, it's often public. PortSwigger's API testing guide lists the kind of paths that may refer to documentation, such as /api, /swagger/index.html and /openapi.json, and suggests walking up the base path: from /api/swagger/v1/users/123, try /api/swagger/v1, /api/swagger and /api.

The same guide also says documentation "may be inaccurate or out of date". Keep that in mind for everything below. The spec is a lead generator, not ground truth.

How OpenAPI declares security

Four rules from the OpenAPI 3.1 specification cover almost everything you'll meet:

  1. A top-level security list declares which security mechanisms can be used across the API.
  2. An operation-level security list replaces it. The spec says this definition overrides the top-level one for that operation.
  3. An empty array removes it. security: [] on an operation means the spec declares no requirement there.
  4. An empty object makes it optional. security: [{}, {"bearerAuth": []}] means "a token works, and so does nothing".

Inside the list, each item is an alternative: only one of them has to be satisfied. Inside one item, every scheme named must be satisfied. So [{"apiKey": []}, {"oauth": [], "mtls": []}] reads as "an API key, or OAuth together with mTLS".

One case the rules don't cover: if there's no security at the top and none on the operation, the spec simply says nothing. That's "undeclared", not "public".

Step 1: list what the spec declares

Here's a stand-in spec, trimmed to what matters. The whole API needs a bearer token, except a health check (removed with []) and the product list (optional with {}).

{
  "openapi": "3.1.0",
  "info": {"title": "Stand-in API", "version": "1.0.0"},
  "servers": [{"url": "http://127.0.0.1:8000"}],
  "security": [{"bearerAuth": []}],
  "components": {
    "securitySchemes": {
      "bearerAuth": {"type": "http", "scheme": "bearer"}
    }
  },
  "paths": {
    "/api/health": {
      "get": {"operationId": "health", "security": [], "responses": {"200": {"description": "ok"}}}
    },
    "/api/products": {
      "get": {"operationId": "listProducts", "security": [{}, {"bearerAuth": []}], "responses": {"200": {"description": "ok"}}}
    },
    "/api/users/me": {
      "get": {"operationId": "me", "responses": {"200": {"description": "ok"}}}
    },
    "/api/invoices/export": {
      "get": {"operationId": "exportInvoices", "responses": {"200": {"description": "ok"}}}
    },
    "/api/orders/{id}": {
      "get": {"operationId": "getOrder", "responses": {"200": {"description": "ok"}}}
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

And a script that applies the four rules to every operation:

"""List every operation in an OpenAPI 3.x spec with the security it declares."""
import json
import sys

METHODS = ("get", "put", "post", "delete", "options", "head", "patch", "trace")


def load(path):
    with open(path, encoding="utf-8") as f:
        if path.endswith((".yaml", ".yml")):
            import yaml  # pip install pyyaml
            return yaml.safe_load(f)
        return json.load(f)


def effective(spec, op):
    # An operation-level "security" replaces the top-level one.
    if "security" in op:
        return op["security"]
    return spec.get("security")  # None: not declared anywhere


def classify(reqs):
    if reqs is None:
        return "undeclared"
    if reqs == []:
        return "public"
    if {} in reqs:
        return "optional"
    # OR between list items, AND inside one item.
    return "required: " + " | ".join("+".join(sorted(r)) for r in reqs)


def audit(spec):
    rows = []
    for path, item in spec.get("paths", {}).items():
        for method in METHODS:
            op = item.get(method)
            if op is not None:
                rows.append((method.upper(), path, classify(effective(spec, op))))
    return rows


if __name__ == "__main__":
    for method, path, auth in audit(load(sys.argv[1])):
        print(f"{method:7} {path:24} {auth}")
Enter fullscreen mode Exit fullscreen mode

Save it as spec_audit.py and run it:

$ python spec_audit.py openapi.json
GET     /api/health              public
GET     /api/products            optional
GET     /api/users/me            required: bearerAuth
GET     /api/invoices/export     required: bearerAuth
GET     /api/orders/{id}         required: bearerAuth
Enter fullscreen mode Exit fullscreen mode

On a real spec with hundreds of operations, this is the table you want before touching the API. It handles OpenAPI 3.x only; Swagger 2.0 files use a different layout.

Step 2: what to do with each bucket

  • public and optional: read what they return. "Public" was a decision someone made, and it's worth checking the data still matches it. A product list is fine. A public endpoint that returns email addresses is a different conversation (I covered how to spot extra fields in an earlier article on excessive data exposure). For optional endpoints, compare the anonymous response with the authenticated one and make sure nothing member-only leaks into the first.
  • required: these are the claims to test. The spec says a token is needed. Does the server agree?
  • undeclared: the spec doesn't tell you anything. Treat these like required and test them.

Step 3: probe with controls

The probe sends every plain GET twice, once with your token and once with no credentials at all, and compares. It skips templated paths like /api/orders/{id} and anything that isn't a GET; those you test by hand, on objects your own account owns.

Before anything else it requests a random path. That's the control. Some apps answer 200 with the same page for every URL, and without the control you'd report each one as an unauthenticated endpoint.

"""Send each GET from the spec twice, with and without your token.
Usage: TOKEN='Bearer sk_test_...' python auth_probe.py openapi.json http://127.0.0.1:8000
Only point this at an app you own or are authorized to test."""
import hashlib
import os
import sys
import urllib.error
import urllib.request
import uuid

from spec_audit import audit, load


def fetch(url, token=None):
    req = urllib.request.Request(url)
    if token:
        req.add_header("Authorization", token)
    try:
        with urllib.request.urlopen(req, timeout=10) as r:
            return r.status, r.read()
    except urllib.error.HTTPError as e:
        with e:
            return e.code, e.read()


def digest(body):
    return hashlib.sha256(body).hexdigest()[:8]


def main(spec_path, base):
    token = os.environ["TOKEN"]
    # Control: a path that can't exist. A 2xx here means a catch-all route.
    c_status, c_body = fetch(f"{base}/{uuid.uuid4().hex}")
    print(f"control  random path -> {c_status}")
    for method, path, declared in audit(load(spec_path)):
        if method != "GET" or "{" in path:
            print(f"skip     {method} {path} (not a plain GET)")
            continue
        a_status, a_body = fetch(base + path)
        t_status, t_body = fetch(base + path, token)
        same = "same body" if digest(a_body) == digest(t_body) else "different body"
        verdict = ""
        if declared.startswith("required") and 200 <= a_status < 300:
            verdict = "  <-- LEAD: auth declared, answered without it"
            if digest(a_body) == digest(c_body):
                verdict = "  (matches the control: catch-all, not a lead)"
        print(f"{declared:20} {path:24} anon={a_status} token={t_status} {same}{verdict}")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2].rstrip("/"))
Enter fullscreen mode Exit fullscreen mode

Against the stand-in API (its code is at the end of the "Fix it" section), in its vulnerable mode:

control  random path -> 404
public               /api/health              anon=200 token=200 same body
optional             /api/products            anon=200 token=200 different body
required: bearerAuth /api/users/me            anon=401 token=200 different body
required: bearerAuth /api/invoices/export     anon=200 token=200 same body  <-- LEAD: auth declared, answered without it
skip     GET /api/orders/{id} (not a plain GET)
Enter fullscreen mode Exit fullscreen mode

Read it line by line. The control says unknown paths get a 404, so a 200 means something. /api/users/me refuses the anonymous request, as declared. /api/products gives a different body with a token, which is what "optional" should look like. And /api/invoices/export, declared as needing a bearer token, answered the anonymous request with the same body the token got.

That last line is a lead. It isn't a finding yet.

Four spec declarations next to the anonymous response each got: public 200, optional 200 with a smaller body, required 401, and required 200 with the same body, which is the lead

Step 4: prove it

A 200 without a token proves the server answered. It doesn't prove the answer is something an anonymous user shouldn't have. The export might return an empty list, or a static sample, or data that's public anyway. Detection isn't proof.

The proof is a value you planted. Use your own test account to create something only that account should see, with a unique marker in it. Here, an invoice with the memo probe-7f3a. Then ask for it with no token and no cookies:

$ curl -s -i http://127.0.0.1:8000/api/invoices/export
HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.14.7
Date: Fri, 27 Nov 2026 13:17:38 GMT
Content-Type: application/json
Content-Length: 50

[{"id": 9001, "owner": 101, "memo": "probe-7f3a"}]
Enter fullscreen mode Exit fullscreen mode

The marker came back to a request that carried no identity at all. That's the finding: a function the spec documents as authenticated, answering anyone. CWE calls it CWE-306, Missing Authentication for Critical Functionality.

A few things keep the proof clean:

  • Your own data only. The marker is in your account. You don't need anyone else's records to show the gap, and you shouldn't go looking for them.
  • Really no credentials. Run the request from a plain client, not a browser tab that might attach a session cookie.
  • Repeat it. Run it again a few minutes later to rule out a cached response from an earlier authenticated request.
  • Report the claim and the reality side by side. The spec's security entry for the operation, the anonymous request, and the marker in the response. A developer can check all three in a minute.

Fix it: deny by default, then hold the spec to it

The bug here is almost never "someone removed the check". It's that the check lived in each handler, and one handler didn't have it. In the stand-in API, the vulnerable build checks the token inside /api/users/me only.

OWASP's API5:2023 entry on broken function level authorization puts the fix plainly: enforcement should "deny all access by default", with explicit grants. Move the check out of the handlers and in front of them, with one small list of routes that are allowed through without a user:

"""Stand-in API for practice. Usage: python mock_api.py vulnerable|fixed"""
import json
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer

TOKENS = {"Bearer sk_test_alice": 101}
PUBLIC = {"/api/health", "/api/products"}  # the fix: an explicit allowlist

ROUTES = {
    "/api/health": lambda user: {"status": "ok"},
    "/api/products": lambda user: [
        {"sku": "A1", "price": 20, **({"member_price": 18} if user else {})}
    ],
    "/api/users/me": lambda user: {"id": user, "email": "alice@example.com"},
    "/api/invoices/export": lambda user: [
        {"id": 9001, "owner": 101, "memo": "probe-7f3a"}
    ],
}
# The vulnerable build forgot the check on one handler.
CHECKED_IN_HANDLER = {"/api/users/me"}


def make_handler(mode):
    class Handler(BaseHTTPRequestHandler):
        def do_GET(self):
            user = TOKENS.get(self.headers.get("Authorization", ""))
            route = ROUTES.get(self.path)
            if route is None:
                return self.send(404, {"error": "not found"})
            if mode == "fixed":
                # Deny by default: every route needs a user unless allowlisted.
                if self.path not in PUBLIC and user is None:
                    return self.send(401, {"error": "unauthorized"})
            elif self.path in CHECKED_IN_HANDLER and user is None:
                return self.send(401, {"error": "unauthorized"})
            self.send(200, route(user))

        def send(self, status, body):
            data = json.dumps(body).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)

        def log_message(self, *args):
            pass

    return Handler


if __name__ == "__main__":
    mode = sys.argv[1] if len(sys.argv) > 1 else "vulnerable"
    HTTPServer(("127.0.0.1", 8000), make_handler(mode)).serve_forever()
Enter fullscreen mode Exit fullscreen mode

The important property is the default. A route added next month is protected until someone adds it to PUBLIC on purpose. In a real app, put this check wherever your framework runs code before every handler (middleware, a before-request hook, a global dependency), not inside each handler.

Rerun the probe against python mock_api.py fixed and the lead is gone:

required: bearerAuth /api/invoices/export     anon=401 token=200 different body
Enter fullscreen mode Exit fullscreen mode

Prove the fix: make the spec and the code agree in a test

Two things can drift apart again: the code's allowlist and the spec's idea of what's open. One test can watch both. The first check says the spec's public and optional operations are exactly the code's PUBLIC set. The second sends an anonymous request to every other route and expects a 401.

import os
import threading
import unittest
import urllib.error
import urllib.request
from http.server import HTTPServer

import mock_api
from spec_audit import audit, load

SPEC = load("openapi.json")


class AuthByDefault(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        mode = os.environ.get("MODE", "fixed")
        cls.server = HTTPServer(("127.0.0.1", 0), mock_api.make_handler(mode))
        cls.base = f"http://127.0.0.1:{cls.server.server_port}"
        threading.Thread(target=cls.server.serve_forever, daemon=True).start()

    @classmethod
    def tearDownClass(cls):
        cls.server.shutdown()

    def status(self, path):
        try:
            with urllib.request.urlopen(self.base + path, timeout=5) as r:
                return r.status
        except urllib.error.HTTPError as e:
            e.close()
            return e.code

    def test_spec_public_list_matches_code(self):
        declared_open = {p for _, p, a in audit(SPEC) if a in ("public", "optional")}
        self.assertEqual(declared_open, mock_api.PUBLIC)

    def test_every_other_route_rejects_anonymous(self):
        for path in mock_api.ROUTES:
            if path in mock_api.PUBLIC:
                continue
            with self.subTest(path=path):
                self.assertEqual(self.status(path), 401)


if __name__ == "__main__":
    unittest.main()
Enter fullscreen mode Exit fullscreen mode

A test only proves something if it can fail. Run it against the vulnerable build first (traceback trimmed):

$ MODE=vulnerable python -m unittest test_auth_default
F.
FAIL: test_every_other_route_rejects_anonymous (...) (path='/api/invoices/export')
AssertionError: 200 != 401

Ran 2 tests in 0.684s

FAILED (failures=1)
Enter fullscreen mode Exit fullscreen mode

And against the fix:

$ MODE=fixed python -m unittest test_auth_default
..
Ran 2 tests in 0.605s

OK
Enter fullscreen mode Exit fullscreen mode

Note that the test walks the code's route table, not the spec. That's deliberate: a route that exists in the code but never made it into the spec still gets tested. OWASP's API9:2023 entry on inventory management points the same way: generate documentation from open standards and build it in your CI/CD pipeline, so the spec stays close to the code instead of drifting from it.

All the code above was run locally on Python 3.14 against the stand-in API, and every output shown is from those runs.

Try it yourself

Legal places to practice:

  • The stand-in above. Start mock_api.py in vulnerable mode, run the audit and the probe, plant your own marker, then switch to fixed and run the test both ways.
  • VAmPI. It ships OpenAPI specs in its openapi_specs directory and serves Swagger UI at /ui. Run it with docker run -p 5000:5000 erev0s/vampi:latest, audit the spec, and check whether the server agrees with it.
  • OWASP crAPI. Challenge 14 asks you to find an endpoint that doesn't perform authentication checks for a user.
  • PortSwigger Web Security Academy. The lab Exploiting an API endpoint using documentation starts with finding exposed docs, then using them.

Conclusion

An OpenAPI spec tells you what the team meant: which endpoints are open, which need a token. The script turns that into two lists. Public and optional endpoints get read for what they return. Required and undeclared ones get an anonymous request, with a random-path control so a catch-all route doesn't fool you. A 200 there is a lead; your own planted marker in the anonymous response is the proof. The fix is a deny-by-default check with a short allowlist, and a test that keeps the spec and that allowlist in step.

Further reading

I'm Krishna, a pentester and the founder of Xalgorix, an open-source AI pentester that only reports vulnerabilities it has actually exploited.


🔐 If this was useful, follow me for more hands-on web & API security write-ups.

🔗 Connect with me on LinkedIn: https://www.linkedin.com/in/xalgord/

Top comments (0)