mirror of
https://github.com/outline/outline.git
synced 2026-11-29 16:40:27 +03:00
Bring error handling to spec for oauth endpoints
This commit is contained in:
1 parent
ea79883e04
commit
aa60f5ccea
9 files changed
+188
-12
No files matched your search
@@ -192,7 +192,7 @@ describe("userProvisioner", () => {
|
||||
|
||||
it("should prefer isAdmin argument over defaultUserRole", async () => {
|
||||
const team = await buildTeam({
|
||||
defaultUserRole: "viewer",
|
||||
defaultUserRole: UserRole.Viewer,
|
||||
});
|
||||
const authenticationProviders = await team.$get("authenticationProviders");
|
||||
const authenticationProvider = authenticationProviders[0];
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Context, Next } from "koa";
|
||||
import { addTags, getRootSpanFromRequestContext } from "@server/logging/tracer";
|
||||
|
||||
export default function apiTracer() {
|
||||
return async function apiTracerMiddleware(ctx: Context, next: Next) {
|
||||
export default function requestTracer() {
|
||||
return async function requestTracerMiddleware(ctx: Context, next: Next) {
|
||||
const params = ctx.request.body ?? ctx.request.query;
|
||||
|
||||
for (const key in params) {
|
||||
@@ -0,0 +1,37 @@
|
||||
import { subMonths } from "date-fns";
|
||||
import { OAuthAuthorizationCode } from "@server/models";
|
||||
import { buildOAuthAuthorizationCode } from "@server/test/factories";
|
||||
import CleanupOAuthAuthorizationCodeTask from "./CleanupOAuthAuthorizationCodeTask";
|
||||
|
||||
const codeExists = async (code: OAuthAuthorizationCode) => {
|
||||
const found = await OAuthAuthorizationCode.findByPk(code.id);
|
||||
return !!found;
|
||||
};
|
||||
|
||||
describe("CleanupOAuthAuthorizationCodeTask", () => {
|
||||
it("should delete authorization codes expired more than one month ago", async () => {
|
||||
const brandNewCode = await buildOAuthAuthorizationCode({
|
||||
expiresAt: new Date(),
|
||||
});
|
||||
const oldCode = await buildOAuthAuthorizationCode({
|
||||
expiresAt: subMonths(new Date(), 2),
|
||||
});
|
||||
|
||||
const task = new CleanupOAuthAuthorizationCodeTask();
|
||||
await task.perform();
|
||||
|
||||
expect(await codeExists(brandNewCode)).toBe(true);
|
||||
expect(await codeExists(oldCode)).toBe(false);
|
||||
});
|
||||
|
||||
it("should not delete codes that expired less than one month ago", async () => {
|
||||
const recentCode = await buildOAuthAuthorizationCode({
|
||||
expiresAt: new Date(),
|
||||
});
|
||||
|
||||
const task = new CleanupOAuthAuthorizationCodeTask();
|
||||
await task.perform();
|
||||
|
||||
expect(await codeExists(recentCode)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { subMonths } from "date-fns";
|
||||
import { Op } from "sequelize";
|
||||
import Logger from "@server/logging/Logger";
|
||||
import { OAuthAuthorizationCode } from "@server/models/oauth/OAuthAuthorizationCode";
|
||||
import { OAuthAuthorizationCode } from "@server/models";
|
||||
import BaseTask, { TaskPriority, TaskSchedule } from "./BaseTask";
|
||||
|
||||
type Props = Record<string, never>;
|
||||
|
||||
@@ -5,6 +5,7 @@ import userAgent, { UserAgentContext } from "koa-useragent";
|
||||
import env from "@server/env";
|
||||
import { NotFoundError } from "@server/errors";
|
||||
import coalesceBody from "@server/middlewares/coaleseBody";
|
||||
import requestTracer from "@server/middlewares/requestTracer";
|
||||
import { AppState, AppContext } from "@server/types";
|
||||
import { Hook, PluginManager } from "@server/utils/PluginManager";
|
||||
import apiKeys from "./apiKeys";
|
||||
@@ -25,7 +26,6 @@ import installation from "./installation";
|
||||
import integrations from "./integrations";
|
||||
import apiErrorHandler from "./middlewares/apiErrorHandler";
|
||||
import apiResponse from "./middlewares/apiResponse";
|
||||
import apiTracer from "./middlewares/apiTracer";
|
||||
import editor from "./middlewares/editor";
|
||||
import notifications from "./notifications";
|
||||
import oauthClients from "./oauthClients";
|
||||
@@ -61,7 +61,7 @@ api.use(
|
||||
);
|
||||
api.use(coalesceBody());
|
||||
api.use<BaseContext, UserAgentContext>(userAgent);
|
||||
api.use(apiTracer());
|
||||
api.use(requestTracer());
|
||||
api.use(apiResponse());
|
||||
api.use(apiErrorHandler());
|
||||
api.use(editor());
|
||||
|
||||
@@ -3,12 +3,12 @@ import Koa from "koa";
|
||||
import bodyParser from "koa-body";
|
||||
import Router from "koa-router";
|
||||
import auth from "@server/middlewares/authentication";
|
||||
import requestTracer from "@server/middlewares/requestTracer";
|
||||
import { OAuthInterface } from "@server/utils/oauth/OAuthInterface";
|
||||
import oauthErrorHandler from "./middlewares/oauthErrorHandler";
|
||||
|
||||
const app = new Koa();
|
||||
|
||||
const router = new Router();
|
||||
|
||||
const oauth = new OAuth2Server({
|
||||
model: OAuthInterface,
|
||||
});
|
||||
@@ -43,6 +43,10 @@ router.post("/token", async (ctx) => {
|
||||
|
||||
const token = await oauth.token(request, response);
|
||||
|
||||
if (response.headers) {
|
||||
ctx.set(response.headers);
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
access_token: token.accessToken,
|
||||
refresh_token: token.refreshToken,
|
||||
@@ -54,6 +58,8 @@ router.post("/token", async (ctx) => {
|
||||
};
|
||||
});
|
||||
|
||||
app.use(requestTracer());
|
||||
app.use(oauthErrorHandler());
|
||||
app.use(bodyParser());
|
||||
app.use(router.routes());
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Context, Next } from "koa";
|
||||
import {
|
||||
ValidationError as SequelizeValidationError,
|
||||
EmptyResultError as SequelizeEmptyResultError,
|
||||
} from "sequelize";
|
||||
|
||||
/**
|
||||
* To adhere to the OAuth 2.0 specification, errors from the /token and /authorize routes
|
||||
* follow the snake_case convention with `error` and `error_description` keys, rather than
|
||||
* our standard error format.
|
||||
*/
|
||||
export default function oauthErrorHandler() {
|
||||
return async function oauthErrorHandlerMiddleware(ctx: Context, next: Next) {
|
||||
try {
|
||||
await next();
|
||||
} catch (err) {
|
||||
if (err instanceof SequelizeEmptyResultError) {
|
||||
ctx.status = 404;
|
||||
ctx.body = {
|
||||
error: "invalid_request",
|
||||
error_description: "Resource not found",
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (err instanceof SequelizeValidationError) {
|
||||
ctx.status = 400;
|
||||
ctx.body = {
|
||||
error: "invalid_request",
|
||||
error_description: err.errors[0].message,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.status = err.code || 500;
|
||||
ctx.body = {
|
||||
error: err.name,
|
||||
error_description: err.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -43,6 +43,9 @@ import {
|
||||
Pin,
|
||||
Comment,
|
||||
Import,
|
||||
OAuthAuthorizationCode,
|
||||
OAuthClient,
|
||||
AuthenticationProvider,
|
||||
} from "@server/models";
|
||||
import AttachmentHelper from "@server/models/helpers/AttachmentHelper";
|
||||
|
||||
@@ -137,7 +140,11 @@ export async function buildSubscription(overrides: Partial<Subscription> = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
export function buildTeam(overrides: Record<string, any> = {}) {
|
||||
export function buildTeam(
|
||||
overrides: Omit<Partial<Team>, "authenticationProviders"> & {
|
||||
authenticationProviders?: Partial<AuthenticationProvider>[];
|
||||
} = {}
|
||||
) {
|
||||
return Team.create(
|
||||
{
|
||||
name: faker.company.name(),
|
||||
@@ -691,6 +698,60 @@ export async function buildPin(overrides: Partial<Pin> = {}): Promise<Pin> {
|
||||
return Pin.create(overrides);
|
||||
}
|
||||
|
||||
export async function buildOAuthClient(overrides: Partial<OAuthClient> = {}) {
|
||||
if (!overrides.teamId) {
|
||||
const team = await buildTeam();
|
||||
overrides.teamId = team.id;
|
||||
}
|
||||
|
||||
if (!overrides.createdById) {
|
||||
const user = await buildUser({
|
||||
teamId: overrides.teamId,
|
||||
});
|
||||
overrides.createdById = user.id;
|
||||
}
|
||||
|
||||
return OAuthClient.create({
|
||||
name: faker.company.name(),
|
||||
description: faker.lorem.paragraph(),
|
||||
redirectUris: ["https://example.com/oauth/callback"],
|
||||
published: true,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
export async function buildOAuthAuthorizationCode(
|
||||
overrides: Partial<OAuthAuthorizationCode> = {}
|
||||
) {
|
||||
if (!overrides.userId) {
|
||||
const user = await buildUser();
|
||||
overrides.userId = user.id;
|
||||
}
|
||||
|
||||
if (!overrides.expiresAt) {
|
||||
overrides.expiresAt = new Date();
|
||||
}
|
||||
|
||||
const code = randomstring.generate(32);
|
||||
|
||||
let client;
|
||||
if (overrides.oauthClientId) {
|
||||
client = await OAuthClient.findByPk(overrides.oauthClientId, {
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
} else {
|
||||
client = await buildOAuthClient();
|
||||
overrides.oauthClientId = client.id;
|
||||
}
|
||||
|
||||
return OAuthAuthorizationCode.create({
|
||||
authorizationCodeHash: OAuthAuthorizationCode.hash(code),
|
||||
scope: ["read"],
|
||||
redirectUri: client.redirectUris[0],
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
export function buildProseMirrorDoc(content: DeepPartial<ProsemirrorData>[]) {
|
||||
return Node.fromJSON(schema, {
|
||||
type: "doc",
|
||||
|
||||
@@ -200,8 +200,39 @@ export const OAuthInterface: RefreshTokenModel &
|
||||
return false;
|
||||
},
|
||||
|
||||
async validateRedirectUri() {
|
||||
// TODO
|
||||
return true;
|
||||
/**
|
||||
* Ensure the redirect URI is not plain HTTP. Custom protocols are allowed.
|
||||
*
|
||||
* @param uri The redirect URI to validate.
|
||||
* @returns True if the URI is valid, false otherwise.
|
||||
*/
|
||||
async validateRedirectUri(uri) {
|
||||
return !uri.startsWith("http://");
|
||||
},
|
||||
|
||||
/**
|
||||
* Invoked to check if the requested scope is valid for a particular client/user combination.
|
||||
*
|
||||
* @param scope The requested scopes.
|
||||
* @returns The scopes if valid, false otherwise.
|
||||
*/
|
||||
async validateScope(user, client, scope) {
|
||||
if (!scope) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const scopes = Array.isArray(scope) ? scope : [scope];
|
||||
return scopes.some((s: string) => {
|
||||
if (s === "read" || s === "write") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const periodCount = (s.match(/\./g) || []).length;
|
||||
const colonCount = (s.match(/:/g) || []).length;
|
||||
|
||||
return periodCount === 1 || colonCount === 1;
|
||||
})
|
||||
? scopes
|
||||
: false;
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user