Fix high audit findings and port the hidden-media rule
Fixed findings from the audit reports (SECURITY, QUALITY, PERFORMANCE): - P-001 · Unbounded per-session timing maps and no connection cap in the sync hub - S-001 · Anonymous `PUT /access` switches off login for every guarded route - S-002 · Malformed cookies crash the Node middleware and fail requests in Java - S-004 · Anonymous `PUT /sync` writes unvalidated JSON into shared session state Also includes the pre-existing uncommitted changes in web-ui, README, shared-styles and the .changeset files, as the owner asked. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7fd2f14f91
commit
199a5efaef
12 files changed
+445
-42
No files matched your search
@@ -715,9 +715,13 @@ public final class AuthClient {
|
||||
if (candidate.startsWith(prefix)) {
|
||||
String value = candidate.substring(prefix.length());
|
||||
try {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8.name());
|
||||
// URLDecoder would turn a literal "+" into a space; escape it first so it survives, as in Node.
|
||||
return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8.name());
|
||||
} catch (UnsupportedEncodingException ex) {
|
||||
return value;
|
||||
} catch (IllegalArgumentException ex) {
|
||||
// A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent.
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,6 +218,34 @@ class AuthClientTest {
|
||||
assertEquals("right", token);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractTokenKeepsALiteralPlusSignInTheCookieValue() {
|
||||
AuthClient client = new AuthClient("https://auth.example.com");
|
||||
|
||||
String token = client.extractToken(name -> null, "auth_session=ab+cd%2Bef");
|
||||
|
||||
assertEquals("ab+cd+ef", token);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractTokenTreatsAMalformedCookieEscapeAsNoToken() {
|
||||
AuthClient client = new AuthClient("https://auth.example.com");
|
||||
|
||||
String token = client.extractToken(name -> null, "auth_session=bad%zz; other=1");
|
||||
|
||||
assertEquals("", token);
|
||||
}
|
||||
|
||||
@Test
|
||||
void middlewareFailsClosedOnAMalformedCookieInsteadOfThrowing() throws Exception {
|
||||
AuthClient client = new AuthClient("https://auth.example.com");
|
||||
|
||||
String result = client.middleware(name -> null, "auth_session=100%",
|
||||
user -> "authenticated", () -> "unauthorized");
|
||||
|
||||
assertEquals("unauthorized", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void middlewareFailsClosedAndDoesNotInvokeTheHandlerOnAnInvalidSession() throws Exception {
|
||||
server = fakeAuthGuard(401, "{\"valid\":false}");
|
||||
|
||||
@@ -211,9 +211,8 @@ export class AuthClient {
|
||||
*/
|
||||
middleware() {
|
||||
return async (req, res, next) => {
|
||||
const token = this.tokenFromRequest(req);
|
||||
try {
|
||||
req.authUser = await this.validate(token);
|
||||
req.authUser = await this.validate(this.tokenFromRequest(req));
|
||||
next();
|
||||
} catch {
|
||||
// Fail closed on both an invalid session and a transport/decoding
|
||||
@@ -236,7 +235,14 @@ export class AuthClient {
|
||||
.split(';')
|
||||
.map(part => part.trim())
|
||||
.find(part => part.startsWith(`${this.cookieName}=`));
|
||||
if (match) return decodeURIComponent(match.slice(this.cookieName.length + 1));
|
||||
if (match) {
|
||||
// A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent.
|
||||
try {
|
||||
return decodeURIComponent(match.slice(this.cookieName.length + 1));
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
@@ -125,6 +125,29 @@ test('tokenFromRequest falls back to the auth_session cookie', () => {
|
||||
assert.equal(client.tokenFromRequest(req), 'cookie-token');
|
||||
});
|
||||
|
||||
test('tokenFromRequest treats a malformed cookie escape as no token', () => {
|
||||
const client = new AuthClient('https://auth.example.com');
|
||||
const req = { headers: { cookie: 'auth_session=bad%zz; other=1' } };
|
||||
assert.equal(client.tokenFromRequest(req), '');
|
||||
});
|
||||
|
||||
test('middleware answers 401 instead of rejecting on a malformed cookie', async () => {
|
||||
const client = new AuthClient('https://auth.example.com', {
|
||||
fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]),
|
||||
});
|
||||
let statusCode = null;
|
||||
const res = {
|
||||
status(code) {
|
||||
statusCode = code;
|
||||
return { json: () => {} };
|
||||
},
|
||||
};
|
||||
await client.middleware()({ headers: { cookie: 'auth_session=100%' } }, res, () => {
|
||||
throw new Error('next should not be called');
|
||||
});
|
||||
assert.equal(statusCode, 401);
|
||||
});
|
||||
|
||||
test('middleware attaches authUser on success and 401s on failure', async () => {
|
||||
const okClient = new AuthClient('https://auth.example.com', {
|
||||
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 1, username: 'a', role: 'user' } }]),
|
||||
|
||||
@@ -94,6 +94,7 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
|
||||
# rather than a generic "internal error" indistinguishable from any other bug.
|
||||
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
|
||||
ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
|
||||
ERR_ADMIN_REQUIRED = "Administrator access required."
|
||||
|
||||
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
|
||||
# authentication is disabled, either because AUTHGUARD_URL is disabled or
|
||||
@@ -338,6 +339,23 @@ def build_auth_router(
|
||||
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
|
||||
return token
|
||||
|
||||
async def require_admin(
|
||||
request: Request,
|
||||
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
|
||||
) -> PublicUser:
|
||||
"""FastAPI dependency gating a route behind an administrator session
|
||||
(the Python counterpart of Go's RequireAdmin). Unlike require_session it
|
||||
never falls back to _LOCAL_PROFILE, so a route that changes the
|
||||
login-required flag cannot be called anonymously, even while login is
|
||||
already disabled."""
|
||||
if not _enabled(client):
|
||||
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
|
||||
assert client is not None
|
||||
profile, _ = await _current_profile_or_401(request, client)
|
||||
if not can_manage_users(profile.role):
|
||||
raise HTTPException(status_code=403, detail=ERR_ADMIN_REQUIRED)
|
||||
return profile
|
||||
|
||||
# --- status / me -------------------------------------------------------
|
||||
|
||||
@router.get("/me")
|
||||
@@ -561,6 +579,7 @@ def build_auth_router(
|
||||
async def update_access_settings(
|
||||
req: UpdateAccessRequest,
|
||||
store: ProxyStore = Depends(get_store), # noqa: B008
|
||||
_admin: PublicUser = Depends(require_admin), # noqa: B008
|
||||
) -> dict[str, bool]:
|
||||
nonlocal login_required_override
|
||||
await store.set_login_required(req.loginRequired)
|
||||
|
||||
@@ -4,7 +4,13 @@ from fastapi import FastAPI, Request
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from shared_backend import authproxy as ap
|
||||
from shared_backend.authclient import APIError, AuthClient, PublicUser, SessionResult
|
||||
from shared_backend.authclient import (
|
||||
DEFAULT_COOKIE_NAME,
|
||||
APIError,
|
||||
AuthClient,
|
||||
PublicUser,
|
||||
SessionResult,
|
||||
)
|
||||
|
||||
|
||||
class _FakeStore(ap.ProxyStore):
|
||||
@@ -113,14 +119,32 @@ class AuthDisabledModeTests(unittest.TestCase):
|
||||
|
||||
|
||||
class AccessSettingsTests(unittest.TestCase):
|
||||
def test_get_and_put_round_trip_through_the_store(self) -> None:
|
||||
def test_get_is_public_and_put_requires_an_admin_session(self) -> None:
|
||||
store = _FakeStore(login_required=True)
|
||||
client = TestClient(_build_app(store))
|
||||
client = TestClient(_build_app(store, _RoleClient()))
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||
|
||||
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||
|
||||
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
|
||||
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||
|
||||
client.cookies.set(DEFAULT_COOKIE_NAME, "admin-token")
|
||||
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||
self.assertEqual(response.json(), {"loginRequired": False})
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": False})
|
||||
|
||||
def test_anonymous_put_is_refused_when_authguard_is_not_configured(self) -> None:
|
||||
store = _FakeStore(login_required=True)
|
||||
client = TestClient(_build_app(store))
|
||||
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||
|
||||
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
|
||||
store = _FakeStore(login_required=True)
|
||||
client = TestClient(
|
||||
@@ -180,6 +204,16 @@ class _FakeClient(AuthClient):
|
||||
return ["auth_session=; Path=/; Max-Age=0"]
|
||||
|
||||
|
||||
class _RoleClient(_FakeClient):
|
||||
"""Resolves two fixed session tokens to an administrator and an ordinary user."""
|
||||
|
||||
async def me(self, token: str) -> PublicUser:
|
||||
roles = {"admin-token": "superadmin", "user-token": "user"}
|
||||
if token not in roles:
|
||||
raise APIError(401, "unauthenticated")
|
||||
return PublicUser(id=1, username="a", email="a@b.com", role=roles[token])
|
||||
|
||||
|
||||
class EnabledModeSetupAndLoginTests(unittest.TestCase):
|
||||
"""Exercises the real (client is not None) path, including the
|
||||
setup-claim flag's interaction with the store."""
|
||||
|
||||
Reference in new issue
Block a user