fix(api): Fix all failing tests

This commit is contained in:
Jesse Wierzbinski 2025-08-21 01:15:38 +02:00
parent 1bfc5fb013
commit 6f97903f3b
No known key found for this signature in database
11 changed files with 111 additions and 179 deletions

View file

@ -0,0 +1,133 @@
import { afterAll, describe, expect, test } from "bun:test";
import { Application, Token } from "@versia-server/kit/db";
import { fakeRequest, getTestUsers } from "@versia-server/tests";
import { randomUUIDv7 } from "bun";
const { deleteUsers, users } = await getTestUsers(1);
const application = await Application.insert({
id: randomUUIDv7(),
redirectUris: ["https://example.com/callback"],
scopes: ["openid", "profile", "email"],
secret: "test-secret",
name: "Test Application",
});
const token = await Token.insert({
id: randomUUIDv7(),
clientId: application.id,
accessToken: "test-access-token",
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
createdAt: new Date().toISOString(),
scopes: application.data.scopes,
userId: users[0].id,
});
afterAll(async () => {
await deleteUsers();
await application.delete();
await token.delete();
});
describe("/oauth/revoke", () => {
test("should revoke token with valid inputs", async () => {
const response = await fakeRequest("/oauth/revoke", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: application.data.id,
client_secret: application.data.secret,
token: "test-access-token",
}),
});
expect(response.status).toBe(200);
const body = await response.json();
expect(body).toEqual({});
});
test("should return error for missing token", async () => {
const response = await fakeRequest("/oauth/revoke", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: application.data.id,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("unauthorized_client");
expect(body.error_description).toBe(
"You are not authorized to revoke this token",
);
});
test("should return error for invalid client credentials", async () => {
const response = await fakeRequest("/oauth/revoke", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: application.data.id,
client_secret: "invalid-secret",
token: "test-access-token",
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("unauthorized_client");
expect(body.error_description).toBe(
"You are not authorized to revoke this token",
);
});
test("should return error for token not found", async () => {
const response = await fakeRequest("/oauth/revoke", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: application.data.id,
client_secret: application.data.secret,
token: "invalid-token",
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("unauthorized_client");
expect(body.error_description).toBe(
"You are not authorized to revoke this token",
);
});
test("should return error for unauthorized client", async () => {
const response = await fakeRequest("/oauth/revoke", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: "unauthorized-client-id",
client_secret: application.data.secret,
token: "test-access-token",
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("unauthorized_client");
expect(body.error_description).toBe(
"You are not authorized to revoke this token",
);
});
});

View file

@ -0,0 +1,87 @@
import { apiRoute, handleZodError, jsonOrForm } from "@versia-server/kit/api";
import { db, Token } from "@versia-server/kit/db";
import { Tokens } from "@versia-server/kit/tables";
import { and, eq } from "drizzle-orm";
import { describeRoute, resolver, validator } from "hono-openapi";
import { z } from "zod/v4";
export default apiRoute((app) => {
app.post(
"/oauth/revoke",
describeRoute({
summary: "Revoke token",
tags: ["OpenID"],
responses: {
200: {
description: "Token deleted",
content: {
"application/json": {
schema: resolver(z.object({})),
},
},
},
401: {
description: "Authorization error",
content: {
"application/json": {
schema: resolver(
z.object({
error: z.string(),
error_description: z.string(),
}),
),
},
},
},
},
}),
jsonOrForm(),
validator(
"json",
z.object({
client_id: z.string(),
client_secret: z.string(),
token: z.string().optional(),
}),
handleZodError,
),
async (context) => {
const { client_id, client_secret, token } =
context.req.valid("json");
const foundToken = await Token.fromSql(
and(
eq(Tokens.accessToken, token ?? ""),
eq(Tokens.clientId, client_id),
),
);
if (!(foundToken && token)) {
return context.json(
{
error: "unauthorized_client",
error_description:
"You are not authorized to revoke this token",
},
401,
);
}
// Check if the client secret is correct
if (foundToken.data.client?.secret !== client_secret) {
return context.json(
{
error: "unauthorized_client",
error_description:
"You are not authorized to revoke this token",
},
401,
);
}
await db.delete(Tokens).where(eq(Tokens.accessToken, token));
return context.json({}, 200);
},
);
});

View file

@ -0,0 +1,316 @@
import {
Account as AccountSchema,
RolePermission,
zBoolean,
} from "@versia/client/schemas";
import { config } from "@versia-server/config";
import { ApiError } from "@versia-server/kit";
import { apiRoute, handleZodError } from "@versia-server/kit/api";
import { db, Media, User } from "@versia-server/kit/db";
import { searchManager } from "@versia-server/kit/search";
import {
AuthorizationCodes,
OpenIdAccounts,
Users,
} from "@versia-server/kit/tables";
import { randomUUIDv7 } from "bun";
import { and, eq, isNull, type SQL } from "drizzle-orm";
import { setCookie } from "hono/cookie";
import { sign } from "hono/jwt";
import { describeRoute, validator } from "hono-openapi";
import * as client from "openid-client";
import { z } from "zod/v4";
import { randomString } from "@/math.ts";
export default apiRoute((app) => {
app.get(
"/oauth/sso/:issuer/callback",
describeRoute({
summary: "SSO callback",
tags: ["OpenID"],
description:
"After the user has authenticated to an external OpenID provider, they are redirected here to complete the OAuth flow and get a code",
responses: {
302: {
description:
"Redirect to frontend's consent route, or redirect to login page with error",
},
422: ApiError.validationFailed().schema,
},
}),
validator(
"param",
z.object({
issuer: z.string(),
}),
handleZodError,
),
validator(
"query",
z.object({
flow: z.string(),
link: zBoolean.default(false),
user_id: z.uuid().optional(),
}),
handleZodError,
),
async (context) => {
const { issuer: issuerId } = context.req.valid("param");
const { flow: flowId, user_id, link } = context.req.valid("query");
const issuer = config.authentication.openid_providers.find(
(provider) => provider.id === issuerId,
);
if (!issuer) {
throw new ApiError(422, "Unknown or invalid issuer");
}
const flow = await db.query.OpenIdLoginFlows.findFirst({
where: (flow): SQL | undefined => eq(flow.id, flowId),
with: {
application: true,
},
});
const redirectWithMessage = (
parameters: Record<string, string | undefined>,
route = config.frontend.routes.login,
) => {
const searchParams = new URLSearchParams(
Object.entries(parameters).filter(
([_, value]) => value !== undefined,
) as [string, string][],
);
return context.redirect(`${route}?${searchParams.toString()}`);
};
if (!flow) {
return redirectWithMessage({
error: "invalid_request",
error_description: "Invalid flow",
});
}
const oidcConfig = await client.discovery(
issuer.url,
issuer.client_id,
issuer.client_secret,
);
const tokens = await client.authorizationCodeGrant(
oidcConfig,
context.req.raw,
{
pkceCodeVerifier: flow.codeVerifier,
expectedState: flow.state ?? undefined,
idTokenExpected: true,
},
);
const claims = tokens.claims();
if (!claims) {
return redirectWithMessage({
error: "invalid_request",
error_description: "Missing or invalid ID token",
});
}
const userInfo = await client.fetchUserInfo(
oidcConfig,
tokens.access_token,
claims.sub,
);
const { sub, email, preferred_username, picture } = userInfo;
// If linking account
if (link && user_id) {
// Check if userId is equal to application.clientId
if (!flow.application?.id.startsWith(user_id)) {
return redirectWithMessage(
{
oidc_account_linking_error: "Account linking error",
oidc_account_linking_error_message: `User ID does not match application client ID (${user_id} != ${flow.application?.id})`,
},
config.frontend.routes.home,
);
}
// Check if account is already linked
const account = await db.query.OpenIdAccounts.findFirst({
where: (account): SQL | undefined =>
and(
eq(account.serverId, sub),
eq(account.issuerId, issuer.id),
),
});
if (account) {
return redirectWithMessage(
{
oidc_account_linking_error:
"Account already linked",
oidc_account_linking_error_message:
"This account has already been linked to this OpenID Connect provider.",
},
config.frontend.routes.home,
);
}
// Link the account
await db.insert(OpenIdAccounts).values({
id: randomUUIDv7(),
serverId: sub,
issuerId: issuer.id,
userId: user_id,
});
return context.redirect(
`${context.get("config").http.base_url}${
context.get("config").frontend.routes.home
}?${new URLSearchParams({
oidc_account_linked: "true",
})}`,
);
}
let userId = (
await db.query.OpenIdAccounts.findFirst({
where: (account): SQL | undefined =>
and(
eq(account.serverId, sub),
eq(account.issuerId, issuer.id),
),
})
)?.userId;
if (!userId) {
// Register new user
if (config.authentication.openid_registration) {
let username =
preferred_username ??
email?.split("@")[0] ??
randomString(8, "hex");
const usernameValidator =
AccountSchema.shape.username.refine(
async (value) =>
!(await User.fromSql(
and(
eq(Users.username, value),
isNull(Users.instanceId),
),
)),
);
try {
await usernameValidator.parseAsync(username);
} catch {
username = randomString(8, "hex");
}
const doesEmailExist = email
? !!(await User.fromSql(eq(Users.email, email)))
: false;
const avatar = picture
? await Media.fromUrl(new URL(picture))
: null;
// Create new user
const user = await User.register(username, {
email: doesEmailExist ? undefined : email,
avatar: avatar ?? undefined,
});
// Add to search index
await searchManager.addUser(user);
// Link account
await db.insert(OpenIdAccounts).values({
id: randomUUIDv7(),
serverId: sub,
issuerId: issuer.id,
userId: user.id,
});
userId = user.id;
} else {
return redirectWithMessage({
error: "invalid_request",
error_description: "No user found with that account",
});
}
}
const user = await User.fromId(userId);
if (!user) {
return redirectWithMessage({
error: "invalid_request",
error_description: "No user found with that account",
});
}
if (!user.hasPermission(RolePermission.OAuth)) {
return redirectWithMessage({
error: "invalid_request",
error_description: `User does not have the '${RolePermission.OAuth}' permission`,
});
}
if (!flow.application) {
throw new ApiError(500, "Application not found");
}
const code = randomString(32, "hex");
await db.insert(AuthorizationCodes).values({
clientId: flow.application.id,
code,
expiresAt: new Date(Date.now() + 60 * 1000).toISOString(), // 1 minute
redirectUri: flow.clientRedirectUri ?? undefined,
userId: user.id,
scopes: flow.clientScopes ?? [],
});
const jwt = await sign(
{
sub: user.id,
iss: new URL(context.get("config").http.base_url).origin,
aud: flow.application.id,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
},
config.authentication.key,
);
// Redirect back to application
setCookie(context, "jwt", jwt, {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
// 2 weeks
maxAge: 60 * 60 * 24 * 14,
});
return redirectWithMessage(
{
redirect_uri: flow.clientRedirectUri ?? undefined,
code,
client_id: flow.application.id,
application: flow.application.name,
website: flow.application.website ?? "",
scope: flow.clientScopes?.join(" "),
state: flow.clientState ?? undefined,
},
config.frontend.routes.consent,
);
},
);
});

View file

@ -0,0 +1,122 @@
import { config } from "@versia-server/config";
import { ApiError } from "@versia-server/kit";
import { apiRoute, handleZodError } from "@versia-server/kit/api";
import { Application, db } from "@versia-server/kit/db";
import { OpenIdLoginFlows } from "@versia-server/kit/tables";
import { randomUUIDv7 } from "bun";
import { describeRoute, validator } from "hono-openapi";
import * as client from "openid-client";
import { z } from "zod/v4";
import { oauthRedirectUri } from "@/lib";
export default apiRoute((app) => {
app.post(
"/oauth/sso/:issuer",
describeRoute({
summary: "Initiate SSO login flow",
tags: ["OpenID"],
responses: {
302: {
description:
"Redirect to SSO provider's authorization endpoint",
},
422: ApiError.validationFailed().schema,
},
}),
validator(
"param",
z.object({
issuer: z.string(),
}),
handleZodError,
),
validator(
"json",
z.object({
client_id: z.string(),
redirect_uri: z.url(),
scopes: z.string().array().default(["read"]),
state: z.string().optional(),
}),
handleZodError,
),
async (context) => {
// This is the Versia client's client_id, not the external OAuth provider's client_id
const { client_id, redirect_uri, scopes, state } =
context.req.valid("json");
const { issuer: issuerId } = context.req.valid("param");
const issuer = config.authentication.openid_providers.find(
(provider) => provider.id === issuerId,
);
if (!issuer) {
throw new ApiError(422, "Unknown or invalid issuer");
}
const application = await Application.fromClientId(client_id);
if (!application) {
throw new ApiError(422, "Unknown or invalid client_id");
}
if (!application.data.redirectUris.includes(redirect_uri)) {
throw new ApiError(
422,
"redirect_uri is not a subset of application's redirect_uris",
);
}
// TODO: Validate oauth scopes
const oidcConfig = await client.discovery(
issuer.url,
issuer.client_id,
issuer.client_secret,
);
const codeVerifier = client.randomPKCECodeVerifier();
const codeChallenge =
await client.calculatePKCECodeChallenge(codeVerifier);
const parameters: Record<string, string> = {
scope: "openid profile email",
code_challenge: codeChallenge,
code_challenge_method: "S256",
};
if (!oidcConfig.serverMetadata().supportsPKCE()) {
parameters.state = client.randomState();
}
// Store into database
const newFlow = (
await db
.insert(OpenIdLoginFlows)
.values({
id: randomUUIDv7(),
codeVerifier,
state: parameters.state,
clientState: state,
clientRedirectUri: redirect_uri,
clientScopes: scopes,
applicationId: application.id,
issuerId,
})
.returning()
)[0];
parameters.redirect_uri = `${oauthRedirectUri(
context.get("config").http.base_url,
issuerId,
)}?${new URLSearchParams({
flow: newFlow.id,
})}`;
const redirectTo = client.buildAuthorizationUrl(
oidcConfig,
parameters,
);
return context.redirect(redirectTo);
},
);
});

View file

@ -0,0 +1,184 @@
import { afterAll, describe, expect, test } from "bun:test";
import { Application, db } from "@versia-server/kit/db";
import { fakeRequest, getTestUsers } from "@versia-server/tests";
import { randomUUIDv7 } from "bun";
import { eq } from "drizzle-orm";
import { randomString } from "@/math";
import { AuthorizationCodes } from "~/packages/kit/tables/schema";
const { deleteUsers, users } = await getTestUsers(1);
const application = await Application.insert({
id: randomUUIDv7(),
redirectUris: ["https://example.com/callback"],
scopes: ["openid", "profile", "email"],
secret: "test-secret",
name: "Test Application",
});
const authorizationCode = (
await db
.insert(AuthorizationCodes)
.values({
clientId: application.id,
code: randomString(10),
redirectUri: application.data.redirectUris[0],
userId: users[0].id,
expiresAt: new Date(Date.now() + 300 * 1000).toISOString(),
})
.returning()
)[0];
afterAll(async () => {
await deleteUsers();
await application.delete();
await db
.delete(AuthorizationCodes)
.where(eq(AuthorizationCodes.code, authorizationCode.code));
});
describe("/oauth/token", () => {
test("should return token with valid inputs", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
code: authorizationCode.code,
redirect_uri: application.data.redirectUris[0],
client_id: application.data.id,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(200);
const body = await response.json();
expect(body.access_token).toBeString();
expect(body.token_type).toBe("Bearer");
expect(body.expires_in).toBeNull();
});
test("should return error for missing code", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
redirect_uri: application.data.redirectUris[0],
client_id: application.data.id,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(422);
const body = await response.json();
expect(body.error).toInclude(`Expected string at "code"`);
});
test("should return error for missing redirect_uri", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
code: authorizationCode.code,
client_id: application.data.id,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(422);
const body = await response.json();
expect(body.error).toInclude(`Expected string at "redirect_uri"`);
});
test("should return error for missing client_id", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
code: authorizationCode.code,
redirect_uri: application.data.redirectUris[0],
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(422);
const body = await response.json();
expect(body.error).toInclude(`Expected string at "client_id"`);
});
test("should return error for invalid client credentials", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
code: authorizationCode.code,
redirect_uri: application.data.redirectUris[0],
client_id: application.data.id,
client_secret: "invalid-secret",
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("invalid_client");
expect(body.error_description).toBe("Invalid client credentials");
});
test("should return error for code not found", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
code: "invalid-code",
redirect_uri: application.data.redirectUris[0],
client_id: application.data.id,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(404);
const body = await response.json();
expect(body.error).toBe("invalid_grant");
expect(body.error_description).toBe(
"Authorization code not found or expired",
);
});
test("should return error for unsupported grant type", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "refresh_token",
code: authorizationCode.code,
redirect_uri: application.data.redirectUris[0],
client_id: application.data.id,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("unsupported_grant_type");
expect(body.error_description).toBe("Unsupported grant type");
});
});

View file

@ -0,0 +1,145 @@
import { Token as TokenSchema } from "@versia/client/schemas";
import { apiRoute, handleZodError, jsonOrForm } from "@versia-server/kit/api";
import { Application, db, Token } from "@versia-server/kit/db";
import { AuthorizationCodes } from "@versia-server/kit/tables";
import { randomUUIDv7 } from "bun";
import { and, eq } from "drizzle-orm";
import { describeRoute, resolver, validator } from "hono-openapi";
import { z } from "zod/v4";
import { randomString } from "@/math";
export default apiRoute((app) => {
app.post(
"/oauth/token",
describeRoute({
summary: "Obtain a token",
description:
"Obtain an access token, to be used during API calls that are not public.",
externalDocs: {
url: "https://docs.joinmastodon.org/methods/oauth/#token",
},
tags: ["OpenID"],
responses: {
200: {
description: "Token",
content: {
"application/json": {
schema: resolver(TokenSchema),
},
},
},
401: {
description: "Invalid grant",
content: {
"application/json": {
schema: resolver(
z.object({
error: z.string(),
error_description: z.string(),
}),
),
},
},
},
},
}),
jsonOrForm(),
validator(
"json",
z.object({
code: z.string(),
grant_type: z.enum([
"authorization_code",
"refresh_token",
"client_credentials",
]),
code_verifier: z.string().optional(),
client_id: z.string(),
client_secret: z.string(),
redirect_uri: z.url(),
refresh_token: z.string().optional(),
scope: z.string().default("read"),
}),
handleZodError,
),
async (context) => {
const { code, client_id, client_secret, redirect_uri, grant_type } =
context.req.valid("json");
if (grant_type !== "authorization_code") {
return context.json(
{
error: "unsupported_grant_type",
error_description: "Unsupported grant type",
},
401,
);
}
// Verify the client_secret
const client = await Application.fromClientId(client_id);
if (!client || client.data.secret !== client_secret) {
return context.json(
{
error: "invalid_client",
error_description: "Invalid client credentials",
},
401,
);
}
const authorizationCode =
await db.query.AuthorizationCodes.findFirst({
where: (codeTable) =>
and(
eq(codeTable.code, code),
eq(codeTable.redirectUri, redirect_uri),
eq(codeTable.clientId, client.id),
),
});
if (
!authorizationCode ||
new Date(authorizationCode.expiresAt).getTime() < Date.now()
) {
return context.json(
{
error: "invalid_grant",
error_description:
"Authorization code not found or expired",
},
404,
);
}
const token = await Token.insert({
accessToken: randomString(64, "base64url"),
clientId: client.id,
id: randomUUIDv7(),
userId: authorizationCode.userId,
expiresAt: null,
});
// Invalidate the code
await db
.delete(AuthorizationCodes)
.where(eq(AuthorizationCodes.code, authorizationCode.code));
return context.json(
{
...token.toApi(),
expires_in: token.data.expiresAt
? Math.floor(
(new Date(token.data.expiresAt).getTime() -
Date.now()) /
1000,
)
: null,
refresh_token: null,
},
200,
);
},
);
});