Multi-tenant API authorization comparison lab
Reproduce the owned Multi-tenant BOLA experiment and inspect its implementation and evidence limits.
Application Security 1 min read
Implementation
api.py Python · 196 lines
vulnerability-research/api-bola-multi-tenant/lab/api.py
1"""Intentionally vulnerable and remediated owned APIs, Python 3.13+.
2
3The in-memory repository models a data-access boundary, not SQL/RLS.
4"""
5import copy
6import hashlib
7import json
8import secrets
9import threading
10import time
11from http.cookies import SimpleCookie
12from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
13from urllib.parse import urlsplit
14
15
16def seed():
17 return {
18 "tenants": {"tenant-a": "Synthetic A", "tenant-b": "Synthetic B"},
19 "users": {
20 "alice": {"tenant": "tenant-a", "role": "manager"},
21 "aaron": {"tenant": "tenant-a", "role": "reader"},
22 "bob": {"tenant": "tenant-b", "role": "manager"}},
23 "customers": {
24 "customer-a": {"tenant": "tenant-a", "owner": "alice"},
25 "customer-aaron": {"tenant": "tenant-a", "owner": "aaron"},
26 "customer-b": {"tenant": "tenant-b", "owner": "bob"}},
27 "documents": {
28 "doc-a": {"tenant": "tenant-a", "owner": "alice", "customer": "customer-a",
29 "title": "SYNTHETIC_A", "amount_cents": 1000},
30 "doc-aaron": {"tenant": "tenant-a", "owner": "aaron", "customer": "customer-aaron",
31 "title": "SYNTHETIC_AARON", "amount_cents": 2000},
32 "doc-b": {"tenant": "tenant-b", "owner": "bob", "customer": "customer-b",
33 "title": "SYNTHETIC_B", "amount_cents": 3000}},
34 "refunds": []}
35
36
37class Rejected(Exception):
38 def __init__(self, status, reason):
39 self.status, self.reason = status, reason
40
41
42class Repository:
43 def __init__(self, state, secure):
44 self.state, self.secure = state, secure
45
46 def visible(self, actor, row):
47 return row["tenant"] == actor["tenant"] and row["owner"] == actor["user"]
48
49 def object(self, actor, object_id):
50 row = self.state["documents"].get(object_id)
51 if row is None or (self.secure and not self.visible(actor, row)):
52 raise Rejected(404, "not_found")
53 return row
54
55 def export(self, actor, client_tenant):
56 if self.secure:
57 return {key: copy.deepcopy(row) for key, row in self.state["documents"].items()
58 if self.visible(actor, row)}
59 return {key: copy.deepcopy(row) for key, row in self.state["documents"].items()
60 if row["tenant"] == (client_tenant or actor["tenant"])}
61
62 def execute(self, actor, operation, object_id=None, body=None, client_tenant=None):
63 body = body or {}
64 if operation == "export":
65 return {"documents": self.export(actor, client_tenant)}
66 row = self.object(actor, object_id)
67 if self.secure and operation not in {"read", "update", "delete", "refund"}:
68 raise Rejected(403, "operation_denied")
69 if self.secure and operation in {"update", "delete", "refund"} and actor["role"] != "manager":
70 raise Rejected(403, "operation_denied")
71 if operation == "read":
72 return copy.deepcopy(row)
73 if operation == "update":
74 if self.secure:
75 if set(body) != {"title"} or not isinstance(body["title"], str) or not 1 <= len(body["title"]) <= 80:
76 raise Rejected(400, "invalid_fields")
77 row.update(body) # Vulnerable path permits authorization-driving fields.
78 return copy.deepcopy(row)
79 if operation == "delete":
80 del self.state["documents"][object_id]
81 return {"deleted": True}
82 if operation == "refund":
83 if self.secure and body:
84 raise Rejected(400, "invalid_fields")
85 # Customer relationship is derived from the authorized object.
86 customer = self.state["customers"].get(row["customer"])
87 if self.secure and (not customer or customer["tenant"] != actor["tenant"]
88 or customer["owner"] != actor["user"]):
89 raise Rejected(404, "not_found")
90 refund = {"document": object_id, "customer": row["customer"],
91 "tenant": row["tenant"], "amount_cents": row["amount_cents"]}
92 self.state["refunds"].append(refund)
93 return {"refund": copy.deepcopy(refund)}
94 raise Rejected(403, "operation_denied")
95
96
97class Application:
98 def __init__(self, secure):
99 self.secure, self.state, self.sessions, self.audit = secure, seed(), {}, []
100 self.repository = Repository(self.state, secure)
101 self.lock = threading.Lock()
102
103 def session(self, user, lifetime=300):
104 token = secrets.token_urlsafe(32)
105 self.sessions[hashlib.sha256(token.encode()).hexdigest()] = {
106 "user": user, **self.state["users"][user], "expires": time.time() + lifetime}
107 return token
108
109 def authenticate(self, cookie):
110 cookies = SimpleCookie()
111 try:
112 cookies.load(cookie or "")
113 token = cookies["lab_session"].value
114 except (KeyError, ValueError):
115 raise Rejected(401, "unauthenticated") from None
116 actor = self.sessions.get(hashlib.sha256(token.encode()).hexdigest())
117 if not actor or actor["expires"] <= time.time():
118 raise Rejected(401, "unauthenticated")
119 return actor
120
121 def dispatch(self, method, path, headers, body):
122 actor, operation = None, "unknown"
123 try:
124 actor = self.authenticate(headers.get("Cookie"))
125 parsed = urlsplit(path)
126 pieces = parsed.path.strip("/").split("/")
127 client_tenant = headers.get("X-Tenant-ID")
128 if pieces == ["export"] and method == "GET":
129 operation, object_id = "export", None
130 elif len(pieces) == 2 and pieces[0] == "documents":
131 operation = {"GET": "read", "PATCH": "update", "DELETE": "delete"}.get(method)
132 object_id = pieces[1]
133 elif len(pieces) == 3 and pieces[0] == "documents" and pieces[2] == "refund" and method == "POST":
134 operation, object_id = "refund", pieces[1]
135 elif pieces == ["agent", "refund"] and method == "POST":
136 operation, object_id = "refund", body.get("document")
137 body = {key: value for key, value in body.items() if key != "document"}
138 if not self.secure:
139 # Deliberate confused deputy: replaces user context with object owner's context.
140 row = self.state["documents"].get(object_id)
141 if row:
142 user = row["owner"]
143 actor = {"user": user, **self.state["users"][user]}
144 else:
145 raise Rejected(404, "not_found")
146 if not operation:
147 raise Rejected(403, "operation_denied")
148 with self.lock:
149 result = self.repository.execute(actor, operation, object_id, body, client_tenant)
150 self.audit.append({"event": "authorization", "decision": "allow",
151 "operation": operation, "principal": actor["user"],
152 "tenant": actor["tenant"]})
153 return 200, result
154 except Rejected as error:
155 self.audit.append({"event": "authorization", "decision": "deny",
156 "operation": operation or "unknown", "reason": error.reason,
157 "principal": actor["user"] if actor else "anonymous",
158 "tenant": actor["tenant"] if actor else None})
159 return error.status, {"error": error.reason}
160
161
162def handler(application):
163 class Handler(BaseHTTPRequestHandler):
164 def log_message(self, *_args):
165 pass
166
167 def handle_request(self):
168 try:
169 length = int(self.headers.get("Content-Length", "0"))
170 if not 0 <= length <= 4096:
171 raise ValueError("length")
172 body = json.loads(self.rfile.read(length)) if length else {}
173 if not isinstance(body, dict):
174 raise ValueError("body")
175 status, result = application.dispatch(self.command, self.path, self.headers, body)
176 except (ValueError, TypeError):
177 status, result = 400, {"error": "invalid_request"}
178 encoded = json.dumps(result, sort_keys=True).encode()
179 self.send_response(status)
180 self.send_header("Content-Type", "application/json")
181 self.send_header("Cache-Control", "no-store")
182 self.send_header("Content-Length", str(len(encoded)))
183 self.end_headers()
184 self.wfile.write(encoded)
185
186 do_GET = do_PATCH = do_DELETE = do_POST = handle_request
187 return Handler
188
189
190def serve(application):
191 # No bind to a public interface, even when run without Docker.
192 server = ThreadingHTTPServer(("127.0.0.1", 0), handler(application))
193 server.daemon_threads = True
194 thread = threading.Thread(target=server.serve_forever, daemon=True)
195 thread.start()
196 return server
Run it
python3 vulnerability-research/api-bola-multi-tenant/lab/test_api.py
The canonical setup and teardown contains prerequisites, isolation, complete code, commands, expected output and evidence collection. The research study contains the threat model, comparison matrix, limitations and consulted sources.
Run from repository root after reading that setup:
python3 vulnerability-research/api-bola-multi-tenant/lab/test_api.py
These are owned teaching targets. Cloud deployment is excluded. See the study's claim ledger before treating local model output as product enforcement evidence.