Repository navigation
Secure Error Handling Fail Closed Problem Details and Safe Logging
Last reviewed: 2026-11-28
Caution
Authorized use only. Forcing errors and dependency outages is a test technique. Use it on your own services, the local Secure API lab, or within a written scope. See LEGAL.md.
Prerequisites: API authorization ยท OWASP Top 10:2025 overview
Make an API's failures safe. Errors must deny rather than allow, clients get a standard and generic error body, and the detail an engineer needs goes to a protected log without secrets.
Covers OWASP Top 10:2025 A10 (Mishandling of Exceptional Conditions), RFC 9457 Problem Details for HTTP APIs, ASVS 5.0.0 V16.3-16.5, and the OWASP Error Handling and Logging cheat sheets. Code is from the lab's impl/fixed_api.py and impl/labcore.py, plus a tested stdlib handler.
No unhandled exception reaches a client, no error path grants access or half-completes a transaction, and every failure can be investigated from the server-side log without that log leaking credentials.
- Writing exception handlers, middleware or an API gateway error policy
- Calling a policy service, database, IdP or third-party API that can fail
- Designing an API's error format
- Reviewing a finding about verbose errors or fail-open behaviour
- Fail Closed
- Problem Details: RFC 9457
- Last-Resort Handler
- Logging Without Leaking
- Verification Tests
OWASP Top 10:2025 adds A10:2025 Mishandling of Exceptional Conditions as a new category with 24 CWEs, including CWE-209 (error message containing sensitive information) and CWE-636 Not Failing Securely ("Failing Open"). On transactions it says to "roll back every part of the transaction and start again (also known as failing closed)". ASVS 16.5.3 asks that the application fails securely, "preventing fail-open conditions such as processing a transaction despite errors resulting from validation logic".
The common fail-open bug is an authorization call wrapped in try/except whose except branch lets the request through. The fixed lab treats any policy error as a denial and says so with 503:
try:
allowed = self.env.policy.is_allowed(user, "read", report) is True
except Exception as exc:
self.env.log.append(f"policy check failed, denying: {exc!r}")
return problem(503, "Service Unavailable", "authorization is temporarily unavailable",
headers=[("Retry-After", "30")])
return json_response(200, report) if allowed else problem(404, "Not Found")In fail-closed-authz-exception, with the policy service switched off, a non-owner read the report on the vulnerable twin (200) and was refused on the fixed twin (503).
Rules of thumb:
- Initialize decisions to "deny" and only set "allow" on a positive, well-typed result (
is True). - Use database transactions so a multi-step operation either completes or rolls back (ASVS 2.3.3).
- When an optional dependency fails, degrade the feature, not the security check (ASVS 16.5.2 names circuit breakers and graceful degradation).
- Timeouts are failures. A policy call that times out denies.
RFC 9457 (July 2023, obsoletes RFC 7807) defines application/problem+json with these members:
| Member | Meaning | Section |
|---|---|---|
type |
URI identifying the problem type; assumed about:blank when absent |
ยง3.1.1, ยง4.2.1 |
status |
The HTTP status code, repeated for convenience | ยง3.1.2 |
title |
Short, human-readable summary of the problem type | ยง3.1.3 |
detail |
Explanation specific to this occurrence | ยง3.1.4 |
instance |
URI reference identifying this occurrence | ยง3.1.5 |
| Extensions | Additional members, such as invalid_fields
|
ยง3.2 |
ยง5 warns generators "to avoid making implementation details such as a stack dump available through the HTTP interface". The lab's helper:
def problem(status: int, title: str, detail: str | None = None, headers=None, **extra) -> Response:
"""RFC 9457 problem details. ``type`` is left at its default, about:blank."""
body = {"type": "about:blank", "title": title, "status": status}
if detail:
body["detail"] = detail
body.update(extra)
return Response(status, json.dumps(body).encode("utf-8"), "application/problem+json", headers)Put only caller-safe facts in detail and extensions: which field failed validation, which limit was hit. Never put SQL, file paths, internal hostnames, exception text or tokens there. Use the same message for "wrong user" and "wrong password", and the same 404 for "not yours" and "missing".
ASVS 16.5.4 asks for a "last resort" error handler that catches all unhandled exceptions. ASVS 16.5.1 asks that the client then gets a generic message with no "stack traces, queries, secret keys, and tokens". The OWASP Error Handling Cheat Sheet describes the same pattern: a global handler that logs the detail and returns a generic response.
A framework-neutral version with a correlation ID, and the test that proves it. Run as written on Python 3.14.10:
import json, logging, uuid
log = logging.getLogger("api")
def problem(status: int, title: str, detail: str | None = None, **extra) -> tuple[int, dict, bytes]:
"""RFC 9457 body; "type" defaults to about:blank (section 4.2.1)."""
body = {"type": "about:blank", "title": title, "status": status, **extra}
if detail:
body["detail"] = detail
return status, {"Content-Type": "application/problem+json"}, json.dumps(body).encode()
def handle(route, request):
"""Last-resort handler: full detail to the server log, a generic body to the client."""
try:
return route(request)
except Exception:
incident = uuid.uuid4().hex
log.exception("unhandled error incident=%s path=%r", incident, request.get("path"))
return problem(500, "Internal Server Error", incident=incident)
def broken(request):
return 1 / int(request["count"])
import unittest
class ProblemDetailsTest(unittest.TestCase):
def test_unhandled_error_is_generic(self):
with self.assertLogs("api", level="ERROR") as logs:
status, headers, body = handle(broken, {"path": "/api/stats", "count": "0"})
self.assertEqual(500, status)
self.assertEqual("application/problem+json", headers["Content-Type"])
doc = json.loads(body)
self.assertEqual({"type", "title", "status", "incident"}, set(doc))
self.assertNotIn(b"Traceback", body)
self.assertNotIn(b"ZeroDivisionError", body)
self.assertIn("ZeroDivisionError", "\n".join(logs.output)) # detail kept server-sideThe incident value lets support find the log entry from a user's report without the response revealing anything. In error-problem-details-no-stacktrace, the vulnerable lab twin returned a Python traceback as text/plain. The fixed twin returned application/problem+json with no traceback and logged the error server-side.
| Rule | Source |
|---|---|
| Log authentication attempts, failed authorization and security-control failures | ASVS 16.3.1-16.3.4 |
| Encode or sanitize logged data to prevent log injection (CR, LF, delimiters); prefer structured formats | ASVS 16.4.1; OWASP Logging CS |
| Protect logs from unauthorized access and modification; ship them to a separate system | ASVS 16.4.2, 16.4.3 |
| Do not log session IDs, access tokens, passwords, connection strings or keys directly; remove, mask, hash or encrypt them | OWASP Logging CS "Data to exclude" |
In Python, %r formatting (as in the handler above) escapes CR and LF in the logged value. A JSON log formatter does the same for every field. Log a hash or the last few characters of a token if you need to correlate, never the token.
| Test | Expected |
|---|---|
Force an exception in a handler (division by zero, None attribute) |
500 application/problem+json, no traceback or exception name in the body, a log entry with the detail |
| Switch off the policy service or make it time out | The protected request is denied (503 or 403), never served |
| Fail the second step of a multi-step write | No partial state remains |
| Send malformed JSON, a wrong type, an unknown field | 400 problem body naming the field, no parser internals |
| Request a missing object and another user's object | Identical 404 bodies |
Send \r\n in a logged field |
One log record, with the characters escaped |
- RFC 9457: Problem Details for HTTP APIs
- OWASP Top 10:2025 A10 Mishandling of Exceptional Conditions
- OWASP ASVS 5.0.0 V16 Security Logging and Error Handling
- OWASP Error Handling Cheat Sheet ยท Logging Cheat Sheet
- README.md - Web Application Security index
-
labs/secure-api/impl/fixed_api.py -
handle,get_report - labs/secure-api/README.md - Lab cases and CI evidence
โฌ ๏ธ Web Application Security index | Master Index | ๐ฏ Role Navigation | Legal Notice
๐ Source: WebAppSecurity/secure-error-handling.md | โ๏ธ Suggest an edit | โฌ
๏ธ Back to Web App Security
- ๐บ๏ธ Browse by Topic
- ๐ All Repository Files
- ๐งญ Learning Paths
- ๐ Master Guide
- ๐ค Glossary
- โ๏ธ Legal & Disclaimer
๐ Foundations & Learning
๐ก๏ธ Defense & Investigations
- Incident Response
- Open Source Intelligence (OSINT)
- Reverse Engineering
- Operations Security (OPSEC)
- Compliance
โ๏ธ Platforms & Infrastructure
๐ก Hardware, Wireless & Field Projects
- PNWC Cyberdeck
- Hardware Testing
- Hardware Hacking
- Software-Defined Radio
- Wardriving
- uConsole
- Space Security
๐งฐ Assessment & Field Reference
๐ฆ Downloads & Project Resources
๐๏ธ Additional Topics