Skip to content

Commit f5ded8b

Browse files
authored
fix: use github owner login for webhook deploy matching (Dokploy#4674)
* fix: use github owner login for webhook deploy matching * fix: prefer github owner name for webhook matching Что: - Инвертирован порядок fallback для GitHub webhook owner: сначала repository.owner.name, затем repository.owner.login. - Обновлен focused regression test для приоритета owner.name и fallback на owner.login. Зачем: - Выполнить maintainer review request в PR Dokploy#4674 и сохранить совместимость deploy matching для payload без owner.name. Риски: - Не выявлены для push/tag matching; preview pull_request путь использует тот же helper, но отдельным PR-event тестом не покрыт. Проверки: - Команды и результаты: git diff --check -- apps/dokploy/pages/api/deploy/github.ts apps/dokploy/__test__/deploy/github-webhook-handler.test.ts - passed; CI=true corepack pnpm --dir apps/dokploy exec vitest --config __test__/vitest.config.ts run __test__/deploy/github-webhook-handler.test.ts --reporter=verbose - passed, 1 file / 4 tests; CI=true corepack pnpm exec biome check apps/dokploy/pages/api/deploy/github.ts apps/dokploy/__test__/deploy/github-webhook-handler.test.ts - exit 0, reported existing Number.parseInt radix info at github.ts:464; mandatory QA subagent Boyle - pass. - Ограничения: repo-wide format-and-lint, typecheck, build, and test не запускались для этого точечного review fix. What: - Inverted the GitHub webhook owner fallback order to prefer repository.owner.name before repository.owner.login. - Updated the focused regression test for owner.name precedence and owner.login fallback. Why: - Address the maintainer review request in PR Dokploy#4674 while preserving deploy matching for payloads without owner.name. Risks: - None identified for push/tag matching; the preview pull_request path uses the same helper but is not covered by a dedicated PR-event test. Checks: - Commands and results: git diff --check -- apps/dokploy/pages/api/deploy/github.ts apps/dokploy/__test__/deploy/github-webhook-handler.test.ts - passed; CI=true corepack pnpm --dir apps/dokploy exec vitest --config __test__/vitest.config.ts run __test__/deploy/github-webhook-handler.test.ts --reporter=verbose - passed, 1 file / 4 tests; CI=true corepack pnpm exec biome check apps/dokploy/pages/api/deploy/github.ts apps/dokploy/__test__/deploy/github-webhook-handler.test.ts - exit 0, reported existing Number.parseInt radix info at github.ts:464; mandatory QA subagent Boyle - pass. - Limitations: repo-wide format-and-lint, typecheck, build, and test were not run for this targeted review fix.
1 parent d87229c commit f5ded8b

2 files changed

Lines changed: 329 additions & 3 deletions

File tree

Lines changed: 323 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,323 @@
1+
import type { NextApiRequest, NextApiResponse } from "next";
2+
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
4+
const mocks = vi.hoisted(() => ({
5+
eq: vi.fn((field: string, value: unknown) => ({ field, value })),
6+
and: vi.fn((...conditions: Array<{ field: string; value: unknown }>) => ({
7+
conditions,
8+
})),
9+
githubFindFirst: vi.fn(),
10+
applicationsFindMany: vi.fn(),
11+
composeFindMany: vi.fn(),
12+
queueAdd: vi.fn(),
13+
verify: vi.fn(),
14+
shouldDeploy: vi.fn(),
15+
}));
16+
17+
vi.mock("drizzle-orm", () => ({
18+
eq: mocks.eq,
19+
and: mocks.and,
20+
}));
21+
22+
vi.mock("@/server/db/schema", () => ({
23+
applications: {
24+
sourceType: "application.sourceType",
25+
autoDeploy: "application.autoDeploy",
26+
triggerType: "application.triggerType",
27+
branch: "application.branch",
28+
repository: "application.repository",
29+
owner: "application.owner",
30+
githubId: "application.githubId",
31+
isPreviewDeploymentsActive: "application.isPreviewDeploymentsActive",
32+
},
33+
compose: {
34+
sourceType: "compose.sourceType",
35+
autoDeploy: "compose.autoDeploy",
36+
triggerType: "compose.triggerType",
37+
branch: "compose.branch",
38+
repository: "compose.repository",
39+
owner: "compose.owner",
40+
githubId: "compose.githubId",
41+
},
42+
github: {
43+
githubInstallationId: "github.githubInstallationId",
44+
},
45+
}));
46+
47+
vi.mock("@dokploy/server/db", () => ({
48+
db: {
49+
query: {
50+
github: {
51+
findFirst: mocks.githubFindFirst,
52+
},
53+
applications: {
54+
findMany: mocks.applicationsFindMany,
55+
},
56+
compose: {
57+
findMany: mocks.composeFindMany,
58+
},
59+
},
60+
},
61+
}));
62+
63+
vi.mock("@dokploy/server", () => ({
64+
IS_CLOUD: false,
65+
shouldDeploy: mocks.shouldDeploy,
66+
checkUserRepositoryPermissions: vi.fn(),
67+
createPreviewDeployment: vi.fn(),
68+
createSecurityBlockedComment: vi.fn(),
69+
findGithubById: vi.fn(),
70+
findPreviewDeploymentByApplicationId: vi.fn(),
71+
findPreviewDeploymentsByPullRequestId: vi.fn(),
72+
getBitbucketHeaders: vi.fn(() => ({})),
73+
removePreviewDeployment: vi.fn(),
74+
}));
75+
76+
vi.mock("@octokit/webhooks", () => ({
77+
Webhooks: vi.fn().mockImplementation(function Webhooks() {
78+
return {
79+
verify: mocks.verify,
80+
};
81+
}),
82+
}));
83+
84+
vi.mock("@/server/queues/queueSetup", () => ({
85+
myQueue: {
86+
add: mocks.queueAdd,
87+
},
88+
}));
89+
90+
vi.mock("@/server/utils/deploy", () => ({
91+
deploy: vi.fn(),
92+
}));
93+
94+
import handler from "@/pages/api/deploy/github";
95+
96+
const getConditionValue = (
97+
where: { conditions?: Array<{ field: string; value: unknown }> } | undefined,
98+
field: string,
99+
) => where?.conditions?.find((condition) => condition.field === field)?.value;
100+
101+
const createResponse = () => {
102+
const res = {
103+
status: vi.fn(),
104+
json: vi.fn(),
105+
} as unknown as NextApiResponse & {
106+
status: ReturnType<typeof vi.fn>;
107+
json: ReturnType<typeof vi.fn>;
108+
};
109+
110+
res.status.mockImplementation(() => res);
111+
res.json.mockImplementation(() => res);
112+
113+
return res;
114+
};
115+
116+
const createPushRequest = (
117+
branch: string,
118+
owner: { login?: string; name?: string } = { login: "agentHits" },
119+
) =>
120+
({
121+
headers: {
122+
"x-hub-signature-256": "sha256=test-signature",
123+
"x-github-event": "push",
124+
},
125+
body: {
126+
installation: {
127+
id: 12345,
128+
},
129+
ref: `refs/heads/${branch}`,
130+
after: "abc123",
131+
head_commit: {
132+
message: "fix: trigger deployment",
133+
},
134+
commits: [
135+
{
136+
modified: ["src/index.ts"],
137+
},
138+
],
139+
repository: {
140+
name: "dokploy",
141+
full_name: "agentHits/dokploy",
142+
clone_url: "https://github.com/agentHits/dokploy.git",
143+
html_url: "https://github.com/agentHits/dokploy",
144+
owner,
145+
},
146+
},
147+
}) as unknown as NextApiRequest;
148+
149+
const createTagRequest = (tagName: string) => {
150+
const req = createPushRequest("main") as unknown as {
151+
body: { ref: string; head_commit: { message: string } };
152+
};
153+
154+
req.body.ref = `refs/tags/${tagName}`;
155+
req.body.head_commit.message = `release: ${tagName}`;
156+
157+
return req as unknown as NextApiRequest;
158+
};
159+
160+
describe("GitHub app webhook auto-deploy", () => {
161+
beforeEach(() => {
162+
vi.clearAllMocks();
163+
mocks.githubFindFirst.mockResolvedValue({
164+
githubId: "github-provider-id",
165+
githubInstallationId: 12345,
166+
githubWebhookSecret: "webhook-secret",
167+
});
168+
mocks.verify.mockResolvedValue(true);
169+
mocks.shouldDeploy.mockReturnValue(true);
170+
mocks.composeFindMany.mockResolvedValue([]);
171+
mocks.queueAdd.mockResolvedValue({ id: "job-id" });
172+
173+
mocks.applicationsFindMany.mockImplementation(({ where }) => {
174+
const matches =
175+
getConditionValue(where, "application.sourceType") === "github" &&
176+
getConditionValue(where, "application.autoDeploy") === true &&
177+
getConditionValue(where, "application.triggerType") === "push" &&
178+
getConditionValue(where, "application.branch") === "main" &&
179+
getConditionValue(where, "application.repository") === "dokploy" &&
180+
getConditionValue(where, "application.owner") === "agentHits" &&
181+
getConditionValue(where, "application.githubId") ===
182+
"github-provider-id";
183+
184+
return Promise.resolve(
185+
matches
186+
? [
187+
{
188+
applicationId: "application-id",
189+
serverId: null,
190+
watchPaths: null,
191+
},
192+
]
193+
: [],
194+
);
195+
});
196+
});
197+
198+
it("matches push events using repository owner name when available", async () => {
199+
const res = createResponse();
200+
201+
await handler(
202+
createPushRequest("main", {
203+
login: "agentHits-login",
204+
name: "agentHits",
205+
}),
206+
res,
207+
);
208+
209+
expect(mocks.queueAdd).toHaveBeenCalledWith(
210+
"deployments",
211+
expect.objectContaining({
212+
applicationId: "application-id",
213+
applicationType: "application",
214+
type: "deploy",
215+
}),
216+
expect.objectContaining({
217+
removeOnComplete: true,
218+
removeOnFail: true,
219+
}),
220+
);
221+
expect(res.status).toHaveBeenCalledWith(200);
222+
expect(res.json).toHaveBeenCalledWith({ message: "Deployed 1 apps" });
223+
});
224+
225+
it("matches compose push events using repository owner login fallback", async () => {
226+
mocks.applicationsFindMany.mockResolvedValue([]);
227+
mocks.composeFindMany.mockImplementation(({ where }) => {
228+
const matches =
229+
getConditionValue(where, "compose.sourceType") === "github" &&
230+
getConditionValue(where, "compose.autoDeploy") === true &&
231+
getConditionValue(where, "compose.triggerType") === "push" &&
232+
getConditionValue(where, "compose.branch") === "main" &&
233+
getConditionValue(where, "compose.repository") === "dokploy" &&
234+
getConditionValue(where, "compose.owner") === "agentHits" &&
235+
getConditionValue(where, "compose.githubId") === "github-provider-id";
236+
237+
return Promise.resolve(
238+
matches
239+
? [
240+
{
241+
composeId: "compose-id",
242+
serverId: null,
243+
watchPaths: null,
244+
},
245+
]
246+
: [],
247+
);
248+
});
249+
const res = createResponse();
250+
251+
await handler(createPushRequest("main"), res);
252+
253+
expect(mocks.queueAdd).toHaveBeenCalledWith(
254+
"deployments",
255+
expect.objectContaining({
256+
applicationType: "compose",
257+
composeId: "compose-id",
258+
type: "deploy",
259+
}),
260+
expect.objectContaining({
261+
removeOnComplete: true,
262+
removeOnFail: true,
263+
}),
264+
);
265+
expect(res.status).toHaveBeenCalledWith(200);
266+
expect(res.json).toHaveBeenCalledWith({ message: "Deployed 1 apps" });
267+
});
268+
269+
it("matches tag events using repository owner login fallback", async () => {
270+
mocks.applicationsFindMany.mockImplementation(({ where }) => {
271+
const matches =
272+
getConditionValue(where, "application.sourceType") === "github" &&
273+
getConditionValue(where, "application.autoDeploy") === true &&
274+
getConditionValue(where, "application.triggerType") === "tag" &&
275+
getConditionValue(where, "application.repository") === "dokploy" &&
276+
getConditionValue(where, "application.owner") === "agentHits" &&
277+
getConditionValue(where, "application.githubId") ===
278+
"github-provider-id";
279+
280+
return Promise.resolve(
281+
matches
282+
? [
283+
{
284+
applicationId: "application-id",
285+
serverId: null,
286+
},
287+
]
288+
: [],
289+
);
290+
});
291+
const res = createResponse();
292+
293+
await handler(createTagRequest("v1.0.0"), res);
294+
295+
expect(mocks.queueAdd).toHaveBeenCalledWith(
296+
"deployments",
297+
expect.objectContaining({
298+
applicationId: "application-id",
299+
applicationType: "application",
300+
titleLog: "Tag created: v1.0.0",
301+
type: "deploy",
302+
}),
303+
expect.objectContaining({
304+
removeOnComplete: true,
305+
removeOnFail: true,
306+
}),
307+
);
308+
expect(res.status).toHaveBeenCalledWith(200);
309+
expect(res.json).toHaveBeenCalledWith({
310+
message: "Deployed 1 apps based on tag v1.0.0",
311+
});
312+
});
313+
314+
it("does not deploy when the pushed branch does not match", async () => {
315+
const res = createResponse();
316+
317+
await handler(createPushRequest("feature"), res);
318+
319+
expect(mocks.queueAdd).not.toHaveBeenCalled();
320+
expect(res.status).toHaveBeenCalledWith(200);
321+
expect(res.json).toHaveBeenCalledWith({ message: "No apps to deploy" });
322+
});
323+
});

‎apps/dokploy/pages/api/deploy/github.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ import {
2323
logWebhookError,
2424
} from "./[refreshToken]";
2525

26+
const getGithubRepositoryOwner = (githubBody: any) =>
27+
githubBody?.repository?.owner?.name ?? githubBody?.repository?.owner?.login;
28+
2629
export default async function handler(
2730
req: NextApiRequest,
2831
res: NextApiResponse,
@@ -109,7 +112,7 @@ export default async function handler(
109112
try {
110113
const tagName = githubBody?.ref.replace("refs/tags/", "");
111114
const repository = githubBody?.repository?.name;
112-
const owner = githubBody?.repository?.owner?.name;
115+
const owner = getGithubRepositoryOwner(githubBody);
113116
const deploymentTitle = `Tag created: ${tagName}`;
114117
const deploymentHash = extractHash(req.headers, githubBody);
115118

@@ -219,7 +222,7 @@ export default async function handler(
219222

220223
const deploymentTitle = extractCommitMessage(req.headers, req.body);
221224
const deploymentHash = extractHash(req.headers, req.body);
222-
const owner = githubBody?.repository?.owner?.name;
225+
const owner = getGithubRepositoryOwner(githubBody);
223226
const normalizedCommits = githubBody?.commits?.flatMap(
224227
(commit: any) => commit.modified,
225228
);
@@ -372,7 +375,7 @@ export default async function handler(
372375
const repository = githubBody?.repository?.name;
373376
const deploymentHash = githubBody?.pull_request?.head?.sha;
374377
const branch = githubBody?.pull_request?.base?.ref;
375-
const owner = githubBody?.repository?.owner?.login;
378+
const owner = getGithubRepositoryOwner(githubBody);
376379
const prAuthor = githubBody?.pull_request?.user?.login;
377380

378381
// Validate PR author information is present

0 commit comments

Comments
 (0)