From 47703e4e1ab2fd0f8edd4fe2387eccb1b06c1221 Mon Sep 17 00:00:00 2001 From: Jonathan White Date: Sat, 14 Nov 2026 16:48:24 -0500 Subject: [PATCH] Add GitHub workflow to kick off Team City builds on approval --- .github/scripts/teamcity-approval.js | 156 ++++++++++++++++++++++++ .github/workflows/teamcity-approval.yml | 51 ++++++++ 2 files changed, 207 insertions(+) create mode 100644 .github/scripts/teamcity-approval.js create mode 100644 .github/workflows/teamcity-approval.yml diff --git a/.github/scripts/teamcity-approval.js b/.github/scripts/teamcity-approval.js new file mode 100644 index 000000000..ba5e87683 --- /dev/null +++ b/.github/scripts/teamcity-approval.js @@ -0,0 +1,156 @@ +const fs = require('node:fs'); +const { setTimeout: sleep } = require('node:timers/promises'); + +const REPOSITORY = 'keepassxreboot/keepassxc'; +const GITHUB_API = 'https://api.github.com'; +const TEAMCITY_API = 'https://ci.keepassxc.org/app/rest'; +const INTERVAL_MS = 20_000; +const POLL_COUNT = 25; + +async function requestJson(url, token, options = {}) { + const response = await fetch(url, { + ...options, + headers: { + Accept: 'application/json', + Authorization: `Bearer ${token}`, + ...options.headers, + }, + redirect: 'error', + signal: AbortSignal.timeout(30_000), + }); + if (!response.ok) { + throw new Error(`${options.method || 'GET'} ${url.pathname} failed: HTTP ${response.status}`); + } + return response.json(); +} + +async function findPullRequests(run, token, request = requestJson) { + const repository = run.head_repository?.full_name; + const branch = run.head_branch; + if (!repository || !branch || !/^[0-9a-f]{40}$/i.test(run.head_sha)) { + throw new Error('Workflow run is missing its head repository, branch, or SHA'); + } + + const matches = []; + const url = new URL(`/repos/${REPOSITORY}/pulls`, GITHUB_API); + url.search = new URLSearchParams({ + state: 'open', + head: `${repository.split('/')[0]}:${branch}`, + per_page: '100', + }); + for (let page = 1; ; page++) { + url.searchParams.set('page', page); + const pulls = await request(url, token); + matches.push(...pulls + .filter((pull) => pull.head?.repo?.full_name === repository + && pull.head.sha === run.head_sha && pull.base?.repo?.full_name === REPOSITORY) + .map((pull) => pull.number)); + if (pulls.length < 100) { + return matches; + } + } +} + +function isMatchingBuild(build, pullNumbers, sha) { + return Number.isSafeInteger(build.id) + && build.approvalInfo?.status === 'waitingForApproval' + && pullNumbers.some((number) => + build.branchName === `pull/${number}` + && build.approvalInfo.approvalReasons?.some((reason) => + reason.url === `https://github.com/${REPOSITORY}/pull/${number}`) + && build.revisions?.revision?.some((revision) => + revision.vcsBranchName === `refs/pull/${number}/head` && revision.version === sha)); +} + +async function queuedBuilds(token, request = requestJson) { + const builds = []; + const count = 100; + const url = new URL(`${TEAMCITY_API}/buildQueue`); + url.searchParams.set('fields', 'count,build(id,buildTypeId,branchName,revisions,approvalInfo)'); + for (let start = 0; ; start += count) { + url.searchParams.set('locator', `project:KeePassXC,count:${count},start:${start}`); + const page = await request(url, token); + if (!Number.isInteger(page.count) || page.count < 0 || !Array.isArray(page.build ?? [])) { + throw new Error('Invalid TeamCity build queue response'); + } + const items = page.build ?? []; + if (items.length !== page.count) { + throw new Error('Incomplete TeamCity build queue response'); + } + builds.push(...items); + if (page.count < count) { + return builds; + } + } +} + +async function approveBuild(id, token, request = requestJson) { + if (!Number.isSafeInteger(id)) { + throw new Error('TeamCity build ID must be a safe integer'); + } + if (!token) { + throw new Error('TeamCity token must be configured'); + } + const url = new URL(`${TEAMCITY_API}/buildQueue/id:${id}/approve`); + url.searchParams.set('approveAll', 'false'); + const result = await request(url, token, { + method: 'POST', + headers: { 'Content-Type': 'text/plain' }, + body: '', + }); + if (!['approved', 'waitingForApproval'].includes(result.status)) { + throw new Error(`Unexpected approval status for TeamCity build ${id}: ${result.status}`); + } + return result; +} + +async function main(event, githubToken, teamcityToken, request = requestJson, wait = sleep) { + if (!githubToken || !teamcityToken) { + throw new Error('GH_TOKEN and TEAMCITY_APPROVAL_TOKEN must be configured'); + } + const run = event.workflow_run; + if (!run || run.event !== 'pull_request') { + throw new Error('Expected a pull_request workflow run'); + } + + const workflowUrl = new URL(`/repos/${REPOSITORY}/actions/workflows/codeql.yml`, GITHUB_API); + const workflow = await request(workflowUrl, githubToken); + if (run.workflow_id !== workflow.id || run.path !== '.github/workflows/codeql.yml') { + throw new Error('The triggering workflow is not the repository CodeQL workflow'); + } + + const approved = new Set(); + for (let attempt = 0; attempt < POLL_COUNT; attempt++) { + if (attempt > 0) { + await wait(INTERVAL_MS); + } + const pulls = await findPullRequests(run, githubToken, request); + if (pulls.length === 0) { + console.log('No open pull request still has the triggering commit; stopping.'); + return; + } + for (const build of await queuedBuilds(teamcityToken, request)) { + if (approved.has(build.id) || !isMatchingBuild(build, pulls, run.head_sha)) { + continue; + } + const result = await approveBuild(build.id, teamcityToken, request); + approved.add(build.id); + console.log(`TeamCity build ${build.id} (${build.buildTypeId}): ${result.status}`); + } + } + if (!approved.size) { + console.log('::warning::No matching TeamCity builds were awaiting approval during the polling window.'); + } else { + console.log(`Submitted approval for ${approved.size} TeamCity build(s).`); + } +} + +if (require.main === module) { + main(JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8')), + process.env.GH_TOKEN, process.env.TEAMCITY_TOKEN).catch((error) => { + console.error(error.message); + process.exitCode = 1; + }); +} + +module.exports = { approveBuild, findPullRequests, isMatchingBuild, main, queuedBuilds }; diff --git a/.github/workflows/teamcity-approval.yml b/.github/workflows/teamcity-approval.yml new file mode 100644 index 000000000..217586119 --- /dev/null +++ b/.github/workflows/teamcity-approval.yml @@ -0,0 +1,51 @@ +# The `Approve TeamCity builds` workflow uses the start of the repository's CodeQL +# pull request workflow as a proxy for GitHub Actions approval. GitHub does not +# provide a specific workflow event for the **Approve workflows to run** button: +# the proxy also runs when GitHub starts a PR workflow automatically, including +# for contributors who do not require manual approval. It does not record who +# pressed the button. Enable it only if that behavior is acceptable. + +# Create the repository secret `TEAMCITY_APPROVAL_TOKEN` using a TeamCity service +# account eligible under the KeePassXC project's untrusted-build approval rules. +# Give it only the access needed to view the build queue and approve those builds. +# The workflow submits one vote per matching build; any additional TeamCity +# approval rules still apply. + +# The workflow checks open PRs against the triggering workflow's head repository, +# branch and SHA. It approves only builds in the KeePassXC project waiting for +# approval with the same PR reference, revision and PR URL. It uses trusted +# default-branch code and does not check out the PR or consume its artifacts. +# It polls for eight minutes to allow TeamCity to enqueue builds. Builds queued +# later require separate approval or a rerun of the CodeQL workflow. + +name: "Approve TeamCity builds" + +on: + workflow_run: + workflows: ["CodeQL"] + types: [in_progress] + +permissions: + actions: read + contents: read + pull-requests: read + +jobs: + approve: + if: >- + github.repository == 'keepassxreboot/keepassxc' && + github.event.workflow_run.event == 'pull_request' + runs-on: ubuntu-latest + timeout-minutes: 12 + steps: + - name: Checkout trusted workflow code + uses: actions/checkout@v4 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Approve matching TeamCity builds + env: + GH_TOKEN: ${{ github.token }} + TEAMCITY_TOKEN: ${{ secrets.TEAMCITY_APPROVAL_TOKEN }} + run: node .github/scripts/teamcity-approval.js