Skip to content
TypeScript

feat(gitlab): merge requests from forks can toggle maintainer edits (#30518)

Antony508f869cb3d3
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
index 1641ff79dc1..e70941f1568 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts
@@ -1643,33 +1643,39 @@ layer("GitLabPullRequestCli.layer", (it) => {
expected: true,
},
{ answer: JSON.stringify({ errors: [{ message: "Field unknown" }] }), expected: false },
- ])("reads merge and label permissions without reading the trigger jobs", ({ answer, expected }) =>
- Effect.gen(function* () {
- mockedExecute.mockImplementation(({ args }) =>
- Effect.succeed(
- output(
- args[1] === "graphql"
- ? answer
- : mergeRequestJson({
- head_pipeline: { id: 31, project_id: 12, status: "success" },
- user: { can_merge: false },
- }),
+ ])(
+ "reads merge and label permissions without reading the trigger jobs or fork settings",
+ ({ answer, expected }) =>
+ Effect.gen(function* () {
+ mockedExecute.mockImplementation(({ args }) =>
+ Effect.succeed(
+ output(
+ args[1] === "graphql"
+ ? answer
+ : mergeRequestJson({
+ head_pipeline: { id: 31, project_id: 12, status: "success" },
+ user: { can_merge: false },
+ source_project_id: 12,
+ target_project_id: 12,
+ allow_collaboration: null,
+ }),
+ ),
),
- ),
- );
- const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+ );
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
- const detail = yield* cli.getMergeRequestDetail({
- cwd: "/w",
- repository: "acme/web",
- number: 7,
- downstreamChecks: false,
- });
+ const detail = yield* cli.getMergeRequestDetail({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ downstreamChecks: false,
+ });
- expect(detail.viewerCanMerge).toBe(false);
- expect(detail.viewerCanEditLabels).toBe(expected);
- expect(mockedExecute).toHaveBeenCalledTimes(2);
- }),
+ expect(detail.viewerCanMerge).toBe(false);
+ expect(detail.maintainerCanModify).toBeUndefined();
+ expect(detail.viewerCanEditLabels).toBe(expected);
+ expect(mockedExecute).toHaveBeenCalledTimes(2);
+ }),
);
it.effect(
@@ -1888,6 +1894,143 @@ layer("GitLabPullRequestCli.layer", (it) => {
}),
);
+ it.effect.each([
+ { viewer: "the author who can push to the fork", username: "bilal", allowed: true },
+ {
+ viewer: "the author who turned them off",
+ username: "bilal",
+ allowCollaboration: false,
+ allowed: true,
+ },
+ { viewer: "a target maintainer the fork lets push", username: "octocat", allowed: false },
+ {
+ viewer: "the author without push access",
+ username: "bilal",
+ pushToSourceBranch: false,
+ allowed: false,
+ },
+ {
+ viewer: "a viewer on a host that rejects the permission read",
+ username: "bilal",
+ rejected: true,
+ allowed: false,
+ },
+ {
+ viewer: "the author of a protected source branch",
+ username: "bilal",
+ sourceBranchProtected: true,
+ allowed: false,
+ },
+ {
+ viewer: "the author of a private fork",
+ username: "bilal",
+ sourceVisibility: "private",
+ allowed: false,
+ },
+ {
+ viewer: "the author targeting a private project",
+ username: "bilal",
+ targetVisibility: "private",
+ allowed: false,
+ },
+ ])("reads a fork's maintainer edits and lets $viewer change them", (row) =>
+ Effect.gen(function* () {
+ const allowCollaboration = row.allowCollaboration ?? true;
+ mockedExecute.mockImplementation(({ args }) =>
+ Effect.succeed(
+ output(
+ args[1] === "graphql"
+ ? JSON.stringify(
+ row.rejected === true
+ ? { errors: [{ message: "Field 'pushToSourceBranch' doesn't exist" }] }
+ : {
+ data: {
+ currentUser: { username: row.username },
+ project: {
+ visibility: row.targetVisibility ?? "public",
+ mergeRequest: {
+ author: { username: "bilal" },
+ userPermissions: {
+ pushToSourceBranch: row.pushToSourceBranch ?? true,
+ },
+ sourceBranchProtected: row.sourceBranchProtected ?? false,
+ sourceProject: { visibility: row.sourceVisibility ?? "public" },
+ },
+ },
+ },
+ },
+ )
+ : mergeRequestJson({
+ author,
+ source_project_id: 40,
+ target_project_id: 12,
+ allow_collaboration: allowCollaboration,
+ }),
+ ),
+ ),
+ );
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ const detail = yield* cli.getMergeRequestDetail({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ downstreamChecks: false,
+ });
+
+ expect(detail.maintainerCanModify).toBe(allowCollaboration);
+ expect(detail.viewerCanEditMaintainerEdits).toBe(row.allowed);
+ }),
+ );
+
+ it.effect("skips a fork's maintainer edits permission read when the caller opts out", () =>
+ Effect.gen(function* () {
+ mockedExecute
+ .mockReturnValueOnce(
+ Effect.succeed(
+ output(
+ mergeRequestJson({
+ source_project_id: 40,
+ target_project_id: 12,
+ allow_collaboration: true,
+ }),
+ ),
+ ),
+ )
+ .mockReturnValueOnce(Effect.succeed(labelPermission));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ const detail = yield* cli.getMergeRequestDetail({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ downstreamChecks: false,
+ maintainerEdits: false,
+ });
+
+ expect(detail.maintainerCanModify).toBe(true);
+ expect(detail.viewerCanEditMaintainerEdits).toBeUndefined();
+ expect(mockedExecute).toHaveBeenCalledTimes(2);
+ }),
+ );
+
+ it.effect("sends maintainer edits as allow_collaboration", () =>
+ Effect.gen(function* () {
+ mockedExecute.mockReturnValueOnce(Effect.succeed(output("{}")));
+ const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli;
+
+ yield* cli.updateMergeRequest({
+ cwd: "/w",
+ repository: "acme/web",
+ number: 7,
+ allowCollaboration: false,
+ });
+
+ expect(argsOfCall(0)).toContain("PUT");
+ expect(JSON.parse(callAt(0).stdin ?? "")).toEqual({ allow_collaboration: false });
+ }),
+ );
+
it.effect.each([
["th", "projects/acme%2Fweb/users?per_page=100"],
["tho", "projects/acme%2Fweb/users?per_page=100&search=tho"],
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
index 7eda058ceb4..f8a52e9f33f 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts
@@ -42,6 +42,7 @@ import {
decodeCommitsJson,
decodeDiffRefsJson,
decodeDiscussionsJson,
+ decodeMaintainerEditsPermissionJson,
decodeLabelNameJson,
decodeLabelPermissionJson,
decodeMergeMessagesJson,
@@ -67,6 +68,7 @@ import {
decodeTriggerJobChecksJson,
decodeViewerJson,
gitLabAwardName,
+ MAINTAINER_EDITS_PERMISSION_GRAPHQL_QUERY,
LABEL_PERMISSION_GRAPHQL_QUERY,
MERGE_MESSAGES_GRAPHQL_QUERY,
MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY,
@@ -380,6 +382,8 @@ export class GitLabPullRequestCli extends Context.Service<
readonly number: number;
/** `false` skips the stage and trigger job reads, as write permission checks do. */
readonly downstreamChecks?: boolean;
+ /** `false` skips a fork's maintainer edits permission read, for views that never show it. */
+ readonly maintainerEdits?: boolean;
}) => Effect.Effect<GitLabMergeRequestDetail, GitLabPullRequestCliError>;
/** Approval and head pipeline state, read in one GraphQL request per 100 merge requests. */
@@ -555,6 +559,7 @@ export class GitLabPullRequestCli extends Context.Service<
readonly number: number;
readonly title?: string | undefined;
readonly description?: string | undefined;
+ readonly allowCollaboration?: boolean | undefined;
}) => Effect.Effect<void, GitLabPullRequestCliError>;
readonly commentOnMergeRequest: (input: {
@@ -1580,6 +1585,19 @@ export const make = Effect.gen(function* () {
}),
);
+ // A read GitLab could not answer (an older host, a field it rejects) is not worth failing the
+ // surrounding operation for. An unusable CLI or account still reaches the caller.
+ const isOptionalReadFailure = (cause: GitLabPullRequestCliError) =>
+ cause._tag !== "GitLabCliUnavailableError" &&
+ cause._tag !== "GitLabCliAuthenticationError" &&
+ cause._tag !== "GitLabCliRateLimitError";
+
+ const orWhenUnanswered = <A>(
+ read: Effect.Effect<A, GitLabPullRequestCliError>,
+ fallback: A,
+ ): Effect.Effect<A, GitLabPullRequestCliError> =>
+ read.pipe(Effect.catchIf(isOptionalReadFailure, () => Effect.succeed(fallback)));
+
const graphqlMutation = (input: {
readonly cwd: string;
readonly host?: string | undefined;
@@ -1675,16 +1693,7 @@ export const make = Effect.gen(function* () {
query: LABEL_PERMISSION_GRAPHQL_QUERY,
variables: { fullPath: input.repository, iid: String(input.number) },
decode: decodeLabelPermissionJson,
- }).pipe(
- // The answer gates one optional control; an unusable CLI or account still surfaces.
- Effect.catchIf(
- (cause) =>
- cause._tag !== "GitLabCliUnavailableError" &&
- cause._tag !== "GitLabCliAuthenticationError" &&
- cause._tag !== "GitLabCliRateLimitError",
- () => Effect.succeed(false),
- ),
- );
+ }).pipe(Effect.catchIf(isOptionalReadFailure, () => Effect.succeed(false)));
const sourceBranch = (input: {
readonly cwd: string;
@@ -1812,18 +1821,12 @@ export const make = Effect.gen(function* () {
return stat === undefined ? [] : [{ repository: read.repository, number, ...stat }];
}),
),
- // One read GitLab could not answer costs its own rows their counts, not every other
- // read's on the same page. An unusable CLI or account still reaches the caller.
- Effect.catchIf(
- (cause) =>
- cause._tag !== "GitLabCliUnavailableError" &&
- cause._tag !== "GitLabCliAuthenticationError" &&
- cause._tag !== "GitLabCliRateLimitError",
- (cause) =>
- Effect.logWarning("GitLab merge request line count read failed", {
- repository: read.repository,
- reason: cause._tag,
- }).pipe(Effect.as([])),
+ // One failed read costs its own rows their counts, not every other read's on the page.
+ Effect.catchIf(isOptionalReadFailure, (cause) =>
+ Effect.logWarning("GitLab merge request line count read failed", {
+ repository: read.repository,
+ reason: cause._tag,
+ }).pipe(Effect.as([])),
),
),
{ concurrency: STAT_REQUEST_CONCURRENCY },
@@ -1998,24 +2001,33 @@ export const make = Effect.gen(function* () {
[mergeRequestDetail(input), labelPermission(input)],
{ concurrency: 2 },
);
- // Only a closed or merged merge request offers its branch for deletion, so an open one,
- // the page most often read, skips the extra query.
+ // Only a closed or merged merge request offers its branch for deletion, and only an open
+ // fork's has maintainer edits to change, so each extra read is skipped elsewhere.
const detail =
read.state === "open"
- ? { ...read, viewerCanEditLabels }
+ ? input.maintainerEdits === false || read.maintainerCanModify === undefined
+ ? { ...read, viewerCanEditLabels }
+ : {
+ ...read,
+ viewerCanEditLabels,
+ viewerCanEditMaintainerEdits: yield* orWhenUnanswered(
+ graphqlRead({
+ cwd: input.cwd,
+ host: input.host,
+ operation: "getMaintainerEditsPermission",
+ query: MAINTAINER_EDITS_PERMISSION_GRAPHQL_QUERY,
+ variables: { fullPath: input.repository, iid: String(input.number) },
+ decode: decodeMaintainerEditsPermissionJson,
+ }),
+ false,
+ ),
+ }
: {
...read,
viewerCanEditLabels,
- viewerCanDeleteBranch: yield* sourceBranch(input).pipe(
- Effect.map((source) => source?.canDelete === true),
- // The answer gates one optional action; an unusable CLI or account still surfaces.
- Effect.catchIf(
- (cause) =>
- cause._tag !== "GitLabCliUnavailableError" &&
- cause._tag !== "GitLabCliAuthenticationError" &&
- cause._tag !== "GitLabCliRateLimitError",
- () => Effect.succeed(false),
- ),
+ viewerCanDeleteBranch: yield* orWhenUnanswered(
+ sourceBranch(input).pipe(Effect.map((source) => source?.canDelete === true)),
+ false,
),
};
if (input.downstreamChecks === false || detail.headPipeline === undefined) return detail;
@@ -2469,6 +2481,9 @@ export const make = Effect.gen(function* () {
stdin: JSON.stringify({
...(input.title === undefined ? {} : { title: input.title }),
...(input.description === undefined ? {} : { description: input.description }),
+ ...(input.allowCollaboration === undefined
+ ? {}
+ : { allow_collaboration: input.allowCollaboration }),
}),
}).pipe(Effect.asVoid);
}),
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
index e2adb243b97..926e793297a 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts
@@ -145,6 +145,7 @@ describe("gitLabViewerPermissions", () => {
resolve: true,
verdicts: ["comment", "approve", "request-changes"],
requestReviewers: true,
+ maintainerEdits: false,
labels: true,
updateMethods: ["rebase"],
});
@@ -157,6 +158,7 @@ describe("gitLabViewerPermissions", () => {
resolve: true,
verdicts: ["comment", "approve", "request-changes"],
requestReviewers: true,
+ maintainerEdits: false,
labels: false,
});
});
@@ -190,13 +192,17 @@ describe("getChangeRequest base freshness", () => {
};
it.effect.each(["getChangeRequestPreview", "getChangeRequestSummary"] as const)(
- "%s preserves merge request fields without fetching project settings",
+ "%s preserves merge request fields without fetching project settings or fork permissions",
(operation) =>
Effect.gen(function* () {
+ const detailInputs: Array<{ readonly maintainerEdits?: boolean }> = [];
const provider = yield* make.pipe(
Effect.provide(
Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({
- getMergeRequestDetail: () => Effect.succeed(detail),
+ getMergeRequestDetail: (input) => {
+ detailInputs.push(input);
+ return Effect.succeed(detail);
+ },
getListStates: () => Effect.succeed(new Map()),
listMergeRequestStats: () => Effect.succeed([]),
@@ -208,6 +214,7 @@ describe("getChangeRequest base freshness", () => {
expect(
yield* read({ cwd: "/w", repository: "acme/web", host: "gitlab.com", number: 7 }),
).toEqual(detail);
+ expect(detailInputs.map((input) => input.maintainerEdits)).toEqual([false]);
}),
);
diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
index 4247008c273..ca0e9ffde5a 100644
--- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
+++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts
@@ -44,7 +44,7 @@ const CAPABILITIES: PullRequestCapabilities = {
},
reviewers: { request: true, listCandidates: true },
labels: true,
- edit: { changeRequest: true, comment: true },
+ edit: { changeRequest: true, comment: true, maintainerEdits: true },
};
const UNAVAILABLE_REQUIREMENT = {
@@ -68,6 +68,7 @@ const MERGE_ACTIONS: ReadonlySet<string> = new Set([
/** Authors may close/reopen/change draft state regardless of role; REST omits authorship. */
export function gitLabViewerPermissions(input: {
readonly viewerCanMerge: boolean;
+ readonly viewerCanEditMaintainerEdits?: boolean | undefined;
readonly viewerCanDeleteBranch?: boolean;
readonly viewerCanEditLabels?: boolean | undefined;
}): PullRequestViewerPermissions {
@@ -81,6 +82,7 @@ export function gitLabViewerPermissions(input: {
resolve: true,
verdicts: CAPABILITIES.review.verdicts,
requestReviewers: true,
+ maintainerEdits: input.viewerCanEditMaintainerEdits === true,
labels: input.viewerCanEditLabels === true,
...(input.viewerCanMerge ? { updateMethods: CAPABILITIES.updateMethods } : {}),
};
@@ -321,12 +323,17 @@ export const make = Effect.gen(function* () {
// Merge settings only affect the detail panel's actions.
getChangeRequestPreview: (input) =>
- cli.getMergeRequestDetail(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))),
+ cli
+ .getMergeRequestDetail({ ...input, maintainerEdits: false })
+ .pipe(Effect.mapError(fail("getChangeRequestPreview"))),
getChangeRequestSummary: (input) =>
Effect.all(
[
- mergeRequestWithStats(input),
+ mergeRequestWithStats(
+ input,
+ cli.getMergeRequestDetail({ ...input, maintainerEdits: false }),
+ ),
listStates({
cwd: input.cwd,
host: input.host,
@@ -582,6 +589,9 @@ export const make = Effect.gen(function* () {
number: input.number,
...(input.title === undefined ? {} : { title: input.title }),
...(input.body === undefined ? {} : { description: input.body }),
+ ...(input.maintainerCanModify === undefined
+ ? {}
+ : { allowCollaboration: input.maintainerCanModify }),
})
.pipe(Effect.mapError(fail("updateChangeRequest"))),
),
diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
index 602d5971f09..e1115cd6603 100644
--- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
+++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts
@@ -92,6 +92,10 @@ const RawMergeRequestSchema = Schema.Struct({
squash: Schema.optional(Schema.NullOr(Schema.Boolean)),
/** Only detail reads with include_diverged_commits_count return this expensive count. */
diverged_commits_count: Schema.optional(Schema.NullOr(Schema.Int)),
+ source_project_id: Schema.optional(Schema.NullOr(Schema.Int)),
+ target_project_id: Schema.optional(Schema.NullOr(Schema.Int)),
+ /** Null on merge requests from the same project, where it means nothing. */
+ allow_collaboration: Schema.optional(Schema.NullOr(Schema.Boolean)),
diff_refs: Schema.optional(Schema.NullOr(RawMergeRequestDiffRefs)),
});
@@ -224,6 +228,9 @@ export interface GitLabMergeRequestDetail extends GitLabMergeRequestListItem {
readonly diffRefs?: GitLabDiffRefs;
/** On a fork the pipeline often belongs to the source project, not the target. */
readonly headPipeline?: { readonly id: number; readonly projectId: number };
+ /** Whether target maintainers may push to the source branch. Only set on merge requests from forks. */
+ readonly maintainerCanModify?: boolean;
+ readonly viewerCanEditMaintainerEdits?: boolean;
}
function toActor(raw: Schema.Schema.Type<typeof RawUserSchema> | null | undefined) {
@@ -524,6 +531,11 @@ function toDetail(raw: Schema.Schema.Type<typeof RawMergeRequestSchema>): GitLab
...(raw.head_pipeline?.id == null || raw.head_pipeline.project_id == null
? {}
: { headPipeline: { id: raw.head_pipeline.id, projectId: raw.head_pipeline.project_id } }),
+ ...(raw.source_project_id != null &&
+ raw.target_project_id != null &&
+ raw.source_project_id !== raw.target_project_id
+ ? { maintainerCanModify: raw.allow_collaboration === true }
+ : {}),
};
}
@@ -1864,6 +1876,67 @@ export function decodeLabelPermissionJson(raw: string): Result.Result<boolean, D
: Result.fail(decoded.failure);
}
+/**
+ * GitLab lets whoever can push to a fork's branch allow maintainer pushes, but once allowed the
+ * target's maintainers can push too, so only the author may change it, as on GitHub. GitLab
+ * drops the setting unless the source branch is unprotected and neither project is private
+ * (`MergeRequest#collaborative_push_possible?`).
+ */
+export const MAINTAINER_EDITS_PERMISSION_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {
+ currentUser { username }
+ project(fullPath: $fullPath) {
+ visibility
+ mergeRequest(iid: $iid) {
+ author { username }
+ userPermissions { pushToSourceBranch }
+ sourceBranchProtected
+ sourceProject { visibility }
+ }
+ }
+}`;
+
+const decodeMaintainerEditsPermission = decodeJsonResult(
+ Schema.Struct({
+ data: Schema.Struct({
+ currentUser: Schema.NullOr(Schema.Struct({ username: Schema.String })),
+ project: Schema.NullOr(
+ Schema.Struct({
+ visibility: Schema.NullOr(Schema.String),
+ mergeRequest: Schema.NullOr(
+ Schema.Struct({
+ author: Schema.NullOr(Schema.Struct({ username: Schema.String })),
+ userPermissions: Schema.Struct({ pushToSourceBranch: Schema.Boolean }),
+ sourceBranchProtected: Schema.Boolean,
+ sourceProject: Schema.NullOr(
+ Schema.Struct({ visibility: Schema.NullOr(Schema.String) }),
+ ),
+ }),
+ ),
+ }),
+ ),
+ }),
+ }),
+);
+
+export function decodeMaintainerEditsPermissionJson(
+ raw: string,
+): Result.Result<boolean, DecodeFailure> {
+ const decoded = decodeMaintainerEditsPermission(raw);
+ if (Result.isFailure(decoded)) return Result.fail(decoded.failure);
+ const { currentUser, project } = decoded.success.data;
+ const mergeRequest = project?.mergeRequest;
+ const isPublicOrInternal = (visibility: string | null | undefined) =>
+ visibility === "public" || visibility === "internal";
+ return Result.succeed(
+ currentUser !== null &&
+ mergeRequest?.author?.username === currentUser.username &&
+ mergeRequest.userPermissions.pushToSourceBranch &&
+ !mergeRequest.sourceBranchProtected &&
+ isPublicOrInternal(project?.visibility) &&
+ isPublicOrInternal(mergeRequest.sourceProject?.visibility),
+ );
+}
+
/** Per-file line counts for one merge request, which the code/tests/generated breakdown sorts. */
export const MERGE_REQUEST_FILE_STATS_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) {
project(fullPath: $fullPath) {