Files
outline/server/middlewares/authentication.test.ts
T
Tom MoorandClaude Opus 5.5 00b124d03c chore: Rename APIContext to Context and flatten its fields (#14684)
* chore: Rename APIContext to Context and flatten its fields

Auth and transaction now live directly on the context instead of in
ctx.state and a nested ctx.context, and model helpers read them directly.
APIContext remains as a deprecated alias.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Remove deprecated APIContext alias

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* fix: Read auth from context in OAuth provider callbacks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Add withUser and withTransaction context helpers

Replaces manual createContext rebuilds that copy fields from an existing context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

* chore: Remove arbitrary property access from Koa context types

AppContext and Context no longer inherit the any index signature from
Koa's DefaultContext, custom fields are declared explicitly, and importing
Koa's loose Context type is disallowed by lint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016MJXFeUxvU46KyvKnP8sXf

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-23 23:17:06 -05:00

432 lines
12 KiB
TypeScript

import { errToString } from "@shared/utils/error";
import { randomString } from "@shared/random";
import { Scope } from "@shared/types";
import {
buildUser,
buildTeam,
buildAdmin,
buildApiKey,
buildOAuthAuthentication,
} from "@server/test/factories";
import { buildMockContext } from "@server/test/support";
import { AuthenticationType } from "@server/types";
import auth from "./authentication";
describe("Authentication middleware", () => {
describe("with session JWT", () => {
it("should authenticate with correct session token", async () => {
const user = await buildUser();
const authMiddleware = auth();
const ctx = buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
expect(ctx.auth?.user.id).toEqual(user.id);
});
it("should return error with invalid session token", async () => {
const user = await buildUser();
const authMiddleware = auth();
try {
const ctx = buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getSessionToken()}error`),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
} catch (e) {
expect(errToString(e)).toBe("Invalid token");
}
});
it("should return error if AuthenticationType mismatches", async () => {
const user = await buildUser();
const authMiddleware = auth({
type: AuthenticationType.API,
});
try {
const ctx = buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
} catch (e) {
expect(errToString(e)).toBe("Invalid authentication type");
}
});
});
describe("with API key", () => {
it("should authenticate user with valid API key", async () => {
const user = await buildUser();
const authMiddleware = auth();
const key = await buildApiKey({ userId: user.id });
const ctx = buildMockContext({
request: {
get: vi.fn(() => `Bearer ${key.value}`),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
expect(ctx.auth?.user.id).toEqual(user.id);
});
it("should authenticate with global read scope on read endpoints", async () => {
const user = await buildUser();
const authMiddleware = auth();
const key = await buildApiKey({
userId: user.id,
scope: [Scope.Read],
});
const ctx = buildMockContext({
originalUrl: "/api/auth.info",
request: {
url: "/auth.info",
get: vi.fn(() => `Bearer ${key.value}`),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
expect(ctx.auth?.user.id).toEqual(user.id);
});
it("should return 403 authorization error when scope does not match", async () => {
const user = await buildUser();
const authMiddleware = auth();
const key = await buildApiKey({
userId: user.id,
scope: [Scope.Read],
});
try {
const ctx = buildMockContext({
originalUrl: "/api/documents.create",
request: {
url: "/documents.create",
get: vi.fn(() => `Bearer ${key.value}`),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
throw new Error("Expected error to be thrown");
} catch (e) {
expect(e).toHaveProperty("status", 403);
expect(e).toHaveProperty("id", "authorization_error");
expect(errToString(e)).toContain(
"does not have access to this resource"
);
}
});
it("should return error with invalid API key", async () => {
const authMiddleware = auth();
try {
const ctx = buildMockContext({
request: {
get: vi.fn(() => `Bearer ${randomString(38)}`),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
} catch (e) {
expect(errToString(e)).toBe("Invalid API key");
}
});
});
describe("with OAuth access token", () => {
it("should authenticate user with valid OAuth access token", async () => {
const user = await buildUser();
const authMiddleware = auth();
const authentication = await buildOAuthAuthentication({
user,
scope: [Scope.Read],
});
const ctx = buildMockContext({
originalUrl: "/api/users.info",
request: {
url: "/users.info",
get: vi.fn(() => `Bearer ${authentication.accessToken}`),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
expect(ctx.auth?.user.id).toEqual(user.id);
});
it("should return error with invalid scope", async () => {
const user = await buildUser();
const authMiddleware = auth();
const authentication = await buildOAuthAuthentication({
user,
scope: [Scope.Read],
});
try {
const ctx = buildMockContext({
originalUrl: "/api/documents.create",
request: {
url: "/documents.create",
get: vi.fn(() => `Bearer ${authentication.accessToken}`),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
} catch (e) {
expect(errToString(e)).toContain(
"does not have access to this resource"
);
}
});
it("should return error with OAuth access token in body", async () => {
const user = await buildUser();
const authMiddleware = auth();
const authentication = await buildOAuthAuthentication({
user,
scope: [Scope.Read],
});
try {
const ctx = buildMockContext({
originalUrl: "/api/users.info",
request: {
url: "/users.info",
get: vi.fn(() => null),
body: {
token: authentication.accessToken,
},
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
} catch (e) {
expect(errToString(e)).toContain(
"must be passed in the Authorization header"
);
}
});
});
it("should return error message if no auth token is available", async () => {
const authMiddleware = auth();
try {
const ctx = buildMockContext({
request: {
get: vi.fn(() => "error"),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
} catch (e) {
expect(errToString(e)).toBe(
'Bad Authorization header format. Format is "Authorization: Bearer <token>"'
);
}
});
it("should allow passing session token in a cookie", async () => {
const user = await buildUser();
const authMiddleware = auth();
const ctx = buildMockContext({
request: {
get: vi.fn(() => null),
},
cookies: {
get: vi.fn(() => user.getSessionToken()),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
expect(ctx.auth?.user.id).toEqual(user.id);
});
it("should return error with session token as a GET param", async () => {
const user = await buildUser();
const authMiddleware = auth();
await expect(
authMiddleware(
buildMockContext({
request: {
get: vi.fn(() => null),
query: {
token: user.getSessionToken(),
},
},
cache: {},
}),
vi.fn()
)
).rejects.toThrow(
"Session token must be passed in the cookie or Authorization header"
);
});
it("should return error with session token in body params", async () => {
const user = await buildUser();
const authMiddleware = auth();
await expect(
authMiddleware(
buildMockContext({
request: {
get: vi.fn(() => null),
body: {
token: user.getSessionToken(),
},
},
cache: {},
}),
vi.fn()
)
).rejects.toThrow(
"Session token must be passed in the cookie or Authorization header"
);
});
it("should not accept transfer token as a GET param", async () => {
const user = await buildUser();
const authMiddleware = auth();
await expect(
authMiddleware(
buildMockContext({
request: {
get: vi.fn(() => null),
query: {
token: user.getTransferToken(),
},
},
cache: {},
}),
vi.fn()
)
).rejects.toThrow(
"Session token must be passed in the cookie or Authorization header"
);
});
it("should not accept transfer token in the Authorization header", async () => {
const user = await buildUser();
const authMiddleware = auth();
await expect(
authMiddleware(
buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getTransferToken()}`),
},
cache: {},
}),
vi.fn()
)
).rejects.toThrow("Invalid token");
});
it("should return an error for suspended users", async () => {
const admin = await buildAdmin();
const user = await buildUser({
suspendedAt: new Date(),
suspendedById: admin.id,
});
const authMiddleware = auth();
let error;
try {
const ctx = buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
} catch (err) {
error = err;
}
expect(errToString(error)).toEqual(
"Your access has been suspended by a workspace admin"
);
expect(error).toHaveProperty("errorData.adminEmail", admin.email);
});
it("should return an error for deleted team", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
await team.destroy();
const authMiddleware = auth();
let error;
try {
const ctx = buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
},
cache: {},
});
await authMiddleware(ctx, vi.fn());
} catch (err) {
error = err;
}
expect(errToString(error)).toEqual("Invalid token");
});
describe("with skip", () => {
it("should ignore credentials when skip returns true", async () => {
const user = await buildUser();
const apiKey = await buildApiKey({
userId: user.id,
scope: ["/api/documents.info"],
});
const next = vi.fn();
const authMiddleware = auth({
optional: true,
skip: (ctx) => !!ctx.query.sig,
});
const ctx = buildMockContext({
request: {
get: vi.fn(() => `Bearer ${apiKey.value}`),
},
query: { sig: "signature" },
originalUrl: "/api/files.get?sig=signature",
cache: {},
});
await authMiddleware(ctx, next);
expect(next).toHaveBeenCalled();
expect(ctx.auth).toEqual({});
});
it("should authenticate when skip returns false", async () => {
const user = await buildUser();
const next = vi.fn();
const authMiddleware = auth({
optional: true,
skip: (ctx) => !!ctx.query.sig,
});
const ctx = buildMockContext({
request: {
get: vi.fn(() => `Bearer ${user.getSessionToken()}`),
},
query: {},
cache: {},
});
await authMiddleware(ctx, next);
expect(next).toHaveBeenCalled();
expect(ctx.auth?.user.id).toEqual(user.id);
});
});
});