-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path__test-workflow-docker-build-images.yml
More file actions
402 lines (350 loc) · 15.3 KB
/
Copy path__test-workflow-docker-build-images.yml
File metadata and controls
402 lines (350 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
---
name: Test for "docker-build-images" workflow
run-name: Test for "docker-build-images" workflow
on: # yamllint disable-line rule:truthy
workflow_call:
permissions:
contents: read
issues: read
packages: write
pull-requests: read
id-token: write
# jscpd:ignore-start
jobs:
arrange:
name: Arrange
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.define-matrix.outputs.result }}
steps:
- run: |
if [ -z "${{ secrets.GITHUB_TOKEN }}" ]; then
echo "GitHub token secret is not set"
exit 1
fi
- id: define-matrix
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
result-encoding: json
script: |
let imageNamePrefix;
if (context.eventName === "pull_request") {
const pullRequestNumber = context.payload.pull_request?.number;
if (!pullRequestNumber) {
throw new Error("Pull request number is not available in the event payload");
}
imageNamePrefix = `pr-${pullRequestNumber}`;
} else {
imageNamePrefix = process.env.GITHUB_REF_NAME;
if (!imageNamePrefix) {
throw new Error("GITHUB_REF_NAME environment variable is not set");
}
}
imageNamePrefix = `test-${imageNamePrefix}-${context.runNumber}`.replace(/\//g, "-");
const tag = '0.1.0';
const matrix = {
include: [
{
name: "mono-arch - signed",
"image-name": `${imageNamePrefix}-mono-arch-signed`,
platforms: '["linux/amd64"]',
sign: true,
tag
},
{
name: "multi-arch - signed",
"image-name": `${imageNamePrefix}-multi-arch-signed`,
platforms: '["linux/amd64","linux/arm64"]',
sign: true,
tag
},
{
name: "mono-arch - unsigned",
"image-name": `${imageNamePrefix}-mono-arch-unsigned`,
platforms: '["linux/amd64"]',
sign: false,
tag
},
{
name: "multi-arch - unsigned",
"image-name": `${imageNamePrefix}-multi-arch-unsigned`,
platforms: '["linux/amd64","linux/arm64"]',
sign: false,
tag
}
]
};
return matrix;
act-build-images:
name: Act - Build images (${{ matrix.name }})
needs: arrange
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.arrange.outputs.matrix) }}
uses: ./.github/workflows/docker-build-images.yml
secrets:
oci-registry-password: ${{ secrets.GITHUB_TOKEN }}
build-secret-github-app-key: ${{ secrets.CI_BOT_APP_PRIVATE_KEY }}
with:
sign: ${{ matrix.sign }}
images: |
[
{
"name": "${{ matrix.image-name }}",
"context": ".",
"dockerfile": "./tests/application/Dockerfile",
"build-args": { "BUILD_RUN_ID": "${{ github.run_id }}" },
"target": "base",
"platforms": ${{ matrix.platforms }},
"tag": "${{ matrix.tag }}"
}
]
assert-images-versions:
name: Assert - Published images (${{ matrix.name }})
needs: [arrange, act-build-images]
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.arrange.outputs.matrix) }}
steps:
- name: Login to GitHub Container Registry
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ github.token }}
- name: Verify image exists
env:
IMAGE_NAME: "${{ matrix.image-name }}:${{ matrix.tag }}"
run: |
docker pull ghcr.io/hoverkraft-tech/ci-github-container/"${IMAGE_NAME}"
- name: Verify package has correct number of versions
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
IMAGE_NAME: ${{ matrix.image-name }}
SIGN: ${{ matrix.sign }}
PLATFORMS: ${{ matrix.platforms }}
with:
script: |
const assert = require("assert");
const versions = await github.paginate(
github.rest.packages.getAllPackageVersionsForPackageOwnedByOrg,
{
package_type: "container",
package_name: `ci-github-container/${process.env.IMAGE_NAME}`,
org: `${{ github.repository_owner }}`,
per_page: 100
}
);
const totalCount = versions.length;
const taggedVersions = versions.filter(version => version.metadata.container.tags.length > 0);
const untaggedVersions = versions.filter(version => version.metadata.container.tags.length === 0);
const platforms = JSON.parse(process.env.PLATFORMS);
const isSinglePlatform = platforms.length === 1;
const isSigned = process.env.SIGN === 'true';
// Expected tagged versions:
// - Always 1 for the main tag
// - Plus 1 for cosign legacy tag (sha256-...) when signed
// Note: ghcr.io doesn't support OCI 1.1 referrers yet, so cosign falls back to legacy attachments
const expectedTaggedVersions = isSigned ? 2 : 1;
// Expected untagged versions:
// - For single platform: 0 (no untagged versions when optimized)
// - For multi platform: number of platforms (one per platform digest-only push)
const expectedUntaggedVersions = isSinglePlatform ? 0 : platforms.length;
assert.equal(
taggedVersions.length,
expectedTaggedVersions,
`Expected ${expectedTaggedVersions} tagged versions, but found ${taggedVersions.length}: ${JSON.stringify(taggedVersions, null, 2)}`
);
assert.equal(
untaggedVersions.length,
expectedUntaggedVersions,
`Expected ${expectedUntaggedVersions} untagged versions, but found ${untaggedVersions.length}: ${JSON.stringify(untaggedVersions, null, 2)}`
);
- name: Verify image manifest and platforms
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
IMAGE_NAME: "${{ matrix.image-name }}:${{ matrix.tag }}"
EXPECTED_PLATFORMS: ${{ matrix.platforms }}
with:
script: |
const assert = require("assert");
const imageName = process.env.IMAGE_NAME;
const image = `ghcr.io/hoverkraft-tech/ci-github-container/${imageName}`;
const { exitCode, stdout, stderr } = await exec.getExecOutput('docker', ['manifest', 'inspect', '-v', image]);
if (exitCode !== 0 || stderr) {
throw new Error(`Failed to inspect manifest for image: ${image}: ${stderr || stdout}`);
}
const manifest = JSON.parse(stdout);
const expectedPlatforms = JSON.parse(process.env.EXPECTED_PLATFORMS);
const expectedPlatformCount = expectedPlatforms.length;
assert.equal(manifest.length, expectedPlatformCount, `Expected ${expectedPlatformCount} platforms, got: ${manifest.length}`);
expectedPlatforms.forEach(platformStr => {
const [os, arch] = platformStr.split('/');
const platformExists = manifest.some(
platform => (
platform?.Descriptor?.platform?.architecture === arch &&
platform?.Descriptor?.platform?.os === os
)
);
assert(platformExists, `Expected platform not found: ${platformStr}`);
});
assert-images-signature:
name: Assert - Images signature (${{ matrix.name }})
needs: [arrange, act-build-images]
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.arrange.outputs.matrix) }}
steps:
- name: Install cosign
if: matrix.sign
uses: sigstore/cosign-installer@faadad0cce49287aee09b3a48701e75088a2c6ad # v4.0.0
- name: Verify image signature
if: matrix.sign
env:
SHOULD_HAVE_SIGNATURE: ${{ matrix.sign }}
IMAGE_NAME: "${{ matrix.image-name }}:${{ matrix.tag }}"
run: |
if [ "${SHOULD_HAVE_SIGNATURE}" = "true" ]; then
echo "Verifying signature for image: ${IMAGE_NAME}"
cosign verify \
--certificate-oidc-issuer https://token.actions.githubusercontent.com \
--certificate-identity-regexp https://github.com/hoverkraft-tech/ci-github-container \
ghcr.io/hoverkraft-tech/ci-github-container/"${IMAGE_NAME}"
exit $?
fi
echo "Image ${IMAGE_NAME} should not have a signature"
if cosign verify \
--certificate-oidc-issuer https://token.actions.githubusercontent.com \
--certificate-identity-regexp https://github.com/hoverkraft-tech/ci-github-container \
ghcr.io/hoverkraft-tech/ci-github-container/"${IMAGE_NAME}"; then
echo "::error::Image ${IMAGE_NAME} should not be signed but signature verification succeeded"
exit 1
fi
echo "Signature verification failed as expected for unsigned image ${IMAGE_NAME}"
cleanup:
name: Cleanup ephemeral test packages
runs-on: ubuntu-latest
if: always()
needs:
- arrange
- assert-images-versions
- assert-images-signature
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.arrange.outputs.matrix) }}
steps:
- name: Delete ephemeral test packages
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
IMAGE_NAME: ${{ matrix.image-name }}
run: |
gh api \
--method DELETE \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
/orgs/${{ github.repository_owner }}/packages/container/ci-github-container%2F"${IMAGE_NAME}" || echo "No ${IMAGE_NAME} package to delete"
act-build-args-secrets-and-registry-caching:
name: Act - Build with args, secrets and registry caching
needs: arrange
uses: ./.github/workflows/docker-build-images.yml
secrets:
oci-registry-password: ${{ secrets.GITHUB_TOKEN }}
build-secrets: |
SECRET_TEST=test-secret
SECRET_ANOTHER_TEST=another-test-secret
build-secret-github-app-key: ${{ secrets.CI_BOT_APP_PRIVATE_KEY }}
with:
cache-type: registry
images: |
[
{
"name": "test-build-args-secrets",
"context": ".",
"target": "test",
"dockerfile": "./tests/application/Dockerfile",
"platforms": ["linux/amd64","linux/arm64"],
"build-args": {
"BUILD_RUN_ID": "${{ github.run_id }}",
"BUILD_ARG_TEST": "test-arg",
"BUILD_ARG_ANOTHER_TEST": "another-test-arg"
},
"secret-envs": {
"SECRET_ENV_TEST": "GITHUB_ACTION",
"SECRET_ENV_ANOTHER_TEST": "GITHUB_JOB"
}
}
]
build-secret-github-app-id: ${{ vars.CI_BOT_APP_ID }}
build-secret-github-app-token-env: |
SECRET_ENV_GITHUB_APP_TOKEN_1
SECRET_ENV_GITHUB_APP_TOKEN_2
assert-build-args-secrets-and-registry-caching:
name: Assert - Build with args, secrets and registry caching
needs: act-build-args-secrets-and-registry-caching
runs-on: "ubuntu-latest"
steps:
- name: Check built images ouput
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
const assert = require("assert");
const builtImagesOutput = `${{ needs.act-build-args-secrets-and-registry-caching.outputs.built-images }}`;
assert(builtImagesOutput.length, `"built-images" output is empty`);
// Check if is valid Json
let builtImages = null;
try {
builtImages = JSON.parse(builtImagesOutput);
} catch (error) {
throw new Error(`"built-images" output is not a valid JSON: ${error}`);
}
const expectedCreatedImages = [
"test-build-args-secrets"
];
assert(typeof builtImages === "object" && !Array.isArray(builtImages), `"built-images" output is not an object`);
assert.equal(Object.keys(builtImages).length, expectedCreatedImages.length, `"built-images" output does not contain ${expectedCreatedImages.length} images`);
for (const image of expectedCreatedImages) {
assert(builtImages[image], `"built-images" output does not contain "${image}" image`);
}
- uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ github.token }}
- name: Check docker image and cache
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
const assert = require("assert");
let expectedTag;
const isPullRequest = `${{ github.event_name }}` === "pull_request";
if (isPullRequest) {
const shortSha = `${{ github.sha }}`.substring(0, 7);
expectedTag = `pr-${{ github.event.pull_request.number }}-${shortSha}`;
} else {
expectedTag = `${{ github.ref_name }}`;
}
const digest = `${{ fromJson(needs.act-build-args-secrets-and-registry-caching.outputs.built-images).test-build-args-secrets.digest }}`;
assert(digest.length, `"built-images" output does not contain digest for "test-build-args-secrets" image`);
assert.match(digest, /^sha256:[0-9a-f]{64}$/, `"built-images" output does not contain valid digest for "test-build-args-secrets" image`);
const expectedImage = `ghcr.io/hoverkraft-tech/ci-github-container/test-build-args-secrets`;
const expectedImageTag = `${expectedImage}:${expectedTag}@${digest}`;
const image = `${{ fromJson(needs.act-build-args-secrets-and-registry-caching.outputs.built-images).test-build-args-secrets.images[0] }}`;
assert.equal(image, expectedImageTag, `"built-images" output is not valid. Expected "${expectedImage}", got "${image}"`);
await exec.exec('docker', ['pull', image]);
let expectedCacheTag;
if (isPullRequest) {
expectedCacheTag = `pr-${{ github.event.pull_request.number }}`;
} else {
expectedCacheTag = `${{ github.ref_name }}`;
}
const cacheImage = `${expectedImage}/cache:${expectedCacheTag}`;
const cacheImages = [
`${cacheImage}-linux-arm64`,
`${cacheImage}-linux-amd64`
];
for (const cacheImage of cacheImages) {
await exec.exec('docker', ['manifest', 'inspect', cacheImage]);
}
# jscpd:ignore-end