Conghao97's picture tcftrees's picture
ProgramGen release
d086025
|
Raw History Blame Contribute Delete
34.5 kB
# 0x7d7b/flask-oauth2-validation
## Project Overview
flask-oauth2-validation is a Python package that equips Flask applications with OAuth2 (RFC-6749) access-token validation for self-encoded JWT (RFC-7519) Bearer tokens (RFC-6750). It targets resource servers (APIs) only: it validates incoming tokens but deliberately implements none of the OAuth2 flows themselves, such as the authorization code flow. Validation works with any authorization server that publishes Authorization Server Metadata (RFC-8414) and issues JWT access tokens following the JWT Profile for OAuth 2.0 Access Tokens (RFC-9068). The package supports two complementary checks: local validation, in which the token's signature is verified against the issuer's public keys (RFC-7517 JWK set, RFC-7800) fetched from the server, and remote validation via OAuth2 token introspection (RFC-7662) using client credentials. Configuration is driven from Flask's app.config, with OAUTH2_ISSUER as the only required attribute, plus optional OAUTH2_CLIENT_ID, OAUTH2_CLIENT_SECRET for introspection, OAUTH2_JWKS_UPDATE_INTERVAL for rotating signing keys, and OAUTH2_AUDIENCE for stricter audience checks. The primary entry point is the OAuth2Decorator class, exported from the top-level flask_oauth2_validation module: once instantiated with the Flask app, its requires_token() decorator protects any route, accepting introspect=True to add remote validation and scopes=[...] to enforce required scopes, while a token property exposes the parsed token to view handlers. Architecturally, the project is a compact src-layout library: decorator.py holds the OAuth2Decorator and its validation pipeline, exceptions.py defines the package's error types, and __init__.py provides the public API. The repository also ships a setuptools-based build (setup.py/pyproject.toml), a tests/ suite, tox.ini, and GitHub Actions workflows for build, test, and coverage. It is MIT-licensed by Henrik Sachse.
Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.
## Submission Constraints (read carefully — the evaluation depends on these)
This is a **closed-book** task. The graded test suite is **hidden** and will be
injected into the workspace at evaluation time. To be scored correctly you MUST
follow these rules:
1. **Do NOT create or modify any files under the test directories** (e.g.
`tests/`, `test/`, `testing/`, or files named `test_*.py` / `conftest.py`).
The grader injects its own test files at those paths; any file you place
there will collide with the injected suite and cause the whole evaluation to
score 0. Implement **only** the library/source code — never the tests.
2. **Your package MUST be importable by the name the tests use.** The hidden
tests `import` your package by its documented top-level name (see the
Project Directory Structure and API Usage Guide below). Provide a valid
`pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that
`pip install -e .` succeeds and the package imports cleanly. If your package
is not installable/importable, every test errors out and the reward is 0.
3. **Match the documented module paths and public API exactly** (names,
signatures, and any literal error/exception strings). Internal helpers not
listed in the API guide may be implemented however you like.
## Install / Reconstruction Contract
Follow this contract before implementing the documented APIs:
- **Project root**: `/workspace/repo` at runtime; the submitted repository root is `.`.
- **Package/distribution name**: `flask-oauth2-validation`
- **Package roots**: `src`
- **Install strategy**: `editable-install`
- **Import/entry**: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
- **Provision commands**:
```bash
python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQg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C4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))'
programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; }
export -f programgen_pip_install
programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel
programgen_pip_install python3 -m pip install 'setuptools>=42' wheel
(
programgen_install_report="$(mktemp)"
trap 'rm -f "$programgen_install_report"' EXIT
SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report"
python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n metadata=item.get('"'"'metadata'"'"', {})\n name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n selected={'"'"''"'"'} | (provided & requested)\n parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n while True:\n added=set()\n for requirement in parsed:\n if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n continue\n if canonicalize_name(requirement.name)==name:\n if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n raise ValueError('"'"'local extra requires a different target distribution'"'"')\n extras={canonicalize_name(value) for value in requirement.extras}\n if not extras <= provided:\n raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n added.update(extras - selected)\n if not added:\n break\n selected.update(added)\n for requirement in parsed:\n if canonicalize_name(requirement.name)==name:\n continue\n if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n requirement.marker=None\n requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report"
)
```
- **Runtime setup**:
```bash
{
[ -e "$PWD"/README.md ] || { mkdir -p "$(dirname "$PWD"/README.md)"; : > "$PWD"/README.md; };
SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps;
}
```
- **Project root for installation**: `.`
- **Build-version environment**: `SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0`, `PDM_BUILD_SCM_VERSION=0.0.0`, `POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0`, `UV_DYNAMIC_VERSIONING_BYPASS=0.0.0`
- **Test directory**: `tests`, `tests/functional`
- **Test command**: `bash -lc 'set -uo pipefail
run=(python3 -m pytest -vv -o addopts= tests/functional/test_config.py tests/functional/test_validation.py)
if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/functional/test_config.py tests/functional/test_validation.py); fi
collect=(python3 -m pytest -q -o addopts= tests/functional/test_config.py tests/functional/test_validation.py)
collected_output=$("${collect[@]}" --collect-only)
collect_rc=$?
if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then
printf "%s\n" "$collected_output" >&2
printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2
exit "$collect_rc"
fi
mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"')
if [ "${#collected[@]}" -gt 500 ]; then
while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"')
fi
"${run[@]}"; exit $?'`
- **Test startup**: run the exact test command above from the project root after installation; hidden tests are injected separately.
## Environment & Project Structure
- **Language**: python
- **Build system**: python
- **Test command**: `bash -lc set -uo pipefail
run=(python3 -m pytest -vv -o addopts= tests/functional/test_config.py tests/functional/test_validation.py)
if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/functional/test_config.py tests/functional/test_validation.py); fi
collect=(python3 -m pytest -q -o addopts= tests/functional/test_config.py tests/functional/test_validation.py)
collected_output=$("${collect[@]}" --collect-only)
collect_rc=$?
if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then
printf "%s\n" "$collected_output" >&2
printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2
exit "$collect_rc"
fi
mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//')
if [ "${#collected[@]}" -gt 500 ]; then
while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}')
fi
"${run[@]}"; exit $?`
### Project Directory Structure
```
.github/workflows/build.yml
.github/workflows/release.yml
.github/workflows/test.yml
.gitignore
.vscode/settings.json
LICENSE
README.md
pyproject.toml
setup.py
src/flask_oauth2_validation/__init__.py
src/flask_oauth2_validation/decorator.py
src/flask_oauth2_validation/exceptions.py
tox.ini
```
## API Usage Guide
Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.
### Capability: Decorator initialization and Flask configuration
# Capability: `OAuth2Decorator` initialization and Flask configuration
## Purpose
Constructing `OAuth2Decorator(app)` turns a Flask app's `app.config` into a fully wired token-validation object. Construction is **eager**: it validates required settings, performs blocking network I/O against the authorization server (issuer metadata and signing keys), and optionally attaches a background key-refresh executor to the app. If construction returns, the decorator is immediately usable; if any prerequisite is missing or the issuer is unreachable, construction raises `TypeError` and the app must not start serving protected routes. All request-time validation errors, by contrast, are expressed as `OAuth2Exception` subclasses converted into HTTP responses - construction never returns a half-configured object.
## Configuration contract
Five config keys are read, each first ensured to exist via `app.config.setdefault(key, None)`. This means instantiation **mutates `app.config`**: after construction, all five keys exist, with `None` for anything the integrator did not set. Configuration is snapshotted at construction; later changes to `app.config` are ignored.
- `OAUTH2_ISSUER` - the only mandatory setting. The check is truthiness (`if not app.config.get('OAUTH2_ISSUER')`), so an empty string or `None` raises `TypeError('An OAUTH2_ISSUER config property is required')`. No URL syntax validation is performed.
- `OAUTH2_CLIENT_ID` - optional. Its presence (truthiness) is what toggles introspection wiring; there is no explicit flag.
- `OAUTH2_CLIENT_SECRET` - required **iff** a client id is present: a truthy `OAUTH2_CLIENT_ID` with a falsy secret raises `TypeError('OAUTH2_CLIENT_SECRET config property required')`. The inverse - a secret without a client id - is silently accepted and ignored (introspection is never wired).
- `OAUTH2_AUDIENCE` - optional, snapshotted at init. String values must equal the token's `aud` claim exactly; a `dict` value is tested by key membership (`decoded['aud'] in self._audience`), so configure a dict whose *keys* are acceptable audiences. Any other type (e.g. a list) makes the audience check degenerate: only the presence of `aud` in the claims is enforced, and any value passes. Any audience mismatch is reported at request time as 401 `Invalid token audience`.
- `OAUTH2_JWKS_UPDATE_INTERVAL` - optional; any truthy value (seconds) creates a `flask_executor.Executor(app, 'oauth2_jwks_update_task')`. `0`/`None` disables background refresh; keys stay fixed for the process lifetime.
## Construction sequence and its external effects
The constructor runs these steps in a fixed order; each can fail with `TypeError`:
1. Apply `setdefault` defaults, set `self.token = None`, initialize internal state (`_jwt`, `_issuer_public_keys`, `_cached_metadata`, `_jwks_update_mutex`, etc.).
2. Validate the issuer (raise on falsy).
3. Validate the client-id/client-secret pairing.
4. **Metadata lookup (RFC-8414):** `GET {issuer}/.well-known/oauth-authorization-server` via `requests.get` - plain string concatenation with no trailing-slash normalization (an issuer ending in `/` produces a `//` path). The JSON response is cached in `_cached_metadata`; every later `_lookup_metadata` call in the same constructor (and there are up to three: `jwks_uri`, then, if introspecting, `introspection_endpoint` and `introspection_endpoint_auth_methods_supported`) reuses that cache. Net effect: **exactly one metadata request per decorator instance**, regardless of how many keys are read from it. A non-200 status raises a `TypeError` whose string is the bare status code; a missing key raises `TypeError('No attribute <key> found in authorization server metadata')`; both are then re-wrapped by the outer handler into `TypeError('Cannot request authorization server metadata: <cause>')`. Connection errors and JSON parse errors land in the same wrapper. There is no timeout, so an unresponsive authorization server blocks app startup.
5. **JWKS fetch (RFC-7517):** `GET {jwks_uri}`; non-200 or any transport/parse failure raises `TypeError('Cannot request public keys from <jwks_uri>: <cause>')` - but with a message-doubling quirk for the non-200 case: the inner status `TypeError` already carries the full `Cannot request public keys from <uri>:` prefix and is then re-caught by the generic wrapper, so the actually raised message is `Cannot request public keys from <uri>: Cannot request public keys from <uri>: <status>`, while connection/JSON failures keep the single-prefixed form. Exact-message assertions in tests must distinguish the two. The response JSON must contain a `keys` array; entries are indexed by their `kid`, and entries without a `kid` are silently dropped. If the document has no `keys` member at all, `_issuer_public_keys` stays `None` and construction **succeeds** - but every later token validation fails with a 401 (`Invalid token signature`) because no public key can ever be resolved.
6. `_jwks_last_update_timestamp = time.time()` and the `jwt.JWT()` instance are created.
7. If `OAUTH2_JWKS_UPDATE_INTERVAL` is truthy, an `Executor` named `oauth2_jwks_update_task` is created **bound to the app**. This requires the `flask_executor` dependency and adds executor plumbing to the app; without an interval, no executor exists and no background refresh ever happens.
8. If (and only if) both client credentials are set, the introspection endpoint is read from the cached metadata (missing key -> wrapped `TypeError`), then the supported auth methods are negotiated: `client_secret_post` is preferred, falling back to `client_secret_basic`; any other list raises `TypeError('The introspection auth methods are not supported: <m1> <m2> ...')`. The chosen method is stored and later dictates the shape of introspection requests (form-body credentials vs. a Basic credential in an `Authentication` header - note the non-standard header name used at request time).
Because steps 4-8 hit the network synchronously, an issuer that does not publish RFC-8414 metadata makes the library unusable even for pure local validation: `jwks_uri` is always fetched first.
## How initialization choices shape request-time behavior
- **Instance, not app, cache:** metadata is cached per decorator instance and never refreshed. JWKS keys are the only thing that can rotate, and only when an update interval was configured at init.
- **Refresh trigger:** with an executor present, every invocation of a protected view submits `_update_keys`; the refresh actually runs only when `int(last_update) + interval < now`, is serialized by a mutex, and updates the timestamp *before* attempting the fetch, so a failing refresh is throttled to one attempt per interval and leaves the previous key set in place (failures are logged, never raised).
- **Introspection availability:** `requires_token(introspect=True)` on an instance constructed without client credentials raises `OAuth2InvalidTokenException('Invalid configuration')` -> HTTP 401 with `error="invalid_token"`, before the token is even parsed.
- **Remote introspection outcomes:** when `introspect=True` and local validation has passed, a POST is sent to the introspection endpoint with **no timeout**. A non-200 status is logged (`Unexpected introspection status code: <code>`) and treated as an ordinary validation failure - the request gets the generic 401 `Invalid token`, not a dedicated error. A 200 response only counts as success if the JSON body contains a truthy `active` field (`'active' in body and body['active']`); `active: false` or a missing `active` also fails. A JSON parse failure is not handled locally and falls into the catch-all, surfacing as 401 `Token validation failed`.
- **Scope enforcement (403):** required scopes come from `requires_token(scopes=[...])` and are checked after the signature, issuer and audience checks pass. The token must carry an `scp` claim, which is consumed as a collection (`set(decoded['scp'])`). If `scp` is absent entirely, the 403 response's `scope` attribute lists **all** required scopes; if `scp` is present but omits requested scopes, it lists only the missing ones. In both cases the value is the sorted, de-duplicated scope names joined by single spaces, and the response is the 403 `insufficient_scope` variant (`scope="..."` instead of `error_description`).
- **`self.token`:** initialized to `None`; after each *successful* local validation it holds the decoded claim set (a dict). It is **not cleared on failure**, so it can hold a stale previous request's token - only read it after `requires_token` has passed for the current request. It is also assigned before any requested introspection runs, so it can be populated even for a request that then 401s (see the truthiness bullet below).
- **Key matching:** the token header's `kid` (extracted by base64-decoding the first dot-separated segment with recomputed padding) must exist in the init-downloaded key map; an unknown kid yields 401 `Invalid token signature`, while an undecodable header yields 400 `Invalid token format`. A third, distinct branch covers a header segment that base64-decodes and parses as JSON but contains no `kid` at all (or an empty header object): 400 `No 'kid' attribute found in token header` - the same status class as a malformed header but a different message, and different again from the unknown-kid 401.
- **Issuer equality:** after the signature decode succeeds, the token's `iss` claim must be present and exactly equal the configured `OAUTH2_ISSUER`; anything else is rejected with 401 `Invalid token issuer`.
- **Time claims:** the decode runs with time checking enabled (`do_time_check=True`), so expired or not-yet-valid tokens are rejected with a 401 whose message is the underlying JWT library's decode-error text, passed through verbatim.
- **Truthiness gate (falsy-result fallback):** `_validate_jwt` returns the decoded claim dict rather than a boolean, and `_handle_token` tests that return value for plain truthiness. A falsy claim set - the empty-claims degenerate case `{}` - is therefore rejected with the generic 401 `Invalid token` instead of a dedicated error (in practice the falsy branch is reached when a requested introspection returns `False`). And because `self.token = decoded` is assigned inside `_validate_jwt` as soon as the local checks pass - before the optional introspection step - `self.token` can already hold the decoded claims for a request that still ends in 401 `Invalid token` when the remote introspection then fails.
## Relationship to the exception components
Construction-time problems raise plain `TypeError`. Runtime problems raise the exception subclasses, whose `.response()` builds a body-less `flask.Response` with the `Content-Type` header removed, the given status code, and a `WWW-Authenticate: Bearer error="..." error_description="..."` header (the 403 variant uses `scope="..."` instead of `error_description`, and is produced exclusively by the scope check described above). `_handle_token` *returns* these response objects rather than raising through Flask's error machinery.
## Edge cases worth testing
- Falsy-but-present `OAUTH2_ISSUER` (e.g. `''`) is rejected like a missing one.
- Metadata URL double slash when the issuer ends with `/`.
- Missing `keys` in the JWKS response: silent `None` key set, deferred 401s.
- Dict-typed `OAUTH2_AUDIENCE` matches by key; list-typed audience effectively disables the audience check.
- Mutable default `scopes=[]` is shared across calls but never mutated - the decorator copies kwargs per invocation and pops `scopes`/`introspect` before calling the view, so views must not declare URL variables named `scopes` or `introspect` (they would be overwritten and dropped).
- `Authorization` handling: header absent -> 400 `Authorization header missing`; present but not starting with the exact, case-sensitive prefix `Bearer ` (or yielding an empty token) -> 400 `Bearer access token missing`.
- Header segment decodes but has no `kid` -> 400 `No 'kid' attribute found in token header`; undecodable header -> 400 `Invalid token format`; decodable header with an unknown `kid` -> 401 `Invalid token signature`.
- `iss` claim missing or unequal to `OAUTH2_ISSUER` -> 401 `Invalid token issuer`; expired/not-yet-valid token -> 401 carrying the JWT library's decode-error message.
- Required scopes with no `scp` claim -> 403 whose `scope` value is the full sorted, de-duplicated required list; `scp` present but partially missing -> only the missing names.
- Introspection non-200 -> logged, then generic 401 `Invalid token`; non-JSON introspection body -> 401 `Token validation failed`; the introspection POST has no timeout.
- JWKS non-200 -> doubly-prefixed error (`Cannot request public keys from <uri>: Cannot request public keys from <uri>: <status>`); transport/JSON failures -> single prefix.
- Any unexpected exception during the validation pipeline is logged and converted to a 401 `Token validation failed`; exceptions raised by the decorated view are captured and re-raised only after OAuth2 handling completes.
#### Exact API Reference
#### `flask_oauth2_validation.decorator.OAuth2Decorator`
- **Import Path**: `from flask_oauth2_validation.decorator import OAuth2Decorator`
- **Required Test Import Paths**:
- flask_oauth2_validation.OAuth2Decorator
- **Exact Test Import Statements**:
- from flask_oauth2_validation import OAuth2Decorator
- **Kind**: class
- **Signature**:
```python
class OAuth2Decorator:
def __init__(self, app: Flask)
def requires_token(self, introspect=False, scopes=[])
token: Any
_issuer: Any
_issuer_public_keys: Any
_jwks_uri: Any
_jwks_update_interval: Any
_executor: Any
_client_id: Any
_client_secret: Any
_introspection_endpoint: Any
_introspection_auth_method: Any
```
- **Raises** (implementation must reproduce these exact messages):
- `An OAUTH2_ISSUER config property is required`
- `Invalid configuration`
- `Invalid token signature`
- `OAUTH2_CLIENT_SECRET config property required`
- `No 'kid' attribute found in token header`
- `Invalid token issuer`
- `Invalid token format`
- `Invalid token audience`
- **Behavior**: This Flask view function decorator provides local and remote
#### `flask_oauth2_validation.exceptions.OAuth2Exception`
- **Import Path**: `from flask_oauth2_validation.exceptions import OAuth2Exception`
- **Signature**:
```python
class OAuth2Exception:
def response(self)
```
- **Behavior**: Describes an HTTP error response which will be
#### `flask_oauth2_validation.exceptions.OAuth2BadRequestException`
- **Import Path**: `from flask_oauth2_validation.exceptions import OAuth2BadRequestException`
- **Signature**:
```python
class OAuth2BadRequestException
```
- **Behavior**: Describes an HTTP 400 (bad request) response:
#### `flask_oauth2_validation.exceptions.OAuth2InvalidTokenException`
- **Import Path**: `from flask_oauth2_validation.exceptions import OAuth2InvalidTokenException`
- **Signature**:
```python
class OAuth2InvalidTokenException
```
- **Behavior**: Describes an HTTP 401 (unauthorized) response:
#### `flask_oauth2_validation.exceptions.OAuth2InsufficientScopeException`
- **Import Path**: `from flask_oauth2_validation.exceptions import OAuth2InsufficientScopeException`
- **Signature**:
```python
class OAuth2InsufficientScopeException
```
- **Behavior**: Describes an HTTP 403 (forbidden) response. It contains
## Detailed Implementation Nodes
### Node: Decorator initialization and Flask configuration
## Functional constraints
- `OAuth2Decorator(app)` is the only constructor form; it takes a `flask.Flask` instance and reads configuration immediately (snapshot semantics - later config edits have no effect).
- Required config: truthy `OAUTH2_ISSUER`. Optional: `OAUTH2_CLIENT_ID` (enables introspection), `OAUTH2_CLIENT_SECRET` (mandatory when client id is set), `OAUTH2_AUDIENCE` (str = exact match; dict = key membership; other types skip the value check), `OAUTH2_JWKS_UPDATE_INTERVAL` (seconds; truthy -> `Executor(app, 'oauth2_jwks_update_task')`).
- All five keys are inserted into `app.config` as `None` via `setdefault` if absent; `app.config` is mutated by construction.
- Construction performs blocking I/O: one `GET {issuer}/.well-known/oauth-authorization-server` (response cached per instance; reused for `jwks_uri`, `introspection_endpoint`, `introspection_endpoint_auth_methods_supported`) and one `GET {jwks_uri}`. Keys without a `kid` are dropped; a JWKS body without `keys` leaves the key set `None` (constructor still succeeds).
- Every construction failure raises `TypeError`: missing issuer, missing client secret, metadata fetch/status/attribute errors (wrapped as `Cannot request authorization server metadata: ...`), JWKS fetch errors (wrapped as `Cannot request public keys from ...`; a non-200 status yields the doubled prefix `Cannot request public keys from <uri>: Cannot request public keys from <uri>: <status>` because the inner status `TypeError` is re-wrapped, while connection/JSON failures keep a single prefix), or unsupported introspection auth methods (post preferred over basic; message joins method names with spaces).
- `self.token` starts as `None` and is overwritten with the decoded JWT claim dict after each successful validation; it is never reset on failure, and it is assigned during local validation before the optional introspection step, so it can be set for a request that ultimately 401s.
- `requires_token(introspect=False, scopes=[])` returns a decorator factory; `introspect=True` without configured credentials fails per request with a 401 `Invalid configuration` response, and `scopes`/`introspect` are popped from kwargs before the view is invoked (views must not use those as parameter names).
- Local validation runs in a fixed order: public-key lookup by the header's `kid` (header decodes but carries no `kid` -> 400 `No 'kid' attribute found in token header`; unknown `kid` -> 401 `Invalid token signature`; undecodable header -> 400 `Invalid token format`), JWT decode with time checking enabled (expired/not-yet-valid tokens -> 401 carrying the underlying JWT library message), exact `iss` equality with `OAUTH2_ISSUER` (401 `Invalid token issuer`), optional audience check (401 `Invalid token audience`), optional scope check.
- Scope enforcement: requested `scopes` require an `scp` claim, consumed as a collection (`set(decoded['scp'])`); missing scopes yield the 403 `insufficient_scope` response whose `scope` attribute is the sorted, de-duplicated missing scope names (the full required list when `scp` is absent).
- Introspection (`introspect=True`): POST to the introspection endpoint with no timeout; a non-200 status is logged and treated as a validation failure (generic 401 `Invalid token`); success requires a truthy `active` field in the JSON body; a JSON parse failure surfaces as 401 `Token validation failed`. Validation success is a truthiness check on the claim dict `_validate_jwt` returns, so a falsy claim set (`{}`) would be rejected with 401 `Invalid token`.
- Runtime validation failures surface as returned `flask.Response` objects: 400 `invalid_request`, 401 `invalid_token`, 403 `insufficient_scope`, each with an empty body and a `WWW-Authenticate` header.
## Usage example
```python
from flask import Flask
from flask_oauth2_validation import OAuth2Decorator
app = Flask(__name__)
app.config['OAUTH2_ISSUER'] = 'https://issuer.example.com/oauth2'
app.config['OAUTH2_CLIENT_ID'] = 'client-id'
app.config['OAUTH2_CLIENT_SECRET'] = 'client-secret'
app.config['OAUTH2_JWKS_UPDATE_INTERVAL'] = 3600
oauth2 = OAuth2Decorator(app) # fetches metadata + JWKS now; TypeError on failure
@app.route('/protected')
@oauth2.requires_token(introspect=True, scopes=['profile'])
def protected():
return oauth2.token # decoded JWT claims dict
```
Keep the example to a single decorator instance per app; metadata is fetched once per instance and cached for its lifetime.