CodeSampleX

Ejemplo

flask 3.1.3: Configure APPLICATION_ROOT in Flask to isolate session cookie paths and URL generation prefixes without modifying application route dispatch.

Muestra verificada para pypi flask 3.1.3: Configure APPLICATION_ROOT in Flask to isolate session cookie paths and URL generation prefixes without modifying…

sha256:2d822f61061b6848329b6ceed4b3d4e26109f96b5e0e0b0d46f602ebe7b7d6a0

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
3
Claves de firma que lo compilaron
3
Entorno declarado python linux x64 python python pip

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-17
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-08

Caso

HOW
Objetivo
Configure APPLICATION_ROOT in Flask to isolate session cookie paths and URL generation prefixes without modifying application route dispatch.
Paquetes
Símbolos
  • flask.Flask.config
Entorno
python
Creado
2026-08-17T17:12:59Z

Contrato

  1. Configuring APPLICATION_ROOT sets the session cookie path to the specified prefix and causes url_for to generate prefixed paths, but leaves request routing unprefixed so requests to the prefixed URL fail with 404 Not Found.
  2. Unprefixed routes continue to match and respond with 200 OK while emitting Set-Cookie headers scoped to the APPLICATION_ROOT path.
  3. Building external URLs via url_for outside request context prepends the APPLICATION_ROOT prefix to the SERVER_NAME host.
  4. Routing incoming requests under the URL prefix requires WSGI-level SCRIPT_NAME middleware rather than APPLICATION_ROOT configuration alone.

Archivos

  • NOTES.md
  • csx.json
  • requirements.txt
  • test/contract.py

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# Flask APPLICATION_ROOT Configuration Mechanics

## Known Solutions Search

An initial query to known solutions returned:
- Sample `sha256:1e3bda7f452643e5b4dc9dfd579fc4168a2122e3619c5e10c9f617b0c8756397`, which covers Flask blueprint request lifecycle hooks rather than application configuration parameters.

No prior contract addressed the failure mode and scoping rules of `APPLICATION_ROOT`.

## Pinned Release

- `flask` == `3.1.3`
- `werkzeug` == `3.1.8`
- `jinja2` == `3.1.6`
- `itsdangerous` == `2.2.0`
- `click` == `8.4.2`
- `blinker` == `1.9.0`
- `markupsafe` == `3.0.3`

## Observed Behavior and Pitfall

A common expectation when configuring a web framework is that setting a configuration variable named `APPLICATION_ROOT` (for instance `app.config["APPLICATION_ROOT"] = "/api"`) instructs the application to mount all routes under that URL path prefix. Under that assumption, defining `@app.route("/health")` should automatically handle incoming HTTP requests to `/api/health`.

In reality, `APPLICATION_ROOT` in Flask does not configure request routing:
1. **Routing remains unprefixed**: The routing map continues to match `/health` rather than `/api/health`. Incoming requests to `/api/health` fail immediately with HTTP `404 Not Found`.
2. **URL building includes the prefix**: Flask's URL builder `url_for` uses `APPLICATION_ROOT` when calculating endpoint paths, generating `/api/health` or `http://example.com/api/health`. This creates a disconnect where generated links produce 404 errors when requested by clients against the same application instance.
3. **Session cookie scope isolation**: Flask uses `APPLICATION_ROOT` as the `Path` attribute on session cookies emitted via `Set-Cookie` headers (e.g. `Path=/api`). When users visit the working direct endpoint `/health`, browsers store the cookie under `/api` and will not send it on subsequent requests to `/health`, silently breaking session persistence.
4. **Correct prefixing mechanism**: Deploying a Flask application under a path prefix requires setting WSGI `SCRIPT_NAME` (for instance using Werkzeug's `DispatcherMiddleware` or reverse proxy path rewriting), which properly adjusts both route resolution and URL generation.
csx.json
{"case":{"believed":"Setting APPLICATION_ROOT automatically prefixes route endpoints and dispatches incoming requests matching the configured root path.","caseId":"case:sha256:c1074647e16f0f6c1711e6a84726c5c1865f704b70cfd351fc1ba32e4d3ec72d","contract":["Configuring APPLICATION_ROOT sets the session cookie path to the specified prefix and causes url_for to generate prefixed paths, but leaves request routing unprefixed so requests to the prefixed URL fail with 404 Not Found.","Unprefixed routes continue to match and respond with 200 OK while emitting Set-Cookie headers scoped to the APPLICATION_ROOT path.","Building external URLs via url_for outside request context prepends the APPLICATION_ROOT prefix to the SERVER_NAME host.","Routing incoming requests under the URL prefix requires WSGI-level SCRIPT_NAME middleware rather than APPLICATION_ROOT configuration alone."],"goal":"Configure APPLICATION_ROOT in Flask to isolate session cookie paths and URL generation prefixes without modifying application route dispatch.","kind":"HOW","packages":["pkg:pypi/flask@3.1.3"],"schemaVersion":1,"symbols":["flask.Flask.config"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/flask@3.1.3"],"schemaVersion":1,"symbols":["flask.Flask.config"],"verifierAdapter":"python@1"}
requirements.txt
blinker==1.9.0
click==8.4.2
Flask==3.1.3
itsdangerous==2.2.0
Jinja2==3.1.6
MarkupSafe==3.0.3
Werkzeug==3.1.8
test/contract.py
import flask
from werkzeug.exceptions import NotFound
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.test import Client
from werkzeug.wrappers import Response


def test_flask_application_root_behavior():
    app = flask.Flask(__name__)
    app.config["APPLICATION_ROOT"] = "/api"
    app.config["SECRET_KEY"] = "contract-verification-key"
    app.config["SERVER_NAME"] = "example.com"

    @app.route("/health")
    def health():
        flask.session["visited"] = True
        return flask.url_for("health")

    client = app.test_client()

    # 1. APPLICATION_ROOT does not prefix request routing; requests to /api/health return 404
    resp_prefixed = client.get("/api/health")
    assert resp_prefixed.status_code == 404, f"Expected 404 on prefixed URL, got {resp_prefixed.status_code}"

    # 2. The direct unprefixed route /health returns 200 OK and generates /api/health via url_for
    resp_direct = client.get("/health")
    assert resp_direct.status_code == 200, f"Expected 200 on direct URL, got {resp_direct.status_code}"
    assert resp_direct.data.decode("utf-8") == "/api/health"

    # 3. Session cookie Path attribute is explicitly set to APPLICATION_ROOT (/api)
    cookie_header = resp_direct.headers.get("Set-Cookie", "")
    assert "Path=/api" in cookie_header, f"Expected Path=/api in Set-Cookie header: {cookie_header}"

    # 4. Outside request context, url_for includes APPLICATION_ROOT prefix with SERVER_NAME
    with app.app_context():
        external_url = flask.url_for("health", _external=True)
        assert external_url == "http://example.com/api/health", f"Expected external URL http://example.com/api/health, got {external_url}"

    # 5. True prefix-based request dispatch requires WSGI SCRIPT_NAME middleware
    mounted_app = DispatcherMiddleware(NotFound(), {"/api": app})
    wsgi_client = Client(mounted_app, Response)

    resp_mounted_prefixed = wsgi_client.get("/api/health")
    assert resp_mounted_prefixed.status_code == 200, f"Expected 200 via DispatcherMiddleware, got {resp_mounted_prefixed.status_code}"
    assert resp_mounted_prefixed.data.decode("utf-8") == "/api/health"

    resp_mounted_direct = wsgi_client.get("/health")
    assert resp_mounted_direct.status_code == 404, f"Expected 404 for unprefixed path on mounted app, got {resp_mounted_direct.status_code}"


if __name__ == "__main__":
    test_flask_application_root_behavior()
    print("Contract test passed successfully.")

Seeder de origen

csx-seed