Merge remote-tracking branch 'origin/main' into tommoor/external-sidebar-links-add

# Conflicts:
#	app/components/Sidebar/components/CollectionRow.tsx
#	app/components/Sidebar/components/DocumentRow.tsx
This commit is contained in:
Tom Moor committed 2026-11-15 16:39:26 -05:00
commit bd73c0983c
224 files changed
+11580 -3255

No files matched your search

+8 -54
View File
@@ -23,10 +23,7 @@ import {
import config from "../../plugin.json";
import env from "../env";
import { createContext } from "@server/context";
import fetch from "@server/utils/fetch";
import UploadUserAvatarTask from "@server/queues/tasks/UploadUserAvatarTask";
import AttachmentHelper from "@server/models/helpers/AttachmentHelper";
import { AttachmentPreset } from "@shared/types";
import { UserFlag } from "@server/models/User";
import { getEmailVerified } from "./getEmailVerified";
import { MicrosoftGraphError } from "../errors";
@@ -34,45 +31,6 @@ import { MicrosoftGraphError } from "../errors";
const router = new Router();
const scopes: string[] = [];
/**
* Loads the user's profile photo from the Microsoft Graph API and encodes it as
* a data URL. Entra ID does not emit a `picture` claim in the ID token, so the
* photo is only available via Graph. Requires no additional permissions beyond
* the delegated `User.Read` already used to load the profile.
*
* @param accessToken The delegated access token for the Microsoft Graph API.
* @returns A base64 encoded data URL for the photo, or undefined if not set.
*/
async function requestPhoto(accessToken: string): Promise<string | undefined> {
try {
const response = await fetch(
"https://graph.microsoft.com/v1.0/me/photo/$value",
{
method: "GET",
allowPrivateIPAddress: true,
// Cap how long we'll wait and how many bytes we'll buffer so a slow or
// oversized response can never stall the login callback.
timeout: 10000,
size: AttachmentHelper.presetToMaxUploadSize(AttachmentPreset.Avatar),
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
// A missing photo returns 404, which we can safely ignore.
if (!response.ok) {
return undefined;
}
const contentType = response.headers.get("content-type") ?? "image/jpeg";
const buffer = await response.buffer();
return `data:${contentType};base64,${buffer.toString("base64")}`;
} catch (_err) {
return undefined;
}
}
if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) {
const strategy = new AzureStrategy(
{
@@ -194,22 +152,18 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) {
scopes,
},
});
// Entra ID does not include the photo in the token, so it must be
// fetched separately from Graph. To avoid the extra round-trip on every
// sign-in we only do so when the user has no avatar yet and hasn't set
// one manually — this also backfills accounts created before avatar
// syncing was supported, and stops once an avatar is stored.
// Entra ID does not include the photo in the token, so it is loaded
// from Graph in the background when the user has no avatar yet.
if (
result.authentication &&
!result.user.avatarUrl &&
!result.user.getFlag(UserFlag.AvatarUpdated)
) {
const avatarUrl = await requestPhoto(accessToken);
if (avatarUrl) {
await new UploadUserAvatarTask().schedule({
userId: result.user.id,
avatarUrl,
});
}
await new UploadUserAvatarTask().schedule({
userId: result.user.id,
avatarUrl: "https://graph.microsoft.com/v1.0/me/photo/$value",
userAuthenticationId: result.authentication.id,
});
}
return done(null, result.user, { ...result, client });
+3 -3
View File
@@ -131,7 +131,7 @@ export class GitHubIssueProvider extends BaseIssueProvider {
required: true,
},
transaction,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: Integration },
});
const authentication = integration.authentication;
@@ -172,7 +172,7 @@ export class GitHubIssueProvider extends BaseIssueProvider {
"settings.github.installation.id": installationId,
},
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
if (!integration) {
@@ -241,7 +241,7 @@ export class GitHubIssueProvider extends BaseIssueProvider {
"settings.github.installation.id": installationId,
},
transaction,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
});
if (!integration) {
+5 -5
View File
@@ -142,7 +142,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
const integration = (await Integration.findOne({
where,
replacements: { jsonCondition },
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
})) as Integration<IntegrationType.Embed>;
@@ -213,7 +213,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
const integrations = (await Integration.findAll({
where: whereCondition,
replacements,
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
})) as Integration<IntegrationType.Embed>[];
@@ -257,7 +257,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
replacements: {
projectJson: JSON.stringify([{ id: String(payload.project_id) }]),
},
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
});
@@ -303,7 +303,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
...(teamId ? { teamId } : {}),
"settings.gitlab.installation.account.id": payload.user_id,
},
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
})) as Integration<IntegrationType.Embed>;
@@ -354,7 +354,7 @@ export class GitLabIssueProvider extends BaseIssueProvider {
replacements: {
projectJson: JSON.stringify([{ id: String(payload.project_id) }]),
},
lock: transaction.LOCK.UPDATE,
lock: transaction.LOCK.NO_KEY_UPDATE,
transaction,
});
+1 -1
View File
@@ -269,7 +269,7 @@ router.get(
account: {
id: userInfo.id,
name: userInfo.username,
avatarUrl: userInfo.avatar_url,
avatarUrl: userInfo.avatar_url ?? "",
},
},
},
+238
View File
@@ -0,0 +1,238 @@
import { randomUUID } from "node:crypto";
import { addHours, subHours } from "date-fns";
import { http, HttpResponse } from "msw";
import { IntegrationService, IntegrationType } from "@shared/types";
import { Integration, IntegrationAuthentication } from "@server/models";
import { buildUser } from "@server/test/factories";
import { server } from "@server/test/msw";
import { GitLab } from "./gitlab";
const author = { id: 7, username: "octo", avatar_url: "https://a.test/a.png" };
const buildBaseUrl = () => `https://${randomUUID()}.example.com`;
async function buildGitLabIntegration({
teamId,
userId,
url,
expiresAt = addHours(new Date(), 1),
}: {
teamId: string;
userId: string;
url: string;
expiresAt?: Date;
}) {
const authentication = await IntegrationAuthentication.create({
service: IntegrationService.GitLab,
userId,
teamId,
clientId: "client-id",
clientSecret: "client-secret",
token: "token",
refreshToken: "refresh",
expiresAt,
});
const integration = await Integration.create({
service: IntegrationService.GitLab,
type: IntegrationType.Embed,
userId,
teamId,
authenticationId: authentication.id,
settings: { gitlab: { url } },
});
return { integration, authentication };
}
describe("GitLab", () => {
describe("getIssue", () => {
it("should request the issue with an encoded project path", async () => {
const customUrl = buildBaseUrl();
let requestUrl: URL | undefined;
let authorization: string | null = null;
server.use(
http.get(
`${customUrl}/api/v4/projects/:project/issues`,
({ request }) => {
requestUrl = new URL(request.url);
authorization = request.headers.get("authorization");
return HttpResponse.json([
{
iid: 12,
title: "Fix it",
description: "Details",
web_url: `${customUrl}/group/repo/-/issues/12`,
state: "opened",
author,
labels: [{ name: "bug", color: "#ff0000" }],
created_at: "2026-01-01T00:00:00Z",
},
]);
}
)
);
const issue = await GitLab.getIssue({
accessToken: "token",
customUrl,
path: "group/repo",
id: 12,
});
expect(issue.title).toEqual("Fix it");
expect(requestUrl?.pathname).toEqual(
"/api/v4/projects/group%2Frepo/issues"
);
expect(requestUrl?.searchParams.get("iids[]")).toEqual("12");
expect(authorization).toEqual("Bearer token");
});
});
describe("getProjects", () => {
it("should follow pagination", async () => {
const user = await buildUser();
const pages: (string | null)[] = [];
server.use(
http.get("https://gitlab.com/api/v4/projects", ({ request }) => {
const page = new URL(request.url).searchParams.get("page");
pages.push(page);
return HttpResponse.json(
[
{
id: Number(page),
name: `project-${page}`,
namespace: { id: 1, full_path: "group" },
},
],
{ headers: { "x-next-page": page === "1" ? "2" : "" } }
);
})
);
const projects = await GitLab.getProjects({
accessToken: "token",
teamId: user.teamId,
});
expect(pages).toEqual(["1", "2"]);
expect(projects.map((project) => project.name)).toEqual([
"project-1",
"project-2",
]);
});
});
describe("unfurl", () => {
it("should refresh an expired token and use the new token", async () => {
const user = await buildUser();
const customUrl = buildBaseUrl();
const { authentication } = await buildGitLabIntegration({
teamId: user.teamId,
userId: user.id,
url: customUrl,
expiresAt: subHours(new Date(), 1),
});
let tokenRequest: Record<string, string> | undefined;
let authorization: string | null = null;
server.use(
http.post(`${customUrl}/oauth/token`, async ({ request }) => {
tokenRequest = (await request.json()) as Record<string, string>;
return HttpResponse.json({
access_token: "new-token",
token_type: "Bearer",
expires_in: 7200,
refresh_token: "new-refresh",
scope: "read_api read_user",
created_at: 0,
});
}),
http.get(
`${customUrl}/api/v4/projects/:project/merge_requests/5`,
({ request }) => {
authorization = request.headers.get("authorization");
return HttpResponse.json({
iid: 5,
title: "Change",
web_url: `${customUrl}/group/repo/-/merge_requests/5`,
state: "opened",
author,
created_at: "2026-01-01T00:00:00Z",
});
}
)
);
const result = await GitLab.unfurl(
`${customUrl}/group/repo/-/merge_requests/5`,
user
);
expect(result).toMatchObject({ title: "Change" });
expect(tokenRequest).toMatchObject({
grant_type: "refresh_token",
refresh_token: "refresh",
client_id: "client-id",
client_secret: "client-secret",
});
expect(authorization).toEqual("Bearer new-token");
await authentication.reload();
expect(authentication.token).toEqual("new-token");
expect(authentication.refreshToken).toEqual("new-refresh");
});
it("should unfurl a project without progress when statistics fail", async () => {
const user = await buildUser();
const customUrl = buildBaseUrl();
await buildGitLabIntegration({
teamId: user.teamId,
userId: user.id,
url: customUrl,
});
server.use(
http.get(`${customUrl}/api/v4/projects/:project`, () =>
HttpResponse.json({
id: 1,
name: "repo",
web_url: `${customUrl}/group/repo`,
visibility: "public",
created_at: "2026-01-01T00:00:00Z",
})
),
http.get(
`${customUrl}/api/v4/projects/:project/issues_statistics`,
() => HttpResponse.json({}, { status: 500 })
)
);
const result = await GitLab.unfurl(`${customUrl}/group/repo`, user);
expect(result).toMatchObject({ name: "repo", progress: undefined });
});
it("should not return the response body of a failed request", async () => {
const user = await buildUser();
const customUrl = buildBaseUrl();
await buildGitLabIntegration({
teamId: user.teamId,
userId: user.id,
url: customUrl,
});
server.use(
http.get(`${customUrl}/api/v4/projects/:project/merge_requests/5`, () =>
HttpResponse.json({ message: "secret" }, { status: 500 })
)
);
const result = await GitLab.unfurl(
`${customUrl}/group/repo/-/merge_requests/5`,
user
);
expect(result).toEqual({
error:
"Error while requesting /projects/group%2Frepo/merge_requests/5 from GitLab; status: 500",
});
});
});
});
+291 -177
View File
@@ -1,12 +1,3 @@
import { Gitlab } from "@gitbeaker/rest";
import type {
EpicSchema,
IssueSchemaWithExpandedLabels,
MergeRequestSchema,
ProjectSchema,
SimpleLabelSchema,
StatisticsSchema,
} from "@gitbeaker/rest";
import z from "zod";
import {
type IntegrationType,
@@ -14,6 +5,7 @@ import {
UnfurlResourceType,
} from "@shared/types";
import { toError, errToString } from "@shared/utils/error";
import { Second } from "@shared/utils/time";
import Logger from "@server/logging/Logger";
import type { User } from "@server/models";
import { Integration, IntegrationAuthentication } from "@server/models";
@@ -22,8 +14,7 @@ import type {
UnfurlProject,
UnfurlSignature,
} from "@server/types";
import fetch from "@server/utils/fetch";
import { validateUrlNotPrivate } from "@server/utils/url";
import fetch, { type Headers } from "@server/utils/fetch";
import { GitLabUtils } from "../shared/GitLabUtils";
import env from "./env";
@@ -36,10 +27,97 @@ const AccessTokenResponseSchema = z.object({
created_at: z.number(),
});
export class GitLab {
private static clientSecret = env.GITLAB_CLIENT_SECRET;
private static clientId = env.GITLAB_CLIENT_ID;
const UserSchema = z.object({
id: z.number(),
username: z.string(),
avatar_url: z.string().nullish(),
});
const LabelSchema = z.object({
name: z.string(),
color: z.string(),
});
const IssueSchema = z.object({
iid: z.number(),
title: z.string(),
description: z.string().nullish(),
web_url: z.string(),
state: z.string(),
author: UserSchema.nullish(),
labels: z.array(LabelSchema),
created_at: z.string(),
});
// Epics are returned without label color details.
const EpicSchema = IssueSchema.extend({
labels: z.array(z.string()),
});
const MergeRequestSchema = z.object({
iid: z.number(),
title: z.string(),
description: z.string().nullish(),
web_url: z.string(),
state: z.string(),
author: UserSchema,
draft: z.boolean().nullish(),
merged_at: z.string().nullish(),
created_at: z.string(),
});
const NamespaceSchema = z.object({
id: z.number(),
full_path: z.string(),
});
const SimpleProjectSchema = z.object({
id: z.number(),
name: z.string(),
namespace: NamespaceSchema,
});
const ProjectSchema = z.object({
id: z.number(),
name: z.string(),
description: z.string().nullish(),
web_url: z.string(),
avatar_url: z.string().nullish(),
visibility: z.string().nullish(),
owner: z
.object({ name: z.string(), avatar_url: z.string().nullish() })
.nullish(),
topics: z.array(z.string()).nullish(),
created_at: z.string(),
});
const IssueStatisticsSchema = z.object({
statistics: z.object({
counts: z.object({
opened: z.number(),
closed: z.number(),
}),
}),
});
type Issue = z.infer<typeof IssueSchema>;
type Epic = z.infer<typeof EpicSchema>;
type MergeRequest = z.infer<typeof MergeRequestSchema>;
type SimpleProject = z.infer<typeof SimpleProjectSchema>;
type Project = z.infer<typeof ProjectSchema>;
type IssueStatistics = z.infer<typeof IssueStatisticsSchema>;
interface RequestParams {
accessToken: string;
customUrl?: string;
}
interface ResourceParams extends RequestParams {
path: string;
id: number;
}
export class GitLab {
/**
* Fetches the custom GitLab URL for a team from the first matching
* integration, falling back to the default.
@@ -58,93 +136,90 @@ export class GitLab {
return url || GitLabUtils.defaultGitlabUrl;
}
/**
* Creates a Gitbeaker client instance.
*
* @param accessToken - The access token for authentication.
* @param customUrl - Optional custom GitLab URL from integration settings.
* @returns A configured Gitbeaker client.
*/
public static async createClient(accessToken: string, customUrl?: string) {
const host = customUrl || GitLabUtils.defaultGitlabUrl;
// Validate the URL to prevent SSRF as GitLab instance does not use our
// fetch wrapper which has built-in SSRF protection.
await validateUrlNotPrivate(host);
return new Gitlab({
host,
oauthToken: accessToken,
});
}
/**
* Fetches an issue from a GitLab project.
*
* @param accessToken - The access token for authentication.
* @param projectPath - The project path (owner/repo).
* @param issueIid - The issue IID (internal ID within the project).
* @param customUrl - Optional custom GitLab URL from integration settings.
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The project path (owner/repo).
* @param params.id - The issue IID (internal ID within the project).
* @returns The issue data.
* @throws If the issue does not exist.
*/
public static async getIssue(
accessToken: string,
projectPath: string,
issueIid: number,
customUrl?: string
) {
const client = await this.createClient(accessToken, customUrl);
const issues = await client.Issues.all({
projectId: projectPath,
iids: [issueIid],
withLabelsDetails: true,
public static async getIssue({ path, id, ...params }: ResourceParams) {
const { data } = await this.request({
...params,
path: `/projects/${encodeURIComponent(path)}/issues?iids[]=${id}&with_labels_details=true`,
schema: z.array(IssueSchema),
});
if (!issues || issues.length === 0) {
throw new Error(`Issue ${issueIid} not found in project ${projectPath}`);
if (data.length === 0) {
throw new Error(`Issue ${id} not found in project ${path}`);
}
return issues[0];
return data[0];
}
/**
* Fetches an epic from a GitLab group.
*
* @param accessToken - The access token for authentication.
* @param groupPath - The full path of the group.
* @param epicIid - The epic IID (internal ID within the group).
* @param customUrl - Optional custom GitLab URL from integration settings.
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The full path of the group.
* @param params.id - The epic IID (internal ID within the group).
* @returns The epic data.
*/
public static async getEpic(
accessToken: string,
groupPath: string,
epicIid: number,
customUrl?: string
) {
const client = await this.createClient(accessToken, customUrl);
return client.Epics.show(groupPath, epicIid);
public static async getEpic({ path, id, ...params }: ResourceParams) {
const { data } = await this.request({
...params,
path: `/groups/${encodeURIComponent(path)}/epics/${id}`,
schema: EpicSchema,
});
return data;
}
/**
* Fetches a merge request from a GitLab project.
*
* @param accessToken - The access token for authentication.
* @param projectPath - The project path (owner/repo).
* @param mrIid - The merge request IID (internal ID within the project).
* @param customUrl - Optional custom GitLab URL from integration settings.
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The project path (owner/repo).
* @param params.id - The merge request IID (internal ID within the project).
* @returns The merge request data.
*/
public static async getMergeRequest(
accessToken: string,
projectPath: string,
mrIid: number,
customUrl?: string
) {
const client = await this.createClient(accessToken, customUrl);
const mr = await client.MergeRequests.show(projectPath, mrIid);
return mr;
public static async getMergeRequest({ path, id, ...params }: ResourceParams) {
const { data } = await this.request({
...params,
path: `/projects/${encodeURIComponent(path)}/merge_requests/${id}`,
schema: MergeRequestSchema,
});
return data;
}
/**
* Fetches a GitLab project and its issue statistics.
*
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The project path (owner/repo).
* @returns The project data and its issue statistics, if available.
*/
public static async getProject({
path,
...params
}: RequestParams & { path: string }) {
const projectPath = `/projects/${encodeURIComponent(path)}`;
const [project, issueStats] = await Promise.all([
this.request({ ...params, path: projectPath, schema: ProjectSchema }),
// Statistics can be slow for projects with many issues, so they are optional.
this.request({
...params,
path: `${projectPath}/issues_statistics`,
schema: IssueStatisticsSchema,
}).catch(() => undefined),
]);
return { project: project.data, issueStats: issueStats?.data };
}
/**
@@ -154,26 +229,21 @@ export class GitLab {
* @param params.customUrl - Optional custom GitLab URL. Falls back to default.
* @returns User information including the resolved URL.
*/
public static async getCurrentUser({
accessToken,
customUrl,
}: {
accessToken: string;
customUrl?: string;
}) {
const url = customUrl || GitLabUtils.defaultGitlabUrl;
const client = await this.createClient(accessToken, url);
const userData = await client.Users.showCurrentUser({
showExpanded: false,
public static async getCurrentUser(params: RequestParams) {
const url = params.customUrl || GitLabUtils.defaultGitlabUrl;
const { data } = await this.request({
...params,
path: "/user",
schema: UserSchema,
});
return { ...userData, url };
return { ...data, url };
}
/**
* Fetches projects accessible to the user.
* Fetches projects that the user can maintain.
*
* @param accessToken - Access token for authentication.
* @param params.accessToken - Access token for authentication.
* @param params.teamId - The team ID used to find the GitLab URL.
* @returns Array of projects.
*/
public static async getProjects({
@@ -184,13 +254,22 @@ export class GitLab {
teamId: string;
}) {
const customUrl = await this.getGitLabUrl(teamId);
const client = await this.createClient(accessToken, customUrl);
const projects: SimpleProject[] = [];
let page: string | null = "1";
for (let i = 0; i < this.maxPages && page; i++) {
const res: { data: SimpleProject[]; headers: Headers } =
await this.request({
accessToken,
customUrl,
// At least Maintainer access to reduce the sheer volume of projects.
path: `/projects?simple=true&min_access_level=40&per_page=100&page=${page}`,
schema: z.array(SimpleProjectSchema),
});
projects.push(...res.data);
page = res.headers.get("x-next-page");
}
const projects = await client.Projects.all({
simple: true,
perPage: 100,
minAccessLevel: 40, // At least Maintainer access to reduce the sheer volume of projects
});
return projects;
}
@@ -250,7 +329,7 @@ export class GitLab {
try {
const customUrl = matchedIntegration.settings?.gitlab?.url;
const { authentication } = matchedIntegration;
const token = await authentication.refreshTokenIfNeeded(
const accessToken = await authentication.refreshTokenIfNeeded(
async (refreshToken: string) =>
GitLab.refreshToken({
refreshToken,
@@ -265,41 +344,41 @@ export class GitLab {
resource.type === UnfurlResourceType.Issue &&
resource.scope === "group"
) {
const epic = await this.getEpic(
token,
resource.owner,
resource.id,
customUrl
);
const epic = await this.getEpic({
accessToken,
customUrl,
path: resource.owner,
id: resource.id,
});
return this.transformIssue(epic);
}
const projectPath = `${resource.owner}/${resource.repo}`;
const path = `${resource.owner}/${resource.repo}`;
if (resource.type === UnfurlResourceType.Issue) {
const issue = await this.getIssue(
token,
projectPath,
resource.id,
customUrl
);
const issue = await this.getIssue({
accessToken,
customUrl,
path,
id: resource.id,
});
return this.transformIssue(issue);
} else if (resource.type === UnfurlResourceType.PR) {
const mr = await this.getMergeRequest(
token,
projectPath,
resource.id,
customUrl
);
const mr = await this.getMergeRequest({
accessToken,
customUrl,
path,
id: resource.id,
});
return this.transformMR(mr);
} else if (resource.type === UnfurlResourceType.Project) {
const client = await this.createClient(token, customUrl);
const [project, issueStats] = await Promise.all([
client.Projects.show(projectPath),
client.IssuesStatistics.all({ projectId: projectPath }),
]);
const { project, issueStats } = await this.getProject({
accessToken,
customUrl,
path,
});
return this.transformProject(project, issueStats);
}
@@ -321,7 +400,7 @@ export class GitLab {
* @param params.clientSecret - Optional custom client secret (falls back to env var).
* @returns The parsed access token response.
*/
public static oauthAccess = async ({
public static async oauthAccess({
code,
customUrl,
clientId,
@@ -331,30 +410,61 @@ export class GitLab {
customUrl?: string;
clientId?: string;
clientSecret?: string;
}) => {
const url = customUrl || GitLabUtils.defaultGitlabUrl;
const res = await fetch(GitLabUtils.getOauthUrl(url) + "/token", {
method: "POST",
}) {
return this.requestToken(customUrl, {
code: code ?? "",
client_id: clientId || this.clientId || "",
client_secret: clientSecret || this.clientSecret || "",
grant_type: "authorization_code",
redirect_uri: GitLabUtils.callbackUrl(),
});
}
/** The time to wait for a response from a GitLab instance. */
private static timeout = 10 * Second.ms;
/** The maximum number of pages to fetch from a paginated endpoint. */
private static maxPages = 10;
private static clientSecret = env.GITLAB_CLIENT_SECRET;
private static clientId = env.GITLAB_CLIENT_ID;
/**
* Makes an authenticated GET request to the GitLab API.
*
* @param params.accessToken - The access token for authentication.
* @param params.customUrl - Optional custom GitLab URL from integration settings.
* @param params.path - The API path, starting with a slash.
* @param params.schema - The schema to parse the response body with.
* @returns The parsed body and the response headers.
* @throws If the response status is not successful.
*/
private static async request<T extends z.ZodType>({
accessToken,
customUrl,
path,
schema,
}: RequestParams & { path: string; schema: T }) {
const baseUrl = customUrl || GitLabUtils.defaultGitlabUrl;
const res = await fetch(`${baseUrl}/api/v4${path}`, {
timeout: this.timeout,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
code,
client_id: clientId || this.clientId,
client_secret: clientSecret || this.clientSecret,
grant_type: "authorization_code",
redirect_uri: GitLabUtils.callbackUrl(),
}),
});
if (res.status !== 200) {
if (!res.ok) {
throw new Error(
`Error while validating oauth code from GitLab; status: ${res.status}`
`Error while requesting ${path} from GitLab; status: ${res.status}`
);
}
return AccessTokenResponseSchema.parse(await res.json());
};
// Read the body at once, a body left unread while awaiting other requests
// can be closed early.
return { data: schema.parse(await res.json()), headers: res.headers };
}
private static async refreshToken({
refreshToken,
@@ -367,39 +477,40 @@ export class GitLab {
clientId?: string;
clientSecret?: string;
}) {
const queryParams = new URLSearchParams({
client_id: clientId || this.clientId!,
client_secret: clientSecret || this.clientSecret!,
grant_type: "refresh_token",
return this.requestToken(customUrl, {
refresh_token: refreshToken,
client_id: clientId || this.clientId || "",
client_secret: clientSecret || this.clientSecret || "",
grant_type: "refresh_token",
redirect_uri: GitLabUtils.callbackUrl(),
});
}
private static async requestToken(
customUrl: string | undefined,
body: Record<string, string>
) {
const res = await fetch(`${GitLabUtils.getOauthUrl(customUrl)}/token`, {
method: "POST",
timeout: this.timeout,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(body),
});
const res = await fetch(
`${GitLabUtils.getOauthUrl(customUrl)}/token?${queryParams.toString()}`,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
}
);
const resJson = await res.json();
if (res.status !== 200) {
Logger.error("failed to refresh access token from GitLab", resJson);
throw new Error(
`Error while refreshing access token from GitLab; status: ${res.status}`
`Error while requesting access token from GitLab; status: ${res.status}`
);
}
return AccessTokenResponseSchema.parse(resJson);
return AccessTokenResponseSchema.parse(await res.json());
}
private static transformIssue(
issue: IssueSchemaWithExpandedLabels | EpicSchema
) {
const labels: (string | SimpleLabelSchema)[] = issue.labels;
private static transformIssue(issue: Issue | Epic) {
const labels: (string | z.infer<typeof LabelSchema>)[] = issue.labels;
return {
type: UnfurlResourceType.Issue,
@@ -411,7 +522,6 @@ export class GitLab {
name: issue.author?.username ?? "",
avatarUrl: issue.author?.avatar_url ?? "",
},
// Epics are returned without label color details.
labels: labels.map((label) =>
typeof label === "string"
? { name: label, color: GitLabUtils.defaultLabelColor }
@@ -425,8 +535,10 @@ export class GitLab {
} satisfies UnfurlIssueOrPR;
}
private static transformMR(mr: MergeRequestSchema) {
private static transformMR(mr: MergeRequest) {
const mrState = mr.merged_at ? "merged" : mr.state;
const draft = !!mr.draft;
return {
type: UnfurlResourceType.PR,
url: mr.web_url,
@@ -435,28 +547,30 @@ export class GitLab {
description: GitLabUtils.sanitizeGitLabMarkdown(mr.description) ?? "",
author: {
name: mr.author.username,
avatarUrl: mr.author.avatar_url,
avatarUrl: mr.author.avatar_url ?? "",
},
state: {
name: mrState,
color: GitLabUtils.getColorForStatus(mrState, !!mr.draft),
draft: mr.draft,
color: GitLabUtils.getColorForStatus(mrState, draft),
draft,
},
createdAt: mr.created_at,
} satisfies UnfurlIssueOrPR;
}
private static transformProject(
project: ProjectSchema,
issueStats: StatisticsSchema
project: Project,
issueStats?: IssueStatistics
) {
const visibility = project.visibility ?? "private";
const owner = project.owner as
| { name: string; avatar_url?: string }
| undefined;
const { opened, closed } = issueStats.statistics.counts;
const total = opened + closed;
const progress = total > 0 ? closed / total : 0;
const { owner } = project;
const counts = issueStats?.statistics.counts;
let progress: number | undefined;
if (counts) {
const total = counts.opened + counts.closed;
progress = total > 0 ? counts.closed / total : 0;
}
return {
type: UnfurlResourceType.Project,
@@ -477,7 +591,7 @@ export class GitLab {
name: visibility.charAt(0).toUpperCase() + visibility.slice(1),
color: GitLabUtils.getColorForVisibility(visibility),
},
labels: (project.topics ?? []).map((topic: string) => ({
labels: (project.topics ?? []).map((topic) => ({
name: topic,
color: GitLabUtils.defaultLabelColor,
})),
+1 -1
View File
@@ -13,7 +13,7 @@ PluginManager.add({
type: Hook.ImportSchema,
value: IntegrationImportBodySchema.extend({
service: z.literal(IntegrationService.Notion),
input: z.array(NotionImportInputItemSchema),
input: z.array(NotionImportInputItemSchema).min(1),
}),
});
@@ -259,6 +259,38 @@ describe("#passkeys.verifyRegistration", () => {
expect(body.message).toEqual("Invalid authentication type");
});
it("should consume the challenge on a failed attempt", async () => {
const team = await buildTeam({ passkeysEnabled: true });
const user = await buildUser({ teamId: team.id });
const options = await server.post(
"/auth/passkeys.generateRegistrationOptions",
user
);
const { data } = await options.json();
const failed = await server.post(
"/auth/passkeys.verifyRegistration",
user,
{
body: buildNoneAttestationResponse(
isoBase64URL.fromBuffer(randomBytes(32)),
data.rp.id
),
}
);
expect(failed.status).toEqual(400);
const res = await server.post("/auth/passkeys.verifyRegistration", user, {
body: buildNoneAttestationResponse(data.challenge, data.rp.id),
});
const body = await res.json();
expect(res.status).toEqual(400);
expect(body.message).toEqual(
"No registration challenge found or challenge expired"
);
});
it("should record the registration in the audit log", async () => {
const planSpy = vi
.spyOn(Team.prototype, "plan", "get")
@@ -290,3 +322,40 @@ describe("#passkeys.verifyRegistration", () => {
planSpy.mockRestore();
});
});
describe("#passkeys.verifyAuthentication", () => {
it("should consume the challenge on a failed attempt", async () => {
const options = await server.post(
"/auth/passkeys.generateAuthenticationOptions",
{ body: {} }
);
const { data } = await options.json();
const body = {
challengeId: data.challengeId,
id: "unknown",
rawId: "unknown",
response: {
authenticatorData: "",
clientDataJSON: "",
signature: "",
},
type: "public-key",
};
const failed = await server.post("/auth/passkeys.verifyAuthentication", {
body,
});
const failedBody = await failed.json();
expect(failed.status).toEqual(400);
expect(failedBody.message).toContain("Passkey not found");
const res = await server.post("/auth/passkeys.verifyAuthentication", {
body,
});
const resBody = await res.json();
expect(res.status).toEqual(400);
expect(resBody.message).toEqual(
"No authentication challenge found or challenge expired"
);
});
});
+4 -9
View File
@@ -157,8 +157,8 @@ router.post(
const body = ctx.input.body;
authorize(user, "createUserPasskey", user.team);
// Retrieve challenge from Redis
const expectedChallenge = await Redis.defaultClient.get(
// Consume the challenge atomically so it can only be used once
const expectedChallenge = await Redis.defaultClient.getdel(
getRegistrationChallengeKey(user.id)
);
@@ -238,8 +238,6 @@ router.post(
});
}
// Delete challenge from Redis
await Redis.defaultClient.del(getRegistrationChallengeKey(user.id));
ctx.body = { data: { verified: true } };
} else {
throw ValidationError("Verification failed");
@@ -301,8 +299,8 @@ router.post(
const body = ctx.input.body;
const { challengeId, client = Client.Web } = body;
// Retrieve challenge from Redis
const expectedChallenge = await Redis.defaultClient.get(
// Consume the challenge atomically so it can only be used once
const expectedChallenge = await Redis.defaultClient.getdel(
getAuthenticationChallengeKey(challengeId)
);
@@ -371,9 +369,6 @@ router.post(
passkey.lastActiveAt = new Date();
await passkey.save({ silent: true });
// Delete challenge from Redis
await Redis.defaultClient.del(getAuthenticationChallengeKey(challengeId));
// Use the signIn utility which handles all sign-in logic
await signIn(ctx, "passkeys", {
user,
@@ -1,5 +1,4 @@
import { uniq } from "es-toolkit/compat";
import { runInAction } from "mobx";
import { observer } from "mobx-react";
import { Trans, useTranslation } from "react-i18next";
import { toast } from "sonner";
@@ -30,16 +29,12 @@ function SlackListItem({ integration, collection }: Props) {
const { t } = useTranslation();
const handleChange = (eventName: string) => async (checked: boolean) => {
runInAction(() => {
if (checked) {
integration.events = uniq([...integration.events, eventName]);
} else {
integration.events = integration.events.filter((n) => n !== eventName);
}
await integration.save({
events: checked
? uniq([...integration.events, eventName])
: integration.events.filter((n) => n !== eventName),
});
await integration.save();
toast.success(t("Settings saved"));
};
@@ -121,7 +121,7 @@ router.post(
const webhookSubscription = await WebhookSubscription.findByPk(id, {
rejectOnEmpty: true,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: WebhookSubscription },
transaction,
});
@@ -152,7 +152,7 @@ router.post(
const webhookSubscription = await WebhookSubscription.findByPk(id, {
rejectOnEmpty: true,
lock: transaction.LOCK.UPDATE,
lock: { level: transaction.LOCK.NO_KEY_UPDATE, of: WebhookSubscription },
transaction,
});
@@ -137,6 +137,67 @@ describe("DeliverWebhookTask", () => {
expect(delivery.responseBody).toEqual("SUCCESS");
});
it("should truncate stored response bodies", async () => {
const subscription = await buildWebhookSubscription({
url: "http://example.com",
events: ["*"],
});
const signedInUser = await buildUser({ teamId: subscription.teamId });
captureWebhook(
"http://example.com",
() => new HttpResponse("a".repeat(5000), { status: 200 })
);
await new DeliverWebhookTask().perform({
subscriptionId: subscription.id,
event: {
name: "users.signin",
userId: signedInUser.id,
teamId: subscription.teamId,
actorId: signedInUser.id,
ip,
},
});
const delivery = await WebhookDelivery.findOne({
where: { webhookSubscriptionId: subscription.id },
rejectOnEmpty: true,
});
expect(delivery.status).toBe("success");
expect(delivery.responseBody).toEqual("a".repeat(1024));
});
it("should not read response bodies over the size limit", async () => {
const subscription = await buildWebhookSubscription({
url: "http://example.com",
events: ["*"],
});
const signedInUser = await buildUser({ teamId: subscription.teamId });
captureWebhook(
"http://example.com",
() => new HttpResponse("a".repeat(128 * 1024), { status: 200 })
);
await new DeliverWebhookTask().perform({
subscriptionId: subscription.id,
event: {
name: "users.signin",
userId: signedInUser.id,
teamId: subscription.teamId,
actorId: signedInUser.id,
ip,
},
});
const delivery = await WebhookDelivery.findOne({
where: { webhookSubscriptionId: subscription.id },
rejectOnEmpty: true,
});
expect(delivery.status).toBe("success");
expect(delivery.statusCode).toBe(200);
expect(delivery.responseBody).toEqual("");
});
it("should hit the subscription url with signature header", async () => {
const subscription = await buildWebhookSubscription({
url: "http://example.com",
@@ -799,9 +799,12 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
});
}
/** Maximum number of bytes to read from webhook response bodies. */
/** Maximum number of bytes to store from webhook response bodies. */
private static readonly MAX_RESPONSE_BODY_SIZE = 1024;
/** Maximum number of bytes to read from webhook response bodies. */
private static readonly MAX_RESPONSE_READ_SIZE = 64 * 1024;
private async sendWebhook({
event,
subscription,
@@ -842,6 +845,7 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
body: JSON.stringify(requestBody),
redirect: "error",
timeout: 5000,
size: DeliverWebhookTask.MAX_RESPONSE_READ_SIZE,
});
status = response.ok ? "success" : "failed";
} catch (err) {
@@ -862,7 +866,6 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
if (response) {
try {
// TODO: Use stream to avoid buffering large responses in memory.
const text = await response.text();
responseBody = text.slice(0, DeliverWebhookTask.MAX_RESPONSE_BODY_SIZE);
} catch (err) {