feat(cache): revalidate auth-sensitive read-only responses
This commit is contained in:
@@ -12,19 +12,29 @@ from starlette.responses import Response
|
||||
# organization must never be reused by the browser.
|
||||
NO_STORE_PATH_PREFIXES = (
|
||||
"/api/auth/v2",
|
||||
"/api/accounts",
|
||||
"/api/background-jobs",
|
||||
"/api/bookmarks",
|
||||
"/api/organizations",
|
||||
"/api/rank/orientation-profiles",
|
||||
"/api/works/v2/classification/",
|
||||
)
|
||||
|
||||
NO_STORE_PATH_FRAGMENTS = (
|
||||
"/company-connections",
|
||||
"/primary-category-aggregations",
|
||||
"/collaboration-graph/",
|
||||
)
|
||||
"/api/accounts",
|
||||
"/api/background-jobs",
|
||||
"/api/bookmarks",
|
||||
"/api/organizations",
|
||||
)
|
||||
|
||||
# Keep these responses in the server-side ETag cache, but require the browser
|
||||
# to revalidate them. A new access token (for example after impersonation)
|
||||
# automatically produces a different cache key.
|
||||
REVALIDATE_PATH_PREFIXES = (
|
||||
"/api/dashboard",
|
||||
"/api/rank/orientation-profiles",
|
||||
"/api/works/v2/classification/",
|
||||
)
|
||||
|
||||
REVALIDATE_PATH_FRAGMENTS = (
|
||||
"/company-connections",
|
||||
"/primary-category-aggregations",
|
||||
)
|
||||
|
||||
NO_STORE_PATH_FRAGMENTS = (
|
||||
"/collaboration-graph/",
|
||||
)
|
||||
# POST is opt-out. Add any endpoint here that MUTATES state (create/update/delete/
|
||||
# trigger side effects), even if it "usually" returns 200.
|
||||
EXCLUDED_POST_PATHS = (
|
||||
@@ -94,11 +104,17 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
def _content_type(self, response: Response) -> str | None:
|
||||
return response.headers.get("content-type")
|
||||
|
||||
def _requires_no_store(self, request: Request) -> bool:
|
||||
path = request.url.path
|
||||
return path.startswith(NO_STORE_PATH_PREFIXES) or any(
|
||||
fragment in path for fragment in NO_STORE_PATH_FRAGMENTS
|
||||
)
|
||||
def _requires_no_store(self, request: Request) -> bool:
|
||||
path = request.url.path
|
||||
return path.startswith(NO_STORE_PATH_PREFIXES) or any(
|
||||
fragment in path for fragment in NO_STORE_PATH_FRAGMENTS
|
||||
)
|
||||
|
||||
def _requires_revalidation(self, request: Request) -> bool:
|
||||
path = request.url.path
|
||||
return path.startswith(REVALIDATE_PATH_PREFIXES) or any(
|
||||
fragment in path for fragment in REVALIDATE_PATH_FRAGMENTS
|
||||
)
|
||||
|
||||
def _set_no_store_headers(self, response: Response) -> None:
|
||||
response.headers["Cache-Control"] = "private, no-store, max-age=0"
|
||||
@@ -117,10 +133,14 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
vary_values.append("Authorization")
|
||||
headers["Vary"] = ", ".join(vary_values)
|
||||
|
||||
def _cache_response_headers(
|
||||
self, request: Request, etag: str, content_type: str | None
|
||||
) -> dict[str, str]:
|
||||
cache_control = f"max-age={self.ttl}"
|
||||
def _cache_response_headers(
|
||||
self, request: Request, etag: str, content_type: str | None
|
||||
) -> dict[str, str]:
|
||||
cache_control = (
|
||||
"no-cache, max-age=0"
|
||||
if self._requires_revalidation(request)
|
||||
else f"max-age={self.ttl}"
|
||||
)
|
||||
headers = {"ETag": etag, "Cache-Control": cache_control}
|
||||
if request.headers.get("authorization"):
|
||||
headers["Cache-Control"] = f"private, {cache_control}"
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||
|
||||
|
||||
def _app_with_counter():
|
||||
app = FastAPI()
|
||||
calls = {"get": 0, "post": 0}
|
||||
calls = {"get": 0, "post": 0, "dashboard": 0, "read_only": 0}
|
||||
|
||||
@app.get("/api/background-jobs/tasks")
|
||||
def get_tasks():
|
||||
@@ -17,6 +19,36 @@ def _app_with_counter():
|
||||
calls["post"] += 1
|
||||
return {"call": calls["post"]}
|
||||
|
||||
@app.get("/api/dashboard/statistics")
|
||||
def get_dashboard_statistics():
|
||||
calls["dashboard"] += 1
|
||||
return {"call": calls["dashboard"]}
|
||||
|
||||
def read_only_response():
|
||||
calls["read_only"] += 1
|
||||
return {"call": calls["read_only"]}
|
||||
|
||||
app.add_api_route(
|
||||
"/api/inse-service/authors/A1/company-connections",
|
||||
read_only_response,
|
||||
methods=["GET"],
|
||||
)
|
||||
app.add_api_route(
|
||||
"/api/works/v2/classification/work/W1",
|
||||
read_only_response,
|
||||
methods=["GET"],
|
||||
)
|
||||
app.add_api_route(
|
||||
"/api/works/v2/author/A1/primary-category-aggregations",
|
||||
read_only_response,
|
||||
methods=["GET"],
|
||||
)
|
||||
app.add_api_route(
|
||||
"/api/rank/orientation-profiles",
|
||||
read_only_response,
|
||||
methods=["POST"],
|
||||
)
|
||||
|
||||
app.add_middleware(ETagCacheMiddleware, ttl=120)
|
||||
return app, calls
|
||||
|
||||
@@ -50,3 +82,70 @@ def test_background_job_post_side_effects_are_never_replayed_from_cache():
|
||||
assert first.json() == {"call": 1}
|
||||
assert second.json() == {"call": 2}
|
||||
assert calls["post"] == 2
|
||||
|
||||
|
||||
def test_dashboard_revalidates_and_uses_a_separate_cache_for_a_new_token():
|
||||
app, calls = _app_with_counter()
|
||||
|
||||
with TestClient(app) as client:
|
||||
first = client.get(
|
||||
"/api/dashboard/statistics",
|
||||
headers={"Authorization": "Bearer real-account"},
|
||||
)
|
||||
revalidated = client.get(
|
||||
"/api/dashboard/statistics",
|
||||
headers={
|
||||
"Authorization": "Bearer real-account",
|
||||
"If-None-Match": first.headers["etag"],
|
||||
},
|
||||
)
|
||||
impersonated = client.get(
|
||||
"/api/dashboard/statistics",
|
||||
headers={
|
||||
"Authorization": "Bearer impersonated-account",
|
||||
"If-None-Match": first.headers["etag"],
|
||||
},
|
||||
)
|
||||
|
||||
assert first.status_code == 200
|
||||
assert first.headers["cache-control"] == "private, no-cache, max-age=0"
|
||||
assert revalidated.status_code == 304
|
||||
assert impersonated.status_code == 200
|
||||
assert impersonated.json() == {"call": 2}
|
||||
assert calls["dashboard"] == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "path"),
|
||||
[
|
||||
("GET", "/api/inse-service/authors/A1/company-connections"),
|
||||
("GET", "/api/works/v2/classification/work/W1"),
|
||||
(
|
||||
"GET",
|
||||
"/api/works/v2/author/A1/primary-category-aggregations",
|
||||
),
|
||||
("POST", "/api/rank/orientation-profiles"),
|
||||
],
|
||||
)
|
||||
def test_read_only_personalized_endpoints_require_revalidation(method, path):
|
||||
app, calls = _app_with_counter()
|
||||
|
||||
with TestClient(app) as client:
|
||||
first = client.request(
|
||||
method,
|
||||
path,
|
||||
headers={"Authorization": "Bearer account"},
|
||||
)
|
||||
revalidated = client.request(
|
||||
method,
|
||||
path,
|
||||
headers={
|
||||
"Authorization": "Bearer account",
|
||||
"If-None-Match": first.headers["etag"],
|
||||
},
|
||||
)
|
||||
|
||||
assert first.status_code == 200
|
||||
assert first.headers["cache-control"] == "private, no-cache, max-age=0"
|
||||
assert revalidated.status_code == 304
|
||||
assert calls["read_only"] == 1
|
||||
|
||||
Reference in New Issue
Block a user