fix: Validate API key and OAuth scopes at the model layer (#13664)

* fix: Validate API key scopes with Sequelize-level validators

* test: Add API regression tests for duplicate OAuth redirect URIs

* fix: Preserve wildcard scope and guard non-string redirect URIs

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Tom MoorandClaude Fable 5.1 authored and GitHub committed 2026-09-04 23:10:32 -04:00
1 parent cd082e7e3b
commit a577d5c2c8
24 files changed
+289 -60

No files matched your search

+1 -1
View File
@@ -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(
+25
View File
@@ -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": {
+1 -1
View File
@@ -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";
+35
View File
@@ -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,
]);
});
});
});
+5 -6
View File
@@ -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);
+1 -2
View File
@@ -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;
/**
+4 -4
View File
@@ -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;
+1 -1
View File
@@ -1,4 +1,4 @@
import { isUUID } from "class-validator";
import isUUID from "validator/lib/isUUID";
import type {
Identifier,
InferAttributes,
@@ -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({
+5 -6
View File
@@ -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);
@@ -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();
@@ -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[];
+2 -20
View File
@@ -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[];
+1 -1
View File
@@ -1,4 +1,4 @@
import { isFQDN } from "class-validator";
import isFQDN from "validator/lib/isFQDN";
import { addAttributeOptions } from "sequelize-typescript";
/**
+1 -1
View File
@@ -1,4 +1,4 @@
import { isHexColor } from "class-validator";
import isHexColor from "validator/lib/isHexColor";
import { addAttributeOptions } from "sequelize-typescript";
/**
+26
View File
@@ -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");
}
}
},
},
});
}
+1 -1
View File
@@ -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";
+43
View File
@@ -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");
}
}
},
},
});
}
@@ -1,4 +1,4 @@
import { isURL } from "class-validator";
import isURL from "validator/lib/isURL";
import { addAttributeOptions } from "sequelize-typescript";
/**
+30
View File
@@ -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();
+1 -8
View File
@@ -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<string>(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;
+24 -1
View File
@@ -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<string>([...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(),
}),
});
@@ -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", () => {
+17
View File
@@ -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", {