diff --git a/server/errors.ts b/server/errors.ts index e42604176d..7a28badfb9 100644 --- a/server/errors.ts +++ b/server/errors.ts @@ -260,6 +260,15 @@ export function InvalidClientMetadataError( }); } +export function InvalidRedirectUriError( + message = "The redirect URI is invalid" +) { + return httpErrors(400, message, { + id: "invalid_redirect_uri", + isReportable: false, + }); +} + export function RequestTimeoutError( message = "Request took too long to complete" ) { diff --git a/server/routes/oauth/index.ts b/server/routes/oauth/index.ts index 960e438940..fc9125681c 100644 --- a/server/routes/oauth/index.ts +++ b/server/routes/oauth/index.ts @@ -3,7 +3,11 @@ import Koa from "koa"; import bodyParser from "koa-body"; import Router from "@koa/router"; import env from "@server/env"; -import { ValidationError, NotFoundError } from "@server/errors"; +import { + InvalidRedirectUriError, + ValidationError, + NotFoundError, +} from "@server/errors"; import { apiContext } from "@server/middlewares/apiContext"; import auth from "@server/middlewares/authentication"; import { rateLimiter } from "@server/middlewares/rateLimiter"; @@ -229,6 +233,8 @@ router.post( contacts, } = ctx.input.body; + assertValidRedirectUris(redirect_uris); + const team = await getTeamFromContext(ctx, { includeOAuthState: false, }); @@ -302,6 +308,7 @@ router.put( async (ctx: APIContext) => { const client = ctx.state.oauthClient as OAuthClient; const { client_name, redirect_uris, client_uri, logo_uri } = ctx.input.body; + assertValidRedirectUris(redirect_uris); const team = await client.$get("team", { transaction: ctx.state.transaction, @@ -351,6 +358,21 @@ router.delete( } ); +/** + * Ensures that every redirect URI in a client registration request is valid. + * + * @param redirectUris - the redirect URIs to validate. + * @throws InvalidRedirectUriError if a redirect URI is not valid. + */ +function assertValidRedirectUris(redirectUris: string[]) { + const invalid = redirectUris.find( + (uri) => !OAuthHelper.isValidRedirectUri(uri) + ); + if (invalid !== undefined) { + throw InvalidRedirectUriError(`Invalid redirect URI: ${invalid}`); + } +} + app.use(requestTracer()); app.use(oauthErrorHandler()); app.use(bodyParser()); diff --git a/server/routes/oauth/middlewares/oauthErrorHandler.ts b/server/routes/oauth/middlewares/oauthErrorHandler.ts index 0dc4e50ffd..1c9499053b 100644 --- a/server/routes/oauth/middlewares/oauthErrorHandler.ts +++ b/server/routes/oauth/middlewares/oauthErrorHandler.ts @@ -60,6 +60,12 @@ export default function oauthErrorHandler() { if (err instanceof OAuthError && status < 500) { // Keep the library's error code, as clients act on it. errorType = err.name; + } else if ( + err instanceof Error && + "id" in err && + err.id === "invalid_redirect_uri" + ) { + errorType = "invalid_redirect_uri"; } else if (status === 400) { errorType = "invalid_request"; } else if ( diff --git a/server/routes/oauth/oauth.test.ts b/server/routes/oauth/oauth.test.ts index 03f9824863..4f68a79b7f 100644 --- a/server/routes/oauth/oauth.test.ts +++ b/server/routes/oauth/oauth.test.ts @@ -166,11 +166,18 @@ describe("#oauth.register", () => { expect(res.status).toEqual(400); }); - it("should reject invalid redirect_uris", async () => { + it.each([ + "not-a-url", + "http://evil.com/callback", + "https://example.com/callback#fragment", + "*", + "ftp://example.com/callback", + "https:/example.com/callback", + ])("should reject invalid redirect_uri %s", async (redirectUri) => { const res = await server.post("/oauth/register", { body: { client_name: "Test Client", - redirect_uris: ["not-a-url"], + redirect_uris: ["https://example.com/callback", redirectUri], }, headers: { host: `${subdomain}.outline.dev`, @@ -178,6 +185,11 @@ describe("#oauth.register", () => { }); expect(res.status).toEqual(400); + const body = await res.json(); + expect(body.error).toEqual("invalid_redirect_uri"); + expect(body.error_description).toEqual( + `Invalid redirect URI: ${redirectUri}` + ); }); it("should reject empty redirect_uris array", async () => { @@ -471,6 +483,26 @@ describe("#oauth.register management (RFC 7592)", () => { expect(res.status).toEqual(401); }); + it("should reject an invalid redirect_uri", async () => { + const registered = await registerClient(server, subdomain); + const res = await server.put(`/oauth/register/${registered.client_id}`, { + body: { + client_name: "Updated Client", + redirect_uris: ["http://evil.com/callback"], + }, + headers: { + Authorization: `Bearer ${registered.registration_access_token}`, + }, + }); + + expect(res.status).toEqual(400); + const body = await res.json(); + expect(body.error).toEqual("invalid_redirect_uri"); + + const client = await OAuthClient.findByClientId(registered.client_id); + expect(client!.redirectUris).toEqual(registered.redirect_uris); + }); + it("should reject invalid body", async () => { const registered = await registerClient(server, subdomain); const res = await server.put(`/oauth/register/${registered.client_id}`, { diff --git a/server/routes/oauth/schema.ts b/server/routes/oauth/schema.ts index 0d60385c97..95edd1aba9 100644 --- a/server/routes/oauth/schema.ts +++ b/server/routes/oauth/schema.ts @@ -26,10 +26,12 @@ export const TokenRevokeSchema = BaseSchema.extend({ export type TokenRevokeReq = z.infer; -// The received count is included in the message so that clients registering an -// oversized list, and our own logs, show how far over the limit they are. +// The URIs themselves are validated by the handler, so that it can respond with +// the invalid_redirect_uri error code. The received count is included in the +// message so that clients registering an oversized list, and our own logs, show +// how far over the limit they are. const redirectUris = z - .array(z.url().max(OAuthClientValidation.maxRedirectUriLength)) + .array(z.string().max(OAuthClientValidation.maxRedirectUriLength)) .min(1) .max(OAuthClientValidation.maxRedirectUris, { error: (issue) => diff --git a/server/utils/oauth/OAuthHelper.test.ts b/server/utils/oauth/OAuthHelper.test.ts new file mode 100644 index 0000000000..7d107f9c17 --- /dev/null +++ b/server/utils/oauth/OAuthHelper.test.ts @@ -0,0 +1,41 @@ +import { OAuthHelper } from "./OAuthHelper"; + +describe("OAuthHelper", () => { + describe("isValidRedirectUri", () => { + it.each([ + "https://example.com/callback", + "https://example.com:8443/callback?state=1", + "https://localhost/callback", + "http://localhost/callback", + "http://localhost:54321/callback", + "http://127.0.0.1:8080/callback", + "http://[::1]:8080/callback", + "com.example.app:/oauth2redirect", + "myapp://callback", + ])("should accept %s", (uri) => { + expect(OAuthHelper.isValidRedirectUri(uri)).toBe(true); + }); + + it.each([ + "not-a-url", + "", + "http://evil.com/callback", + "https://example.com/callback#fragment", + "https://*.example.com/callback", + "*", + "ftp://example.com/callback", + "ws://example.com/callback", + "wss://example.com/callback", + "blob:https://example.com/550e8400-e29b-41d4-a716-446655440000", + "javascript:alert(1)", + "data:text/html,hello", + "file:///etc/passwd", + "https://example.com/call\nback", + "https://example.com/call back", + "https:/example.com/callback", + "https:example.com/callback", + ])("should reject %j", (uri) => { + expect(OAuthHelper.isValidRedirectUri(uri)).toBe(false); + }); + }); +}); diff --git a/server/utils/oauth/OAuthHelper.ts b/server/utils/oauth/OAuthHelper.ts index 12f3b1d368..a395a61e23 100644 --- a/server/utils/oauth/OAuthHelper.ts +++ b/server/utils/oauth/OAuthHelper.ts @@ -1,10 +1,7 @@ import type { Context } from "koa"; +import isURL from "validator/lib/isURL"; import type { OAuthClientValidation } from "@shared/validations"; -import { - isLoopbackUri, - isPrivateUseSchemeUrl, - isUrl, -} from "@shared/utils/urls"; +import { isLoopbackUri, isPrivateUseSchemeUrl } from "@shared/utils/urls"; import env from "@server/env"; type ClientType = (typeof OAuthClientValidation.clientTypes)[number]; @@ -69,23 +66,33 @@ export class OAuthHelper { * @returns true if the URI is valid. */ public static isValidRedirectUri(uri: string): boolean { - if (uri.includes("#") || uri.includes("*")) { + if (/[\s#*]/.test(uri)) { + return false; + } + + // The recommended private-use form, e.g. com.example.app:/oauth2redirect, + // has no host so it is checked separately. + if (isPrivateUseSchemeUrl(uri)) { + return true; + } + + // Matches the syntax check of the IsUrlList model validator, and requires + // the "//" authority delimiter that new URL() would otherwise repair. + if ( + !/^https?:\/\//i.test(uri) || + !isURL(uri, { + protocols: ["http", "https"], + require_tld: false, + require_protocol: true, + allow_underscores: true, + }) + ) { return false; } // Loopback addresses may use http:// since TLS certificates cannot be // obtained for them. - if (isLoopbackUri(uri) && new URL(uri).protocol === "http:") { - return true; - } - - // The recommended private-use form, e.g. com.example.app:/oauth2redirect, - // has no host so isUrl would reject it. - if (isPrivateUseSchemeUrl(uri)) { - return true; - } - - return isUrl(uri, { requireHttps: true }); + return /^https:/i.test(uri) || isLoopbackUri(uri); } /**