Skip to content

Commit

Permalink
feat: (#107) webhook listener filter docker events based on image tag.
Browse files Browse the repository at this point in the history
Fixes #107
  • Loading branch information
hikinine committed May 25, 2024
1 parent 874d1f9 commit 41bdfdf
Showing 1 changed file with 48 additions and 1 deletion.
49 changes: 48 additions & 1 deletion pages/api/deploy/[refreshToken].ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,20 @@ export default async function handler(
const deploymentTitle = extractCommitMessage(req.headers, req.body);

const sourceType = application.sourceType;
if (sourceType === "github") {

if (sourceType === "docker") {
const applicationDockerTag = extractImageTagFromApplication(application.dockerImage);
if (applicationDockerTag) {
const webhookDockerTag = extractImageTagFromRequestEventPayload(req.headers, req.body);
if (webhookDockerTag && (webhookDockerTag !== applicationDockerTag)) {
res.status(301).json({
message: `Application Image Tag(${applicationDockerTag}) doesn't match request event payload Image Tag(${webhookDockerTag}).`
});
return;
}
}
}
else if (sourceType === "github") {
const branchName = extractBranchName(req.headers, req.body);
if (!branchName || branchName !== application.branch) {
res.status(301).json({ message: "Branch Not Match" });
Expand Down Expand Up @@ -79,6 +92,40 @@ export default async function handler(
res.status(400).json({ message: "Error To Deploy Application", error });
}
}

/**
* Return the last part of the image name, which is the tag
* Example: "my-image" => null
* Example: "my-image:latest" => "latest"
* Example: "my-image:1.0.0" => "1.0.0"
* Example: "myregistryhost:5000/fedora/httpd:version1.0" => "version1.0"
* @link https://docs.docker.com/reference/cli/docker/image/tag/
*/
function extractImageTagFromApplication(dockerImage: string | null) {
if (!dockerImage || typeof dockerImage !== "string") {
return null;
}

const partsOfDockerImageName = dockerImage.split(':')
if (partsOfDockerImageName.length === 1) {
return null;
}

return partsOfDockerImageName[partsOfDockerImageName.length - 1];
}

/**
* @link https://docs.docker.com/docker-hub/webhooks/#example-webhook-payload
*/
function extractImageTagFromRequestEventPayload(headers: any, body: any) {
if (headers["user-agent"]?.includes("Go-http-client")) {
if (body.push_data && body.repository) {
return body.push_data.tag;
}
}
return null;
}

function extractCommitMessage(headers: any, body: any) {
// GitHub
if (headers["x-github-event"]) {
Expand Down

0 comments on commit 41bdfdf

Please sign in to comment.