diff --git a/app/scenes/ApiKeyNew/index.tsx b/app/scenes/ApiKeyNew/index.tsx index c86224c885..2258ca742e 100644 --- a/app/scenes/ApiKeyNew/index.tsx +++ b/app/scenes/ApiKeyNew/index.tsx @@ -83,7 +83,7 @@ function ApiKeyNew({ onSubmit }: Props) { await apiKeys.create({ name, expiresAt: expiresAt?.toISOString(), - scope: scope ? scope.split(" ") : undefined, + scope: scope ? scope.split(/[\s,]+/).filter(Boolean) : undefined, }); toast.success( t( diff --git a/server/.oxlintrc.json b/server/.oxlintrc.json index b8e20e663b..d36f3cf20c 100644 --- a/server/.oxlintrc.json +++ b/server/.oxlintrc.json @@ -23,6 +23,31 @@ ] }, "plugins": ["import"] + }, + { + "files": ["models/**/*.ts"], + "rules": { + "no-restricted-imports": [ + "error", + { + "name": "fetch-with-proxy", + "message": "Use `@server/utils/fetch` instead" + }, + { + "name": "node-fetch", + "message": "Use `@server/utils/fetch` instead" + }, + { + "name": "passport", + "message": "Use the `@outlinewiki/koa-passport` package" + }, + { + "name": "class-validator", + "message": "class-validator decorators are never executed by Sequelize. Use a decorator from `server/models/validators` or sequelize-typescript, and import check functions from `validator/lib/*`." + } + ] + }, + "plugins": ["import"] } ], "env": { diff --git a/server/models/AccessRequest.ts b/server/models/AccessRequest.ts index 49e9912921..4137ab10b1 100644 --- a/server/models/AccessRequest.ts +++ b/server/models/AccessRequest.ts @@ -13,12 +13,12 @@ import { AllowNull, DefaultScope, BeforeCreate, + IsIn, } from "sequelize-typescript"; import Document from "./Document"; import Team from "./Team"; import User from "./User"; import IdModel from "./base/IdModel"; -import { IsIn } from "class-validator"; import { ValidationError } from "@server/errors"; import type { APIContext } from "@server/types"; diff --git a/server/models/ApiKey.test.ts b/server/models/ApiKey.test.ts index 09a53e8018..0ba0c285c5 100644 --- a/server/models/ApiKey.test.ts +++ b/server/models/ApiKey.test.ts @@ -129,5 +129,40 @@ describe("#ApiKey", () => { expect(apiKey.canAccess("/mcp")).toBe(true); }); + + it("should not allow MCP access when no scope is well-formed", async () => { + const apiKey = await buildApiKey({ + name: "Dev", + scope: [Scope.Read], + }); + apiKey.scope = ["documents:read,documents:write"]; + + expect(apiKey.canAccess("/mcp")).toBe(false); + expect(apiKey.canAccess("/api/documents.info")).toBe(false); + }); + }); + + describe("scope", () => { + it("should reject malformed scopes", async () => { + await expect( + buildApiKey({ + name: "Dev", + scope: ["documents:read,documents:write"], + }) + ).rejects.toThrow("Scope must be a valid API scope"); + }); + + it("should accept well-formed scopes", async () => { + const apiKey = await buildApiKey({ + name: "Dev", + scope: ["documents:read", "/api/users.info", Scope.Write], + }); + + expect(apiKey.scope).toEqual([ + "documents:read", + "/api/users.info", + Scope.Write, + ]); + }); }); }); diff --git a/server/models/ApiKey.ts b/server/models/ApiKey.ts index 87961504f2..debc969242 100644 --- a/server/models/ApiKey.ts +++ b/server/models/ApiKey.ts @@ -1,4 +1,3 @@ -import { Matches } from "class-validator"; import { subMinutes } from "date-fns"; import type { InferAttributes, InferCreationAttributes } from "sequelize"; import { Op } from "sequelize"; @@ -22,6 +21,7 @@ import User from "./User"; import ParanoidModel from "./base/ParanoidModel"; import { SkipChangeset } from "./decorators/Changeset"; import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; +import IsScope from "./validators/IsScope"; import Length from "./validators/Length"; @Table({ tableName: "apiKeys", modelName: "apiKey" }) @@ -52,10 +52,7 @@ class ApiKey extends ParanoidModel< name: string; /** A list of scopes that this API key has access to */ - @Matches(AuthenticationHelper.scopeGrammarRegex, { - each: true, - message: "Scope must be a valid API scope", - }) + @IsScope @Column(DataType.ARRAY(DataType.STRING)) scope: string[] | null; @@ -178,7 +175,9 @@ class ApiKey extends ParanoidModel< // MCP endpoint access is allowed if the key has any valid scope. // Fine-grained scope enforcement happens at the tool level. if (path.startsWith("/mcp")) { - return this.scope.length > 0; + return this.scope.some((scope) => + AuthenticationHelper.isValidScope(scope) + ); } return AuthenticationHelper.canAccess(path, this.scope); diff --git a/server/models/Document.ts b/server/models/Document.ts index 23976e251b..2c8632c365 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -42,7 +42,6 @@ import { AfterUpdate, IsFloat, } from "sequelize-typescript"; -import { MaxLength } from "class-validator"; import isUUID from "validator/lib/isUUID"; import type { DocumentPermission, @@ -386,8 +385,8 @@ class Document extends ArchivableModel< text: string; /** The likely language of the content, in ISO 639-1 format. */ + @Length({ max: 2, msg: "language must be an ISO 639-1 code" }) @Column(DataType.STRING(2)) - @MaxLength(2) language: string; /** diff --git a/server/models/Emoji.ts b/server/models/Emoji.ts index c370f8b0a2..6c8ac52329 100644 --- a/server/models/Emoji.ts +++ b/server/models/Emoji.ts @@ -7,6 +7,7 @@ import { Column, DataType, ForeignKey, + Is, Table, } from "sequelize-typescript"; import { EmojiValidation } from "@shared/validations"; @@ -15,7 +16,6 @@ import Team from "./Team"; import User from "./User"; import IdModel from "./base/IdModel"; import Length from "./validators/Length"; -import { Matches } from "class-validator"; import FileStorage from "@server/storage/files"; import Attachment from "./Attachment"; @@ -28,9 +28,9 @@ class Emoji extends IdModel< max: EmojiValidation.maxNameLength, msg: `emoji name must be less than ${EmojiValidation.maxNameLength} characters`, }) - @Matches(EmojiValidation.allowedNameCharacters, { - message: - "emoji name can only contain lowercase letters, numbers, and underscores", + @Is({ + args: EmojiValidation.allowedNameCharacters, + msg: "emoji name can only contain lowercase letters, numbers, and underscores", }) @Column(DataType.STRING) name: string; diff --git a/server/models/Template.ts b/server/models/Template.ts index acfc5460ac..5c1091ef46 100644 --- a/server/models/Template.ts +++ b/server/models/Template.ts @@ -1,4 +1,4 @@ -import { isUUID } from "class-validator"; +import isUUID from "validator/lib/isUUID"; import type { Identifier, InferAttributes, diff --git a/server/models/oauth/OAuthAuthentication.test.ts b/server/models/oauth/OAuthAuthentication.test.ts index 978edf079e..1924d57b79 100644 --- a/server/models/oauth/OAuthAuthentication.test.ts +++ b/server/models/oauth/OAuthAuthentication.test.ts @@ -2,6 +2,19 @@ import { Scope } from "@shared/types"; import { buildOAuthAuthentication, buildUser } from "@server/test/factories"; describe("OAuthAuthentication", () => { + describe("scope", () => { + it("should reject malformed scopes", async () => { + const user = await buildUser(); + + await expect( + buildOAuthAuthentication({ + user, + scope: ["documents:read,documents:write"], + }) + ).rejects.toThrow("Scope must be a valid API scope"); + }); + }); + describe("canAccess", () => { it("should allow MCP access for scoped tokens", async () => { const user = await buildUser(); @@ -24,6 +37,17 @@ describe("OAuthAuthentication", () => { expect(authentication.canAccess("/mcp")).toBe(false); }); + it("should deny MCP access when no scope is well-formed", async () => { + const user = await buildUser(); + const authentication = await buildOAuthAuthentication({ + user, + scope: [Scope.Read], + }); + authentication.scope = ["documents:read,documents:write"]; + + expect(authentication.canAccess("/mcp")).toBe(false); + }); + it("should always allow the revoke endpoint", async () => { const user = await buildUser(); const authentication = await buildOAuthAuthentication({ diff --git a/server/models/oauth/OAuthAuthentication.ts b/server/models/oauth/OAuthAuthentication.ts index f428812530..efd0061cdd 100644 --- a/server/models/oauth/OAuthAuthentication.ts +++ b/server/models/oauth/OAuthAuthentication.ts @@ -1,4 +1,3 @@ -import { Matches } from "class-validator"; import { subMinutes } from "date-fns"; import type { FindOptions, @@ -19,6 +18,7 @@ import env from "@server/env"; import User from "@server/models/User"; import ParanoidModel from "@server/models/base/ParanoidModel"; import { SkipChangeset } from "@server/models/decorators/Changeset"; +import IsScope from "@server/models/validators/IsScope"; import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; import { hash } from "@server/utils/crypto"; import OAuthClient from "./OAuthClient"; @@ -81,10 +81,7 @@ class OAuthAuthentication extends ParanoidModel< grantId: string | null; /** A list of scopes that this authentication has access to */ - @Matches(AuthenticationHelper.scopeGrammarRegex, { - each: true, - message: "Scope must be a valid API scope", - }) + @IsScope @Column(DataType.ARRAY(DataType.STRING)) scope: string[]; @@ -148,7 +145,9 @@ class OAuthAuthentication extends ParanoidModel< // MCP endpoint access is allowed if the token has any valid scope. // Fine-grained scope enforcement happens at the tool level. if (path.startsWith("/mcp")) { - return this.scope.length > 0; + return this.scope.some((scope) => + AuthenticationHelper.isValidScope(scope) + ); } return AuthenticationHelper.canAccess(path, this.scope); diff --git a/server/models/oauth/OAuthAuthorizationCode.test.ts b/server/models/oauth/OAuthAuthorizationCode.test.ts index 353ef5fa74..677b71f213 100644 --- a/server/models/oauth/OAuthAuthorizationCode.test.ts +++ b/server/models/oauth/OAuthAuthorizationCode.test.ts @@ -23,6 +23,25 @@ const buildCode = async () => { }; describe("OAuthAuthorizationCode", () => { + describe("scope", () => { + it("should reject malformed scopes", async () => { + const user = await buildUser(); + const client = await buildOAuthClient({ teamId: user.teamId }); + + await expect( + OAuthAuthorizationCode.create({ + authorizationCodeHash: hash(crypto.randomBytes(32).toString("hex")), + scope: ["documents:read,documents:write"], + redirectUri: client.redirectUris[0], + oauthClientId: client.id, + userId: user.id, + expiresAt: new Date(Date.now() + 10000), + grantId: crypto.randomUUID(), + }) + ).rejects.toThrow("Scope must be a valid API scope"); + }); + }); + describe("consume", () => { it("should consume the code once", async () => { const code = await buildCode(); diff --git a/server/models/oauth/OAuthAuthorizationCode.ts b/server/models/oauth/OAuthAuthorizationCode.ts index 60062e16f1..445d62faca 100644 --- a/server/models/oauth/OAuthAuthorizationCode.ts +++ b/server/models/oauth/OAuthAuthorizationCode.ts @@ -1,4 +1,3 @@ -import { Matches } from "class-validator"; import type { InferAttributes, InferCreationAttributes } from "sequelize"; import { Column, @@ -8,12 +7,12 @@ import { Table, Length, } from "sequelize-typescript"; -import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; import { OAuthClientValidation } from "@shared/validations"; import env from "@server/env"; import User from "@server/models/User"; import IdModel from "@server/models/base/IdModel"; import { SkipChangeset } from "@server/models/decorators/Changeset"; +import IsScope from "@server/models/validators/IsScope"; import { hash } from "@server/utils/crypto"; import OAuthClient from "./OAuthClient"; @@ -56,10 +55,7 @@ class OAuthAuthorizationCode extends IdModel< grantId: string | null; /** A list of scopes that this authorization code has access to */ - @Matches(AuthenticationHelper.scopeGrammarRegex, { - each: true, - message: "Scope must be a valid API scope", - }) + @IsScope @Column(DataType.ARRAY(DataType.STRING)) scope: string[]; diff --git a/server/models/oauth/OAuthClient.ts b/server/models/oauth/OAuthClient.ts index f0d6e79be4..ef535dd9f6 100644 --- a/server/models/oauth/OAuthClient.ts +++ b/server/models/oauth/OAuthClient.ts @@ -1,10 +1,3 @@ -import { - ArrayMaxSize, - ArrayMinSize, - ArrayNotEmpty, - ArrayUnique, - IsUrl, -} from "class-validator"; import type { InferAttributes, InferCreationAttributes } from "sequelize"; import { Column, @@ -27,6 +20,7 @@ import { SkipChangeset } from "@server/models/decorators/Changeset"; import Encrypted from "@server/models/decorators/Encrypted"; import { hash } from "@server/utils/crypto"; import IsUrlOrRelativePath from "@server/models/validators/IsUrlOrRelativePath"; +import IsUrlList from "@server/models/validators/IsUrlList"; import Length from "@server/models/validators/Length"; import NotContainsUrl from "@server/models/validators/NotContainsUrl"; import type { FindOptions } from "sequelize"; @@ -103,19 +97,7 @@ class OAuthClient extends ParanoidModel< @Column(DataType.BOOLEAN) published: boolean; - @ArrayNotEmpty() - @ArrayUnique() - @ArrayMinSize(1) - @ArrayMaxSize(10) - @IsUrl( - { - require_tld: false, - allow_underscores: true, - }, - { - each: true, - } - ) + @IsUrlList({ min: 1, max: OAuthClientValidation.maxRedirectUris }) @Column(DataType.ARRAY(DataType.STRING)) redirectUris: string[]; diff --git a/server/models/validators/IsFQDN.ts b/server/models/validators/IsFQDN.ts index ea4c59eb47..df25bd512c 100644 --- a/server/models/validators/IsFQDN.ts +++ b/server/models/validators/IsFQDN.ts @@ -1,4 +1,4 @@ -import { isFQDN } from "class-validator"; +import isFQDN from "validator/lib/isFQDN"; import { addAttributeOptions } from "sequelize-typescript"; /** diff --git a/server/models/validators/IsHexColor.ts b/server/models/validators/IsHexColor.ts index 320ef0e617..b90eeb7c20 100644 --- a/server/models/validators/IsHexColor.ts +++ b/server/models/validators/IsHexColor.ts @@ -1,4 +1,4 @@ -import { isHexColor } from "class-validator"; +import isHexColor from "validator/lib/isHexColor"; import { addAttributeOptions } from "sequelize-typescript"; /** diff --git a/server/models/validators/IsScope.ts b/server/models/validators/IsScope.ts new file mode 100644 index 0000000000..41068003c4 --- /dev/null +++ b/server/models/validators/IsScope.ts @@ -0,0 +1,26 @@ +import { addAttributeOptions } from "sequelize-typescript"; +import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; + +/** + * A decorator that validates that every element of a string array is a + * well-formed API scope. + */ +export default function IsScope(target: object, propertyName: string) { + return addAttributeOptions(target, propertyName, { + validate: { + validScope(value: string[] | null) { + if (!value) { + return; + } + if (!Array.isArray(value)) { + throw new Error("Scope must be an array"); + } + for (const scope of value) { + if (!AuthenticationHelper.isValidScope(scope)) { + throw new Error("Scope must be a valid API scope"); + } + } + }, + }, + }); +} diff --git a/server/models/validators/IsUrl.ts b/server/models/validators/IsUrl.ts index 80c1268f74..4adebfa232 100644 --- a/server/models/validators/IsUrl.ts +++ b/server/models/validators/IsUrl.ts @@ -1,4 +1,4 @@ -import { isURL } from "class-validator"; +import isURL from "validator/lib/isURL"; import { addAttributeOptions } from "sequelize-typescript"; import env from "@server/env"; diff --git a/server/models/validators/IsUrlList.ts b/server/models/validators/IsUrlList.ts new file mode 100644 index 0000000000..ac916f1a34 --- /dev/null +++ b/server/models/validators/IsUrlList.ts @@ -0,0 +1,43 @@ +import { addAttributeOptions } from "sequelize-typescript"; +import isURL from "validator/lib/isURL"; + +/** + * A decorator that validates that a value is an array of unique, well-formed + * URLs with a length within the given bounds. A top-level domain is not + * required, allowing local and internal hostnames. + */ +export default function IsUrlList({ + min = 1, + max, +}: { + min?: number; + max: number; +}): (target: object, propertyName: string) => void { + return (target: object, propertyName: string) => + addAttributeOptions(target, propertyName, { + validate: { + validUrlList(value: string[] | null) { + if (!Array.isArray(value)) { + throw new Error("Must be an array of urls"); + } + if (value.length < min || value.length > max) { + throw new Error(`Must contain between ${min} and ${max} urls`); + } + if (new Set(value).size !== value.length) { + throw new Error("Must not contain duplicate urls"); + } + for (const url of value) { + if ( + typeof url !== "string" || + !isURL(url, { + require_tld: false, + allow_underscores: true, + }) + ) { + throw new Error("Must be a valid url"); + } + } + }, + }, + }); +} diff --git a/server/models/validators/IsUrlOrRelativePath.ts b/server/models/validators/IsUrlOrRelativePath.ts index 19703b1fd6..f00924de19 100644 --- a/server/models/validators/IsUrlOrRelativePath.ts +++ b/server/models/validators/IsUrlOrRelativePath.ts @@ -1,4 +1,4 @@ -import { isURL } from "class-validator"; +import isURL from "validator/lib/isURL"; import { addAttributeOptions } from "sequelize-typescript"; /** diff --git a/server/routes/api/apiKeys/apiKeys.test.ts b/server/routes/api/apiKeys/apiKeys.test.ts index 68acaff701..c0d02c162f 100644 --- a/server/routes/api/apiKeys/apiKeys.test.ts +++ b/server/routes/api/apiKeys/apiKeys.test.ts @@ -44,6 +44,36 @@ describe("#apiKeys.create", () => { expect(body.data.lastActiveAt).toBeNull(); }); + it("should allow the wildcard scope", async () => { + const user = await buildUser(); + + const res = await server.post("/api/apiKeys.create", user, { + body: { + name: "My API Key", + scope: ["*"], + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(200); + expect(body.data.scope).toEqual(["*"]); + }); + + it("should reject malformed scopes", async () => { + const user = await buildUser(); + + const res = await server.post("/api/apiKeys.create", user, { + body: { + name: "My API Key", + scope: ["documents:read,documents:write"], + }, + }); + const body = await res.json(); + + expect(res.status).toEqual(400); + expect(body.message).toContain("Scope must be a valid API scope"); + }); + it("should allow creating an api key with scopes", async () => { const user = await buildUser(); diff --git a/server/routes/api/apiKeys/apiKeys.ts b/server/routes/api/apiKeys/apiKeys.ts index 779d750430..713e1c595e 100644 --- a/server/routes/api/apiKeys/apiKeys.ts +++ b/server/routes/api/apiKeys/apiKeys.ts @@ -1,6 +1,5 @@ import Router from "koa-router"; import { Op, Sequelize, type WhereOptions } from "sequelize"; -import { Scope } from "@shared/types"; import auth from "@server/middlewares/authentication"; import { rateLimiter } from "@server/middlewares/rateLimiter"; import { transaction } from "@server/middlewares/transaction"; @@ -17,8 +16,6 @@ import * as T from "./schema"; const router = new Router(); -const globalScopes = new Set(Object.values(Scope)); - router.post( "apiKeys.create", rateLimiter(RateLimiterStrategy.TwentyFivePerMinute), @@ -37,11 +34,7 @@ router.post( name, userId: user.id, expiresAt, - scope: scope?.map((s) => - s.startsWith("/api/") || s.includes(":") || globalScopes.has(s) - ? s - : `/api/${s.replace(/^\//, "")}` - ), + scope, }); apiKey.user = user; diff --git a/server/routes/api/apiKeys/schema.ts b/server/routes/api/apiKeys/schema.ts index 54f5964712..69f13ff648 100644 --- a/server/routes/api/apiKeys/schema.ts +++ b/server/routes/api/apiKeys/schema.ts @@ -1,8 +1,21 @@ import { z } from "zod"; import { ApiKey } from "@server/models"; import { BaseSchema } from "@server/routes/api/schema"; +import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; +import { Scope } from "@shared/types"; import { ApiKeyValidation } from "@shared/validations"; +const globalScopes = new Set([...Object.values(Scope), "*"]); + +/** + * Normalizes a user-supplied scope into its canonical form by prefixing bare + * route scopes with `/api/`. + */ +const normalizeScope = (scope: string) => + scope.startsWith("/api/") || scope.includes(":") || globalScopes.has(scope) + ? scope + : `/api/${scope.replace(/^\//, "")}`; + export const APIKeysCreateSchema = BaseSchema.extend({ body: z.object({ /** API Key name */ @@ -14,7 +27,17 @@ export const APIKeysCreateSchema = BaseSchema.extend({ /** API Key expiry date */ expiresAt: z.coerce.date().optional(), /** A list of scopes that this API key has access to */ - scope: z.array(z.string()).optional(), + scope: z + .array( + z + .string() + .trim() + .transform(normalizeScope) + .refine((scope) => AuthenticationHelper.isValidScope(scope), { + error: "Scope must be a valid API scope", + }) + ) + .optional(), }), }); diff --git a/server/routes/api/oauthClients/oauthClients.test.ts b/server/routes/api/oauthClients/oauthClients.test.ts index 0a034cebc3..e3f1d259fc 100644 --- a/server/routes/api/oauthClients/oauthClients.test.ts +++ b/server/routes/api/oauthClients/oauthClients.test.ts @@ -285,6 +285,25 @@ describe("oauthClients.create", () => { expect(body.data.name).toEqual("Test Client"); expect(body.data.redirectUris).toEqual(["https://example.com/callback"]); }); + + it("should reject duplicate redirect uris", async () => { + const team = await buildTeam(); + const admin = await buildAdmin({ teamId: team.id }); + + const res = await server.post("/api/oauthClients.create", admin, { + body: { + name: "Test Client", + redirectUris: [ + "https://example.com/callback", + "https://example.com/callback", + ], + }, + }); + + const body = await res.json(); + expect(res.status).toEqual(400); + expect(body.message).toContain("Must not contain duplicate urls"); + }); }); describe("oauthclients.update", () => { diff --git a/server/routes/oauth/oauth.test.ts b/server/routes/oauth/oauth.test.ts index c86e274f47..c3d73975a8 100644 --- a/server/routes/oauth/oauth.test.ts +++ b/server/routes/oauth/oauth.test.ts @@ -174,6 +174,23 @@ describe("#oauth.register", () => { expect(res.status).toEqual(201); }); + it("should reject duplicate redirect_uris", async () => { + const res = await server.post("/oauth/register", { + body: { + client_name: "Test Client", + redirect_uris: [ + "https://example.com/callback", + "https://example.com/callback", + ], + }, + headers: { + host: `${subdomain}.outline.dev`, + }, + }); + + expect(res.status).toEqual(400); + }); + it("should reject too many redirect_uris and report the received count", async () => { const count = OAuthClientValidation.maxRedirectUris + 1; const res = await server.post("/oauth/register", {