From 6763ecbd5fc77f26296aeefde3f80b1393da2c2a Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 30 Apr 2026 07:48:49 -0400 Subject: [PATCH] fix: API keys with global read scope not being saved correctly (#12225) * fix: Api keys with global read scope not being saved correctly * refactor: Hoist global scopes Set to module level --------- Co-authored-by: Claude Opus 4.7 --- server/middlewares/authentication.test.ts | 56 +++++++++++++++++++++++ server/middlewares/authentication.ts | 6 +-- server/routes/api/apiKeys/apiKeys.test.ts | 4 ++ server/routes/api/apiKeys/apiKeys.ts | 6 ++- 4 files changed, 66 insertions(+), 6 deletions(-) diff --git a/server/middlewares/authentication.test.ts b/server/middlewares/authentication.test.ts index 5505aed166..f92acca961 100644 --- a/server/middlewares/authentication.test.ts +++ b/server/middlewares/authentication.test.ts @@ -97,6 +97,62 @@ describe("Authentication middleware", () => { ); expect(state.auth.user.id).toEqual(user.id); }); + it("should authenticate with global read scope on read endpoints", async () => { + const state = {} as DefaultState; + const user = await buildUser(); + const authMiddleware = auth(); + const key = await buildApiKey({ + userId: user.id, + scope: [Scope.Read], + }); + + await authMiddleware( + { + originalUrl: "/api/auth.info", + // @ts-expect-error mock request + request: { + url: "/auth.info", + get: jest.fn(() => `Bearer ${key.value}`), + }, + state, + cache: {}, + }, + jest.fn() + ); + expect(state.auth.user.id).toEqual(user.id); + }); + + it("should return 403 authorization error when scope does not match", async () => { + const state = {} as DefaultState; + const user = await buildUser(); + const authMiddleware = auth(); + const key = await buildApiKey({ + userId: user.id, + scope: [Scope.Read], + }); + + try { + await authMiddleware( + { + originalUrl: "/api/documents.create", + // @ts-expect-error mock request + request: { + url: "/documents.create", + get: jest.fn(() => `Bearer ${key.value}`), + }, + state, + cache: {}, + }, + jest.fn() + ); + throw new Error("Expected error to be thrown"); + } catch (e) { + expect(e.status).toBe(403); + expect(e.id).toBe("authorization_error"); + expect(e.message).toContain("does not have access to this resource"); + } + }); + it("should return error with invalid API key", async () => { const state = {} as DefaultState; const authMiddleware = auth(); diff --git a/server/middlewares/authentication.ts b/server/middlewares/authentication.ts index 91e8d6f342..6c9da3540e 100644 --- a/server/middlewares/authentication.ts +++ b/server/middlewares/authentication.ts @@ -177,7 +177,7 @@ async function validateAuthentication( throw AuthenticationError("Access token is expired"); } if (!authentication.canAccess(ctx.originalUrl)) { - throw AuthenticationError( + throw AuthorizationError( "Access token does not have access to this resource" ); } @@ -220,9 +220,7 @@ async function validateAuthentication( } if (!apiKey.canAccess(ctx.originalUrl)) { - throw AuthenticationError( - "API key does not have access to this resource" - ); + throw AuthorizationError("API key does not have access to this resource"); } user = await User.findByPk(apiKey.userId, { diff --git a/server/routes/api/apiKeys/apiKeys.test.ts b/server/routes/api/apiKeys/apiKeys.test.ts index b3697c01cb..c3c589eb53 100644 --- a/server/routes/api/apiKeys/apiKeys.test.ts +++ b/server/routes/api/apiKeys/apiKeys.test.ts @@ -53,6 +53,8 @@ describe("#apiKeys.create", () => { "*.info", "users.*", "collections:read", + "read", + "write", ], }, }); @@ -66,6 +68,8 @@ describe("#apiKeys.create", () => { "/api/*.info", "/api/users.*", "collections:read", + "read", + "write", ]); }); diff --git a/server/routes/api/apiKeys/apiKeys.ts b/server/routes/api/apiKeys/apiKeys.ts index 3672e991d2..5f0f559b4a 100644 --- a/server/routes/api/apiKeys/apiKeys.ts +++ b/server/routes/api/apiKeys/apiKeys.ts @@ -1,6 +1,6 @@ import Router from "koa-router"; import { Op, Sequelize, type WhereOptions } from "sequelize"; -import { UserRole } from "@shared/types"; +import { Scope, UserRole } from "@shared/types"; import auth from "@server/middlewares/authentication"; import { transaction } from "@server/middlewares/transaction"; import validate from "@server/middlewares/validate"; @@ -14,6 +14,8 @@ import * as T from "./schema"; const router = new Router(); +const globalScopes = new Set(Object.values(Scope)); + router.post( "apiKeys.create", auth({ @@ -33,7 +35,7 @@ router.post( userId: user.id, expiresAt, scope: scope?.map((s) => - s.startsWith("/api/") || s.includes(":") + s.startsWith("/api/") || s.includes(":") || globalScopes.has(s) ? s : `/api/${s.replace(/^\//, "")}` ),