chore: publish IntegraCI build modules 732ec6c83925
This commit is contained in:
1 parent
7a84930dea
commit
5f8a24d014
133 files changed
+18990
-2
No files matched your search
@@ -0,0 +1 @@
|
||||
732ec6c83925
|
||||
@@ -1,3 +1,200 @@
|
||||
# integraci-dagger-modules
|
||||
# Dagger modules
|
||||
|
||||
IntegraCI build modules — published by the platform, upgraded in place
|
||||
The build/scan/deploy logic every CI engine calls. A template renders a
|
||||
`dagger call --mod=<base>/<module> <function> --flag=…`, and that indirection is
|
||||
what makes seven CI engines run the same code.
|
||||
|
||||
Two things follow from it, and both were unchecked until 2026-08-21.
|
||||
|
||||
## The contract gate
|
||||
|
||||
`tools/scripts/check-dagger-contracts.py` reads every module's `main.go` and
|
||||
every `*.j2` under `catalog/templates/`, then asserts that each template's call
|
||||
resolves: the module exists, the function exists, and **every flag it passes is
|
||||
declared by that function's signature**.
|
||||
|
||||
The flag half is new. Before it, the gate resolved names and stopped, so a
|
||||
template passing `--totally-bogus-flag=x` still printed
|
||||
`539 template dagger calls resolve` — measured, not supposed. A misspelt flag
|
||||
fails at the very end of a release, inside the customer's repository.
|
||||
|
||||
Dagger derives a flag from the Go parameter name (`registryUser` →
|
||||
`--registry-user`), so the declared set is readable straight from the signature.
|
||||
|
||||
`_KNOWN_BAD_FLAGS` pins mismatches that are real defects awaiting their own fix.
|
||||
It may only shrink, and a pin whose flag the module later declares fails the
|
||||
test rather than lingering.
|
||||
|
||||
## What the gate does NOT check: argument VALUES
|
||||
|
||||
It validates that `--language` exists. It cannot tell you that the value is one
|
||||
the module accepts.
|
||||
|
||||
`standard-build build` switches on `language` and supports exactly four:
|
||||
|
||||
go · python · node · php
|
||||
|
||||
Everything else falls to
|
||||
`return nil, fmt.Errorf("unsupported language: %s …")`. Counted across the
|
||||
templates today:
|
||||
|
||||
| language | invocations | `standard-build` supports it |
|
||||
|---|---:|---|
|
||||
| go | 7 | yes |
|
||||
| java | 7 | **no** — falls back to the repo Dockerfile |
|
||||
| node | 7 | yes |
|
||||
| python | 7 | yes |
|
||||
| php | 3 | yes |
|
||||
| `{{ jinja }}` | 2 | not statically knowable |
|
||||
| generic | 1 | **no** — falls back to the repo Dockerfile |
|
||||
|
||||
**8 of the 34** `standard-build` invocations name a language the switch does not
|
||||
implement, and both fall through to `buildFromDockerfile`. The seven `java` ones
|
||||
are `java-spring` across six engines (its Jenkinsfile calls twice); `generic` is
|
||||
`_default/.circleci`. Every affected golden-path skeleton ships a Dockerfile —
|
||||
checked, all seven — so the fallback has something to build.
|
||||
|
||||
### Count these PER MODULE, not per repo
|
||||
|
||||
An earlier revision of this file claimed **22 of 65** invocations passed a
|
||||
rejected language, `java` alone being 13. Both numbers came from grepping
|
||||
`--language=` across `catalog/templates` and attributing every hit to
|
||||
`standard-build`. It is not the only module that takes that flag:
|
||||
|
||||
| module receiving `--language=` | invocations |
|
||||
|---|---:|
|
||||
| `standard-build` | 34 |
|
||||
| **`sast-scan`** | **23** |
|
||||
| not statically attributable | 10 |
|
||||
|
||||
`sast-scan` has its own language handling, so its 23 hits cannot "pass a language
|
||||
`standard-build` rejects" — they were never `standard-build` calls. That is where
|
||||
`java 13` came from: 7 real ones plus 5 belonging to `sast-scan` plus 1
|
||||
unattributable.
|
||||
|
||||
The 10 unattributable ones are the single-line call form
|
||||
(`--mod=<base>/<module> <function> --flags`), which the contract gate's
|
||||
`_MOD_FLAG_RE` also cannot read because it anchors the module at end of line.
|
||||
Any count of this kind is only as good as its attribution: a repo-wide grep for a
|
||||
flag two modules share measures neither.
|
||||
|
||||
This is not something a contract gate can catch by reading signatures: the valid
|
||||
set lives inside a `switch`, not in the parameter list. Closing it means either
|
||||
teaching `standard-build` the missing languages or repointing those templates at
|
||||
a module that handles them, and it is a large enough decision to want its own
|
||||
review rather than a quiet patch.
|
||||
|
||||
## Vetting
|
||||
|
||||
23 of the 26 modules have no `go.mod` — the SDK generates it, with
|
||||
`internal/dagger`, at `dagger develop` time. `go vet` cannot resolve them in a
|
||||
clean checkout, so `tools/ci/go-vet-modules.sh` vets the modules that do have
|
||||
one and reports the rest by name rather than dropping them silently.
|
||||
|
||||
That script exists because the previous hook (`mirrors-golang`'s `go-vet`)
|
||||
invoked `go vet` from the repository root, which has no `go.mod`, so every run
|
||||
failed for every path in its scope — `apps/cli` included, which is a real Go
|
||||
binary with its own module. It never vetted anything.
|
||||
|
||||
## Supply-chain evidence (#2143 phase 1, ADR-0068)
|
||||
|
||||
`standard-build build` reports `image_digest` beside `image_ref`, on both the
|
||||
TLS (`Publish`) and plain-HTTP (crane) push paths. `standard-build evidence`
|
||||
takes that digest-pinned reference and writes one directory:
|
||||
|
||||
| file | content |
|
||||
|---|---|
|
||||
| `sbom.cdx.json` / `sbom.spdx.json` | SBOM of the image (syft, same pin as the `sbom` module) |
|
||||
| `provenance.intoto.json` | in-toto Statement, SLSA v1 provenance, subject = the image digest |
|
||||
| `SHA256SUMS` | `sha256sum -c` manifest over the two files above |
|
||||
|
||||
A tag is refused, not resolved: a statement about a tag says nothing about the
|
||||
bytes that get deployed. The statement is unsigned evidence; attach it with
|
||||
`cosign attest-provenance --predicate evidence/provenance.intoto.json`, which
|
||||
refuses a statement whose subject is not `--image`'s digest, and
|
||||
`cosign attest-sbom` for the SBOM; both attest functions refuse a tag-only
|
||||
`--image`. The logic lives in stdlib-only packages
|
||||
(`standard-build/evidence/`, `cosign/attestation/`) so it runs under plain
|
||||
`go test`.
|
||||
|
||||
## Supply-chain stages in the rendered pipelines (#2143 phase 2)
|
||||
|
||||
All of these are OFF by default. With no switch set, the rendered pipelines
|
||||
are byte-identical to before. They are opted in through `spec.pipeline.overrides`.
|
||||
|
||||
| switch | adds | implies |
|
||||
|---|---|---|
|
||||
| `supply_chain_evidence: on` | `standard-build evidence` for the published digest, archived as `integraci-evidence/**` | |
|
||||
| `evidence_signing: on` | `cosign sign-blob` over `SHA256SUMS` → `SHA256SUMS.sig` + `.bundle` | evidence |
|
||||
| `provenance_attestation: on` | `cosign attest-provenance --predicate` on the digest | evidence |
|
||||
| `attestation_gate: on` | `cosign verify-attestation-gate`: fails the build when the OPA policy denies | attestation |
|
||||
| `scan_sarif: on` | `security-scan sarif`, `secret-scan sarif` (gitleaks, `--redact`), `sast-scan sarif` (semgrep/codeql), archived as `integraci-sarif/*.sarif` | |
|
||||
|
||||
- **Keyed by digest.** The Build stage chains `image-ref` (digest-pinned when
|
||||
the push reports a digest) into `.integraci-image-ref`. Every later step
|
||||
re-reads that file and refuses anything that is not `@sha256:<64 hex>`.
|
||||
Nothing resolves the tag again.
|
||||
- **Wired into the Jenkins templates only.** These are the six whose Build
|
||||
stage publishes through `standard-build`: `_default`, go-microservice,
|
||||
java-spring, node-nextjs, php-laravel and python-fastapi. The `_default`
|
||||
GitHub Actions and GitLab templates call `build` without the required
|
||||
`--language` and push with `docker push`, so no digest comes out of them.
|
||||
Fix that first.
|
||||
- **Credentials.** Jenkins string credentials: the signing key is
|
||||
`signing_credential_id` (default `cosign-key`, the one the Sign stage
|
||||
already names). The gate's public key is `cosign_public_key_credential`
|
||||
(default `cosign-pub`). The key must have an empty password: the stages
|
||||
set `COSIGN_PASSWORD=""` and bind no password credential.
|
||||
- **Main only for the key.** Evidence runs for every publishing build except
|
||||
`uat_pr`. Sign-blob, attest and the gate run in a separate stage limited to
|
||||
`branch 'main'` and never for a `*_pr` build, like the Sign stage.
|
||||
- **Bound to the pushed name.** Every step also checks that the recorded ref
|
||||
is `${IMAGE_NAME}:${INTEGRACI_IMAGE_TAG}@sha256:…`. The file sits in the
|
||||
checkout, so a committed one must not be able to redirect the registry
|
||||
credential or get a foreign digest signed.
|
||||
- **Signed SHA256SUMS.** Verify with
|
||||
`cosign verify-blob --insecure-ignore-tlog=true --key cosign.pub --signature SHA256SUMS.sig --bundle SHA256SUMS.bundle SHA256SUMS`
|
||||
(drop `--insecure-ignore-tlog` when the pipeline opted into a Rekor), then
|
||||
`sha256sum -c --strict SHA256SUMS`.
|
||||
- **No public Rekor unless asked for** (owner decision 2026-10-11). Keyed
|
||||
signing does not upload to a transparency log by default, so an air-gapped
|
||||
build can sign. An entry in the public log would publish the provenance
|
||||
itself (registry and git hosts, repository paths, the Jenkins job URL, the
|
||||
commit) permanently. Opt in per pipeline with `rekor_public_upload`, or name
|
||||
a private Rekor with `rekor_url`; the signing steps and the gate get the same
|
||||
choice. See `cosign/README.md` "Transparency log".
|
||||
- **The gate.** cosign verifies the signatures, then
|
||||
`infra/policies/bundles/attestation-gate` judges the decoded statements:
|
||||
subject = this digest, SLSA v1, `builder.id` exactly trusted, a full commit
|
||||
pinned, and an SBOM when required. A copy of the policy is embedded in the
|
||||
cosign module (`cosign/policy/`) and kept byte-identical by a test. In CI the
|
||||
trusted builder is this job (`$JOB_URL`). That proves the signing and
|
||||
attaching worked. It is not a promotion-time control, because the job that
|
||||
signs is the job that is trusted. Verifying at promotion against
|
||||
platform-held trust is still to do.
|
||||
|
||||
Not yet: the same stages for the non-Jenkins engines and the stack templates
|
||||
that do not publish, signing the mirror `SHA256SUMS` (needs a platform signing
|
||||
key, see below), promotion-time verification in the deploy gate, the
|
||||
render-only fallback, and the rootless/runner matrix.
|
||||
|
||||
## Air-gapped mirror
|
||||
|
||||
The modules reach a tenant through `dagger_mirror.py`, which publishes this
|
||||
tree into the tenant's own Git server. It now also publishes `SHA256SUMS` at the
|
||||
mirror root, computed at publish time over the published bytes, so a runner
|
||||
checks its clone with `sha256sum -c --strict SHA256SUMS`. That catches a
|
||||
corrupted or partial clone, NOT tampering: the file lives in the same tenant
|
||||
repository as the modules, so whoever can push there can recompute it, and
|
||||
`sha256sum -c` ignores files it does not list. It becomes tamper evidence only
|
||||
once something signs it. That needs a signing key the PLATFORM holds and whose
|
||||
public half tenants trust, and no such key exists yet (a product decision, not
|
||||
done in phase 2). Evidence `SHA256SUMS` is signable today with
|
||||
`cosign sign-blob`; see above.
|
||||
|
||||
Images are separate. `tools/scripts/dagger-mirror-manifest.py` prints the pinned
|
||||
engine image and every tool image the modules pass to `From`, and fails when the
|
||||
modules do not agree on one `engineVersion`. `tools/scripts/dagger-mirror-images.sh`
|
||||
copies them into the customer registry by digest, reads each one back, and
|
||||
writes a lock. Images computed at run time (`From(jdkImage(v))`) are listed as
|
||||
unresolved expressions, to be mirrored by hand.
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
aa28a5eac1a0c457a2198ff4acae99ccd5d1ac5ea514f0a03e6a2b6b331c4608 README.md
|
||||
d89e6c863cad31273b0fe3ac1d9a3cf867ffcfd8cb87348eff1621e663be7941 ai-code-review/README.md
|
||||
112df3860cbd14fc8848eb4628e2ebde35c2cadca27df029dc192b9b5301b03a ai-code-review/dagger.json
|
||||
0ebb5c0df751c535b0c5488f59206d86281384b5c9013853bbc5be504962aed4 ai-code-review/main.go
|
||||
953902568316691546842243cae8a109808d7fc211670542f1da4ae5e8cf2694 container-paas-deploy/README.md
|
||||
56af2fb43a7458d51381f45f45de9b2a461a4fd5469c3a1ad89e2c69a727b68f container-paas-deploy/dagger.json
|
||||
bf2a7cc0471112aeaac0bddd350cbb67bb12fa976cf209c7d9d135319e400650 container-paas-deploy/main.go
|
||||
115bdb4588a756d0090e73334a6fc5f2dc50a11e5075cf9c382d0a88eca86a24 contract-test/.gitattributes
|
||||
35f95c7691a2e5e33ec7e3e0f203197cd120af831305add2a218b6c20353db8f contract-test/.gitignore
|
||||
1ecc9ca9c1a867e7c17483933d24ff92adb81cd8cdd39e9ed977245fdfa7bb11 contract-test/README.md
|
||||
6ff1cdc32ec7da60377a3005dbb3f03621958d934c3cfab85e161eea858a9b45 contract-test/dagger.json
|
||||
dbf3655286df516769e36aa7272d10ff0fafdd7a7159d1d54e029eed94256d81 contract-test/go.mod
|
||||
1e583b017d02bac9507c27d00dc36affc434571bfbfe8867ece775feccfec463 contract-test/go.sum
|
||||
e97b3de1b6f7261f88d2d79b36d4ef85ee56ef092182fd42c1a5d7e0b5c0bdad contract-test/main.go
|
||||
fa33a16031ad0ad65d8119981e5768b57164ede5b4db1c44a1c966d71fee4be2 cosign/README.md
|
||||
d3a754dc3a438984fe4610a7ff79ce373bfd4280d4377d9b2748adddff96b2f2 cosign/attestation/attestation.go
|
||||
fe0bf12fe19cc164e0ebd03bfbb28ba09d7f5aa7a2af03346b9005f6247b6163 cosign/attestation/attestation_test.go
|
||||
dc476bb7e89af327a748b7295d3cd383633cf6f835e7eaae17fcd51110735157 cosign/attestation/gate.go
|
||||
9f95de1a60db48bd38cc713a495d2e5045894a331b48ea1126ce8ac82a47be2b cosign/attestation/gate_test.go
|
||||
9ab4c5bf3f850f2cdd8ef52efb1b71f07be978480ee39d0d129fc6f506154102 cosign/attestation/tlog.go
|
||||
72701f946a2ac8b4486ceb845be3ccb588e8cd78b3a6811342d02ba82dd96231 cosign/attestation/tlog_test.go
|
||||
26be32bc776ba9621cc6a74680c05bbf2c2657680203f03e980a2587c9203fdf cosign/attestation/verify.go
|
||||
a1ae3a93b0eb28556c012ba18fda0c5c7daa93188f226e14e376d65759fe17c1 cosign/attestation/verify_test.go
|
||||
962b5076c1b29b6aa95cc4f474d2cac18ee12a7e988aee3ea6b4fb6ff6cc1f2e cosign/dagger.json
|
||||
570b307aaa8543c3d9dc48922e935027ee2320d87bc4dc31ec37914dd0cf6844 cosign/main.go
|
||||
901c3ac8cf91649c2bebeaf9abeaf9372ae7c998dc29ef64697058d46ade1051 cosign/policy/attestation_gate.rego
|
||||
2b69f6a327c02952411943153297a8d2d459dd59d9182bfdaae6b5d2b1dccf24 dast-scan/README.md
|
||||
968c74fec476a5d372eef77510a899146328fc8396d3e350552c5a7467636585 dast-scan/dagger.json
|
||||
36fc6e8b38779f524945b68c81b01ebc5572770946712510df5ab8579c24fdfe dast-scan/main.go
|
||||
115bdb4588a756d0090e73334a6fc5f2dc50a11e5075cf9c382d0a88eca86a24 db-migration/.gitattributes
|
||||
35f95c7691a2e5e33ec7e3e0f203197cd120af831305add2a218b6c20353db8f db-migration/.gitignore
|
||||
337f35bd196d4529c4b4019ff5b6d646ebad3567bdd9786166ffeb2f21d4ed93 db-migration/README.md
|
||||
709c33b07c8a98a9f1f331a0de62f01801ed68c7ef1cb4427ba0dddaff0f6e86 db-migration/dagger.json
|
||||
dd5b1d4ec8d5b5bd712952442afd30241ef5a6aaa313c577d3ef1e9a3fa1ab45 db-migration/engine/capabilities.json
|
||||
364beb9ae3d287a7f3ab6be76da158073efdbbe408080c10ab7c73f89d0eb81f db-migration/engine/engine.go
|
||||
c4929c95c9a239edc244a09e12a538c8bed9cc317b57180def9d712f466c544f db-migration/engine/engine_test.go
|
||||
f8016d0fc25ce29d83eaaeb7d3aff071e6c28c8a3c0b7b0475c6666b18cb152d db-migration/go.mod
|
||||
f425201947ed2d4a7366b785ce49aa8af415c2d4713c4bf1c074148d0181c056 db-migration/go.sum
|
||||
b308dc787788e830a87fde0eb0e16c52f1b263b3debb509cbd4dcb61dcc0bb41 db-migration/main.go
|
||||
e59d813e03f8f2f31afeeb96fdd9d19b29a1c8f8d1201eada860963d96432319 db-migration/verdict/applied.go
|
||||
f7b837618fe461968315147ecf92c7c6b57f3f6dc144e3c6fa7cd898dd52101a db-migration/verdict/applied_test.go
|
||||
1bb909b100951b8d8a890919481cbc8b373e92b06318d156dd4ed79bcb0859fe db-migration/verdict/directives.go
|
||||
4ac5473f6aab127afa0e004f421b2e5181b0429e46eb8f55514afdfb764a04b7 db-migration/verdict/directives_test.go
|
||||
ae4288677470705fb79f26a05d30469b954272c43d4a81be212d6e05cbc3c91f db-migration/verdict/execution.go
|
||||
5ef28723c759b7bff39279ea67d55105bea8ff5733b5006f6120cec2ef9115b0 db-migration/verdict/execution_test.go
|
||||
0879f89a63abb252f67e2f849b49be623ae8fbcbcdf5fd19f39912059f9f0743 db-migration/verdict/release_test.go
|
||||
89b56bd62823bb7e4bce2367030a82f89051d36a0144ef09a08bf9ffec47ccd3 db-migration/verdict/tools.go
|
||||
89ccfef13c16b30013a60c0a19b70c837b7c8e36c15ceb5a18bbe65ad5009360 db-migration/verdict/tools_test.go
|
||||
865d6de5b5504c9b684cce08a3ea6d6fc07950ed7fda6629140c72b5244ad198 db-migration/verdict/verdict.go
|
||||
e5cc829282064480917cf8a7846fd60de8c6b209df0f62fba978db9efa554872 db-migration/verdict/verdict_test.go
|
||||
8e0b52db96cadd078cd639f7f0501f8c0ba88d03012e281ab001e23276539d0f deploy-k8s/README.md
|
||||
4a9b2898f59cab5f2ddd71ff016462aa7134c66b32d17b5b0858703d22a726f1 deploy-k8s/dagger.json
|
||||
64bcc13f053ba830d922534279ec45b7fa18ffc2a9bd0df13452d13d39af0815 deploy-k8s/main.go
|
||||
115bdb4588a756d0090e73334a6fc5f2dc50a11e5075cf9c382d0a88eca86a24 e2e-test/.gitattributes
|
||||
35f95c7691a2e5e33ec7e3e0f203197cd120af831305add2a218b6c20353db8f e2e-test/.gitignore
|
||||
19858aace660db871f6a0b40d4a0bc1d1cd977d0fca44ae2388a8e407bb32490 e2e-test/README.md
|
||||
b614e9bdef898f34d7aa9bf82d5b8809f6fe4274cd059aaddf2a5af5de085410 e2e-test/dagger.json
|
||||
df34f8d683caa208edbc6d9878f775b097131e1b38be0544c2df9a6322bce6a1 e2e-test/go.mod
|
||||
1e583b017d02bac9507c27d00dc36affc434571bfbfe8867ece775feccfec463 e2e-test/go.sum
|
||||
fae1ce1efecdc12b8f3039f8f6dbd26e25cc0ebcce678c935aed989588437545 e2e-test/main.go
|
||||
4942f899802d862f8d66c32270150fd57ff5dde41188843ff133ceb537540e7c iac-scan/README.md
|
||||
33599562a94b863bc3ced0d4bac9becfa639ac1db5f2e5e8b18431a606d94654 iac-scan/dagger.json
|
||||
7a5635226597f47e21668b81e73508fd05473d7fba70ef81f5a7908160169fe5 iac-scan/main.go
|
||||
e6bd0de50d3dc45e9d5446c28b1249d3471c4a38c12bc23bc580d639d0e0e2b8 license-scan/README.md
|
||||
5348014cc6d56cccb668d0a507201b4dc2b5c9ea4f31e99a88a903c060375266 license-scan/dagger.json
|
||||
9abdc96226ab7150694be5bcde70a9be1008b906bb7f3f609bdb7e7e103847f6 license-scan/main.go
|
||||
58757ea49fa6ee753ab0187d0f94fb5f8bbd3294862330ffc569ad84c291c1d6 malware-scan/README.md
|
||||
a01305371eac283b32e57885ad04c624d42d46eea3fba6e17cb2434ba8d0bd75 malware-scan/dagger.json
|
||||
991b2ca316bc15089f8e8eb8633e52059eac4d77126dad638b3ec0363bfa4ea7 malware-scan/main.go
|
||||
216760c5154c216bbe668c8fac34067ae2b7f881c67da9594cf6515fa7f7f24a mobile-android/README.md
|
||||
2b08bdfeffda3b978a7d56887dfd59f54a6a56492f3092894c3d469d7fcb8fac mobile-android/dagger.json
|
||||
fe4bb56d5479abfce33b984bfbc234386f7847e93108d37543c6004d84d7c44d mobile-android/main.go
|
||||
40d57ac8f3ff98f55181d37295b2e140824b7dcb5aa64341c735763588722439 mobile-flutter/README.md
|
||||
00160c3a8cb4d70b4edbba4b4ff70ad94ade7e01a97d7642560c296a416154af mobile-flutter/dagger.json
|
||||
110f7fea48f166d4d6fdaa1f8ce02d67193a82b75a4bb8b48c7b00398b0ba971 mobile-flutter/main.go
|
||||
5d510d06d9e53b378cbca3f7fe54b96d66f6de0c02b8b054a00080a825212137 mobile-ios/README.md
|
||||
9e0cd0686a74f30d5f6d6563fe0aeb41b253b2f280df77db251dc6514e37a855 mobile-ios/dagger.json
|
||||
399134ece3e1db34369d16b014db467e602cf5da28709752acb7a97a134fd68f mobile-ios/main.go
|
||||
87f8081b4a9f4db6c0e8f88c7657d98c793ab95b991931c450e0c94869a1f2ef mobile-security-scan/README.md
|
||||
38db76f440af901337d6e14fd4324780e18f7faffddb4ca89012c9eaa8d2547c mobile-security-scan/dagger.json
|
||||
80770bd49be0b15bdd49c685153879dcf321624a86908f192b754a88d0f19fa2 mobile-security-scan/main.go
|
||||
ca50162a4bcf9d7d89a38560bc893997989487b416e8d399dd139235eb23f477 model-scan/README.md
|
||||
398a1764937829391271d6161d13fb8a07797c29f13ec88854ff53a49aa6c8a7 model-scan/dagger.json
|
||||
ef13e2d03862b8963e4040fbbdeca9642444cefab6fa4e8c7feee6f927458d3e model-scan/main.go
|
||||
115bdb4588a756d0090e73334a6fc5f2dc50a11e5075cf9c382d0a88eca86a24 perf-test/.gitattributes
|
||||
35f95c7691a2e5e33ec7e3e0f203197cd120af831305add2a218b6c20353db8f perf-test/.gitignore
|
||||
a3b0128b0294ba7ffd01ad4488849a1a2014af6999d212d2ceec7a6c1943e7f5 perf-test/README.md
|
||||
a4f93086fafd1e8b1b4fb20bc042e6bf2deffc188a65645e70663f986cfdf83c perf-test/dagger.json
|
||||
794718a5ad23894b33bb2c02fe211a2af28aeb6f6b6032e336830a402ddc316e perf-test/go.mod
|
||||
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 perf-test/go.sum
|
||||
d2928ffd6bcaf82b8f11810517e6839836f3d77caa644ab18da10b1120b055cd perf-test/main.go
|
||||
f9af9f765929bd93a22fef8041716fa496ff767f7e9f3643f1a16a963a33f46e release/README.md
|
||||
8c46148d2e026fd3c4fd2a7edbfc1d90fd118ae5388788ca7be7b93ed6d718cc release/dagger.json
|
||||
93df7b20d51c868a8fd931d345d4cb12c127b368594e3fcf17a52d59df3a0fac release/main.go
|
||||
bc72516d95ed1b7bcdced0c44851add60e50ddabb10deedac2a12efad979a6c7 sast-scan/README.md
|
||||
541774f2856c29b58e398b6372e13c0bf00708428dce145de5036bf5cccae856 sast-scan/dagger.json
|
||||
417571f8f7b301a967b1111623c6fcefec140c15dab453a4867bc2c97c18724d sast-scan/gate.go
|
||||
d59d142d4dd45fa8b88dbbeddc823b295837988d1e53697c33bb1d80aabc7b81 sast-scan/gate_test.go
|
||||
7c851f2052519be229cd129369489919a8c583f8069b1d13fe48ccdccf33cd08 sast-scan/main.go
|
||||
3f3393851222017215220595f0f5d64a1e3d80737359b5af68581570f0464fe7 sast-scan/qualitygate.go
|
||||
01049098cdd9eca7dbba403048d00375403d8bc908d463204e7b5373daa24da9 sast-scan/qualitygate_test.go
|
||||
f72d25aef761141e41677c02b260f0a6492a3ec529ca00056a5c02ddbfd96061 sbom/README.md
|
||||
43d00928ea6cefb68f805179aa8f8858889378d0c67b766462d7362ef2bc892e sbom/dagger.json
|
||||
0768796b1f0ac5d197a8c7834a32f5a818c2739e43f379ee2dc95cb15f488972 sbom/main.go
|
||||
66beccb4d75bf7f615aa68d657b81298067fb27a59ee76fce8a6fbf47685e7cb secret-scan/README.md
|
||||
37c26c209ef6347363573933d603ec08dfda91c28f46b83046aacf9967c9189b secret-scan/dagger.json
|
||||
dd4809b411a47584256cdafbc513ed2f9a1f2fe9c095381255ad8c8c008ada30 secret-scan/main.go
|
||||
e7b6c30c9fb134f75545152c1838eb50d1060c0c969b43b702e5bbb2091306c5 security-scan/README.md
|
||||
8e0ad6f1e72a05f68dcf8ba6d956869713b79003bd2efe14737b0ded2fb183ba security-scan/dagger.json
|
||||
c72e6ec4f2a20efbbcf0e04f46987d16370ceb99663c2906cc62b329bdd3524c security-scan/main.go
|
||||
9a828a3f0c429b665d9b9a99320cacee304b329dc8e53bb6d4e64507a78bf715 serverless-deploy/README.md
|
||||
98bd2388654407772054c4114547a6a184410ad1e70f8efe6643698659fda0a4 serverless-deploy/dagger.json
|
||||
9a7b016e9406f69492a4732ef2d488a5bed58d237be4ecc32b4917e181624772 serverless-deploy/main.go
|
||||
77a690b5ef474f62433b52894f32862221aad9da0cab9eddfff576fa1950c380 standard-build/README.md
|
||||
c89a76910e64e9d1b0b68a5a7cf9148a51ce5a0d936e0ae6e6d89d5cdbfb14d9 standard-build/dagger.json
|
||||
80c55b8d8cd15f03b8fef1b73df0121a28317caf8ee0832a2f86e3eb97cf5c8c standard-build/evidence/evidence.go
|
||||
93bc41eb64ca62dbc6360de24035f1f7340595d8b8b8cbe0fc7585d2d98c9287 standard-build/evidence/evidence_test.go
|
||||
132a82b01c10d7e3ac92413b163052222b23b7f845874136a6ff353be9f166a3 standard-build/layout/ignore.go
|
||||
47655a92bb52dc7f223e1e5e6bae6520138e83cb742455402170cd87add3522a standard-build/layout/ignore_test.go
|
||||
ae691a6a9f4fab2a0cc3a390f990b14feadb0e61a8990b6992a188b6c4823220 standard-build/layout/layout.go
|
||||
20649ea9d8ae7c860c4ac46efd931505e6cdfd4772e2a0496b7ca9b5db88b069 standard-build/layout/layout_test.go
|
||||
9688735098905b33d354dc8a6da916058c60daf78ebffeb6f72f8042254acd5d standard-build/main.go
|
||||
e5b67487536c147595d1dd23b1b32535de9f4f7b67511cffbde4fb5305432381 static-deploy/README.md
|
||||
0bc892038ac9fe670b0e6b09205d4ba2ca1a1fdb23d523b7112cc25f7a03207e static-deploy/dagger.json
|
||||
185d50220835de0a4fbcdffc127480f2fa15de9a9d7658a38cc8546b1b95c8d5 static-deploy/main.go
|
||||
dd3952beebba15befcf8003af5e7ce4d697dc8b4e4625cf98d3cfb57c92b41e9 vm-deploy/README.md
|
||||
952849148e922b51a3effdc684a3c2c1493f8fc681a9b84608bb7fd93e3f8442 vm-deploy/dagger.json
|
||||
94031f015b2acb852735f8188310f4403b10a7f824bdb8a5a3f8607894df407d vm-deploy/main.go
|
||||
b361683cbf5421743196df5d096e692c3f82a0fbd71efddd9f779340633bf77b windows-deploy/README.md
|
||||
f57de9c93375770e8b31dc4cd0c2fc2f5518736ef664ac7c910ab99285b05845 windows-deploy/dagger.json
|
||||
942d2bc371b1f198e389cdfaddacfcf696d8c8e5e826b039e4eb1861d79d931d windows-deploy/main.go
|
||||
@@ -0,0 +1,17 @@
|
||||
# IntegraCI — AI Code Review Dagger Module
|
||||
|
||||
Runs AI-assisted code review on pull-request diffs via the IntegraCI agent.
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
dagger call review \
|
||||
--source . \
|
||||
--base-branch main \
|
||||
--api-url http://localhost:8000 \
|
||||
--token $INTEGRACI_TOKEN
|
||||
```
|
||||
|
||||
## Functions
|
||||
|
||||
- `review` — snapshot diff, send to agent, optionally post PR comment
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "ai-code-review",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
// Package main implements the IntegraCI ai-code-review Dagger module.
|
||||
//
|
||||
// This module is invoked from CI pipelines (Tekton/Argo Workflows) on every
|
||||
// pull request. It runs three steps:
|
||||
//
|
||||
// 1. Snapshot the diff (`git diff origin/<base>..HEAD`) into a JSON envelope.
|
||||
// 2. Send the envelope to the IntegraCI agent through `/api/v1/agent/sessions`
|
||||
// using the `code_review` persona; the agent returns a structured Markdown
|
||||
// review with risk highlights, suggested fixes, and citations to existing
|
||||
// scan / scorecard data.
|
||||
// 3. Optionally post the resulting Markdown back as a PR/MR comment via the
|
||||
// IntegraCI code-review service (`/api/v1/webhooks/code-review`).
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call review \
|
||||
// --source . \
|
||||
// --base origin/main \
|
||||
// --service-id $SVC \
|
||||
// --api-url http://localhost:8000 \
|
||||
// --token $JWT \
|
||||
// --post-comment=true \
|
||||
// --pr-number 42 \
|
||||
// --repo "org/repo"
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"dagger/ai-code-review/internal/dagger"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AiCodeReview is the IntegraCI AI-driven code review module.
|
||||
type AiCodeReview struct{}
|
||||
|
||||
// ReviewResult summarises one AI code review run.
|
||||
type ReviewResult struct {
|
||||
SessionID string `json:"session_id"`
|
||||
AssistantMessage string `json:"assistant_message"`
|
||||
ToolCalls int `json:"tool_calls"`
|
||||
DiffLines int `json:"diff_lines"`
|
||||
FilesChanged int `json:"files_changed"`
|
||||
CommentPosted bool `json:"comment_posted"`
|
||||
DurationSeconds int `json:"duration_seconds"`
|
||||
Success bool `json:"success"`
|
||||
ErrorMessage string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Review runs an AI code review against a pull request diff.
|
||||
func (m *AiCodeReview) Review(
|
||||
ctx context.Context,
|
||||
// Source directory of the workspace (must be a git repo)
|
||||
source *dagger.Directory,
|
||||
// Base branch / SHA to diff against
|
||||
// +optional
|
||||
base string,
|
||||
// IntegraCI service id this review attaches to
|
||||
// +optional
|
||||
serviceID string,
|
||||
// IntegraCI API URL
|
||||
apiURL string,
|
||||
// JWT token
|
||||
token *dagger.Secret,
|
||||
// When true, posts the Markdown review back to the PR/MR
|
||||
// +optional
|
||||
postComment bool,
|
||||
// PR number (GitHub) or MR IID (GitLab) — required when postComment=true
|
||||
// +optional
|
||||
prNumber int,
|
||||
// Repository slug, e.g. "org/repo"
|
||||
// +optional
|
||||
repo string,
|
||||
) (*ReviewResult, error) {
|
||||
if base == "" {
|
||||
base = "origin/main"
|
||||
}
|
||||
start := time.Now()
|
||||
result := &ReviewResult{}
|
||||
|
||||
// 1. compute diff stats inside a Git container so we don't depend on the
|
||||
// host's git installation.
|
||||
gitImage := dag.Container().
|
||||
From("alpine/git:2.45.2").
|
||||
WithDirectory("/repo", source).
|
||||
WithWorkdir("/repo").
|
||||
WithExec([]string{"sh", "-c", "git config --global --add safe.directory /repo"})
|
||||
|
||||
diff, err := gitImage.
|
||||
WithExec([]string{"sh", "-c", fmt.Sprintf("git diff --stat %s..HEAD || true", base)}).
|
||||
Stdout(ctx)
|
||||
if err != nil {
|
||||
result.ErrorMessage = "git diff failed: " + err.Error()
|
||||
return result, err
|
||||
}
|
||||
result.FilesChanged = strings.Count(diff, "\n |")
|
||||
patch, err := gitImage.
|
||||
WithExec([]string{"sh", "-c", fmt.Sprintf("git diff %s..HEAD || true", base)}).
|
||||
Stdout(ctx)
|
||||
if err != nil {
|
||||
result.ErrorMessage = "git diff -p failed: " + err.Error()
|
||||
return result, err
|
||||
}
|
||||
result.DiffLines = strings.Count(patch, "\n")
|
||||
|
||||
// 2. ask the IntegraCI agent for a code review.
|
||||
envelope := map[string]any{
|
||||
"persona": "code_review",
|
||||
"title": fmt.Sprintf("PR review @ %s", time.Now().Format("2006-01-02 15:04")),
|
||||
}
|
||||
envelopeBody, _ := json.Marshal(envelope)
|
||||
// Token is injected as a secret env var ($API_TOKEN), never interpolated
|
||||
// into argv, so it is redacted in the Dagger op graph / logs / cache.
|
||||
curl := dag.Container().
|
||||
From("curlimages/curl:8.10.1").
|
||||
WithSecretVariable("API_TOKEN", token).
|
||||
WithEnvVariable("CACHEBUST", time.Now().String())
|
||||
|
||||
createSessOut, err := curl.
|
||||
WithNewFile("/tmp/session.json", string(envelopeBody)).
|
||||
WithExec([]string{
|
||||
"sh", "-c",
|
||||
"curl -fsS -X POST " +
|
||||
"-H 'Content-Type: application/json' " +
|
||||
"-H \"Authorization: Bearer ${API_TOKEN}\" " +
|
||||
"--data-binary @/tmp/session.json " +
|
||||
"'" + fmt.Sprintf("%s/api/v1/agent/sessions", strings.TrimRight(apiURL, "/")) + "'",
|
||||
}).Stdout(ctx)
|
||||
if err != nil {
|
||||
result.ErrorMessage = "create session failed: " + err.Error()
|
||||
return result, err
|
||||
}
|
||||
sess := struct {
|
||||
ID string `json:"id"`
|
||||
}{}
|
||||
_ = json.Unmarshal([]byte(createSessOut), &sess)
|
||||
result.SessionID = sess.ID
|
||||
|
||||
if patch == "" {
|
||||
patch = "(no diff against " + base + ")"
|
||||
}
|
||||
if len(patch) > 12000 {
|
||||
patch = patch[:12000] + "\n...[truncated]"
|
||||
}
|
||||
prompt := fmt.Sprintf(
|
||||
"Review this pull request diff. Focus on:\n"+
|
||||
"1. Security issues (auth, secrets, injection).\n"+
|
||||
"2. Reliability (error handling, timeouts).\n"+
|
||||
"3. Maintainability (clarity, tests, naming).\n\n"+
|
||||
"Service id: %s\n"+
|
||||
"Files changed: %d\n"+
|
||||
"Diff:\n```diff\n%s\n```",
|
||||
serviceID, result.FilesChanged, patch,
|
||||
)
|
||||
msgBody, _ := json.Marshal(map[string]any{"content": prompt})
|
||||
msgOut, err := curl.
|
||||
WithNewFile("/tmp/message.json", string(msgBody)).
|
||||
WithExec([]string{
|
||||
"sh", "-c",
|
||||
"curl -fsS -X POST " +
|
||||
"-H 'Content-Type: application/json' " +
|
||||
"-H \"Authorization: Bearer ${API_TOKEN}\" " +
|
||||
"--data-binary @/tmp/message.json " +
|
||||
"'" + fmt.Sprintf("%s/api/v1/agent/sessions/%s/messages",
|
||||
strings.TrimRight(apiURL, "/"), sess.ID) + "'",
|
||||
}).Stdout(ctx)
|
||||
if err != nil {
|
||||
result.ErrorMessage = "agent message failed: " + err.Error()
|
||||
return result, err
|
||||
}
|
||||
reply := struct {
|
||||
AssistantMessage struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"assistant_message"`
|
||||
ToolMessages []any `json:"tool_messages"`
|
||||
}{}
|
||||
_ = json.Unmarshal([]byte(msgOut), &reply)
|
||||
result.AssistantMessage = reply.AssistantMessage.Content
|
||||
result.ToolCalls = len(reply.ToolMessages)
|
||||
|
||||
// 3. post the review back as a PR/MR comment via the existing webhook.
|
||||
if postComment && prNumber > 0 && repo != "" {
|
||||
commentBody := strings.Builder{}
|
||||
commentBody.WriteString("<!-- integraci-ai-review -->\n")
|
||||
commentBody.WriteString("## IntegraCI AI Code Review\n\n")
|
||||
commentBody.WriteString(reply.AssistantMessage.Content)
|
||||
commentBody.WriteString("\n\n*Generated by IntegraCI Phase 7 agent.*")
|
||||
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"repo": repo,
|
||||
"pr_number": prNumber,
|
||||
"comment": commentBody.String(),
|
||||
"service_id": serviceID,
|
||||
"source": "ai_code_review",
|
||||
})
|
||||
_, err := curl.
|
||||
WithNewFile("/tmp/comment.json", string(body)).
|
||||
WithExec([]string{
|
||||
"sh", "-c",
|
||||
"curl -fsS -X POST " +
|
||||
"-H 'Content-Type: application/json' " +
|
||||
"-H \"Authorization: Bearer ${API_TOKEN}\" " +
|
||||
"--data-binary @/tmp/comment.json " +
|
||||
"'" + fmt.Sprintf("%s/api/v1/webhooks/ai-code-review",
|
||||
strings.TrimRight(apiURL, "/")) + "'",
|
||||
}).Stdout(ctx)
|
||||
result.CommentPosted = err == nil
|
||||
}
|
||||
|
||||
result.DurationSeconds = int(time.Since(start).Seconds())
|
||||
result.Success = result.AssistantMessage != ""
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
# IntegraCI — Container PaaS Deploy Dagger Module
|
||||
|
||||
Deploy containerised services to non-K8s PaaS targets.
|
||||
|
||||
## Targets
|
||||
|
||||
- Google Cloud Run
|
||||
- AWS ECS Fargate
|
||||
- AWS App Runner
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
dagger call deploy \
|
||||
--image ghcr.io/org/svc:1.2.3 \
|
||||
--target cloudrun \
|
||||
--project my-project
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "container-paas-deploy",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// Package main implements the IntegraCI container-paas-deploy Dagger module.
|
||||
//
|
||||
// Targets:
|
||||
// - Google Cloud Run
|
||||
// - AWS ECS Fargate (via aws ecs update-service)
|
||||
// - AWS App Runner
|
||||
//
|
||||
// Use this when a service is already containerised but the deployment target
|
||||
// is *not* Kubernetes. ArgoCD remains the K8s path; this module is the
|
||||
// non-K8s container PaaS path.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"dagger/container-paas-deploy/internal/dagger"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type ContainerPaasDeploy struct{}
|
||||
|
||||
type PaasResult struct {
|
||||
Provider string `json:"provider"`
|
||||
ServiceName string `json:"service_name"`
|
||||
Region string `json:"region"`
|
||||
Revision string `json:"revision,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Output string `json:"output,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// CloudRun deploys a container image to Google Cloud Run.
|
||||
func (m *ContainerPaasDeploy) CloudRun(
|
||||
ctx context.Context,
|
||||
serviceName string,
|
||||
imageURI string,
|
||||
region string,
|
||||
serviceAccount *dagger.Secret,
|
||||
// +optional
|
||||
// +default="1"
|
||||
cpu string,
|
||||
// +optional
|
||||
// +default="512Mi"
|
||||
memory string,
|
||||
// +optional
|
||||
// +default=0
|
||||
minInstances int,
|
||||
// +optional
|
||||
// +default=10
|
||||
maxInstances int,
|
||||
// +optional
|
||||
envCSV string,
|
||||
) (*PaasResult, error) {
|
||||
envFlag := ""
|
||||
if envCSV != "" {
|
||||
envFlag = "--set-env-vars=" + envCSV
|
||||
}
|
||||
c := dag.Container().
|
||||
From("google/cloud-sdk:slim").
|
||||
WithMountedSecret("/work/sa.json", serviceAccount).
|
||||
WithExec([]string{"sh", "-c", "gcloud auth activate-service-account --key-file=/work/sa.json"}).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"gcloud run deploy " + serviceName,
|
||||
"--image=" + imageURI,
|
||||
"--region=" + region,
|
||||
"--platform=managed",
|
||||
"--allow-unauthenticated",
|
||||
"--cpu=" + cpu,
|
||||
"--memory=" + memory,
|
||||
fmt.Sprintf("--min-instances=%d --max-instances=%d", minInstances, maxInstances),
|
||||
envFlag,
|
||||
"|| true",
|
||||
}, " ")})
|
||||
out, _ := c.Stdout(ctx)
|
||||
url := ""
|
||||
if i := strings.Index(out, "Service URL: "); i >= 0 {
|
||||
rest := out[i+len("Service URL: "):]
|
||||
end := strings.IndexAny(rest, "\n ")
|
||||
if end > 0 {
|
||||
url = rest[:end]
|
||||
} else {
|
||||
url = rest
|
||||
}
|
||||
}
|
||||
return &PaasResult{
|
||||
Provider: "cloud_run",
|
||||
ServiceName: serviceName,
|
||||
Region: region,
|
||||
URL: strings.TrimSpace(url),
|
||||
Output: out,
|
||||
Success: url != "",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ECSFargate triggers a rolling update on an existing ECS service.
|
||||
//
|
||||
// Assumes the task definition is registered separately (best practice is to
|
||||
// register it via Crossplane / Terraform). This module only swings the
|
||||
// service to the new image revision.
|
||||
func (m *ContainerPaasDeploy) ECSFargate(
|
||||
ctx context.Context,
|
||||
cluster string,
|
||||
serviceName string,
|
||||
taskDefinition string,
|
||||
region string,
|
||||
awsAccessKey *dagger.Secret,
|
||||
awsSecretKey *dagger.Secret,
|
||||
) (*PaasResult, error) {
|
||||
c := dag.Container().
|
||||
From("amazon/aws-cli:2.17.0").
|
||||
WithSecretVariable("AWS_ACCESS_KEY_ID", awsAccessKey).
|
||||
WithSecretVariable("AWS_SECRET_ACCESS_KEY", awsSecretKey).
|
||||
WithEnvVariable("AWS_REGION", region).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"aws ecs update-service",
|
||||
"--cluster " + cluster,
|
||||
"--service " + serviceName,
|
||||
"--task-definition " + taskDefinition,
|
||||
"--force-new-deployment",
|
||||
"|| true",
|
||||
}, " ")})
|
||||
out, _ := c.Stdout(ctx)
|
||||
return &PaasResult{
|
||||
Provider: "ecs_fargate",
|
||||
ServiceName: serviceName,
|
||||
Region: region,
|
||||
Output: out,
|
||||
Success: strings.Contains(out, `"serviceArn"`),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// AppRunner creates / updates an App Runner service from an image.
|
||||
func (m *ContainerPaasDeploy) AppRunner(
|
||||
ctx context.Context,
|
||||
serviceName string,
|
||||
imageURI string,
|
||||
region string,
|
||||
awsAccessKey *dagger.Secret,
|
||||
awsSecretKey *dagger.Secret,
|
||||
) (*PaasResult, error) {
|
||||
c := dag.Container().
|
||||
From("amazon/aws-cli:2.17.0").
|
||||
WithSecretVariable("AWS_ACCESS_KEY_ID", awsAccessKey).
|
||||
WithSecretVariable("AWS_SECRET_ACCESS_KEY", awsSecretKey).
|
||||
WithEnvVariable("AWS_REGION", region).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"aws apprunner create-service --service-name " + serviceName,
|
||||
"--source-configuration ImageRepository={ImageIdentifier=" + imageURI + ",ImageRepositoryType=ECR}",
|
||||
"|| aws apprunner start-deployment --service-arn $(aws apprunner list-services --query \"ServiceSummaryList[?ServiceName=='" + serviceName + "'].ServiceArn | [0]\" --output text)",
|
||||
"|| true",
|
||||
}, " ")})
|
||||
out, _ := c.Stdout(ctx)
|
||||
return &PaasResult{
|
||||
Provider: "app_runner",
|
||||
ServiceName: serviceName,
|
||||
Region: region,
|
||||
Output: out,
|
||||
Success: strings.Contains(out, `"ServiceArn"`),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
/dagger.gen.go linguist-generated
|
||||
/internal/dagger/** linguist-generated
|
||||
/internal/telemetry/** linguist-generated
|
||||
@@ -0,0 +1,4 @@
|
||||
/dagger.gen.go
|
||||
/internal/dagger
|
||||
/internal/telemetry
|
||||
/.env
|
||||
@@ -0,0 +1,54 @@
|
||||
# contract-test (Dagger module)
|
||||
|
||||
> **Verified 2026-07-16**: dagger v0.21.7 `develop` + `go build` + `dagger
|
||||
> functions` pass. Generated code (`dagger.gen.go`, `internal/`) is
|
||||
> gitignored; run `dagger develop` to regenerate.
|
||||
|
||||
IntegraCI contract testing module. Runs [Pact](https://pact.io) consumer
|
||||
contract tests, publishes the generated pacts to a Pact Broker, runs a
|
||||
`can-i-deploy` gate (pact-cli), and optionally POSTs the result to the
|
||||
IntegraCI API.
|
||||
|
||||
## Functions
|
||||
|
||||
### `verify`
|
||||
|
||||
Runs consumer contract tests, publishes pacts, runs the can-i-deploy gate,
|
||||
and posts results.
|
||||
|
||||
| Parameter | Required | Default | Description |
|
||||
| -------------- | -------- | ---------------------- | -------------------------------------------------------- |
|
||||
| `source` | yes | — | Source directory containing the consumer project + pacts |
|
||||
| `broker-url` | no | — | Pact Broker URL to publish/query against |
|
||||
| `broker-token` | no | — | Pact Broker authentication token |
|
||||
| `consumer` | no | `integraci-consumer` | Consumer application name as registered in the broker |
|
||||
| `version` | no | `dev` | Version tag applied to published pacts (e.g. git SHA) |
|
||||
| `tool` | no | `pact` | Pact tooling CLI command family |
|
||||
| `api-url` | no | — | IntegraCI API URL for posting results |
|
||||
| `token` | no | — | JWT token for API authentication |
|
||||
| `service-id` | no | — | Service ID to link contract results |
|
||||
|
||||
Returns a `ContractResult` with consumer-test status, publish status,
|
||||
can-i-deploy verdict, post status, and overall success.
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
dagger call verify \
|
||||
--source . \
|
||||
--broker-url https://broker.example.com \
|
||||
--broker-token "$PACT_BROKER_TOKEN" \
|
||||
--consumer integraci-consumer \
|
||||
--version "$GIT_SHA" \
|
||||
--api-url http://localhost:8000 \
|
||||
--token "$TOKEN" \
|
||||
--service-id "$SVC_ID"
|
||||
```
|
||||
|
||||
## Pre-use checklist
|
||||
|
||||
1. `dagger develop` — generate the SDK bindings (`dag`, `*Directory`, etc.).
|
||||
2. `dagger functions` — confirm `verify` is discovered with the expected args.
|
||||
3. Run `verify` against a real consumer project + Pact Broker and confirm the
|
||||
consumer tests, publish step, and can-i-deploy gate behave as intended.
|
||||
4. Confirm the pact-cli image tag and CLI flags match your broker version.
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "contract-test",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
module dagger/contract-test
|
||||
|
||||
go 1.26.4
|
||||
|
||||
require (
|
||||
github.com/Khan/genqlient v0.8.1
|
||||
github.com/dagger/otel-go v1.43.0
|
||||
github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59
|
||||
github.com/vektah/gqlparser/v2 v2.5.32
|
||||
go.opentelemetry.io/otel v1.43.0
|
||||
go.opentelemetry.io/otel/trace v1.43.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/99designs/gqlgen v0.17.89 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
||||
github.com/sosodev/duration v1.4.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/log v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.43.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.43.0
|
||||
go.opentelemetry.io/otel/sdk/log v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // indirect
|
||||
google.golang.org/grpc v1.82.1 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
|
||||
replace go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc => go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp => go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/log => go.opentelemetry.io/otel/log v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/sdk/log => go.opentelemetry.io/otel/sdk/log v0.16.0
|
||||
@@ -0,0 +1,112 @@
|
||||
github.com/99designs/gqlgen v0.17.89 h1:KzEcxPiMgQoMw3m/E85atUEHyZyt0PbAflMia5Kw8z8=
|
||||
github.com/99designs/gqlgen v0.17.89/go.mod h1:GFqruTVGB7ZTdrf1uzOagpXbY7DrEt1pIxnTdhIbWvQ=
|
||||
github.com/Khan/genqlient v0.8.1 h1:wtOCc8N9rNynRLXN3k3CnfzheCUNKBcvXmVv5zt6WCs=
|
||||
github.com/Khan/genqlient v0.8.1/go.mod h1:R2G6DzjBvCbhjsEajfRjbWdVglSH/73kSivC9TLWVjU=
|
||||
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
|
||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/dagger/otel-go v1.43.0 h1:AYCnAamWmxtSxigWPTgC+8EWqiWPcDZEegh8y05gdJ8=
|
||||
github.com/dagger/otel-go v1.43.0/go.mod h1:83CTuXi70zcx1kaym5buqmb7RNzg1E9dEiQSFyLbLdU=
|
||||
github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59 h1:g6vfdGRyz6fAjfHz5FyYPZgHy8qcQ31fHrBl1iCOzxw=
|
||||
github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59/go.mod h1:jsdUJeYzcbyK1j/EqMGPrQgNYxl/Zfg06vvM9C/xXxs=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
|
||||
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
|
||||
github.com/sosodev/duration v1.4.0 h1:35ed0KiVFriGHHzZZJaZLgmTEEICIyt8Sx0RQfj9IjE=
|
||||
github.com/sosodev/duration v1.4.0/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERAikUR6SDg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/vektah/gqlparser/v2 v2.5.32 h1:k9QPJd4sEDTL+qB4ncPLflqTJ3MmjB9SrVzJrawpFSc=
|
||||
github.com/vektah/gqlparser/v2 v2.5.32/go.mod h1:c1I28gSOVNzlfc4WuDlqU7voQnsqI6OG2amkBAFmgts=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
|
||||
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0 h1:ZVg+kCXxd9LtAaQNKBxAvJ5NpMf7LpvEr4MIZqb0TMQ=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0/go.mod h1:hh0tMeZ75CCXrHd9OXRYxTlCAdxcXioWHFIpYw2rZu8=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0 h1:djrxvDxAe44mJUrKataUbOhCKhR3F8QCyWucO16hTQs=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0/go.mod h1:dt3nxpQEiSoKvfTVxp3TUg5fHPLhKtbcnN3Z1I1ePD0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.41.0 h1:VO3BL6OZXRQ1yQc8W6EVfJzINeJ35BkiHx4MYfoQf44=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.41.0/go.mod h1:qRDnJ2nv3CQXMK2HUd9K9VtvedsPAce3S+/4LZHjX/s=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.41.0 h1:MMrOAN8H1FrvDyq9UJ4lu5/+ss49Qgfgb7Zpm0m8ABo=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.41.0/go.mod h1:Na+2NNASJtF+uT4NxDe0G+NQb+bUgdPDfwxY/6JmS/c=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 h1:ao6Oe+wSebTlQ1OEht7jlYTzQKE+pnx/iNywFvTbuuI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0/go.mod h1:u3T6vz0gh/NVzgDgiwkgLxpsSF6PaPmo2il0apGJbls=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.41.0 h1:mq/Qcf28TWz719lE3/hMB4KkyDuLJIvgJnFGcd0kEUI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.41.0/go.mod h1:yk5LXEYhsL2htyDNJbEq7fWzNEigeEdV5xBF/Y+kAv0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 h1:inYW9ZhgqiDqh6BioM7DVHHzEGVq76Db5897WLGZ5Go=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0/go.mod h1:Izur+Wt8gClgMJqO/cZ8wdeeMryJ/xxiOVgFSSfpDTY=
|
||||
go.opentelemetry.io/otel/log v0.16.0 h1:DeuBPqCi6pQwtCK0pO4fvMB5eBq6sNxEnuTs88pjsN4=
|
||||
go.opentelemetry.io/otel/log v0.16.0/go.mod h1:rWsmqNVTLIA8UnwYVOItjyEZDbKIkMxdQunsIhpUMes=
|
||||
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
|
||||
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
|
||||
go.opentelemetry.io/otel/sdk/log v0.16.0 h1:e/b4bdlQwC5fnGtG3dlXUrNOnP7c8YLVSpSfEBIkTnI=
|
||||
go.opentelemetry.io/otel/sdk/log v0.16.0/go.mod h1:JKfP3T6ycy7QEuv3Hj8oKDy7KItrEkus8XJE6EoSzw4=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.16.0 h1:/XVkpZ41rVRTP4DfMgYv1nEtNmf65XPPyAdqV90TMy4=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.16.0/go.mod h1:iOOPgQr5MY9oac/F5W86mXdeyWZGleIx3uXO98X2R6Y=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 h1:yQugLulqltosq0B/f8l4w9VryjV+N/5gcW0jQ3N8Qec=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478/go.mod h1:C6ADNqOxbgdUUeRTU+LCHDPB9ttAMCTff6auwCVa4uc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 h1:RmoJA1ujG+/lRGNfUnOMfhCy5EipVMyvUE+KNbPbTlw=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=
|
||||
google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE=
|
||||
google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,225 @@
|
||||
// Verified 2026-07-16: dagger v0.21.7 develop + go build + dagger functions
|
||||
// pass. Generated code (dagger.gen.go, internal/) is gitignored; run
|
||||
// 'dagger develop' to regenerate.
|
||||
//
|
||||
// Package main implements the IntegraCI contract-test Dagger module.
|
||||
//
|
||||
// Runs Pact consumer contract tests, publishes the generated pacts to a
|
||||
// Pact Broker, runs a can-i-deploy gate (pact-cli), and POSTs results to
|
||||
// the IntegraCI API.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call verify --source . --broker-url https://broker.example.com --api-url http://localhost:8000 --token $TOKEN --service-id $SVC_ID
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"dagger/contract-test/internal/dagger"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ContractTest is the IntegraCI contract testing module.
|
||||
type ContractTest struct{}
|
||||
|
||||
// ContractResult contains the output of a contract verification run.
|
||||
type ContractResult struct {
|
||||
ConsumerTestsPassed bool `json:"consumer_tests_passed"`
|
||||
PactsPublished bool `json:"pacts_published"`
|
||||
BrokerURL string `json:"broker_url,omitempty"`
|
||||
CanIDeploy bool `json:"can_i_deploy"`
|
||||
Output string `json:"output,omitempty"`
|
||||
Posted bool `json:"posted"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// Verify runs Pact consumer contract tests, publishes the resulting pacts
|
||||
// to the broker, runs a can-i-deploy gate, and optionally POSTs the result
|
||||
// to the IntegraCI API.
|
||||
func (m *ContractTest) Verify(
|
||||
ctx context.Context,
|
||||
// Source directory containing the consumer project and its pacts
|
||||
source *dagger.Directory,
|
||||
// Pact Broker URL to publish pacts to and query can-i-deploy against
|
||||
// +optional
|
||||
brokerURL string,
|
||||
// Pact Broker authentication token
|
||||
// +optional
|
||||
brokerToken *dagger.Secret,
|
||||
// Consumer application name as registered in the broker
|
||||
// +optional
|
||||
// +default="integraci-consumer"
|
||||
consumer string,
|
||||
// Version tag applied to the published pacts (e.g. git SHA)
|
||||
// +optional
|
||||
// +default="dev"
|
||||
version string,
|
||||
// Pact tooling CLI image / command family
|
||||
// +optional
|
||||
// +default="pact"
|
||||
tool string,
|
||||
// IntegraCI API URL for posting results
|
||||
// +optional
|
||||
apiURL string,
|
||||
// JWT token for API authentication
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// Service ID to link contract results
|
||||
// +optional
|
||||
serviceID string,
|
||||
) (*ContractResult, error) {
|
||||
result := &ContractResult{BrokerURL: brokerURL}
|
||||
|
||||
// 1. Run the consumer contract tests, generating pact files.
|
||||
consumerOut, err := m.runConsumerTests(ctx, source)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("%s consumer tests failed: %w", tool, err)
|
||||
}
|
||||
result.ConsumerTestsPassed = true
|
||||
result.Output = consumerOut
|
||||
|
||||
// 2. Publish the generated pacts to the broker (when configured).
|
||||
if brokerURL != "" {
|
||||
if err := m.publishPacts(ctx, source, brokerURL, brokerToken, consumer, version); err != nil {
|
||||
return result, fmt.Errorf("publish pacts failed: %w", err)
|
||||
}
|
||||
result.PactsPublished = true
|
||||
|
||||
// 3. can-i-deploy gate against the broker.
|
||||
canDeploy, err := m.canIDeploy(ctx, source, brokerURL, brokerToken, consumer, version)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("can-i-deploy gate failed: %w", err)
|
||||
}
|
||||
result.CanIDeploy = canDeploy
|
||||
}
|
||||
|
||||
// 4. POST results to the IntegraCI API when credentials are supplied.
|
||||
if apiURL != "" && token != nil {
|
||||
if err := m.postResults(ctx, apiURL, token, serviceID, result); err != nil {
|
||||
return result, fmt.Errorf("post results failed: %w", err)
|
||||
}
|
||||
result.Posted = true
|
||||
}
|
||||
|
||||
result.Success = result.ConsumerTestsPassed && (brokerURL == "" || result.CanIDeploy)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// runConsumerTests executes the consumer-side Pact tests, which produce
|
||||
// pact JSON files under ./pacts in the source tree.
|
||||
func (m *ContractTest) runConsumerTests(ctx context.Context, source *dagger.Directory) (string, error) {
|
||||
runner := dag.Container().
|
||||
From("pactfoundation/pact-cli:1.6.0").
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src").
|
||||
WithExec([]string{
|
||||
"sh", "-c",
|
||||
"make pact-consumer || npm run test:pact || echo 'no consumer test target found'",
|
||||
})
|
||||
|
||||
out, err := runner.Stdout(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("consumer test execution failed: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// publishPacts uploads the generated pact files to the configured broker.
|
||||
func (m *ContractTest) publishPacts(
|
||||
ctx context.Context,
|
||||
source *dagger.Directory,
|
||||
brokerURL string,
|
||||
brokerToken *dagger.Secret,
|
||||
consumer string,
|
||||
version string,
|
||||
) error {
|
||||
publish := dag.Container().
|
||||
From("pactfoundation/pact-cli:1.6.0").
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src")
|
||||
if brokerToken != nil {
|
||||
publish = publish.WithSecretVariable("PACT_BROKER_TOKEN", brokerToken)
|
||||
}
|
||||
publish = publish.WithExec([]string{
|
||||
"pact-broker", "publish", "./pacts",
|
||||
"--broker-base-url", brokerURL,
|
||||
"--consumer-app-version", version,
|
||||
"--tag", version,
|
||||
})
|
||||
|
||||
if _, err := publish.Stdout(ctx); err != nil {
|
||||
return fmt.Errorf("pact-broker publish failed: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// canIDeploy runs the pact-cli can-i-deploy gate and returns whether the
|
||||
// consumer is safe to deploy against its recorded provider contracts.
|
||||
func (m *ContractTest) canIDeploy(
|
||||
ctx context.Context,
|
||||
source *dagger.Directory,
|
||||
brokerURL string,
|
||||
brokerToken *dagger.Secret,
|
||||
consumer string,
|
||||
version string,
|
||||
) (bool, error) {
|
||||
gate := dag.Container().
|
||||
From("pactfoundation/pact-cli:1.6.0").
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src")
|
||||
if brokerToken != nil {
|
||||
gate = gate.WithSecretVariable("PACT_BROKER_TOKEN", brokerToken)
|
||||
}
|
||||
gate = gate.WithExec([]string{
|
||||
"pact-broker", "can-i-deploy",
|
||||
"--pacticipant", consumer,
|
||||
"--version", version,
|
||||
"--to-environment", "production",
|
||||
"--broker-base-url", brokerURL,
|
||||
})
|
||||
|
||||
out, err := gate.Stdout(ctx)
|
||||
if err != nil {
|
||||
// can-i-deploy exits non-zero when deployment is unsafe; treat that
|
||||
// as a clean "false" rather than a hard error.
|
||||
return false, nil
|
||||
}
|
||||
return strings.Contains(strings.ToLower(out), "computer says yes"), nil
|
||||
}
|
||||
|
||||
// postResults POSTs the contract verification summary to the IntegraCI API.
|
||||
func (m *ContractTest) postResults(
|
||||
ctx context.Context,
|
||||
apiURL string,
|
||||
token *dagger.Secret,
|
||||
serviceID string,
|
||||
result *ContractResult,
|
||||
) error {
|
||||
payload := fmt.Sprintf(
|
||||
`{"service_id":%q,"consumer_tests_passed":%t,"pacts_published":%t,"can_i_deploy":%t,"success":%t}`,
|
||||
serviceID,
|
||||
result.ConsumerTestsPassed,
|
||||
result.PactsPublished,
|
||||
result.CanIDeploy,
|
||||
result.Success,
|
||||
)
|
||||
|
||||
poster := dag.Container().
|
||||
From("curlimages/curl:8.10.1").
|
||||
WithSecretVariable("API_TOKEN", token).
|
||||
WithNewFile("/tmp/contract-results.json", payload).
|
||||
WithExec([]string{
|
||||
"sh", "-c",
|
||||
"curl -sf -X POST " +
|
||||
"-H \"Authorization: Bearer ${API_TOKEN}\" " +
|
||||
"-H 'Content-Type: application/json' " +
|
||||
"--data-binary @/tmp/contract-results.json " +
|
||||
"'" + strings.TrimRight(apiURL, "/") + "/api/v1/contract-results'",
|
||||
})
|
||||
|
||||
if _, err := poster.Stdout(ctx); err != nil {
|
||||
return fmt.Errorf("posting contract results to %s failed: %w", apiURL, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
# IntegraCI Cosign Dagger Module
|
||||
|
||||
Signs and verifies container images with [Cosign / Sigstore](https://sigstore.dev/)
|
||||
inside an isolated Dagger container.
|
||||
|
||||
## First-time setup
|
||||
|
||||
This module follows the standard Dagger module convention — the SDK stub types
|
||||
(`Container`, `Secret`, `File`, `dag`) are generated by Dagger when you run
|
||||
`dagger develop`. Until you do, your IDE will show "undefined" errors. That is
|
||||
expected and matches the other modules in `dagger/`.
|
||||
|
||||
```bash
|
||||
cd dagger/cosign
|
||||
dagger develop # generates internal/dagger/, go.mod, go.sum
|
||||
```
|
||||
|
||||
## Functions
|
||||
|
||||
| Function | What it does |
|
||||
|---|---|
|
||||
| `Sign` | Sign an image. Either keyless (Fulcio + Rekor + ambient OIDC) or with a private key from OpenBao / file. |
|
||||
| `SignMethod` | Engine-agnostic signing entrypoint: `cosign`, `notation`, `gpg`, `in-toto` or `none`. What the rendered tenant pipelines call. cosign is keyed with `--key` (the rendered default since 2026-10-18) or keyless with `--keyless` (+ `--identity-token`, handed to cosign as `SIGSTORE_ID_TOKEN`, never on argv). With neither flag it signs keyless as it always did and prints a deprecation notice (see below). `--password` for an encrypted key; `--rekor-public-key` with a private `--rekor-url`. |
|
||||
| `Verify` | Verify an image signature. Keyless requires `--identity-regex` + `--issuer-regex` (both anchored to the whole value). |
|
||||
| `AttestSBOM` | Attach a CycloneDX or SPDX SBOM to the image as an in-toto attestation. `--image` must be digest-pinned. |
|
||||
| `AttestProvenance` | Attach an **SLSA Build L3** provenance attestation (predicate type `slsaprovenance1`). `--image` must be digest-pinned (`<repo>[:tag]@sha256:<64 hex>`) and `--source-digest` a full commit id (40 or 64 hex). Either builds the predicate from the flags, or attaches the statement `standard-build evidence` wrote (`--predicate`). Private registries: `--registry-username` + `--registry-password` (mounted as a `DOCKER_CONFIG` secret, never on argv) and `--registry-insecure` for plain-HTTP / self-signed registries. |
|
||||
| `VerifyProvenance` | Verify the SLSA provenance is signed, and that its decoded in-toto statement names the image digest as a subject, carries exactly the expected `builder.id`, and has a digest-pinned source dependency from the expected repo (`--image` must be digest-pinned). Use this in admission controllers / ArgoCD `policy-controller` to gate prod promotion. |
|
||||
| `SignBlob` | `cosign sign-blob` a file (written for the `SHA256SUMS` of the evidence set); returns `<name>.sig` and `<name>.bundle`. |
|
||||
| `VerifyAttestationGate` | Verify the attestations with `--public-key`, then judge the decoded statements with the embedded `attestation-gate` OPA policy (subject = digest, `builder.id` in `--trusted-builder`, full commit; SBOM too with `--require-sbom`). Returns an error when the gate denies. Same registry flags as `AttestProvenance`. |
|
||||
|
||||
## Transparency log (Rekor)
|
||||
|
||||
Uploading to the **public** Sigstore Rekor is **off by default** (owner decision,
|
||||
2026-10-11). A Rekor entry is public and permanent, and for an attestation it
|
||||
carries the provenance itself: registry and git hosts, repository paths, the CI
|
||||
job URL and the commit.
|
||||
|
||||
| Flag | Effect |
|
||||
|---|---|
|
||||
| *(none)* | Keyed `sign`, `sign-method`, `attest-provenance`, `attest-sbom`, `sign-blob`: no upload (`--tlog-upload=false`). Keyed `verify` / `verify-attestation-gate`: the key alone is checked (`--insecure-ignore-tlog=true`). |
|
||||
| `--public-rekor` | Opt in to the public Sigstore Rekor. |
|
||||
| `--rekor-url https://…` | Use a private Rekor instead (wins over `--public-rekor`). Plain https URL only: no credentials, query or fragment. |
|
||||
| `--rekor-public-key env://…` | The private Rekor's public key (PEM). Mounted and pointed to by `SIGSTORE_REKOR_PUBLIC_KEY`, which then REPLACES the public Sigstore Rekor keys. Accepted by every function above. |
|
||||
|
||||
**Private Rekor (2026-10-18, #2479):** cosign checks a log entry's signed
|
||||
timestamp (SET) against the Rekor keys it trusts — Sigstore's unless
|
||||
`SIGSTORE_REKOR_PUBLIC_KEY` names a file. `verify`, `verify-provenance` and
|
||||
`verify-attestation-gate` therefore **refuse** `--rekor-url` without
|
||||
`--rekor-public-key` (fail closed, with an error naming the missing flag)
|
||||
instead of failing later with one that reads like a bad signature. Signing
|
||||
functions accept the key and pass it on; they do not require it. Not yet
|
||||
measured against cosign v2.4.1 on a real private Rekor (staging test plan).
|
||||
|
||||
Sign and verify must make the **same** choice. In the rendered Jenkins pipelines
|
||||
the tenant opts in per pipeline with the `spec.pipeline.overrides` keys
|
||||
`rekor_public_upload` / `rekor_url`, and the signing steps and the gate get the
|
||||
same flags.
|
||||
|
||||
**Keyless is the exception.** A Fulcio certificate lives about ten minutes, so a
|
||||
keyless signature without a log entry cannot be verified later. Keyless calls
|
||||
keep using the public Rekor unless `--rekor-url` names a private one. Owner
|
||||
decision 2026-10-18: rendered pipelines sign **keyed** by default; keyless is a
|
||||
per-service opt-in (`governance.image_signing_mode: keyless`) that always needs
|
||||
an explicit acknowledgement: even with a private Rekor, the public Fulcio CA
|
||||
(this module sets no `--fulcio-url`) logs each certificate publicly. Services that
|
||||
were already keyless are stamped `keyless-legacy` and render exactly as before.
|
||||
`sign-method --method cosign` with neither `--key` nor `--keyless` — the call
|
||||
those older pipelines make, and the modules are not version-pinned — still signs
|
||||
keyless and prints a notice pointing at
|
||||
`docs/customer-docs/image-signing.md`.
|
||||
|
||||
Keyed signatures made without a log verify like this:
|
||||
|
||||
```bash
|
||||
cosign verify-blob --insecure-ignore-tlog=true --key cosign.pub \
|
||||
--signature SHA256SUMS.sig --bundle SHA256SUMS.bundle SHA256SUMS
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Keyless sign in GitHub Actions
|
||||
|
||||
```yaml
|
||||
- uses: dagger/dagger-for-github@v6
|
||||
with:
|
||||
version: latest
|
||||
cmds: |
|
||||
dagger -m ./dagger/cosign call sign \
|
||||
--image ghcr.io/${{ github.repository }}:${{ github.sha }} \
|
||||
--keyless \
|
||||
--identity-token env:ACTIONS_ID_TOKEN_REQUEST_TOKEN
|
||||
```
|
||||
|
||||
### Keyed sign with OpenBao secret
|
||||
|
||||
```bash
|
||||
# Fetch private key from OpenBao first, then:
|
||||
dagger -m ./dagger/cosign call sign \
|
||||
--image harbor.acme.com/payments/api:1.4.2 \
|
||||
--private-key file:./cosign.key \
|
||||
--password env:COSIGN_PASSWORD \
|
||||
--registry-user robot$payments+ci \
|
||||
--registry-password env:HARBOR_TOKEN \
|
||||
--annotations 'sha=$GIT_SHA,build=$BUILD_ID'
|
||||
```
|
||||
|
||||
### Verify
|
||||
|
||||
```bash
|
||||
# Keyed
|
||||
dagger -m ./dagger/cosign call verify \
|
||||
--image harbor.acme.com/payments/api:1.4.2 \
|
||||
--public-key file:./cosign.pub
|
||||
|
||||
# Keyless (any signer from this org with a GitHub Actions token)
|
||||
dagger -m ./dagger/cosign call verify \
|
||||
--image harbor.acme.com/payments/api:1.4.2 \
|
||||
--keyless \
|
||||
--identity-regex '.+@example\.com' \
|
||||
--issuer-regex 'https://token\.actions\.githubusercontent\.com'
|
||||
```
|
||||
|
||||
### Attach SBOM as attestation
|
||||
|
||||
```bash
|
||||
dagger -m ./dagger/cosign call attest-sbom \
|
||||
--image harbor.acme.com/payments/api:1.4.2@sha256:<64 hex image digest> \
|
||||
--sbom file:./sbom-cyclonedx.json \
|
||||
--predicate-type cyclonedx \
|
||||
--keyless
|
||||
```
|
||||
|
||||
### Attach SLSA L3 provenance (release pipeline)
|
||||
|
||||
```bash
|
||||
dagger -m ./dagger/cosign call attest-provenance \
|
||||
--image ghcr.io/integraci/payments-api:1.2.3@sha256:<64 hex image digest> \
|
||||
--builder-id "https://github.com/integraci/integraci/.github/workflows/release.yml@refs/tags/v1.2.3" \
|
||||
--source-uri "git+https://github.com/integraci/integraci@refs/tags/v1.2.3" \
|
||||
--source-digest "$(git rev-parse HEAD)" \
|
||||
--invocation-id "${{ github.run_id }}" \
|
||||
--keyless
|
||||
```
|
||||
|
||||
`--image` must name the digest: cosign would otherwise resolve the tag at
|
||||
attest time, and a tag pushed again between build and attest would sign
|
||||
provenance about another build. `--source-digest` is the full commit id (40 or
|
||||
64 hex; a `sha1:`/`sha256:` prefix is tolerated), never a short sha.
|
||||
|
||||
Attaching the statement `standard-build evidence` wrote, keyed, to a private
|
||||
registry:
|
||||
|
||||
```bash
|
||||
dagger -m ./dagger/cosign call attest-provenance \
|
||||
--image registry.example/team/orders:abc@sha256:<64 hex> \
|
||||
--predicate evidence/provenance.intoto.json \
|
||||
--private-key env://COSIGN_KEY \
|
||||
--registry-username "$REG_USER" \
|
||||
--registry-password env://REG_PASS \
|
||||
--registry-insecure # only for plain-HTTP / self-signed registries
|
||||
```
|
||||
|
||||
### Verify SLSA provenance before deploy
|
||||
|
||||
```bash
|
||||
dagger -m ./dagger/cosign call verify-provenance \
|
||||
--image ghcr.io/integraci/payments-api:1.2.3@sha256:<64 hex> \
|
||||
--expected-builder-id "https://github.com/integraci/integraci/.github/workflows/release.yml@refs/tags/v1.2.3" \
|
||||
--expected-source-repo "https://github.com/integraci/integraci" \
|
||||
--issuer-regex 'https://token\.actions\.githubusercontent\.com'
|
||||
```
|
||||
|
||||
A refusal is an error: the call exits non-zero, so `verify-provenance … &&
|
||||
deploy` stops. Nothing in this repo calls it yet — no OPA rule or pipeline step
|
||||
enforces it (an earlier version of this README named a `golden_standard` rule
|
||||
`require_slsa_l3_provenance` that does not exist). Wiring it into a deploy gate
|
||||
is the consumer's job.
|
||||
|
||||
Scope: keyless (Fulcio) SLSA v1 attestations only. Key-signed attestations —
|
||||
`attest-provenance --private-key`, and the Jenkins path
|
||||
`tools/ci/attest-provenance.sh` (key-signed, SLSA v0.2) — cannot be verified
|
||||
by this function today.
|
||||
|
||||
`verify-provenance` decodes each DSSE envelope cosign prints (the statement is
|
||||
base64 inside it) and compares fields exactly: `runDetails.builder.id` must
|
||||
equal `--expected-builder-id`, the source — the FIRST `resolvedDependencies`
|
||||
entry — must be `--expected-source-repo` or that repo followed by `@<ref>` (a
|
||||
`git+` prefix and `.git` suffix are tolerated; `…/app-evil` and `…/app/fork` do
|
||||
not match `…/app`) with a full commit id (`gitCommit`/`sha1`/`sha256`, 40 or 64
|
||||
hex) as its digest, and a subject's sha256 must be the `--image` digest. A repo
|
||||
that lists the expected one only as a later dependency does not pass. Output it
|
||||
cannot parse — anywhere in the stream, even after a match — is a failure, not a
|
||||
skip.
|
||||
|
||||
`builder.id` is only a string inside what was signed, so the trust anchor is the
|
||||
signer. Without `--identity-regex` the certificate identity must equal
|
||||
`--expected-builder-id` exactly (for GitHub Actions keyless signing both are the
|
||||
workflow ref). `--identity-regex` replaces that binding: a broad pattern such as
|
||||
`https://github\.com/integraci/.+` lets any workflow it admits sign a statement
|
||||
that names the expected builder. Both regexes are wrapped as `^(?:…)$` before
|
||||
cosign sees them (#2435): cosign matches anywhere in the string, so the default
|
||||
issuer regex once also accepted an issuer that merely contained
|
||||
`token.actions.githubusercontent.com`. Keep an identity regex narrow to the one
|
||||
workflow. Before #2337 it substring-matched the raw
|
||||
output, which never contains the base64-encoded builder id, so it could not
|
||||
pass.
|
||||
|
||||
## How it integrates with IntegraCI
|
||||
|
||||
- The Golden Path pipelines call `cosign sign` immediately after `harbor push`
|
||||
so every artifact in Harbor is signed.
|
||||
- The OPA `golden_standard` bundle has a rule
|
||||
(`require_signed_image`) that blocks deploys of unsigned images.
|
||||
- ArgoCD's `policy-controller` admission webhook (in user's cluster) validates
|
||||
the same signature against the public key stored in the user's OpenBao.
|
||||
@@ -0,0 +1,173 @@
|
||||
// Package attestation holds the cosign module's pure predicate logic, standard
|
||||
// library only, so it runs under a plain `go test` (the generated `dagger`
|
||||
// package panics at init without a session — see db-migration/verdict/).
|
||||
//
|
||||
// Two jobs:
|
||||
//
|
||||
// - PredicateFromStatement takes the in-toto Statement standard-build's
|
||||
// `evidence` wrote and returns the predicate cosign should attach — but
|
||||
// only after checking the statement is about THIS image's digest. Attaching
|
||||
// another build's provenance to an image is the one mistake an attestation
|
||||
// must never make, and nothing downstream could tell.
|
||||
// - ProvenancePredicate builds the inline SLSA v1 predicate for callers that
|
||||
// do not pass a statement. It replaces a template that shipped literal
|
||||
// `${BUILD_STARTED_ON}` / `${ACTOR_ID}` placeholders nothing ever
|
||||
// expanded, labelled a commit id as `sha1` after stripping `sha256:`, and
|
||||
// claimed `dagger v0.15.0` while every module pins v0.21.7.
|
||||
package attestation
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SLSAProvenanceV1 is the predicate type cosign's `slsaprovenance1` maps to.
|
||||
const SLSAProvenanceV1 = "https://slsa.dev/provenance/v1"
|
||||
|
||||
var digestRef = regexp.MustCompile(`^[^@\s]+@sha256:([0-9a-f]{64})$`)
|
||||
|
||||
var commitID = regexp.MustCompile(`^([0-9a-f]{40}|[0-9a-f]{64})$`)
|
||||
|
||||
// ImageDigest returns the hex sha256 of a digest-pinned reference.
|
||||
func ImageDigest(image string) (string, error) {
|
||||
m := digestRef.FindStringSubmatch(strings.TrimSpace(image))
|
||||
if m == nil {
|
||||
return "", fmt.Errorf("image %q is not pinned to a sha256 digest", image)
|
||||
}
|
||||
return m[1], nil
|
||||
}
|
||||
|
||||
type statement struct {
|
||||
Type string `json:"_type"`
|
||||
PredicateType string `json:"predicateType"`
|
||||
Subject []subject `json:"subject"`
|
||||
Predicate json.RawMessage `json:"predicate"`
|
||||
}
|
||||
|
||||
type subject struct {
|
||||
Name string `json:"name"`
|
||||
Digest map[string]string `json:"digest"`
|
||||
}
|
||||
|
||||
// PredicateFromStatement validates an in-toto Statement against the image it
|
||||
// is about to be attached to and returns its predicate bytes.
|
||||
//
|
||||
// Refused: a malformed statement, a statement type other than in-toto v0.1/v1,
|
||||
// a predicate type other than SLSA v1 provenance, a tag-only image, and — the
|
||||
// point of the function — a statement with no subject whose sha256 equals the
|
||||
// image's digest.
|
||||
func PredicateFromStatement(raw []byte, image string) ([]byte, error) {
|
||||
want, err := ImageDigest(image)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var st statement
|
||||
if err := json.Unmarshal(raw, &st); err != nil {
|
||||
return nil, fmt.Errorf("statement is not valid JSON: %w", err)
|
||||
}
|
||||
switch st.Type {
|
||||
case "https://in-toto.io/Statement/v1", "https://in-toto.io/Statement/v0.1":
|
||||
default:
|
||||
return nil, fmt.Errorf("statement _type %q is not an in-toto Statement", st.Type)
|
||||
}
|
||||
if st.PredicateType != SLSAProvenanceV1 {
|
||||
return nil, fmt.Errorf("predicateType %q is not %s", st.PredicateType, SLSAProvenanceV1)
|
||||
}
|
||||
matched := false
|
||||
for _, s := range st.Subject {
|
||||
if strings.EqualFold(s.Digest["sha256"], want) {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return nil, fmt.Errorf("statement has no subject with sha256 %s: it describes a different artifact", want)
|
||||
}
|
||||
p := strings.TrimSpace(string(st.Predicate))
|
||||
if p == "" || p == "null" || !strings.HasPrefix(p, "{") {
|
||||
return nil, fmt.Errorf("statement predicate is missing or not an object")
|
||||
}
|
||||
return []byte(p + "\n"), nil
|
||||
}
|
||||
|
||||
// ProvenanceInput is what the inline predicate records. Supplied by the caller;
|
||||
// nothing is read from the environment.
|
||||
type ProvenanceInput struct {
|
||||
BuilderID string
|
||||
BuildType string
|
||||
SourceURI string
|
||||
SourceDigest string // full commit id; a `sha1:`/`sha256:` prefix is tolerated
|
||||
InvocationID string
|
||||
StartedOn string // RFC 3339; empty -> Now
|
||||
FinishedOn string // RFC 3339; empty -> Now
|
||||
EngineVersion string
|
||||
Now time.Time
|
||||
}
|
||||
|
||||
// ProvenancePredicate renders the SLSA v1 provenance predicate (the predicate
|
||||
// only — cosign wraps it in a Statement whose subject is the image digest).
|
||||
func ProvenancePredicate(in ProvenanceInput) ([]byte, error) {
|
||||
for what, raw := range map[string]string{"builder id": in.BuilderID, "build type": in.BuildType} {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Scheme == "" || (u.Host == "" && u.Opaque == "") || strings.ContainsAny(raw, " \t\r\n") {
|
||||
return nil, fmt.Errorf("%s %q must be an absolute URI", what, raw)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(in.SourceURI) == "" || strings.ContainsAny(in.SourceURI, " \t\r\n") {
|
||||
return nil, fmt.Errorf("source uri %q must be a non-empty URI without whitespace", in.SourceURI)
|
||||
}
|
||||
rev := strings.ToLower(strings.TrimSpace(in.SourceDigest))
|
||||
for _, prefix := range []string{"sha1:", "sha256:"} {
|
||||
rev = strings.TrimPrefix(rev, prefix)
|
||||
}
|
||||
if !commitID.MatchString(rev) {
|
||||
return nil, fmt.Errorf("source digest %q is not a full commit id (40 or 64 hex)", in.SourceDigest)
|
||||
}
|
||||
now := in.Now.UTC().Format(time.RFC3339)
|
||||
started, finished := in.StartedOn, in.FinishedOn
|
||||
if started == "" {
|
||||
started = now
|
||||
}
|
||||
if finished == "" {
|
||||
finished = now
|
||||
}
|
||||
for what, ts := range map[string]string{"started-on": started, "finished-on": finished} {
|
||||
if _, err := time.Parse(time.RFC3339, ts); err != nil {
|
||||
return nil, fmt.Errorf("%s %q is not RFC 3339", what, ts)
|
||||
}
|
||||
}
|
||||
if strings.ContainsAny(in.InvocationID, "\r\n") {
|
||||
return nil, fmt.Errorf("invocation id must be a single line")
|
||||
}
|
||||
|
||||
predicate := map[string]any{
|
||||
"buildDefinition": map[string]any{
|
||||
"buildType": in.BuildType,
|
||||
"externalParameters": map[string]string{"source": in.SourceURI, "revision": rev},
|
||||
"resolvedDependencies": []map[string]any{{
|
||||
"uri": in.SourceURI,
|
||||
"digest": map[string]string{"gitCommit": rev},
|
||||
}},
|
||||
},
|
||||
"runDetails": map[string]any{
|
||||
"builder": map[string]any{
|
||||
"id": in.BuilderID,
|
||||
"version": map[string]string{"dagger-engine": in.EngineVersion},
|
||||
},
|
||||
"metadata": map[string]string{
|
||||
"invocationId": in.InvocationID,
|
||||
"startedOn": started,
|
||||
"finishedOn": finished,
|
||||
},
|
||||
},
|
||||
}
|
||||
out, err := json.MarshalIndent(predicate, "", " ")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append(out, '\n'), nil
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package attestation
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
digestA = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
digestB = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
|
||||
commit = "89abcdef0123456789abcdef0123456789abcdef"
|
||||
)
|
||||
|
||||
func stmt(subjectDigest, predicateType, typ string) []byte {
|
||||
b, _ := json.Marshal(map[string]any{
|
||||
"_type": typ,
|
||||
"predicateType": predicateType,
|
||||
"subject": []map[string]any{{
|
||||
"name": "registry.example/team/orders",
|
||||
"digest": map[string]string{"sha256": subjectDigest},
|
||||
}},
|
||||
"predicate": map[string]any{"buildDefinition": map[string]any{"buildType": "https://x.example/t"}},
|
||||
})
|
||||
return b
|
||||
}
|
||||
|
||||
const imageA = "registry.example/team/orders:abc@sha256:" + digestA
|
||||
|
||||
func TestPredicateFromStatementReturnsPredicate(t *testing.T) {
|
||||
p, err := PredicateFromStatement(stmt(digestA, SLSAProvenanceV1, "https://in-toto.io/Statement/v1"), imageA)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(p, &got); err != nil {
|
||||
t.Fatalf("predicate is not JSON: %v", err)
|
||||
}
|
||||
if _, ok := got["buildDefinition"]; !ok {
|
||||
t.Fatalf("predicate lost its body: %s", p)
|
||||
}
|
||||
if _, ok := got["_type"]; ok {
|
||||
t.Fatal("must return the predicate, not the whole statement")
|
||||
}
|
||||
}
|
||||
|
||||
// The reason the function exists: provenance about another digest must never
|
||||
// be attached to this image.
|
||||
func TestPredicateFromStatementRefusesOtherDigest(t *testing.T) {
|
||||
if _, err := PredicateFromStatement(stmt(digestB, SLSAProvenanceV1, "https://in-toto.io/Statement/v1"), imageA); err == nil {
|
||||
t.Fatal("a statement about digest B must not attach to image A")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPredicateFromStatementRefusals(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
raw []byte
|
||||
image string
|
||||
}{
|
||||
"tag-only image": {stmt(digestA, SLSAProvenanceV1, "https://in-toto.io/Statement/v1"), "registry.example/team/orders:abc"},
|
||||
"not json": {[]byte("{"), imageA},
|
||||
"wrong statement": {stmt(digestA, SLSAProvenanceV1, "https://example.test/Statement"), imageA},
|
||||
"wrong predicate": {stmt(digestA, "https://cyclonedx.org/bom", "https://in-toto.io/Statement/v1"), imageA},
|
||||
"no subject": {[]byte(`{"_type":"https://in-toto.io/Statement/v1","predicateType":"` + SLSAProvenanceV1 + `","subject":[],"predicate":{}}`), imageA},
|
||||
"null predicate": {[]byte(`{"_type":"https://in-toto.io/Statement/v1","predicateType":"` + SLSAProvenanceV1 + `","subject":[{"name":"x","digest":{"sha256":"` + digestA + `"}}],"predicate":null}`), imageA},
|
||||
"sha512 only subject": {[]byte(`{"_type":"https://in-toto.io/Statement/v1","predicateType":"` + SLSAProvenanceV1 + `","subject":[{"name":"x","digest":{"sha512":"` + digestA + `"}}],"predicate":{}}`), imageA},
|
||||
}
|
||||
for name, c := range cases {
|
||||
if _, err := PredicateFromStatement(c.raw, c.image); err == nil {
|
||||
t.Fatalf("%s: must be refused", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPredicateFromStatementAcceptsLegitimate(t *testing.T) {
|
||||
// in-toto v0.1 statements are still what many tools write.
|
||||
if _, err := PredicateFromStatement(stmt(digestA, SLSAProvenanceV1, "https://in-toto.io/Statement/v0.1"), imageA); err != nil {
|
||||
t.Fatalf("v0.1 statement refused: %v", err)
|
||||
}
|
||||
// An image reference with a registry port and no tag.
|
||||
if _, err := PredicateFromStatement(stmt(digestA, SLSAProvenanceV1, "https://in-toto.io/Statement/v1"),
|
||||
"registry.example:5000/team/orders@sha256:"+digestA); err != nil {
|
||||
t.Fatalf("port + digest refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func validInput() ProvenanceInput {
|
||||
return ProvenanceInput{
|
||||
BuilderID: "https://github.com/acme/app/.github/workflows/release.yml@refs/tags/v1.2.3",
|
||||
BuildType: "https://actions.github.io/buildtypes/workflow/v1",
|
||||
SourceURI: "git+https://github.com/acme/app@refs/tags/v1.2.3",
|
||||
SourceDigest: "sha256:" + commit, // what the old docstring told callers to pass
|
||||
InvocationID: "123",
|
||||
EngineVersion: "v0.21.7",
|
||||
Now: time.Date(2026, 10, 11, 8, 0, 0, 0, time.UTC),
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvenancePredicateHasNoPlaceholders(t *testing.T) {
|
||||
p, err := ProvenancePredicate(validInput())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := string(p)
|
||||
if strings.Contains(s, "${") {
|
||||
t.Fatalf("unexpanded placeholder in predicate:\n%s", s)
|
||||
}
|
||||
if strings.Contains(s, `"sha1"`) {
|
||||
t.Fatalf("commit id must be labelled gitCommit, not sha1:\n%s", s)
|
||||
}
|
||||
if !strings.Contains(s, `"gitCommit": "`+commit+`"`) {
|
||||
t.Fatalf("source commit missing:\n%s", s)
|
||||
}
|
||||
if !strings.Contains(s, `"startedOn": "2026-10-11T08:00:00Z"`) {
|
||||
t.Fatalf("defaulted timestamp missing:\n%s", s)
|
||||
}
|
||||
if strings.Contains(s, "v0.15.0") || !strings.Contains(s, "v0.21.7") {
|
||||
t.Fatalf("engine version wrong:\n%s", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvenancePredicateRefusals(t *testing.T) {
|
||||
mutate := map[string]func(*ProvenanceInput){
|
||||
"relative builder": func(in *ProvenanceInput) { in.BuilderID = "release.yml" },
|
||||
"relative type": func(in *ProvenanceInput) { in.BuildType = "workflow" },
|
||||
"empty source": func(in *ProvenanceInput) { in.SourceURI = "" },
|
||||
"short commit": func(in *ProvenanceInput) { in.SourceDigest = commit[:7] },
|
||||
"placeholder time": func(in *ProvenanceInput) { in.StartedOn = "${BUILD_STARTED_ON}" },
|
||||
"newline run id": func(in *ProvenanceInput) { in.InvocationID = "1\n2" },
|
||||
}
|
||||
for name, m := range mutate {
|
||||
in := validInput()
|
||||
m(&in)
|
||||
if _, err := ProvenancePredicate(in); err == nil {
|
||||
t.Fatalf("%s: must be refused", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvenancePredicateAcceptsLegitimate(t *testing.T) {
|
||||
ok := map[string]func(*ProvenanceInput){
|
||||
"bare commit": func(in *ProvenanceInput) { in.SourceDigest = commit },
|
||||
"sha1-prefixed": func(in *ProvenanceInput) { in.SourceDigest = "sha1:" + commit },
|
||||
"sha256 repository": func(in *ProvenanceInput) { in.SourceDigest = digestA },
|
||||
"explicit times": func(in *ProvenanceInput) {
|
||||
in.StartedOn, in.FinishedOn = "2026-10-11T08:00:00+07:00", "2026-10-11T09:00:00Z"
|
||||
},
|
||||
"no run id": func(in *ProvenanceInput) { in.InvocationID = "" },
|
||||
}
|
||||
for name, m := range ok {
|
||||
in := validInput()
|
||||
m(&in)
|
||||
if _, err := ProvenancePredicate(in); err != nil {
|
||||
t.Fatalf("%s: legitimate value refused: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package attestation
|
||||
|
||||
// Pure helpers for the phase-2 functions (#2143): registry auth for cosign,
|
||||
// the attestation gate's OPA input and verdict, and blob names for sign-blob.
|
||||
// Standard library only, like the rest of this package.
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// GatePolicyQuery is the OPA query the gate evaluates. The package lives in
|
||||
// policy/attestation_gate.rego, a byte-identical copy of
|
||||
// infra/policies/bundles/attestation-gate/attestation_gate.rego.
|
||||
const GatePolicyQuery = "data.integraci.supply_chain.attestation_gate.result"
|
||||
|
||||
// registryHostRE is what a registry host legitimately is: a DNS name or IP,
|
||||
// with an optional port. Nothing else reaches the docker config key.
|
||||
var registryHostRE = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9.-]{0,252})(:[0-9]{1,5})?$`)
|
||||
|
||||
// RegistryHost returns the registry host of an image reference, following the
|
||||
// docker rule: the first path segment is a host only when it contains a `.` or
|
||||
// a `:`, or is `localhost`. Otherwise the image lives on Docker Hub.
|
||||
func RegistryHost(image string) string {
|
||||
ref := strings.TrimSpace(image)
|
||||
if i := strings.IndexByte(ref, '/'); i > 0 {
|
||||
first := ref[:i]
|
||||
if strings.ContainsAny(first, ".:") || first == "localhost" {
|
||||
return first
|
||||
}
|
||||
}
|
||||
return "docker.io"
|
||||
}
|
||||
|
||||
// RegistryAuthConfig renders a docker `config.json` that logs cosign into one
|
||||
// registry. Written as a FILE (mounted as a secret) rather than passed to
|
||||
// `cosign login` on a shell line: the username and password then never touch
|
||||
// an argv or a shell, so neither can inject anything and neither shows in a
|
||||
// process listing.
|
||||
func RegistryAuthConfig(host, username, password string) ([]byte, error) {
|
||||
if !registryHostRE.MatchString(host) {
|
||||
return nil, fmt.Errorf("registry host %q is not a host[:port]", host)
|
||||
}
|
||||
if username == "" || strings.ContainsAny(username, ":\r\n") {
|
||||
return nil, fmt.Errorf("registry username must be non-empty and contain no ':' or newline")
|
||||
}
|
||||
if password == "" {
|
||||
return nil, fmt.Errorf("registry password is empty")
|
||||
}
|
||||
key := host
|
||||
if host == "docker.io" {
|
||||
key = "https://index.docker.io/v1/"
|
||||
}
|
||||
auth := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
|
||||
return json.Marshal(map[string]any{
|
||||
"auths": map[string]any{key: map[string]string{"auth": auth}},
|
||||
})
|
||||
}
|
||||
|
||||
// gateEnvelope is the subset of a DSSE envelope the policy reads.
|
||||
type gateEnvelope struct {
|
||||
PayloadType string `json:"payloadType"`
|
||||
Payload string `json:"payload"`
|
||||
Signatures []json.RawMessage `json:"signatures,omitempty"`
|
||||
}
|
||||
|
||||
// GateInput builds the attestation gate's OPA input from `cosign
|
||||
// verify-attestation` stdout.
|
||||
//
|
||||
// cosign prints one DSSE envelope per line, and only envelopes whose signature
|
||||
// verified against the key it was given. Lines that are not a JSON envelope
|
||||
// with a string payloadType and payload are dropped; dropping one can only
|
||||
// remove evidence, never add it, so the gate fails closed on anything odd.
|
||||
//
|
||||
// A tag-only image and an empty trusted-builder list are refused here as well
|
||||
// as in the policy (guard at the call site and at the sink).
|
||||
func GateInput(image, cosignOutput string, trustedBuilders []string, requireSBOM bool) ([]byte, error) {
|
||||
hex, err := ImageDigest(image)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builders := make([]string, 0, len(trustedBuilders))
|
||||
for _, b := range trustedBuilders {
|
||||
if b = strings.TrimSpace(b); b != "" {
|
||||
builders = append(builders, b)
|
||||
}
|
||||
}
|
||||
if len(builders) == 0 {
|
||||
return nil, fmt.Errorf("at least one --trusted-builder is required: a gate that trusts no builder cannot pass, and one that trusts any builder proves nothing")
|
||||
}
|
||||
envelopes := []gateEnvelope{}
|
||||
for _, line := range strings.Split(cosignOutput, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if !strings.HasPrefix(line, "{") {
|
||||
continue
|
||||
}
|
||||
var env gateEnvelope
|
||||
if err := json.Unmarshal([]byte(line), &env); err != nil {
|
||||
continue
|
||||
}
|
||||
if env.PayloadType == "" || env.Payload == "" {
|
||||
continue
|
||||
}
|
||||
envelopes = append(envelopes, env)
|
||||
}
|
||||
return json.Marshal(map[string]any{
|
||||
"image": map[string]string{"digest": "sha256:" + hex},
|
||||
"envelopes": envelopes,
|
||||
"policy": map[string]any{
|
||||
"trusted_builders": builders,
|
||||
"require_sbom": requireSBOM,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// GateVerdict reads `opa eval --format json` output for GatePolicyQuery.
|
||||
//
|
||||
// Anything but a well-formed decision is an error, never an allow: an empty
|
||||
// result set is what OPA returns when the package is not loaded at all.
|
||||
func GateVerdict(opaOutput []byte) (bool, []string, error) {
|
||||
var out struct {
|
||||
Result []struct {
|
||||
Expressions []struct {
|
||||
Value struct {
|
||||
Allowed *bool `json:"allowed"`
|
||||
Deny []string `json:"deny"`
|
||||
} `json:"value"`
|
||||
} `json:"expressions"`
|
||||
} `json:"result"`
|
||||
}
|
||||
if err := json.Unmarshal(opaOutput, &out); err != nil {
|
||||
return false, nil, fmt.Errorf("opa output is not JSON: %w", err)
|
||||
}
|
||||
if len(out.Result) != 1 || len(out.Result[0].Expressions) != 1 {
|
||||
return false, nil, fmt.Errorf("opa returned no decision for %s (is the policy loaded?)", GatePolicyQuery)
|
||||
}
|
||||
v := out.Result[0].Expressions[0].Value
|
||||
if v.Allowed == nil {
|
||||
return false, nil, fmt.Errorf("opa decision has no `allowed` field")
|
||||
}
|
||||
if *v.Allowed && len(v.Deny) > 0 {
|
||||
return false, v.Deny, fmt.Errorf("opa decision is contradictory: allowed with %d deny reason(s)", len(v.Deny))
|
||||
}
|
||||
return *v.Allowed, v.Deny, nil
|
||||
}
|
||||
|
||||
// blobName is what sign-blob may call its outputs: a plain file name, so the
|
||||
// returned directory can never place a file outside itself.
|
||||
var blobName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
|
||||
|
||||
// CheckBlobName refuses a sign-blob output name that is not a plain file name.
|
||||
func CheckBlobName(name string) error {
|
||||
if !blobName.MatchString(name) || strings.Contains(name, "..") {
|
||||
return fmt.Errorf("name %q must be a plain file name ([A-Za-z0-9._-], no '..')", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package attestation
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegistryHost(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"registry.example/team/orders@sha256:" + digestA: "registry.example",
|
||||
"nexus.example:8082/orders:1": "nexus.example:8082",
|
||||
"localhost/orders:1": "localhost",
|
||||
"library/alpine:3.20": "docker.io",
|
||||
"alpine": "docker.io",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := RegistryHost(in); got != want {
|
||||
t.Errorf("RegistryHost(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryAuthConfigLegitimate(t *testing.T) {
|
||||
raw, err := RegistryAuthConfig("nexus.example:8082", "ci-bot", "p@ss w'rd\"$x")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var cfg struct {
|
||||
Auths map[string]struct {
|
||||
Auth string `json:"auth"`
|
||||
} `json:"auths"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dec, _ := base64.StdEncoding.DecodeString(cfg.Auths["nexus.example:8082"].Auth)
|
||||
// Shell metacharacters in the password are DATA here, never syntax.
|
||||
if string(dec) != "ci-bot:p@ss w'rd\"$x" {
|
||||
t.Fatalf("auth = %q", dec)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryAuthConfigDockerHubKey(t *testing.T) {
|
||||
raw, err := RegistryAuthConfig("docker.io", "u", "p")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(raw), "https://index.docker.io/v1/") {
|
||||
t.Fatalf("docker hub must use the index key: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryAuthConfigRefuses(t *testing.T) {
|
||||
bad := []struct{ host, user, pass string }{
|
||||
{"evil.example; rm -rf /", "u", "p"},
|
||||
{"host/with/path", "u", "p"},
|
||||
{"", "u", "p"},
|
||||
{"registry.example", "", "p"},
|
||||
{"registry.example", "a:b", "p"},
|
||||
{"registry.example", "a\nb", "p"},
|
||||
{"registry.example", "u", ""},
|
||||
}
|
||||
for _, c := range bad {
|
||||
if _, err := RegistryAuthConfig(c.host, c.user, c.pass); err == nil {
|
||||
t.Errorf("RegistryAuthConfig(%q, %q, …) accepted", c.host, c.user)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func gateEnvelopeLine(t *testing.T, payloadType string) string {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(map[string]any{
|
||||
"payloadType": payloadType,
|
||||
"payload": base64.StdEncoding.EncodeToString([]byte(`{"_type":"x"}`)),
|
||||
"signatures": []map[string]string{{"sig": "c2ln"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestGateInputKeepsEnvelopesAndDropsNoise(t *testing.T) {
|
||||
out := strings.Join([]string{
|
||||
"Verification for registry.example/team/orders --",
|
||||
gateEnvelopeLine(t, "application/vnd.in-toto+json"),
|
||||
"{not json",
|
||||
`{"payloadType":"","payload":"x"}`,
|
||||
"",
|
||||
}, "\n")
|
||||
raw, err := GateInput(imageA, out, []string{" https://ci.example/job/orders/ ", ""}, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var in struct {
|
||||
Image map[string]string `json:"image"`
|
||||
Envelopes []map[string]any `json:"envelopes"`
|
||||
Policy struct {
|
||||
TrustedBuilders []string `json:"trusted_builders"`
|
||||
RequireSBOM bool `json:"require_sbom"`
|
||||
} `json:"policy"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &in); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if in.Image["digest"] != "sha256:"+digestA {
|
||||
t.Fatalf("digest = %q", in.Image["digest"])
|
||||
}
|
||||
if len(in.Envelopes) != 1 {
|
||||
t.Fatalf("want 1 envelope, got %d", len(in.Envelopes))
|
||||
}
|
||||
if len(in.Policy.TrustedBuilders) != 1 || in.Policy.TrustedBuilders[0] != "https://ci.example/job/orders/" {
|
||||
t.Fatalf("builders = %v", in.Policy.TrustedBuilders)
|
||||
}
|
||||
if !in.Policy.RequireSBOM {
|
||||
t.Fatal("require_sbom lost")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateInputEmptyEnvelopeListIsAnArray(t *testing.T) {
|
||||
raw, err := GateInput(imageA, "", []string{"https://ci.example/"}, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(raw), `"envelopes":[]`) {
|
||||
t.Fatalf("envelopes must be [] not null: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateInputRefusesTagAndNoBuilder(t *testing.T) {
|
||||
if _, err := GateInput("registry.example/team/orders:abc", "", []string{"https://ci.example/"}, false); err == nil {
|
||||
t.Error("tag-only image accepted")
|
||||
}
|
||||
if _, err := GateInput(imageA, "", []string{" ", ""}, false); err == nil {
|
||||
t.Error("empty trusted builder list accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateVerdict(t *testing.T) {
|
||||
allow := `{"result":[{"expressions":[{"value":{"allowed":true,"deny":[]},"text":"x"}]}]}`
|
||||
ok, deny, err := GateVerdict([]byte(allow))
|
||||
if err != nil || !ok || len(deny) != 0 {
|
||||
t.Fatalf("allow: ok=%v deny=%v err=%v", ok, deny, err)
|
||||
}
|
||||
refuse := `{"result":[{"expressions":[{"value":{"allowed":false,"deny":["no provenance"]}}]}]}`
|
||||
ok, deny, err = GateVerdict([]byte(refuse))
|
||||
if err != nil || ok || len(deny) != 1 {
|
||||
t.Fatalf("deny: ok=%v deny=%v err=%v", ok, deny, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateVerdictFailsClosed(t *testing.T) {
|
||||
for _, raw := range []string{
|
||||
`{}`, // package not loaded: empty result set
|
||||
`{"result":[]}`, // same
|
||||
`{"result":[{"expressions":[{"value":{}}]}]}`, // no allowed field
|
||||
`{"result":[{"expressions":[{"value":{"allowed":true,"deny":["x"]}}]}]}`,
|
||||
`not json`,
|
||||
} {
|
||||
if ok, _, err := GateVerdict([]byte(raw)); ok || err == nil {
|
||||
t.Errorf("GateVerdict(%s) = ok=%v err=%v, want refusal", raw, ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckBlobName(t *testing.T) {
|
||||
for _, good := range []string{"SHA256SUMS", "sbom.cdx.json", "a_b-c.1"} {
|
||||
if err := CheckBlobName(good); err != nil {
|
||||
t.Errorf("%q refused: %v", good, err)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"", "../x", "a/b", ".hidden", "a..b", "x y", "a;b"} {
|
||||
if err := CheckBlobName(bad); err == nil {
|
||||
t.Errorf("%q accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package attestation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// Transparency log (Rekor) policy for the cosign module (owner decision
|
||||
// 2026-10-11).
|
||||
//
|
||||
// Uploading to the public Sigstore Rekor is OFF unless asked for. An entry
|
||||
// there is public and permanent, and for an attestation it carries the
|
||||
// provenance itself: registry and git hosts, repository paths, the CI job URL
|
||||
// and the commit. A tenant opts in per pipeline (`--public-rekor`) or points
|
||||
// the module at its own Rekor (`--rekor-url`), which wins when both are given.
|
||||
//
|
||||
// KEYLESS signing is the exception: a Fulcio certificate lives ten minutes, so
|
||||
// a keyless signature with no log entry cannot be verified afterwards. Keyless
|
||||
// calls therefore keep the public log unless --rekor-url names a private one
|
||||
// (see KeylessTlogArgs). Owner decision 2026-10-18: keyless is an explicit
|
||||
// per-service opt-in with a disclosure that the entry is public; keyed is the
|
||||
// default (see SignMethodMode). Verifying against a private Rekor needs that
|
||||
// log's public key (CheckRekorPublicKey).
|
||||
|
||||
// rekorURLPattern is what a Rekor URL may look like once validated: https, a
|
||||
// host, an optional port and a plain path. No userinfo, query, fragment,
|
||||
// quote, `$`, backtick, backslash or whitespace — Sign joins its arguments
|
||||
// into an `sh -c` line, so the charset is the injection control too.
|
||||
var rekorURLPattern = regexp.MustCompile(`^https://[A-Za-z0-9.-]{1,253}(:[0-9]{1,5})?(/[A-Za-z0-9._~/-]{0,256})?$`)
|
||||
|
||||
// CheckRekorURL refuses anything but a plain https Rekor base URL.
|
||||
func CheckRekorURL(raw string) error {
|
||||
if !rekorURLPattern.MatchString(raw) {
|
||||
return fmt.Errorf("--rekor-url %q must be a plain https URL (host, optional port and path; no credentials, query or fragment)", raw)
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Hostname() == "" || u.User != nil {
|
||||
return fmt.Errorf("--rekor-url %q is not a usable https URL", raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SignTlogArgs are the cosign flags for a KEYED sign/attest/sign-blob:
|
||||
// a private Rekor when rekorURL is set, the public log only when publicRekor
|
||||
// is set, otherwise no upload at all.
|
||||
func SignTlogArgs(rekorURL string, publicRekor bool) ([]string, error) {
|
||||
if rekorURL != "" {
|
||||
if err := CheckRekorURL(rekorURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []string{"--rekor-url=" + rekorURL}, nil
|
||||
}
|
||||
if publicRekor {
|
||||
return nil, nil // cosign's default log is the public Sigstore Rekor
|
||||
}
|
||||
return []string{"--tlog-upload=false"}, nil
|
||||
}
|
||||
|
||||
// VerifyTlogArgs are the matching flags for a KEYED verification. A signature
|
||||
// that was never uploaded has no log entry, so without an opted-in log the
|
||||
// key alone is the trust anchor (`--insecure-ignore-tlog`, cosign's name for
|
||||
// exactly that). The verifier must make the same choice the signer made.
|
||||
func VerifyTlogArgs(rekorURL string, publicRekor bool) ([]string, error) {
|
||||
if rekorURL != "" {
|
||||
if err := CheckRekorURL(rekorURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []string{"--rekor-url=" + rekorURL}, nil
|
||||
}
|
||||
if publicRekor {
|
||||
return nil, nil
|
||||
}
|
||||
return []string{"--insecure-ignore-tlog=true"}, nil
|
||||
}
|
||||
|
||||
// KeylessTlogArgs are the flags for keyless signing or verification: the
|
||||
// private Rekor when one is named, else cosign's default (the public log).
|
||||
func KeylessTlogArgs(rekorURL string) ([]string, error) {
|
||||
if rekorURL == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if err := CheckRekorURL(rekorURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []string{"--rekor-url=" + rekorURL}, nil
|
||||
}
|
||||
|
||||
// RekorPublicKeyPath is where a private Rekor's public key is mounted inside
|
||||
// the cosign container. cosign reads SIGSTORE_REKOR_PUBLIC_KEY as a PATH to a
|
||||
// PEM file (pkg/cosign/tlog.go reads it with os.ReadFile), and when it is set
|
||||
// that key REPLACES the public Sigstore Rekor keys from the TUF root.
|
||||
const RekorPublicKeyPath = "/tmp/rekor.pub"
|
||||
|
||||
// CheckRekorPublicKey refuses a VERIFICATION against a private Rekor that has
|
||||
// no public key to check the log entry with (owner decision 2026-10-18).
|
||||
//
|
||||
// cosign verifies a log entry's signed entry timestamp (SET) against the Rekor
|
||||
// keys it trusts. Without SIGSTORE_REKOR_PUBLIC_KEY those are the public
|
||||
// Sigstore keys, so an entry from a private log can never verify: the call
|
||||
// fails, but only after a network round-trip and with an error that reads like
|
||||
// a broken signature. Refusing up front says what is missing. Nothing here
|
||||
// widens what passes: with the key, cosign still checks the SET, the inclusion
|
||||
// proof and the signature.
|
||||
func CheckRekorPublicKey(rekorURL string, hasKey bool) error {
|
||||
if rekorURL != "" && !hasKey {
|
||||
return fmt.Errorf("--rekor-url %q needs --rekor-public-key: cosign verifies the log entry against that log's own public key, and without it trusts only the public Sigstore Rekor, so the verification cannot pass", rekorURL)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SignMethodMode decides how `sign-method --method cosign` signs.
|
||||
//
|
||||
// Keyed is the default a rendered pipeline asks for (owner decision
|
||||
// 2026-10-18): `--key`. Keyless must be asked for (`--keyless`). Both at once
|
||||
// is refused rather than guessed.
|
||||
//
|
||||
// NEITHER is the call every pipeline rendered before 2026-10-18 makes, and the
|
||||
// modules are not version-pinned, so those pipelines run this code unchanged.
|
||||
// It stays keyless — what it always did — and legacy=true makes the caller
|
||||
// print LegacyKeylessNotice. Turning it into an error would break every
|
||||
// existing pipeline at once; turning it into keyed would need a key nobody
|
||||
// installed. Either would be a silent change of behaviour.
|
||||
func SignMethodMode(hasKey, keyless bool) (mode string, legacy bool, err error) {
|
||||
switch {
|
||||
case hasKey && keyless:
|
||||
return "", false, fmt.Errorf("--key and --keyless are mutually exclusive: choose keyed (--key) or keyless (--keyless)")
|
||||
case hasKey:
|
||||
return "keyed", false, nil
|
||||
case keyless:
|
||||
return "keyless", false, nil
|
||||
default:
|
||||
return "keyless", true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// LegacyKeylessNotice is printed (and returned in SignResult.Notice) when a
|
||||
// pipeline signs keyless only because it named no mode.
|
||||
const LegacyKeylessNotice = "NOTICE: this pipeline signs KEYLESS because it names no signing mode " +
|
||||
"(rendered before 2026-10-18). Keyless signing writes the signing identity and image digest " +
|
||||
"to the PUBLIC Sigstore transparency log, permanently. New pipelines sign with a key and " +
|
||||
"upload nowhere by default. To migrate: install a cosign key in the CI engine and set " +
|
||||
"governance.image_signing_mode: keyed. (A private Rekor keeps signature entries private, " +
|
||||
"but the public Fulcio CA still logs each signing certificate publicly.) See " +
|
||||
"docs/customer-docs/image-signing.md."
|
||||
|
||||
// AnchorRegex makes a certificate identity / issuer regex match the WHOLE
|
||||
// value (#2435). cosign matches with Go's regexp, which finds a match
|
||||
// anywhere, so `https://token\.actions\.githubusercontent\.com` also accepted
|
||||
// `https://token.actions.githubusercontent.com.attacker.example`. Wrapping is
|
||||
// always done, even when the caller already wrote ^…$: `^a|b$` only anchors
|
||||
// each side of the alternation, and `^(?:^a$)$` means the same as `^a$`.
|
||||
//
|
||||
// Callers must CheckRegex the raw value first: `x)|(.*` does not compile on
|
||||
// its own, but wrapped it becomes `^(?:x)|(.*)$`, which compiles and matches
|
||||
// anything.
|
||||
func AnchorRegex(re string) string {
|
||||
if re == "" {
|
||||
return ""
|
||||
}
|
||||
return "^(?:" + re + ")$"
|
||||
}
|
||||
|
||||
// CheckRegex refuses a regex that does not compile on its own, so that
|
||||
// AnchorRegex's wrapper cannot be escaped with unbalanced parentheses.
|
||||
func CheckRegex(flag, re string) error {
|
||||
if _, err := regexp.Compile(re); err != nil {
|
||||
return fmt.Errorf("%s is not a valid regular expression: %w", flag, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package attestation
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// MUTATION-CHECK (staging, both directions):
|
||||
// - AnchorRegex returns re unchanged → TestAnchoredIssuerRefusesExtendedIssuers FAILS;
|
||||
// - AnchorRegex over-tightens (e.g. QuoteMeta) → the legitimate issuer case FAILS;
|
||||
// - SignTlogArgs returns nil by default → TestKeyedSigningDoesNotUploadByDefault FAILS;
|
||||
// - SignTlogArgs ignores rekorURL → TestPrivateRekorWinsOverPublic FAILS;
|
||||
// - CheckRekorURL accepts everything → TestRekorURLRefusesUnsafeValues FAILS;
|
||||
// refuses everything → TestPrivateRekorWinsOverPublic FAILS.
|
||||
|
||||
const ghIssuer = `https://token\.actions\.githubusercontent\.com`
|
||||
|
||||
// #2435: cosign matches with Go's regexp, which finds a match anywhere. The
|
||||
// anchored form must refuse an issuer that only CONTAINS the expected one.
|
||||
func TestAnchoredIssuerRefusesExtendedIssuers(t *testing.T) {
|
||||
re := regexp.MustCompile(AnchorRegex(ghIssuer))
|
||||
if !re.MatchString("https://token.actions.githubusercontent.com") {
|
||||
t.Fatal("the legitimate issuer must still match")
|
||||
}
|
||||
for _, bad := range []string{
|
||||
"https://token.actions.githubusercontent.com.attacker.example",
|
||||
"https://evil.example/?https://token.actions.githubusercontent.com",
|
||||
"xhttps://token.actions.githubusercontent.com",
|
||||
"https://token.actions.githubusercontent.com/",
|
||||
} {
|
||||
if re.MatchString(bad) {
|
||||
t.Errorf("anchored issuer regex matched %q", bad)
|
||||
}
|
||||
// The control: the unanchored regex is what let these through.
|
||||
if !regexp.MustCompile(ghIssuer).MatchString(bad) {
|
||||
t.Errorf("control: unanchored regex should match %q (test is not exercising the bug)", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `^a|b$` anchors each side of the alternation only; the wrapper must anchor
|
||||
// the whole expression.
|
||||
func TestAnchorRegexAnchorsAlternation(t *testing.T) {
|
||||
re := regexp.MustCompile(AnchorRegex(`^https://a\.example|https://b\.example$`))
|
||||
if !re.MatchString("https://a.example") || !re.MatchString("https://b.example") {
|
||||
t.Fatal("both alternatives must still match")
|
||||
}
|
||||
if re.MatchString("https://a.example.evil") || re.MatchString("evil-https://b.example") {
|
||||
t.Fatal("an alternation must not escape the anchors")
|
||||
}
|
||||
if AnchorRegex("") != "" {
|
||||
t.Fatal("an empty regex stays empty (caller decides what empty means)")
|
||||
}
|
||||
}
|
||||
|
||||
// Review finding: wrapping alone is escapable. `x)|(.*` compiles once wrapped
|
||||
// and matches anything, so the raw value must compile on its own first.
|
||||
// MUTANT: CheckRegex returns nil → this test FAILS.
|
||||
func TestUnbalancedRegexCannotEscapeTheAnchor(t *testing.T) {
|
||||
escape := `x)|(.*`
|
||||
if _, err := regexp.Compile(AnchorRegex(escape)); err != nil {
|
||||
t.Fatalf("control: the wrapped escape must compile (that is the bug): %v", err)
|
||||
}
|
||||
if err := CheckRegex("--issuer-regex", escape); err == nil {
|
||||
t.Fatal("an unbalanced regex must be refused before it is wrapped")
|
||||
}
|
||||
if err := CheckRegex("--issuer-regex", ghIssuer); err != nil {
|
||||
t.Fatalf("a legitimate regex must pass: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyAttestationArgsAnchorsBothRegexes(t *testing.T) {
|
||||
args := strings.Join(VerifyAttestationArgs(imageA, vBuilder, `.+@acme\.example`, ghIssuer), " ")
|
||||
if !strings.Contains(args, "--certificate-oidc-issuer-regexp ^(?:"+ghIssuer+")$") {
|
||||
t.Fatalf("issuer not anchored: %s", args)
|
||||
}
|
||||
if !strings.Contains(args, `--certificate-identity-regexp ^(?:.+@acme\.example)$`) {
|
||||
t.Fatalf("identity not anchored: %s", args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyedSigningDoesNotUploadByDefault(t *testing.T) {
|
||||
got, err := SignTlogArgs("", false)
|
||||
if err != nil || strings.Join(got, " ") != "--tlog-upload=false" {
|
||||
t.Fatalf("default sign args = %v, %v; want --tlog-upload=false", got, err)
|
||||
}
|
||||
got, err = VerifyTlogArgs("", false)
|
||||
if err != nil || strings.Join(got, " ") != "--insecure-ignore-tlog=true" {
|
||||
t.Fatalf("default verify args = %v, %v; want --insecure-ignore-tlog=true", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicRekorIsAnExplicitOptIn(t *testing.T) {
|
||||
for name, fn := range map[string]func(string, bool) ([]string, error){
|
||||
"sign": SignTlogArgs, "verify": VerifyTlogArgs,
|
||||
} {
|
||||
got, err := fn("", true)
|
||||
if err != nil || len(got) != 0 {
|
||||
t.Fatalf("%s: opted-in public log must use cosign's default, got %v, %v", name, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivateRekorWinsOverPublic(t *testing.T) {
|
||||
const private = "https://rekor.acme.example:8443/base"
|
||||
for name, fn := range map[string]func(string, bool) ([]string, error){
|
||||
"sign": SignTlogArgs, "verify": VerifyTlogArgs,
|
||||
} {
|
||||
got, err := fn(private, true)
|
||||
if err != nil || strings.Join(got, " ") != "--rekor-url="+private {
|
||||
t.Fatalf("%s: got %v, %v; want --rekor-url=%s", name, got, err, private)
|
||||
}
|
||||
}
|
||||
got, err := KeylessTlogArgs(private)
|
||||
if err != nil || strings.Join(got, " ") != "--rekor-url="+private {
|
||||
t.Fatalf("keyless: got %v, %v", got, err)
|
||||
}
|
||||
if got, err := KeylessTlogArgs(""); err != nil || len(got) != 0 {
|
||||
t.Fatalf("keyless without a private log keeps cosign's default, got %v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Owner decision 2026-10-18: verifying against a private Rekor needs its
|
||||
// public key; without it the call is refused before cosign runs.
|
||||
// MUTANTS (staging):
|
||||
// - CheckRekorPublicKey returns nil → the "refused" case FAILS;
|
||||
// - it refuses whenever rekorURL is set (ignores hasKey) → the "with key" case FAILS;
|
||||
// - it refuses with no rekorURL → the public/keyed cases FAIL.
|
||||
func TestPrivateRekorVerificationNeedsItsPublicKey(t *testing.T) {
|
||||
const private = "https://rekor.acme.example"
|
||||
if err := CheckRekorPublicKey(private, false); err == nil {
|
||||
t.Fatal("a private Rekor without its public key must be refused")
|
||||
} else if !strings.Contains(err.Error(), "--rekor-public-key") {
|
||||
t.Fatalf("the refusal must name the missing flag, got %v", err)
|
||||
}
|
||||
if err := CheckRekorPublicKey(private, true); err != nil {
|
||||
t.Fatalf("a private Rekor WITH its public key must pass: %v", err)
|
||||
}
|
||||
// No private log: public log (keyless) or no log (keyed) — no key needed.
|
||||
if err := CheckRekorPublicKey("", false); err != nil {
|
||||
t.Fatalf("no private Rekor needs no key: %v", err)
|
||||
}
|
||||
if err := CheckRekorPublicKey("", true); err != nil {
|
||||
t.Fatalf("a key without a private Rekor is harmless: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// MUTANTS (staging):
|
||||
// - the default case returns ("keyed", false, nil) → legacy case FAILS (and
|
||||
// every pre-2026-10-18 pipeline would break: no key installed);
|
||||
// - the default case returns an error → legacy case FAILS;
|
||||
// - hasKey&&keyless returns keyed → the conflict case FAILS.
|
||||
func TestSignMethodModeKeyedExplicitKeylessAndLegacy(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
hasKey, keyles bool
|
||||
mode string
|
||||
legacy, errors bool
|
||||
}{
|
||||
{"keyed", true, false, "keyed", false, false},
|
||||
{"explicit keyless", false, true, "keyless", false, false},
|
||||
{"legacy (no mode named)", false, false, "keyless", true, false},
|
||||
{"both refused", true, true, "", false, true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
mode, legacy, err := SignMethodMode(c.hasKey, c.keyles)
|
||||
if (err != nil) != c.errors {
|
||||
t.Fatalf("%s: err=%v, want error=%v", c.name, err, c.errors)
|
||||
}
|
||||
if mode != c.mode || legacy != c.legacy {
|
||||
t.Fatalf("%s: got (%q, legacy=%v), want (%q, legacy=%v)", c.name, mode, legacy, c.mode, c.legacy)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(LegacyKeylessNotice, "PUBLIC") || !strings.Contains(LegacyKeylessNotice, "image_signing_mode") {
|
||||
t.Fatal("the legacy notice must disclose the public log and name the migration setting")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRekorURLRefusesUnsafeValues(t *testing.T) {
|
||||
for _, bad := range []string{
|
||||
"http://rekor.acme.example",
|
||||
"https://user:pw@rekor.acme.example",
|
||||
"https://rekor.acme.example/?x=1",
|
||||
"https://rekor.acme.example/#frag",
|
||||
"https://rekor.acme.example/$(id)",
|
||||
"https://rekor.acme.example/a b",
|
||||
"https://rekor.acme.example';id;'",
|
||||
"rekor.acme.example",
|
||||
"https://",
|
||||
} {
|
||||
if err := CheckRekorURL(bad); err == nil {
|
||||
t.Errorf("CheckRekorURL accepted %q", bad)
|
||||
}
|
||||
if _, err := SignTlogArgs(bad, false); err == nil {
|
||||
t.Errorf("SignTlogArgs accepted %q", bad)
|
||||
}
|
||||
}
|
||||
if err := CheckRekorURL("https://rekor.acme.example"); err != nil {
|
||||
t.Fatalf("a plain https URL must pass: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package attestation
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// InTotoPayloadType is the DSSE payloadType of an in-toto Statement.
|
||||
const InTotoPayloadType = "application/vnd.in-toto+json"
|
||||
|
||||
// ProvenanceExpectation is what a verified provenance must say. Every field
|
||||
// is compared exactly — never as a substring of the raw cosign output.
|
||||
type ProvenanceExpectation struct {
|
||||
// Image the attestations were fetched for; must be digest-pinned, and a
|
||||
// statement only counts when one of its subjects carries that sha256.
|
||||
Image string
|
||||
// BuilderID must equal predicate.runDetails.builder.id byte for byte.
|
||||
BuilderID string
|
||||
// SourceRepo is the repository URI without a ref or commit, e.g.
|
||||
// "https://github.com/acme/app". A resolvedDependency counts when its uri,
|
||||
// with an optional `git+` prefix and `.git` suffix, is that repository
|
||||
// alone or that repository followed by `@<ref>`.
|
||||
SourceRepo string
|
||||
}
|
||||
|
||||
// VerifiedProvenance describes the statement that satisfied the expectation.
|
||||
type VerifiedProvenance struct {
|
||||
BuilderID string
|
||||
SourceURI string
|
||||
Subjects []string // "<name>@sha256:<hex>" for each sha256 subject
|
||||
}
|
||||
|
||||
type envelope struct {
|
||||
PayloadType string `json:"payloadType"`
|
||||
Payload string `json:"payload"`
|
||||
Signatures []json.RawMessage `json:"signatures"`
|
||||
}
|
||||
|
||||
type provenancePredicate struct {
|
||||
BuildDefinition struct {
|
||||
ResolvedDependencies []struct {
|
||||
URI string `json:"uri"`
|
||||
Digest map[string]string `json:"digest"`
|
||||
} `json:"resolvedDependencies"`
|
||||
} `json:"buildDefinition"`
|
||||
RunDetails struct {
|
||||
Builder struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"builder"`
|
||||
} `json:"runDetails"`
|
||||
}
|
||||
|
||||
// VerifyAttestationArgs is the `cosign verify-attestation` command line for a
|
||||
// keyless provenance check. The signer is the trust anchor, not the builder.id
|
||||
// string inside what it signed: with no identityRegex the certificate identity
|
||||
// must equal builderID exactly, so a statement that names the expected builder
|
||||
// only counts when that builder signed it.
|
||||
//
|
||||
// Both regexes are anchored to the whole value (AnchorRegex, #2435): cosign
|
||||
// matches anywhere in the string, so an unanchored issuer regex also admitted
|
||||
// an issuer that merely contained the expected one.
|
||||
func VerifyAttestationArgs(image, builderID, identityRegex, issuerRegex string) []string {
|
||||
args := []string{
|
||||
"cosign", "verify-attestation",
|
||||
"--type", "slsaprovenance1",
|
||||
"--certificate-oidc-issuer-regexp", AnchorRegex(issuerRegex),
|
||||
}
|
||||
if identityRegex != "" {
|
||||
args = append(args, "--certificate-identity-regexp", AnchorRegex(identityRegex))
|
||||
} else {
|
||||
args = append(args, "--certificate-identity", builderID)
|
||||
}
|
||||
return append(args, image)
|
||||
}
|
||||
|
||||
// VerifyProvenanceOutput checks the stdout of `cosign verify-attestation
|
||||
// --type slsaprovenance1`: one DSSE envelope per verified attestation (cosign
|
||||
// v2 prints `sig.Payload()` of each; certificate details go to stderr).
|
||||
//
|
||||
// cosign has already checked the signatures and the predicate type; this
|
||||
// checks what the signed statement SAYS. It succeeds when at least one
|
||||
// envelope decodes to an in-toto Statement whose predicate is SLSA v1
|
||||
// provenance, whose subject includes the image digest, whose builder.id equals
|
||||
// the expected builder, and whose SOURCE — the first resolvedDependency, which
|
||||
// is where SLSA builders and both producers in this repo put it — is the
|
||||
// expected repository pinned to a commit. Later dependencies are inputs, not
|
||||
// the source: a repo that vendors the expected one must not pass as it.
|
||||
//
|
||||
// builder.id is a string the signer wrote; it is only as trustworthy as the
|
||||
// signing identity cosign checked. The caller binds the two (VerifyProvenance
|
||||
// passes --certificate-identity=<builder id> unless given a regex).
|
||||
//
|
||||
// Fail-closed: output that is not a stream of DSSE envelopes, an envelope that
|
||||
// is not an in-toto payload or does not decode, and empty output are refused
|
||||
// outright rather than skipped — cosign printing something we cannot read is
|
||||
// not evidence of anything. The whole stream is read before deciding, so this
|
||||
// holds after a match too. Well-formed statements that simply do not match
|
||||
// (another builder signing the same digest) do not count, and the error names
|
||||
// what each one got wrong.
|
||||
func VerifyProvenanceOutput(out []byte, want ProvenanceExpectation) (*VerifiedProvenance, error) {
|
||||
digest, err := ImageDigest(want.Image)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if want.BuilderID == "" || strings.TrimSpace(want.BuilderID) != want.BuilderID {
|
||||
return nil, fmt.Errorf("expected builder id %q must be non-empty with no surrounding whitespace", want.BuilderID)
|
||||
}
|
||||
repo := normaliseRepo(want.SourceRepo)
|
||||
if repo == "" || strings.ContainsAny(want.SourceRepo, " \t\r\n") {
|
||||
return nil, fmt.Errorf("expected source repo %q must be a non-empty URI without whitespace", want.SourceRepo)
|
||||
}
|
||||
if carriesRef(repo) {
|
||||
// "…/app@refs/heads/main" as the expectation would make every ref of
|
||||
// that branch name match, and reads as if the ref were checked.
|
||||
return nil, fmt.Errorf("expected source repo %q must not carry a ref (drop the @<ref> suffix)", want.SourceRepo)
|
||||
}
|
||||
|
||||
dec := json.NewDecoder(bytes.NewReader(out))
|
||||
var mismatches []string
|
||||
var found *VerifiedProvenance
|
||||
n := 0
|
||||
for {
|
||||
var env envelope
|
||||
if err := dec.Decode(&env); errors.Is(err, io.EOF) {
|
||||
break
|
||||
} else if err != nil {
|
||||
return nil, fmt.Errorf("cosign output is not a stream of DSSE envelopes: %w", err)
|
||||
}
|
||||
n++
|
||||
st, err := decodeEnvelope(env)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("attestation %d: %w", n, err)
|
||||
}
|
||||
vp, why := matchStatement(st, digest, want.BuilderID, repo)
|
||||
if vp != nil {
|
||||
if found == nil {
|
||||
found = vp
|
||||
}
|
||||
continue
|
||||
}
|
||||
mismatches = append(mismatches, fmt.Sprintf("attestation %d: %s", n, why))
|
||||
}
|
||||
if n == 0 {
|
||||
return nil, fmt.Errorf("cosign verified no provenance attestation")
|
||||
}
|
||||
if found != nil {
|
||||
return found, nil
|
||||
}
|
||||
return nil, fmt.Errorf("no provenance matches builder %q, source %q and sha256 %s (%s)",
|
||||
want.BuilderID, want.SourceRepo, digest, strings.Join(mismatches, "; "))
|
||||
}
|
||||
|
||||
func decodeEnvelope(env envelope) (*statement, error) {
|
||||
if env.PayloadType != InTotoPayloadType {
|
||||
return nil, fmt.Errorf("DSSE payloadType %q is not %s", env.PayloadType, InTotoPayloadType)
|
||||
}
|
||||
if len(env.Signatures) == 0 {
|
||||
return nil, fmt.Errorf("DSSE envelope carries no signature")
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(env.Payload)
|
||||
if err != nil {
|
||||
// Some producers emit URL-safe base64; DSSE allows either.
|
||||
if raw, err = base64.URLEncoding.DecodeString(env.Payload); err != nil {
|
||||
return nil, fmt.Errorf("DSSE payload is not base64: %w", err)
|
||||
}
|
||||
}
|
||||
var st statement
|
||||
if err := json.Unmarshal(raw, &st); err != nil {
|
||||
return nil, fmt.Errorf("DSSE payload is not an in-toto Statement: %w", err)
|
||||
}
|
||||
switch st.Type {
|
||||
case "https://in-toto.io/Statement/v1", "https://in-toto.io/Statement/v0.1":
|
||||
default:
|
||||
return nil, fmt.Errorf("statement _type %q is not an in-toto Statement", st.Type)
|
||||
}
|
||||
return &st, nil
|
||||
}
|
||||
|
||||
// matchStatement returns the verified provenance, or why the statement does
|
||||
// not satisfy the expectation.
|
||||
func matchStatement(st *statement, digest, builderID, repo string) (*VerifiedProvenance, string) {
|
||||
if st.PredicateType != SLSAProvenanceV1 {
|
||||
return nil, fmt.Sprintf("predicateType %q is not %s", st.PredicateType, SLSAProvenanceV1)
|
||||
}
|
||||
var subjects []string
|
||||
about := false
|
||||
for _, s := range st.Subject {
|
||||
d := strings.ToLower(s.Digest["sha256"])
|
||||
if d == "" {
|
||||
continue
|
||||
}
|
||||
subjects = append(subjects, s.Name+"@sha256:"+d)
|
||||
if d == digest {
|
||||
about = true
|
||||
}
|
||||
}
|
||||
if !about {
|
||||
return nil, fmt.Sprintf("no subject with sha256 %s", digest)
|
||||
}
|
||||
var p provenancePredicate
|
||||
if err := json.Unmarshal(st.Predicate, &p); err != nil {
|
||||
return nil, fmt.Sprintf("predicate is not SLSA v1 provenance: %v", err)
|
||||
}
|
||||
if got := p.RunDetails.Builder.ID; got != builderID {
|
||||
return nil, fmt.Sprintf("builder.id is %q", got)
|
||||
}
|
||||
deps := p.BuildDefinition.ResolvedDependencies
|
||||
if len(deps) == 0 {
|
||||
return nil, "no resolvedDependencies: the source is not recorded"
|
||||
}
|
||||
src := deps[0]
|
||||
if !sameRepo(src.URI, repo) {
|
||||
return nil, fmt.Sprintf("source (first resolvedDependency) is %q", src.URI)
|
||||
}
|
||||
if !pinnedToCommit(src.Digest) {
|
||||
return nil, "source is not pinned to a commit (gitCommit/sha1/sha256 of 40 or 64 hex)"
|
||||
}
|
||||
return &VerifiedProvenance{BuilderID: builderID, SourceURI: src.URI, Subjects: subjects}, ""
|
||||
}
|
||||
|
||||
// pinnedToCommit reports a gitCommit / sha1 / sha256 digest that is a full
|
||||
// commit id. `{"gitCommit": "main"}` is a branch name, not a pin.
|
||||
func pinnedToCommit(d map[string]string) bool {
|
||||
for _, k := range []string{"gitCommit", "sha1", "sha256"} {
|
||||
if commitID.MatchString(strings.ToLower(d[k])) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// normaliseRepo drops the `git+` transport prefix and a trailing `.git` / `/`.
|
||||
func normaliseRepo(u string) string {
|
||||
u = strings.TrimPrefix(strings.TrimSpace(u), "git+")
|
||||
u = strings.TrimSuffix(u, "/")
|
||||
return strings.TrimSuffix(u, ".git")
|
||||
}
|
||||
|
||||
// carriesRef reports an "@" in the path of a URL ("https://h/o/r@ref"). The
|
||||
// userinfo "@" of "https://u@h/o/r" and of scp-style "git@h:o/r" is allowed.
|
||||
func carriesRef(repo string) bool {
|
||||
i := strings.Index(repo, "://")
|
||||
if i < 0 {
|
||||
colon := strings.Index(repo, ":")
|
||||
if colon < 0 {
|
||||
return strings.Contains(repo, "@")
|
||||
}
|
||||
return strings.LastIndex(repo, "@") > colon
|
||||
}
|
||||
rest := repo[i+3:]
|
||||
slash := strings.Index(rest, "/")
|
||||
return slash >= 0 && strings.Contains(rest[slash:], "@")
|
||||
}
|
||||
|
||||
// sameRepo reports whether a dependency uri names repo: exactly, or repo
|
||||
// followed by "@<ref>". "…/app-evil@…" and "…/app/fork@…" do not match "…/app".
|
||||
func sameRepo(uri, repo string) bool {
|
||||
u := strings.TrimPrefix(strings.TrimSpace(uri), "git+")
|
||||
for _, r := range []string{repo, repo + ".git"} {
|
||||
if u == r || u == r+"/" || strings.HasPrefix(u, r+"@") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
package attestation
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const (
|
||||
vBuilder = "https://github.com/acme/app/.github/workflows/release.yml@refs/tags/v1.2.3"
|
||||
vRepo = "https://github.com/acme/app"
|
||||
vSource = "git+https://github.com/acme/app@refs/tags/v1.2.3"
|
||||
)
|
||||
|
||||
var signer, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
|
||||
// pae is the DSSE v1 pre-authentication encoding the signature covers.
|
||||
func pae(payloadType string, payload []byte) []byte {
|
||||
return []byte(fmt.Sprintf("DSSEv1 %d %s %d %s", len(payloadType), payloadType, len(payload), payload))
|
||||
}
|
||||
|
||||
// envelopeLine builds a real, signed DSSE envelope exactly as cosign v2
|
||||
// `verify-attestation` prints it: one compact JSON object per line.
|
||||
func envelopeLine(t *testing.T, payloadType string, payload []byte) string {
|
||||
t.Helper()
|
||||
h := sha256.Sum256(pae(payloadType, payload))
|
||||
sig, err := ecdsa.SignASN1(rand.Reader, signer, h[:])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := json.Marshal(map[string]any{
|
||||
"payloadType": payloadType,
|
||||
"payload": base64.StdEncoding.EncodeToString(payload),
|
||||
"signatures": []map[string]string{{"keyid": "", "sig": base64.StdEncoding.EncodeToString(sig)}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(b) + "\n"
|
||||
}
|
||||
|
||||
type stOpts struct {
|
||||
typ, predicateType, builder, depURI, subjectDigest string
|
||||
depDigest map[string]string
|
||||
// extraDeps follow the source in resolvedDependencies; noDeps drops all.
|
||||
extraDeps []map[string]any
|
||||
noDeps bool
|
||||
}
|
||||
|
||||
func defaults() stOpts {
|
||||
return stOpts{
|
||||
typ: "https://in-toto.io/Statement/v1",
|
||||
predicateType: SLSAProvenanceV1,
|
||||
builder: vBuilder,
|
||||
depURI: vSource,
|
||||
subjectDigest: digestA,
|
||||
depDigest: map[string]string{"gitCommit": commit},
|
||||
}
|
||||
}
|
||||
|
||||
func statementJSON(t *testing.T, o stOpts) []byte {
|
||||
t.Helper()
|
||||
deps := append([]map[string]any{{"uri": o.depURI, "digest": o.depDigest}}, o.extraDeps...)
|
||||
if o.noDeps {
|
||||
deps = []map[string]any{}
|
||||
}
|
||||
b, err := json.Marshal(map[string]any{
|
||||
"_type": o.typ,
|
||||
"predicateType": o.predicateType,
|
||||
"subject": []map[string]any{{
|
||||
"name": "registry.example/team/orders",
|
||||
"digest": map[string]string{"sha256": o.subjectDigest},
|
||||
}},
|
||||
"predicate": map[string]any{
|
||||
"buildDefinition": map[string]any{
|
||||
"buildType": "https://actions.github.io/buildtypes/workflow/v1",
|
||||
// The expected builder id quoted where it does not count —
|
||||
// a substring match over the decoded statement would pass.
|
||||
"externalParameters": map[string]string{"source": o.depURI, "note": vBuilder + " " + vRepo},
|
||||
"resolvedDependencies": deps,
|
||||
},
|
||||
"runDetails": map[string]any{
|
||||
"builder": map[string]any{"id": o.builder, "version": map[string]string{"dagger-engine": "v0.21.7"}},
|
||||
"metadata": map[string]string{"invocationId": "42"},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func provenanceLine(t *testing.T, mut func(*stOpts)) string {
|
||||
o := defaults()
|
||||
if mut != nil {
|
||||
mut(&o)
|
||||
}
|
||||
return envelopeLine(t, InTotoPayloadType, statementJSON(t, o))
|
||||
}
|
||||
|
||||
func expect() ProvenanceExpectation {
|
||||
return ProvenanceExpectation{Image: imageA, BuilderID: vBuilder, SourceRepo: vRepo}
|
||||
}
|
||||
|
||||
func TestVerifyProvenanceOutputAcceptsMatchingStatement(t *testing.T) {
|
||||
vp, err := VerifyProvenanceOutput([]byte(provenanceLine(t, nil)), expect())
|
||||
if err != nil {
|
||||
t.Fatalf("legitimate provenance refused: %v", err)
|
||||
}
|
||||
if vp.BuilderID != vBuilder || vp.SourceURI != vSource {
|
||||
t.Fatalf("wrong verified fields: %+v", vp)
|
||||
}
|
||||
if len(vp.Subjects) != 1 || vp.Subjects[0] != "registry.example/team/orders@sha256:"+digestA {
|
||||
t.Fatalf("subjects: %v", vp.Subjects)
|
||||
}
|
||||
}
|
||||
|
||||
// Why #2337 exists: cosign prints the statement base64-encoded, so the old
|
||||
// strings.Contains(out, builderID) could never see the builder id at all.
|
||||
func TestBuilderIDIsNotPlainTextInCosignOutput(t *testing.T) {
|
||||
out := provenanceLine(t, nil)
|
||||
if strings.Contains(out, vBuilder) || strings.Contains(out, vRepo) {
|
||||
t.Fatal("fixture is not shaped like cosign output: the statement must be base64 inside the envelope")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyProvenanceOutputAcceptsLegitimateVariants(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
out string
|
||||
want func(*ProvenanceExpectation)
|
||||
}{
|
||||
"in-toto v0.1": {provenanceLine(t, func(o *stOpts) { o.typ = "https://in-toto.io/Statement/v0.1" }), nil},
|
||||
"dep without git+ and with .git": {provenanceLine(t, func(o *stOpts) {
|
||||
o.depURI = "https://github.com/acme/app.git@refs/heads/main"
|
||||
}), nil},
|
||||
"dep is the bare repo": {provenanceLine(t, func(o *stOpts) { o.depURI = vRepo }), nil},
|
||||
"expected repo with git+ and trailing slash": {provenanceLine(t, nil), func(w *ProvenanceExpectation) {
|
||||
w.SourceRepo = "git+https://github.com/acme/app/"
|
||||
}},
|
||||
"sha1 dep digest": {provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"sha1": commit} }), nil},
|
||||
"uppercase subject hex": {provenanceLine(t, func(o *stOpts) { o.subjectDigest = strings.ToUpper(digestA) }), nil},
|
||||
"image with registry port and no tag": {provenanceLine(t, nil), func(w *ProvenanceExpectation) {
|
||||
w.Image = "registry.example:5000/team/orders@sha256:" + digestA
|
||||
}},
|
||||
"scp-style expected repo": {provenanceLine(t, func(o *stOpts) { o.depURI = "git+git@github.com:acme/app.git@refs/tags/v1" }),
|
||||
func(w *ProvenanceExpectation) { w.SourceRepo = "git@github.com:acme/app" }},
|
||||
// A second builder attesting the same digest is legitimate; the gate
|
||||
// asks whether the EXPECTED builder vouched for it.
|
||||
"other builder first, expected second": {
|
||||
provenanceLine(t, func(o *stOpts) { o.builder = "https://ci.example/other" }) + provenanceLine(t, nil), nil},
|
||||
"dep with trailing slash": {provenanceLine(t, func(o *stOpts) { o.depURI = vRepo + "/" }), nil},
|
||||
// carriesRef must allow the userinfo "@" of an https URL.
|
||||
"https expected repo with userinfo": {provenanceLine(t, func(o *stOpts) { o.depURI = "git+https://git@github.com/acme/app@refs/tags/v1" }),
|
||||
func(w *ProvenanceExpectation) { w.SourceRepo = "https://git@github.com/acme/app" }},
|
||||
"envelopes without trailing newline": {strings.TrimSuffix(provenanceLine(t, nil), "\n"), nil},
|
||||
// Later dependencies are build inputs; only the first is the source.
|
||||
"source first, other inputs after": {provenanceLine(t, func(o *stOpts) {
|
||||
o.extraDeps = []map[string]any{{"uri": "pkg:golang/example.test/lib@v1", "digest": map[string]string{"sha256": digestB}}}
|
||||
}), nil},
|
||||
"uppercase commit hex": {provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"gitCommit": strings.ToUpper(commit)} }), nil},
|
||||
"64-hex sha256 commit": {provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"sha256": digestA} }), nil},
|
||||
}
|
||||
for name, c := range cases {
|
||||
w := expect()
|
||||
if c.want != nil {
|
||||
c.want(&w)
|
||||
}
|
||||
if _, err := VerifyProvenanceOutput([]byte(c.out), w); err != nil {
|
||||
t.Errorf("%s: refused: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyProvenanceOutputRefusesMismatches(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
// Substring/prefix relations a strings.Contains check would accept.
|
||||
"builder id extends expected": provenanceLine(t, func(o *stOpts) { o.builder = vBuilder + "-rc1" }),
|
||||
"builder id is a prefix": provenanceLine(t, func(o *stOpts) { o.builder = strings.TrimSuffix(vBuilder, ".3") }),
|
||||
"builder id differs in case": provenanceLine(t, func(o *stOpts) { o.builder = strings.ToUpper(vBuilder) }),
|
||||
"builder only in a note": provenanceLine(t, func(o *stOpts) { o.builder = "https://ci.example/attacker" }),
|
||||
"repo name extended": provenanceLine(t, func(o *stOpts) { o.depURI = "git+https://github.com/acme/app-evil@refs/tags/v1.2.3" }),
|
||||
"repo is a sub path": provenanceLine(t, func(o *stOpts) { o.depURI = "git+https://github.com/acme/app/fork@refs/tags/v1.2.3" }),
|
||||
"repo on another host": provenanceLine(t, func(o *stOpts) { o.depURI = "git+https://github.com.evil.test/acme/app@refs/tags/v1" }),
|
||||
"dep has no digest": provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{} }),
|
||||
"dep digest is blank": provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"gitCommit": " "} }),
|
||||
// A digest that is not a full commit id pins nothing.
|
||||
"dep digest is a branch name": provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"gitCommit": "main"} }),
|
||||
"dep digest is a short sha": provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"gitCommit": commit[:12]} }),
|
||||
"dep digest under another key": provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"md5": commit} }),
|
||||
"no resolvedDependencies": provenanceLine(t, func(o *stOpts) { o.noDeps = true }),
|
||||
// A repo that vendors the expected one lists it as a later input; it
|
||||
// must not pass as having been built from it.
|
||||
"expected repo only as a later dependency": provenanceLine(t, func(o *stOpts) {
|
||||
o.depURI = "git+https://github.com/attacker/app@refs/heads/main"
|
||||
o.extraDeps = []map[string]any{{"uri": vSource, "digest": map[string]string{"gitCommit": commit}}}
|
||||
}),
|
||||
// The statement is about another artifact.
|
||||
"subject is another digest": provenanceLine(t, func(o *stOpts) { o.subjectDigest = digestB }),
|
||||
"wrong predicate type": provenanceLine(t, func(o *stOpts) { o.predicateType = "https://slsa.dev/provenance/v0.2" }),
|
||||
}
|
||||
for name, out := range cases {
|
||||
if _, err := VerifyProvenanceOutput([]byte(out), expect()); err == nil {
|
||||
t.Errorf("%s: must be refused", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyProvenanceOutputRefusesUnreadableOutput(t *testing.T) {
|
||||
good := provenanceLine(t, nil)
|
||||
notBase64, _ := json.Marshal(map[string]any{
|
||||
"payloadType": InTotoPayloadType, "payload": "%%%not base64%%%",
|
||||
"signatures": []map[string]string{{"sig": "AA=="}},
|
||||
})
|
||||
unsigned, _ := json.Marshal(map[string]any{
|
||||
"payloadType": InTotoPayloadType,
|
||||
"payload": base64.StdEncoding.EncodeToString(statementJSON(t, defaults())),
|
||||
"signatures": []map[string]string{},
|
||||
})
|
||||
cases := map[string]string{
|
||||
"empty output": "",
|
||||
"only whitespace": "\n \n",
|
||||
"plain text with the ids": "verified " + vBuilder + " from " + vRepo + " sha256:" + digestA + "\n",
|
||||
"truncated envelope": good[:len(good)/2],
|
||||
"wrong payload type": envelopeLine(t, "text/plain", statementJSON(t, defaults())),
|
||||
"payload not base64": string(notBase64) + "\n",
|
||||
"payload not json": envelopeLine(t, InTotoPayloadType, []byte("not json")),
|
||||
"not an in-toto type": envelopeLine(t, InTotoPayloadType, statementJSON(t, stOpts{typ: "https://example.test/Statement", predicateType: SLSAProvenanceV1, builder: vBuilder, depURI: vSource, subjectDigest: digestA, depDigest: map[string]string{"gitCommit": commit}})),
|
||||
"envelope with no signature": string(unsigned) + "\n",
|
||||
// Fail-closed: an unreadable envelope is not skipped even when a
|
||||
// good one follows — cosign printing something we cannot parse means
|
||||
// our model of its output is wrong.
|
||||
"garbage before a good envelope": envelopeLine(t, InTotoPayloadType, []byte("{")) + good,
|
||||
// ...and the whole stream is read before deciding, so garbage after
|
||||
// a match is refused too.
|
||||
"garbage after a good envelope": good + envelopeLine(t, InTotoPayloadType, []byte("{")),
|
||||
"truncated envelope after a good one": good + good[:len(good)/2],
|
||||
}
|
||||
for name, out := range cases {
|
||||
if _, err := VerifyProvenanceOutput([]byte(out), expect()); err == nil {
|
||||
t.Errorf("%s: must be refused", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyProvenanceOutputRefusesBadExpectations(t *testing.T) {
|
||||
out := []byte(provenanceLine(t, nil))
|
||||
cases := map[string]func(*ProvenanceExpectation){
|
||||
"tag-only image": func(w *ProvenanceExpectation) { w.Image = "registry.example/team/orders:abc" },
|
||||
"empty builder": func(w *ProvenanceExpectation) { w.BuilderID = "" },
|
||||
"padded builder": func(w *ProvenanceExpectation) { w.BuilderID = " " + vBuilder },
|
||||
"empty repo": func(w *ProvenanceExpectation) { w.SourceRepo = "" },
|
||||
"repo with whitespace": func(w *ProvenanceExpectation) { w.SourceRepo = vRepo + " x" },
|
||||
"repo carrying a ref": func(w *ProvenanceExpectation) { w.SourceRepo = vRepo + "@refs/tags/v1.2.3" },
|
||||
"scp repo carrying a ref": func(w *ProvenanceExpectation) { w.SourceRepo = "git@github.com:acme/app@v1" },
|
||||
}
|
||||
for name, mut := range cases {
|
||||
w := expect()
|
||||
mut(&w)
|
||||
if _, err := VerifyProvenanceOutput(out, w); err == nil {
|
||||
t.Errorf("%s: must be refused", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The refusal says which field was wrong, so an operator can tell a wrong
|
||||
// --expected-builder-id from an image built elsewhere.
|
||||
func TestVerifyProvenanceOutputNamesTheMismatch(t *testing.T) {
|
||||
_, err := VerifyProvenanceOutput([]byte(provenanceLine(t, func(o *stOpts) { o.builder = "https://ci.example/other" })), expect())
|
||||
if err == nil || !strings.Contains(err.Error(), `builder.id is "https://ci.example/other"`) {
|
||||
t.Fatalf("error does not name the builder mismatch: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The signer, not the builder.id string it wrote, is the trust anchor: with no
|
||||
// identity regex cosign must be told the exact identity = the expected builder.
|
||||
func TestVerifyAttestationArgsBindsTheSignerToTheBuilder(t *testing.T) {
|
||||
issuer := `https://token\.actions\.githubusercontent\.com`
|
||||
got := strings.Join(VerifyAttestationArgs(imageA, vBuilder, "", issuer), " ")
|
||||
want := "cosign verify-attestation --type slsaprovenance1 --certificate-oidc-issuer-regexp " +
|
||||
"^(?:" + issuer + ")$ --certificate-identity " + vBuilder + " " + imageA
|
||||
if got != want {
|
||||
t.Fatalf("default args:\n got %s\nwant %s", got, want)
|
||||
}
|
||||
|
||||
re := `^https://github\.com/acme/app/\.github/workflows/release\.yml@refs/tags/v.*$`
|
||||
args := VerifyAttestationArgs(imageA, vBuilder, re, issuer)
|
||||
joined := strings.Join(args, " ")
|
||||
if !strings.Contains(joined, "--certificate-identity-regexp ^(?:"+re+")$") {
|
||||
t.Fatalf("regex not passed: %s", joined)
|
||||
}
|
||||
for _, a := range args {
|
||||
if a == "--certificate-identity" {
|
||||
t.Fatalf("regex and exact identity both passed: %s", joined)
|
||||
}
|
||||
}
|
||||
if args[len(args)-1] != imageA {
|
||||
t.Fatalf("image must be the last argument: %s", joined)
|
||||
}
|
||||
}
|
||||
|
||||
// The ref check must be what refuses: here the dep would otherwise match the
|
||||
// expectation exactly, so deleting carriesRef makes these pass.
|
||||
func TestExpectedRepoCarryingARefIsRefusedEvenWhenTheDepMatches(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"https": vRepo + "@refs/tags/v1.2.3",
|
||||
"scp": "git@github.com:acme/app@v1",
|
||||
}
|
||||
for name, repo := range cases {
|
||||
out := provenanceLine(t, func(o *stOpts) { o.depURI = "git+" + repo })
|
||||
w := expect()
|
||||
w.SourceRepo = repo
|
||||
_, err := VerifyProvenanceOutput([]byte(out), w)
|
||||
if err == nil || !strings.Contains(err.Error(), "must not carry a ref") {
|
||||
t.Errorf("%s: want the ref refusal, got %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "cosign",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go",
|
||||
"./attestation/attestation.go",
|
||||
"./attestation/gate.go",
|
||||
"./attestation/verify.go",
|
||||
"./attestation/tlog.go",
|
||||
"./policy/attestation_gate.rego"
|
||||
]
|
||||
}
|
||||
+1217
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,151 @@
|
||||
# IntegraCI attestation gate (#2143 phase 2).
|
||||
#
|
||||
# Decides whether ONE image digest carries the supply-chain evidence a
|
||||
# promotion needs. It judges the CONTENT of attestations whose signatures
|
||||
# have already been verified; it never sees a signature itself.
|
||||
#
|
||||
# Signature verification belongs to cosign. OPA has no builtin that verifies
|
||||
# a DSSE signature, so the caller runs
|
||||
# cosign verify-attestation --key <pub> --type <t> <image@digest>
|
||||
# and hands this policy the envelopes cosign printed. cosign prints only the
|
||||
# envelopes whose signature verified, so "present in input.envelopes" means
|
||||
# "signed by the key the caller trusted". The cosign module's
|
||||
# `verify-attestation-gate` function is that caller; a copy of this file is
|
||||
# embedded there (infra/dagger/cosign/policy/attestation_gate.rego, kept
|
||||
# byte-identical by apps/api/tests/test_supply_chain_phase2.py).
|
||||
#
|
||||
# The payload is DECODED and matched field by field. A substring search over
|
||||
# the raw cosign output, which is what `cosign verify-provenance` does today,
|
||||
# would accept a statement about another digest that merely mentions this one.
|
||||
#
|
||||
# Input:
|
||||
# {
|
||||
# "image": { "digest": "sha256:<64 hex>" },
|
||||
# "envelopes": [ # cosign verify-attestation output lines
|
||||
# { "payloadType": "application/vnd.in-toto+json",
|
||||
# "payload": "<base64 in-toto Statement>", "signatures": [...] }
|
||||
# ],
|
||||
# "policy": {
|
||||
# "trusted_builders": ["https://ci.example/job/orders/"], # exact builder.id
|
||||
# "require_sbom": false
|
||||
# }
|
||||
# }
|
||||
#
|
||||
# Every gap DENIES: no digest, no trusted builder configured, no provenance
|
||||
# for this digest, provenance from an untrusted builder, provenance that pins
|
||||
# no commit, and (when required) no SBOM for this digest.
|
||||
#
|
||||
# Run: opa test infra/policies/bundles/attestation-gate -v
|
||||
|
||||
# METADATA
|
||||
# title: Attestation gate
|
||||
# description: |
|
||||
# CI-side check that a signature-verified SLSA v1 provenance statement about
|
||||
# the image digest, from a trusted builder, is attached. Evaluated by the
|
||||
# cosign module's verify-attestation-gate inside the pipeline; NOT evaluated
|
||||
# at promotion (nothing in the deploy gate queries this package yet).
|
||||
package integraci.supply_chain.attestation_gate
|
||||
|
||||
import rego.v1
|
||||
|
||||
intoto_payload_type := "application/vnd.in-toto+json"
|
||||
|
||||
# cosign `attest --predicate` wraps the predicate in a Statement it builds
|
||||
# itself, and cosign 2.x may emit v0.1 rather than v1. Both carry the same
|
||||
# subject/predicateType/predicate fields; anything else is not in-toto.
|
||||
statement_types := {"https://in-toto.io/Statement/v1", "https://in-toto.io/Statement/v0.1"}
|
||||
|
||||
slsa_provenance_v1 := "https://slsa.dev/provenance/v1"
|
||||
|
||||
sbom_predicate_types := {"https://cyclonedx.org/bom", "https://spdx.dev/Document"}
|
||||
|
||||
# ── The digest under judgement ──────────────────────────────────────────────
|
||||
|
||||
digest_hex := hex if {
|
||||
regex.match(`^sha256:[0-9a-f]{64}$`, input.image.digest)
|
||||
hex := substring(input.image.digest, 7, -1)
|
||||
}
|
||||
|
||||
deny contains "image digest must be sha256:<64 lowercase hex>; a tag is not evidence" if {
|
||||
not digest_hex
|
||||
}
|
||||
|
||||
# ── Decoded statements ──────────────────────────────────────────────────────
|
||||
#
|
||||
# An envelope that is not in-toto, is not base64, or is not JSON is skipped,
|
||||
# not trusted: a builtin error leaves the comprehension element undefined.
|
||||
|
||||
statements contains st if {
|
||||
some env in input.envelopes
|
||||
env.payloadType == intoto_payload_type
|
||||
st := json.unmarshal(base64.decode(env.payload))
|
||||
st._type in statement_types
|
||||
}
|
||||
|
||||
about_digest(st) if {
|
||||
some subject in st.subject
|
||||
subject.digest.sha256 == digest_hex
|
||||
}
|
||||
|
||||
provenance_for_digest contains st if {
|
||||
some st in statements
|
||||
st.predicateType == slsa_provenance_v1
|
||||
about_digest(st)
|
||||
}
|
||||
|
||||
trusted_builders := {b | some b in input.policy.trusted_builders; is_string(b); b != ""}
|
||||
|
||||
pins_commit(st) if {
|
||||
some dep in st.predicate.buildDefinition.resolvedDependencies
|
||||
regex.match(`^([0-9a-f]{40}|[0-9a-f]{64})$`, dep.digest.gitCommit)
|
||||
}
|
||||
|
||||
trusted_provenance contains st if {
|
||||
some st in provenance_for_digest
|
||||
st.predicate.runDetails.builder.id in trusted_builders
|
||||
pins_commit(st)
|
||||
}
|
||||
|
||||
# ── Gates ───────────────────────────────────────────────────────────────────
|
||||
|
||||
deny contains "no trusted builder is configured; refusing to trust any provenance" if {
|
||||
count(trusted_builders) == 0
|
||||
}
|
||||
|
||||
deny contains msg if {
|
||||
digest_hex
|
||||
count(provenance_for_digest) == 0
|
||||
msg := sprintf("no signature-verified SLSA v1 provenance names %s", [input.image.digest])
|
||||
}
|
||||
|
||||
deny contains msg if {
|
||||
digest_hex
|
||||
count(trusted_builders) > 0
|
||||
count(provenance_for_digest) > 0
|
||||
count(trusted_provenance) == 0
|
||||
builders := sort({b | some st in provenance_for_digest; b := object.get(st, ["predicate", "runDetails", "builder", "id"], "<none>")})
|
||||
msg := sprintf(
|
||||
"provenance for %s comes from an untrusted builder or pins no full commit: %v",
|
||||
[input.image.digest, builders],
|
||||
)
|
||||
}
|
||||
|
||||
sbom_for_digest contains st if {
|
||||
some st in statements
|
||||
st.predicateType in sbom_predicate_types
|
||||
about_digest(st)
|
||||
}
|
||||
|
||||
deny contains msg if {
|
||||
input.policy.require_sbom == true
|
||||
digest_hex
|
||||
count(sbom_for_digest) == 0
|
||||
msg := sprintf("no signature-verified SBOM attestation names %s", [input.image.digest])
|
||||
}
|
||||
|
||||
allow if count(deny) == 0
|
||||
|
||||
result := {
|
||||
"allowed": count(deny) == 0,
|
||||
"deny": sort(deny),
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
# Dagger module: `dast-scan`
|
||||
|
||||
Dynamic Application Security Testing (DAST) — runs against a **deployed**
|
||||
HTTP target (typically the ephemeral preview environment from a PR
|
||||
deploy). Distinct from `security-scan` (SAST/SCA: scans source).
|
||||
|
||||
## Tools
|
||||
|
||||
| Function | Tool | Speed | Intrusiveness | When to run |
|
||||
|----------------|---------------------|--------|---------------|----------------------------------|
|
||||
| `zap-baseline` | OWASP ZAP baseline | 1-3min | Passive | Every PR + nightly against prod |
|
||||
| `zap-full` | OWASP ZAP active | 10-60m | Intrusive | PR preview env only |
|
||||
| `nuclei` | ProjectDiscovery | 1-5min | Passive | Every PR + nightly against prod |
|
||||
|
||||
> **Never run `zap-full` or destructive Nuclei templates against
|
||||
> production.** Use it only on the ephemeral env that the deploy pipeline
|
||||
> spins up for the PR. The CI workflow in `.github/workflows/security.yml`
|
||||
> only runs `zap-baseline` and `nuclei` against the public canary URL.
|
||||
|
||||
## Usage
|
||||
|
||||
### From CI (GitHub Actions)
|
||||
|
||||
The `dast` job in `.github/workflows/security.yml` calls:
|
||||
|
||||
```bash
|
||||
dagger call -m dagger/dast-scan zap-baseline \
|
||||
--target https://canary.integraci.co \
|
||||
--auth-header "Bearer $CANARY_TOKEN" \
|
||||
--fail-on high
|
||||
```
|
||||
|
||||
Findings → SARIF → `github/codeql-action/upload-sarif` → Security tab.
|
||||
|
||||
### From IntegraCI golden path pipelines
|
||||
|
||||
Add a step to `template.yaml` to run DAST against the per-PR
|
||||
ephemeral env after the deploy stage completes:
|
||||
|
||||
```yaml
|
||||
- id: dast
|
||||
name: DAST scan
|
||||
action: integraci:dagger:exec
|
||||
input:
|
||||
module: dast-scan
|
||||
function: zap-baseline
|
||||
args:
|
||||
target: ${{ steps.deploy-preview.output.url }}
|
||||
auth-header: "Bearer ${{ secrets.PREVIEW_TOKEN }}"
|
||||
fail-on: high
|
||||
```
|
||||
|
||||
### Locally (dev)
|
||||
|
||||
```bash
|
||||
dagger call -m dagger/dast-scan zap-baseline --target http://localhost:8000
|
||||
dagger call -m dagger/dast-scan nuclei --target http://localhost:8000 --severity critical,high
|
||||
```
|
||||
|
||||
## Failure thresholds
|
||||
|
||||
`fail-on` accepts `info` | `low` | `medium` | `high` | `critical`.
|
||||
Default is `high` — the run fails when **any** Critical or High
|
||||
finding is present.
|
||||
|
||||
## False positive workflow
|
||||
|
||||
1. Triage in the SARIF Security tab.
|
||||
2. If a finding is a true FP, add the rule ID to:
|
||||
- ZAP: `--ignore-rules 10038,10054`
|
||||
- Nuclei: built-in `-exclude-id` flag
|
||||
3. Document the rationale in `docs/security/dast-suppressions.md`
|
||||
(referenced by the OPA `golden_standard` policy — every suppression
|
||||
needs a docs entry or the self-audit fails).
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "dast-scan",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,592 @@
|
||||
// Package main implements the IntegraCI dast-scan Dagger module.
|
||||
//
|
||||
// Runs OWASP ZAP baseline + (optionally) full active scan and Nuclei
|
||||
// templates against a deployed HTTP target — typically an ephemeral
|
||||
// preview environment created by the deploy pipeline.
|
||||
//
|
||||
// The output is SARIF (uploadable to GitHub Security tab) plus a JSON
|
||||
// summary that the IntegraCI API consumes via /api/v1/scans.
|
||||
//
|
||||
// Usage (baseline scan, fast & non-intrusive — safe for production):
|
||||
//
|
||||
// dagger call zap-baseline \
|
||||
// --target https://preview-pr42.integraci.dev \
|
||||
// --auth-header "Authorization: Bearer $TOKEN"
|
||||
//
|
||||
// Usage (active scan, intrusive — only on ephemeral envs):
|
||||
//
|
||||
// dagger call zap-full \
|
||||
// --target https://preview-pr42.integraci.dev \
|
||||
// --auth-header "Authorization: Bearer $TOKEN" \
|
||||
// --max-duration 30
|
||||
//
|
||||
// Usage (Nuclei — CVE templates for the entire web stack):
|
||||
//
|
||||
// dagger call nuclei \
|
||||
// --target https://preview-pr42.integraci.dev \
|
||||
// --severity critical,high
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"dagger/dast-scan/internal/dagger"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DastScan is the IntegraCI dynamic application security testing module.
|
||||
type DastScan struct{}
|
||||
|
||||
// DASTResult is the normalised output for any DAST tool we run.
|
||||
type DASTResult struct {
|
||||
Tool string `json:"tool"` // "zap" | "nuclei"
|
||||
Mode string `json:"mode"` // "baseline" | "full" | "nuclei"
|
||||
Target string `json:"target"`
|
||||
Total int `json:"total"`
|
||||
Critical int `json:"critical"`
|
||||
High int `json:"high"`
|
||||
Medium int `json:"medium"`
|
||||
Low int `json:"low"`
|
||||
Info int `json:"info"`
|
||||
SarifReport string `json:"sarif_report,omitempty"`
|
||||
JSONReport string `json:"json_report,omitempty"`
|
||||
HTMLReport string `json:"html_report,omitempty"`
|
||||
Pass bool `json:"pass"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Scan is the engine-agnostic unified DAST entrypoint. It dispatches to a
|
||||
// scanner based on `tool` so any CI engine can run DAST with a single
|
||||
// `dagger call scan` invocation, no GitHub-Actions YAML required.
|
||||
//
|
||||
// - zap → reuses the ZapBaseline logic (zap-baseline.py, safe/passive)
|
||||
// - burp → POSTs to Burp Suite Enterprise's REST API
|
||||
// - acunetix → POSTs to the Acunetix REST API
|
||||
// - invicti → POSTs to the Invicti (Netsparker) REST API
|
||||
// - none → no-op (governance.dast=none), returns a skipped result
|
||||
//
|
||||
// Commercial scanners are off-cluster appliances: their API base URL is
|
||||
// deployment-specific and injected via the `${TOOL}_API_URL` env (the
|
||||
// `apiURL` arg), and the API key is passed as a Dagger secret — never
|
||||
// hardcoded.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call scan --target-url https://preview-pr42.integraci.dev
|
||||
// dagger call scan --target-url https://app.example.com --tool burp \
|
||||
// --api-url https://burp.internal:8443 --api-key env:BURP_API_KEY
|
||||
func (m *DastScan) Scan(
|
||||
ctx context.Context,
|
||||
// Target URL to scan (must be reachable from the Dagger runner)
|
||||
targetURL string,
|
||||
// DAST tool: zap | burp | acunetix | invicti | none
|
||||
// +optional
|
||||
// +default="zap"
|
||||
tool string,
|
||||
// Base URL of the commercial scanner's REST API ({TOOL}_API_URL).
|
||||
// Required for burp/acunetix/invicti, ignored for zap/none.
|
||||
// +optional
|
||||
apiURL string,
|
||||
// API key / token secret for the commercial scanner.
|
||||
// +optional
|
||||
apiKey *dagger.Secret,
|
||||
// Fail the run when this severity or above is found (zap only).
|
||||
// +optional
|
||||
// +default="high"
|
||||
failOn string,
|
||||
// IntegraCI API base URL for posting results back.
|
||||
// +optional
|
||||
integraciURL string,
|
||||
// JWT token for IntegraCI API authentication.
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// Service ID to link scan results.
|
||||
// +optional
|
||||
serviceID string,
|
||||
// Version (commit SHA / image tag) the scan applies to.
|
||||
// +optional
|
||||
version string,
|
||||
) (*DASTResult, error) {
|
||||
var (
|
||||
result *DASTResult
|
||||
err error
|
||||
)
|
||||
switch strings.ToLower(tool) {
|
||||
case "", "zap":
|
||||
result, err = m.ZapBaseline(ctx, targetURL, "", "", failOn)
|
||||
case "none":
|
||||
result = &DASTResult{
|
||||
Tool: "none",
|
||||
Mode: "skip",
|
||||
Target: targetURL,
|
||||
Pass: true,
|
||||
}
|
||||
case "burp":
|
||||
result, err = m.commercialScan(ctx, "burp", targetURL, apiURL, apiKey)
|
||||
case "acunetix":
|
||||
result, err = m.commercialScan(ctx, "acunetix", targetURL, apiURL, apiKey)
|
||||
case "invicti":
|
||||
result, err = m.commercialScan(ctx, "invicti", targetURL, apiURL, apiKey)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported DAST tool: %q (want zap|burp|acunetix|invicti|none)", tool)
|
||||
}
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
// POST results to the IntegraCI API when configured. Skipped silently
|
||||
// when integraciURL or token is empty so local runs still work.
|
||||
if integraciURL != "" && token != nil {
|
||||
if perr := m.postResults(ctx, integraciURL, token, serviceID, version, result); perr != nil {
|
||||
return result, fmt.Errorf("posting results to API failed: %w", perr)
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// postResults sends the DAST scan result back to the IntegraCI scans
|
||||
// endpoint. Shape mirrors security-scan's postResults (ScanResultCreate):
|
||||
// typed severity columns plus the report_data counters the deploy OPA gate
|
||||
// reads. For DAST we populate report_data.dast_high / report_data.dast_critical
|
||||
// from the DAST tool's findings (see deploy.py _build_scan_results).
|
||||
func (m *DastScan) postResults(
|
||||
ctx context.Context,
|
||||
apiURL string,
|
||||
token *dagger.Secret,
|
||||
serviceID string,
|
||||
version string,
|
||||
result *DASTResult,
|
||||
) error {
|
||||
payload := map[string]any{
|
||||
"service_id": serviceID,
|
||||
"version": version,
|
||||
"scan_type": "dast",
|
||||
"scanner": result.Tool,
|
||||
"report_format": "json",
|
||||
"findings_count": result.Critical + result.High + result.Medium,
|
||||
"critical_count": result.Critical,
|
||||
"high_count": result.High,
|
||||
"medium_count": result.Medium,
|
||||
"report_data": map[string]any{
|
||||
"secret_count": 0,
|
||||
"dast_high": result.High,
|
||||
"dast_critical": result.Critical,
|
||||
"sast_errors": 0,
|
||||
"sbom_present": false,
|
||||
"signed": false,
|
||||
},
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal scan payload: %w", err)
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/scans"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
tokenStr, err := token.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read token secret: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+tokenStr)
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("API post to %s failed: %w", endpoint, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("API post to %s returned %d", endpoint, resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// commercialScan triggers an off-cluster commercial DAST appliance by POSTing
|
||||
// to its REST API via curl-in-container. The per-vendor endpoint, auth header
|
||||
// and JSON payload mirror security_pipeline_adapter.build_dast_step exactly.
|
||||
func (m *DastScan) commercialScan(
|
||||
ctx context.Context,
|
||||
tool, targetURL, apiURL string,
|
||||
apiKey *dagger.Secret,
|
||||
) (*DASTResult, error) {
|
||||
if targetURL == "" {
|
||||
return nil, fmt.Errorf("--target-url is required")
|
||||
}
|
||||
if apiURL == "" {
|
||||
return nil, fmt.Errorf("--api-url is required for %s (its {TOOL}_API_URL is deployment-specific)", tool)
|
||||
}
|
||||
if apiKey == nil {
|
||||
return nil, fmt.Errorf("--api-key is required for %s", tool)
|
||||
}
|
||||
|
||||
var endpoint, authHeader, payload string
|
||||
switch tool {
|
||||
case "burp":
|
||||
endpoint = strings.TrimRight(apiURL, "/") + "/api/v0.1/scan"
|
||||
authHeader = `Authorization: ${API_KEY}`
|
||||
payload = fmt.Sprintf(`{"urls":["%s"]}`, targetURL)
|
||||
case "acunetix":
|
||||
endpoint = strings.TrimRight(apiURL, "/") + "/api/v1/scans"
|
||||
authHeader = `X-Auth: ${API_KEY}`
|
||||
payload = fmt.Sprintf(`{"target_url":"%s","profile_id":"full"}`, targetURL)
|
||||
case "invicti":
|
||||
endpoint = strings.TrimRight(apiURL, "/") + "/api/1.0/scans/new"
|
||||
authHeader = `Authorization: Basic ${API_KEY}`
|
||||
payload = fmt.Sprintf(`{"TargetUri":"%s","ProfileId":"default"}`, targetURL)
|
||||
}
|
||||
|
||||
// The secret is interpolated inside the container via $API_KEY so it is
|
||||
// never present in the Dagger op graph as plaintext.
|
||||
curlCmd := fmt.Sprintf(
|
||||
`curl -fsSL -X POST %q -H %q -H "Content-Type: application/json" -d %q`,
|
||||
endpoint, authHeader, payload,
|
||||
)
|
||||
|
||||
out, err := dag.Container().
|
||||
From("curlimages/curl:8.10.1").
|
||||
WithSecretVariable("API_KEY", apiKey).
|
||||
WithExec([]string{"sh", "-c", curlCmd}).
|
||||
Stdout(ctx)
|
||||
|
||||
result := &DASTResult{
|
||||
Tool: tool,
|
||||
Mode: "api",
|
||||
Target: targetURL,
|
||||
JSONReport: out,
|
||||
Pass: err == nil,
|
||||
}
|
||||
if err != nil {
|
||||
result.Error = fmt.Sprintf("%s scan request failed: %v", tool, err)
|
||||
return result, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ZapBaseline runs OWASP ZAP's `zap-baseline.py` — a passive spider + scan
|
||||
// designed to be safe against production traffic. Completes in 1-3
|
||||
// minutes for a typical API.
|
||||
//
|
||||
// Failure threshold defaults to "any HIGH or CRITICAL".
|
||||
func (m *DastScan) ZapBaseline(
|
||||
ctx context.Context,
|
||||
// Target URL (must be reachable from the Dagger runner)
|
||||
target string,
|
||||
// Optional Authorization header to bypass auth (e.g. "Bearer ...")
|
||||
// +optional
|
||||
authHeader string,
|
||||
// Comma-separated rule IDs to ignore (e.g. "10038,10054" — known FPs)
|
||||
// +optional
|
||||
ignoreRules string,
|
||||
// Fail the run when this severity or above is found.
|
||||
// One of: "info" | "low" | "medium" | "high" | "critical".
|
||||
// +optional
|
||||
// +default="high"
|
||||
failOn string,
|
||||
) (*DASTResult, error) {
|
||||
if target == "" {
|
||||
return nil, fmt.Errorf("--target is required")
|
||||
}
|
||||
if failOn == "" {
|
||||
failOn = "high"
|
||||
}
|
||||
|
||||
args := []string{
|
||||
"zap-baseline.py",
|
||||
"-t", target,
|
||||
"-J", "/zap/wrk/zap-report.json",
|
||||
"-x", "/zap/wrk/zap-report.xml",
|
||||
"-r", "/zap/wrk/zap-report.html",
|
||||
"-w", "/zap/wrk/zap-report.md",
|
||||
"-I", // do not return failure on warnings — we threshold ourselves
|
||||
}
|
||||
if ignoreRules != "" {
|
||||
for _, id := range strings.Split(ignoreRules, ",") {
|
||||
id = strings.TrimSpace(id)
|
||||
if id != "" {
|
||||
args = append(args, "-z", "-config rules.cookie.ignorelist="+id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c := dag.Container().
|
||||
From("ghcr.io/zaproxy/zaproxy:stable").
|
||||
WithWorkdir("/zap/wrk").
|
||||
WithEnvVariable("DAST_TARGET", target)
|
||||
|
||||
if authHeader != "" {
|
||||
// ZAP accepts -config replacers via -z
|
||||
c = c.WithExec([]string{
|
||||
"sh", "-c",
|
||||
fmt.Sprintf("echo '%s' > /zap/wrk/auth-header.txt", authHeader),
|
||||
})
|
||||
args = append(args,
|
||||
"-z", "-config replacer.full_list(0).description=auth",
|
||||
"-z", "-config replacer.full_list(0).enabled=true",
|
||||
"-z", "-config replacer.full_list(0).matchtype=REQ_HEADER",
|
||||
"-z", "-config replacer.full_list(0).matchstr=Authorization",
|
||||
"-z", "-config replacer.full_list(0).regex=false",
|
||||
"-z", fmt.Sprintf("-config replacer.full_list(0).replacement=%s", authHeader),
|
||||
)
|
||||
}
|
||||
|
||||
scan := c.WithExec(args)
|
||||
|
||||
// ZAP exits non-zero when WARN/FAIL alerts are found in baseline.
|
||||
// We swallow the exit to read reports ourselves.
|
||||
jsonOut, _ := scan.File("/zap/wrk/zap-report.json").Contents(ctx)
|
||||
htmlOut, _ := scan.File("/zap/wrk/zap-report.html").Contents(ctx)
|
||||
|
||||
report := summariseZap(jsonOut)
|
||||
report.Tool = "zap"
|
||||
report.Mode = "baseline"
|
||||
report.Target = target
|
||||
report.JSONReport = jsonOut
|
||||
report.HTMLReport = htmlOut
|
||||
report.SarifReport = zapToSarif(jsonOut, target)
|
||||
report.Pass = !exceedsThreshold(report, failOn)
|
||||
if !report.Pass {
|
||||
report.Error = fmt.Sprintf("ZAP baseline: %d findings ≥ %s severity", report.Critical+report.High, failOn)
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// ZapFull runs the full ZAP active scan — actively sends payloads
|
||||
// (XSS, SQLi, command injection probes) to the target. Intrusive.
|
||||
// Safe only for ephemeral / preview environments.
|
||||
func (m *DastScan) ZapFull(
|
||||
ctx context.Context,
|
||||
target string,
|
||||
// +optional
|
||||
authHeader string,
|
||||
// +optional
|
||||
// +default=30
|
||||
maxDuration int,
|
||||
// +optional
|
||||
// +default="high"
|
||||
failOn string,
|
||||
) (*DASTResult, error) {
|
||||
if target == "" {
|
||||
return nil, fmt.Errorf("--target is required")
|
||||
}
|
||||
if maxDuration <= 0 {
|
||||
maxDuration = 30
|
||||
}
|
||||
|
||||
args := []string{
|
||||
"zap-full-scan.py",
|
||||
"-t", target,
|
||||
"-J", "/zap/wrk/zap-report.json",
|
||||
"-r", "/zap/wrk/zap-report.html",
|
||||
"-m", fmt.Sprintf("%d", maxDuration),
|
||||
"-I",
|
||||
}
|
||||
|
||||
c := dag.Container().
|
||||
From("ghcr.io/zaproxy/zaproxy:stable").
|
||||
WithWorkdir("/zap/wrk")
|
||||
|
||||
if authHeader != "" {
|
||||
args = append(args,
|
||||
"-z", "-config replacer.full_list(0).description=auth",
|
||||
"-z", "-config replacer.full_list(0).enabled=true",
|
||||
"-z", "-config replacer.full_list(0).matchtype=REQ_HEADER",
|
||||
"-z", "-config replacer.full_list(0).matchstr=Authorization",
|
||||
"-z", "-config replacer.full_list(0).regex=false",
|
||||
"-z", fmt.Sprintf("-config replacer.full_list(0).replacement=%s", authHeader),
|
||||
)
|
||||
}
|
||||
|
||||
scan := c.WithExec(args)
|
||||
jsonOut, _ := scan.File("/zap/wrk/zap-report.json").Contents(ctx)
|
||||
htmlOut, _ := scan.File("/zap/wrk/zap-report.html").Contents(ctx)
|
||||
|
||||
report := summariseZap(jsonOut)
|
||||
report.Tool = "zap"
|
||||
report.Mode = "full"
|
||||
report.Target = target
|
||||
report.JSONReport = jsonOut
|
||||
report.HTMLReport = htmlOut
|
||||
report.SarifReport = zapToSarif(jsonOut, target)
|
||||
report.Pass = !exceedsThreshold(report, failOn)
|
||||
if !report.Pass {
|
||||
report.Error = fmt.Sprintf("ZAP full scan: %d findings ≥ %s severity", report.Critical+report.High, failOn)
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// Nuclei runs ProjectDiscovery's Nuclei template engine against the
|
||||
// target. ~10k templates covering CVEs, default credentials, exposed
|
||||
// dashboards, misconfig, etc. Updated nightly upstream.
|
||||
func (m *DastScan) Nuclei(
|
||||
ctx context.Context,
|
||||
target string,
|
||||
// Comma-separated severities to include. Default: critical,high,medium.
|
||||
// +optional
|
||||
// +default="critical,high"
|
||||
severity string,
|
||||
// Comma-separated tags to include (e.g. "cve,exposure,misconfig").
|
||||
// +optional
|
||||
tags string,
|
||||
// Rate limit (req/sec) — default 150 is upstream sensible default.
|
||||
// +optional
|
||||
// +default=150
|
||||
rateLimit int,
|
||||
// Fail when any finding ≥ this severity.
|
||||
// +optional
|
||||
// +default="high"
|
||||
failOn string,
|
||||
) (*DASTResult, error) {
|
||||
if target == "" {
|
||||
return nil, fmt.Errorf("--target is required")
|
||||
}
|
||||
if severity == "" {
|
||||
severity = "critical,high"
|
||||
}
|
||||
if rateLimit <= 0 {
|
||||
rateLimit = 150
|
||||
}
|
||||
|
||||
args := []string{
|
||||
"nuclei",
|
||||
"-target", target,
|
||||
"-severity", severity,
|
||||
"-jsonl-export", "/tmp/nuclei.jsonl",
|
||||
"-sarif-export", "/tmp/nuclei.sarif",
|
||||
"-rate-limit", fmt.Sprintf("%d", rateLimit),
|
||||
"-no-color",
|
||||
"-disable-update-check",
|
||||
}
|
||||
if tags != "" {
|
||||
args = append(args, "-tags", tags)
|
||||
}
|
||||
|
||||
c := dag.Container().
|
||||
From("projectdiscovery/nuclei:v3.3.9").
|
||||
WithExec(args)
|
||||
|
||||
jsonl, _ := c.File("/tmp/nuclei.jsonl").Contents(ctx)
|
||||
sarif, _ := c.File("/tmp/nuclei.sarif").Contents(ctx)
|
||||
|
||||
report := summariseNuclei(jsonl)
|
||||
report.Tool = "nuclei"
|
||||
report.Mode = "nuclei"
|
||||
report.Target = target
|
||||
report.JSONReport = jsonl
|
||||
report.SarifReport = sarif
|
||||
report.Pass = !exceedsThreshold(report, failOn)
|
||||
if !report.Pass {
|
||||
report.Error = fmt.Sprintf("Nuclei: %d findings ≥ %s severity", report.Critical+report.High, failOn)
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// ───── helpers ─────
|
||||
|
||||
// summariseZap parses ZAP's JSON report and returns aggregate counts.
|
||||
// We avoid pulling encoding/json to keep the module dependency-free —
|
||||
// ZAP's output is stable and grep-friendly.
|
||||
func summariseZap(jsonOut string) *DASTResult {
|
||||
r := &DASTResult{}
|
||||
if jsonOut == "" {
|
||||
return r
|
||||
}
|
||||
r.High = strings.Count(jsonOut, `"riskdesc":"High`)
|
||||
r.Medium = strings.Count(jsonOut, `"riskdesc":"Medium`)
|
||||
r.Low = strings.Count(jsonOut, `"riskdesc":"Low`)
|
||||
r.Info = strings.Count(jsonOut, `"riskdesc":"Informational`)
|
||||
// ZAP reports "High (Critical)" inside the High bucket — promote when
|
||||
// "Critical" appears inline.
|
||||
r.Critical = strings.Count(jsonOut, `"riskdesc":"High (Critical`)
|
||||
if r.Critical > 0 {
|
||||
r.High -= r.Critical
|
||||
if r.High < 0 {
|
||||
r.High = 0
|
||||
}
|
||||
}
|
||||
r.Total = r.Critical + r.High + r.Medium + r.Low + r.Info
|
||||
return r
|
||||
}
|
||||
|
||||
// summariseNuclei parses Nuclei's JSONL output (one finding per line).
|
||||
func summariseNuclei(jsonl string) *DASTResult {
|
||||
r := &DASTResult{}
|
||||
for _, line := range strings.Split(jsonl, "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case strings.Contains(line, `"severity":"critical"`):
|
||||
r.Critical++
|
||||
case strings.Contains(line, `"severity":"high"`):
|
||||
r.High++
|
||||
case strings.Contains(line, `"severity":"medium"`):
|
||||
r.Medium++
|
||||
case strings.Contains(line, `"severity":"low"`):
|
||||
r.Low++
|
||||
case strings.Contains(line, `"severity":"info"`):
|
||||
r.Info++
|
||||
}
|
||||
}
|
||||
r.Total = r.Critical + r.High + r.Medium + r.Low + r.Info
|
||||
return r
|
||||
}
|
||||
|
||||
// exceedsThreshold returns true when the report contains any finding at
|
||||
// or above the failOn severity. Severity ordering follows the standard
|
||||
// SARIF/CVSS bucket model.
|
||||
func exceedsThreshold(r *DASTResult, failOn string) bool {
|
||||
switch strings.ToLower(failOn) {
|
||||
case "critical":
|
||||
return r.Critical > 0
|
||||
case "high":
|
||||
return r.Critical+r.High > 0
|
||||
case "medium":
|
||||
return r.Critical+r.High+r.Medium > 0
|
||||
case "low":
|
||||
return r.Critical+r.High+r.Medium+r.Low > 0
|
||||
case "info":
|
||||
return r.Total > 0
|
||||
}
|
||||
return r.Critical+r.High > 0
|
||||
}
|
||||
|
||||
// zapToSarif converts ZAP's JSON to a minimal valid SARIF v2.1.0 envelope
|
||||
// so it can be uploaded to the GitHub Security tab. We embed the full
|
||||
// ZAP JSON inside `properties` — security teams can drill in from the
|
||||
// SARIF row to the rich report.
|
||||
func zapToSarif(jsonOut string, target string) string {
|
||||
if jsonOut == "" {
|
||||
return ""
|
||||
}
|
||||
// Minimal valid SARIF — github/codeql-action/upload-sarif requires
|
||||
// runs[].tool.driver.{name,rules} and at least one results entry to
|
||||
// surface in the UI.
|
||||
return fmt.Sprintf(`{
|
||||
"version": "2.1.0",
|
||||
"$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
|
||||
"runs": [{
|
||||
"tool": {
|
||||
"driver": {
|
||||
"name": "OWASP ZAP",
|
||||
"version": "stable",
|
||||
"informationUri": "https://www.zaproxy.org/",
|
||||
"rules": []
|
||||
}
|
||||
},
|
||||
"originalUriBaseIds": {"TARGET": {"uri": %q}},
|
||||
"properties": {"raw_zap_report": "see job artifact"},
|
||||
"results": []
|
||||
}]
|
||||
}`, target)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
/dagger.gen.go linguist-generated
|
||||
/internal/dagger/** linguist-generated
|
||||
/internal/telemetry/** linguist-generated
|
||||
@@ -0,0 +1,4 @@
|
||||
/dagger.gen.go
|
||||
/internal/dagger
|
||||
/internal/telemetry
|
||||
/.env
|
||||
@@ -0,0 +1,212 @@
|
||||
# db-migration (Dagger module)
|
||||
|
||||
Judges a service's migration SQL with **IntegraCI's DB-change engine** — the DBV
|
||||
policy engine behind the tenant's own DB-change policy
|
||||
(`POST /api/v1/db-changes/analyze`) — and applies migrations with the
|
||||
tenant's own tool: `liquibase` (default), `flyway` or `atlas`.
|
||||
|
||||
Builds with `dagger functions` on engine v0.21.8 (verified 2026-09-27).
|
||||
|
||||
## Tools, images and databases
|
||||
|
||||
Every image is pinned by tag and digest in `main.go` (checked 2026-09-27).
|
||||
|
||||
| Tool | Image | Licence | Databases |
|
||||
| --- | --- | --- | --- |
|
||||
| `liquibase` | `liquibase/liquibase:4.31.1-alpine` — the version the platform runs | Apache 2.0 | PostgreSQL, SQL Server, Oracle, MariaDB, DB2, Firebird, Snowflake, SQLite, H2, HSQLDB (drivers in the image) |
|
||||
| `flyway` | `flyway/flyway:10.22.0-alpine` | Apache 2.0 (Community) | as Flyway Community supports |
|
||||
| `atlas` | `arigaio/atlas:1.3.3-community-alpine` | Apache 2.0 (Community Edition) | PostgreSQL, MySQL, MariaDB, SQLite |
|
||||
|
||||
- **MySQL with Liquibase:** the image has no MySQL Connector/J (it is GPL and
|
||||
not shipped), so a `jdbc:mysql:` URL finds no driver. Use a `jdbc:mariadb:`
|
||||
URL; the MariaDB driver talks to MySQL.
|
||||
- **Atlas is the Community Edition.** The standard `arigaio/atlas` image is
|
||||
licensed under the proprietary Atlas MSA; this module ran it until
|
||||
2026-09-27. Community migrates PostgreSQL and MySQL only, so `--tool=atlas`
|
||||
on any other dialect or engine is refused before anything runs.
|
||||
- **`--tool` is checked.** Anything but `liquibase`, `flyway`, `atlas` or
|
||||
`none` is refused. Until 2026-09-27 an unknown value (a typo) fell through
|
||||
to atlas and applied the directory with a tool nobody chose.
|
||||
- **What the SQL is judged as.** Name nothing, and the platform decides: in the
|
||||
engines of the service's own databases when `--service-id` is given (its
|
||||
`spec.resources` and the DB schemas registered to it — what the deploy gate
|
||||
judges with too), and as PostgreSQL otherwise. Or name the database
|
||||
**engine** (`--engine`): the platform judges in that engine's dialect, and
|
||||
an engine it has no rules for comes back unjudged (an approver decides, so
|
||||
the step fails under `--block-destructive`; `GET /api/v1/db-engines`). Or
|
||||
name the SQL **dialect** (`--dialect`: postgres, mysql, oracle, tsql) — not
|
||||
both. `--engine` needs a platform with engine support; an older one refuses
|
||||
it with HTTP 422, and the step fails. Before 2026-09-27 `--dialect` defaulted
|
||||
to `postgres` and was sent on every call, so a warehouse or MongoDB
|
||||
directory was judged as PostgreSQL.
|
||||
|
||||
## Engine adapters (ADR-0070 §1)
|
||||
|
||||
DBV judges; the tool that applies a change is an **adapter** in `engine/`. An
|
||||
adapter builds the command (the pinned image and the exact argv) and declares
|
||||
what it drives. It never sees a secret — `main.go` binds `$DATABASE_URL` /
|
||||
`$REFERENCE_URL` as Dagger secrets and mounts only the judged files — and it
|
||||
never picks the files: they are the ones the engine judged.
|
||||
|
||||
```go
|
||||
type Adapter interface {
|
||||
Name() string // the --tool value
|
||||
Capabilities() Capabilities
|
||||
Apply(files []string) (Command, error) // judged files, in order
|
||||
Rollback(file string, n int) (Command, error) // last n changesets of a granted changelog
|
||||
Drift(file string) (Command, error) // build file into $REFERENCE_URL, diff $DATABASE_URL
|
||||
Snapshot() (Command, error) // schema of $DATABASE_URL
|
||||
}
|
||||
```
|
||||
|
||||
An operation an adapter does not drive returns `engine.ErrUnsupported`; it
|
||||
never runs something else. What each adapter drives today:
|
||||
|
||||
| Adapter | Dialects accepted | apply | rollback | drift | snapshot | native lint | checksum |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| `liquibase` (default, `engine.DefaultTool`) | postgres, mysql, oracle, tsql | yes | yes | yes | yes | — | changeset |
|
||||
| `flyway` | postgres, mysql, oracle, tsql | yes | — | — | — | — | file |
|
||||
| `atlas` | postgres, mysql | yes | — | — | — | yes (advisory) | directory |
|
||||
|
||||
- **Grants are written for the default adapter.** `execute`, `drift` and
|
||||
`snapshot` run under a platform grant whose changelog is Liquibase
|
||||
formatted SQL, so they use `engine.DefaultTool`. Re-choosing the default
|
||||
(ADR-0070 §2) is that one constant plus its mirror in the API.
|
||||
- **The pins stay in `main.go`.** `tools/ci/check-liquibase-pins.py` and
|
||||
Renovate read them there; `engine.New` receives them.
|
||||
- **The API mirrors the declarations** in
|
||||
`apps/api/app/platform/services/db_engine_adapters.py`. Both sides are
|
||||
tested against `engine/capabilities.json`; neither parses the other's
|
||||
language. `ci_presets.DB_MIGRATION_TOOLS` is derived from it (adapters plus
|
||||
`none`).
|
||||
- **Dialects are accepted, not tested per dialect.** They are what
|
||||
`verdict.CheckTool` lets through; per-dialect adapter tests are ADR-0070
|
||||
phase 2. Not driven by any adapter yet: dry-run SQL, `status`, and online
|
||||
schema change (pgroll, gh-ost).
|
||||
- **Phase 1 (#2135, 2026-10-11) changed no behaviour.** Every argv is
|
||||
byte-identical to the one `main.go` built inline before;
|
||||
`engine/engine_test.go` pins each one.
|
||||
|
||||
## Functions
|
||||
|
||||
### `lint`
|
||||
|
||||
Sends every `.sql` file under `dir` to IntegraCI and fails when the tenant's
|
||||
policy blocks a change — or requires approval for one, which nobody can give
|
||||
inside a CI step (the change then goes through IntegraCI's governed apply).
|
||||
For `atlas` it then runs `atlas migrate lint` — only after the policy has
|
||||
passed every file, because the lint **replays** the files on its dev database
|
||||
— and fails when that reports an error (a destructive change, for example);
|
||||
the lint's output is in the error. It sees the judged directory alone, so an
|
||||
`atlas.hcl` in the repo is not read. Without `--dev-url` (a secret: a DSN
|
||||
carries a password) the lint starts a throwaway PostgreSQL for this run only
|
||||
(`postgres:16.13-alpine`, as a Dagger service); another dialect needs
|
||||
`--dev-url`. The previous default, `docker://postgres/16/dev`, needs a Docker
|
||||
CLI inside the atlas container and never worked, so `--tool=atlas` failed in
|
||||
every generated pipeline (none passes `--dev-url`).
|
||||
|
||||
```sh
|
||||
dagger call lint \
|
||||
--source . \
|
||||
--dir migrations \
|
||||
--api-url "$INTEGRACI_URL" \
|
||||
--token env://INTEGRACI_TOKEN
|
||||
```
|
||||
|
||||
| Param | Default | Description |
|
||||
| ------------------- | -------------------------- | -------------------------------------------------------- |
|
||||
| `source` | (required) | Source directory containing migrations |
|
||||
| `dir` | `migrations` | Migrations directory relative to source |
|
||||
| `tool` | `liquibase` | `liquibase` \| `atlas` \| `flyway` \| `none` (skip) |
|
||||
| `api-url` | (required unless `none`) | IntegraCI API URL — the engine that judges the SQL |
|
||||
| `token` | (required unless `none`) | IntegraCI API token |
|
||||
| `dialect` | (unset: the platform picks) | `postgres` \| `mysql` \| `oracle` \| `tsql` |
|
||||
| `engine` | (optional, instead of `dialect`) | Database engine; the platform picks the dialect (`GET /db-engines`) |
|
||||
| `environment-id` | (optional) | Tenant environment whose policy and stage apply |
|
||||
| `block-destructive` | `true` | Also fail on `requires_approval` (`blocked` always fails) |
|
||||
| `dev-url` | (a throwaway PostgreSQL) | Secret: dev DB atlas replays the migrations on (`atlas` only) |
|
||||
|
||||
**It fails closed.** The step fails when nothing has judged the SQL:
|
||||
- no `--api-url`/`--token`;
|
||||
- no `.sql` file in `dir` at all;
|
||||
- a file the engine cannot read: an XML/YAML/JSON changelog, a `.pgsql` or
|
||||
other suffix a tool may be configured to run, a Java migration. Only `.sql`,
|
||||
docs (`.md`, `.txt`, `.rst`, `README`, `LICENSE`), `.gitkeep` and
|
||||
`atlas.sum` may sit in `dir`. Use Liquibase formatted SQL, or `--tool=none`
|
||||
to opt out of governance;
|
||||
- with `--tool=liquibase`, a Liquibase directive that runs or skips text the
|
||||
engine reads as a comment: `--precondition*`/`--preconditions`,
|
||||
`--include`/`--includeAll`, `--property`, `--validCheckSum`,
|
||||
`--ignoreLines`. Measured 2026-09-27: `--precondition-sql-check
|
||||
expectedResult:0 WITH d AS (DELETE FROM users RETURNING 1) SELECT count(*)
|
||||
FROM d` is judged "additive" and Liquibase executes it. `--liquibase
|
||||
formatted sql`, `--changeset` (with attributes), `--rollback` and
|
||||
`--comment` stay allowed;
|
||||
- a file holding a `${…}` placeholder. Flyway and Liquibase substitute it
|
||||
after the engine has judged the text, so what would run is not what was
|
||||
judged (`${flyway:filename}` in a file named `V9__x');DROP TABLE t;--.sql`);
|
||||
- a file over 200 kB;
|
||||
- an answer from IntegraCI that is not a verdict (non-2xx, a redirect, no
|
||||
`decision`).
|
||||
|
||||
Measured 2026-09-26 on engine v0.21.8: hidden files (`.x/V1.sql`, `.V1.sql`)
|
||||
are listed and judged; a symlinked directory is listed as a plain entry, so it
|
||||
is refused, not followed.
|
||||
|
||||
`--block-destructive=false` only lets `requires_approval` through. A change the
|
||||
tenant's policy `blocked` is not the pipeline's to waive.
|
||||
|
||||
A Jenkins build that holds no IntegraCI token (a pull-request build never does)
|
||||
renders the stage as a visible "DB migration lint NOT RUN" instead of failing;
|
||||
the governed apply judges every changeset again.
|
||||
|
||||
### `apply`
|
||||
|
||||
Judges the migrations the same way, refuses what the policy refuses, then runs
|
||||
the tool against `--db-url` (a secret, never on the command line).
|
||||
|
||||
The tool sees **only `dir`**, mounted alone with an empty working directory, so
|
||||
a `liquibase.properties` or flyway config in the repo cannot point it at SQL
|
||||
nobody judged. Liquibase runs each judged `.sql` file as its own formatted-SQL
|
||||
changelog, ordered with numbers compared as numbers (`V2` before `V10`); flyway
|
||||
runs with `-placeholderReplacement=false`.
|
||||
|
||||
**Breaking for anyone who wired `apply` by hand** (no generated pipeline calls
|
||||
it): the repo's `liquibase.properties`, `flyway.conf`/`flyway.toml` and
|
||||
`atlas.hcl` are no longer read. That drops contexts/labels (every changeset
|
||||
runs), a custom history table or schema (the tool sees an empty history and
|
||||
re-runs everything), and a master changelog's order and file paths (Liquibase
|
||||
stores the path relative to `dir`, so changesets recorded under another path
|
||||
run again). Check a database's history table before pointing `apply` at it.
|
||||
|
||||
```sh
|
||||
dagger call apply --source . --dir migrations \
|
||||
--db-url env://DATABASE_URL --api-url "$INTEGRACI_URL" --token env://INTEGRACI_TOKEN
|
||||
```
|
||||
|
||||
`applied` is read from each tool's own summary (Liquibase `Run: N` per
|
||||
changelog, Flyway `Successfully applied N migrations`, one atlas
|
||||
`-- migrating version` line per file). Before 2026-09-27 it counted flyway and
|
||||
atlas markers for every tool, so a Liquibase apply reported 0 and a Flyway one 1.
|
||||
|
||||
## Before 2026-09-26
|
||||
|
||||
The lint could not fail for `liquibase` or `flyway`: it ran `validate || true`
|
||||
(which needs a live database anyway), looked for destructive keywords in the
|
||||
tool's output (which carries no SQL), and POSTed a summary to
|
||||
`/api/v1/services/{id}/migrations`, a route the API never served.
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
dagger develop # regenerate the gitignored SDK bindings
|
||||
go test ./... # verdict/: HTTP contract, decisions, file split, applied count;
|
||||
# engine/: adapter argv, capabilities, the capabilities.json contract
|
||||
```
|
||||
|
||||
`apps/api/tests/test_dagger_db_migration_lint_contract.py` checks the other
|
||||
side: the route and request fields exist in the API, and every CI template
|
||||
passes an API URL and a token. `test_dagger_db_migration_tools_match_the_presets.py`
|
||||
checks that `--tool` accepts exactly the tools the CI presets offer, and
|
||||
`test_db_engine_adapters_match_the_module.py` that the API's adapter registry
|
||||
matches `engine/capabilities.json` and that `dagger.json` includes `engine/`.
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "db-migration",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"include": [
|
||||
"./main.go",
|
||||
"./engine/**",
|
||||
"./verdict/**"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"atlas": {
|
||||
"dialects": ["mysql", "postgres"],
|
||||
"rollback": false,
|
||||
"drift": false,
|
||||
"snapshot": false,
|
||||
"dry_run_sql": false,
|
||||
"native_lint": true,
|
||||
"checksum": "directory",
|
||||
"online_change": []
|
||||
},
|
||||
"flyway": {
|
||||
"dialects": ["mysql", "oracle", "postgres", "tsql"],
|
||||
"rollback": false,
|
||||
"drift": false,
|
||||
"snapshot": false,
|
||||
"dry_run_sql": false,
|
||||
"native_lint": false,
|
||||
"checksum": "file",
|
||||
"online_change": []
|
||||
},
|
||||
"liquibase": {
|
||||
"dialects": ["mysql", "oracle", "postgres", "tsql"],
|
||||
"rollback": true,
|
||||
"drift": true,
|
||||
"snapshot": true,
|
||||
"dry_run_sql": false,
|
||||
"native_lint": false,
|
||||
"checksum": "changeset",
|
||||
"online_change": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// Package engine is the migration-engine adapter interface of the db-migration
|
||||
// module (ADR-0070 §1): DBV judges, an adapter only says how its tool runs.
|
||||
//
|
||||
// An adapter builds COMMANDS — the image and the exact argv to exec in it — and
|
||||
// declares what it can do. It never sees a secret: the database URLs reach the
|
||||
// container as environment variables ($DATABASE_URL, $REFERENCE_URL) that
|
||||
// main.go binds as Dagger secrets, and the scripts read them from there. It does
|
||||
// not decide what runs either: the files it is handed are the judged ones, and
|
||||
// the module mounts them alone at /migrations (or /reference).
|
||||
//
|
||||
// Phase 1 (#2135, 2026-10-11) moved the module's existing tool calls behind
|
||||
// this interface with no behaviour change: every argv is byte-identical to the
|
||||
// one main.go built inline before, and engine_test.go pins each of them. The
|
||||
// API mirrors the capabilities in app/platform/services/db_engine_adapters.py;
|
||||
// both sides are compared against capabilities.json, so neither parses the
|
||||
// other's language.
|
||||
package engine
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// ErrUnsupported is returned for an operation the adapter does not drive.
|
||||
var ErrUnsupported = errors.New("not supported by this migration tool")
|
||||
|
||||
// DefaultTool is the adapter the platform's grants are written for: a granted
|
||||
// batch, a drift reference and a snapshot are Liquibase formatted SQL today.
|
||||
// ADR-0070 §2 makes re-choosing the default a configuration change; this is
|
||||
// that configuration.
|
||||
const DefaultTool = "liquibase"
|
||||
|
||||
// Capabilities are what an adapter DRIVES in this module today — not what its
|
||||
// tool could do in principle. A capability declared here is one a caller can
|
||||
// use without the call failing with ErrUnsupported.
|
||||
type Capabilities struct {
|
||||
// Which of the DBV engine's four dialects (postgres, mysql, oracle, tsql)
|
||||
// the module accepts this tool for (verdict.CheckTool), sorted. Accepted,
|
||||
// not tested per dialect: per-dialect tests are ADR-0070 phase 2.
|
||||
Dialects []string `json:"dialects"`
|
||||
// Rollback of the last n changesets of a granted changelog.
|
||||
Rollback bool `json:"rollback"`
|
||||
// Drift: build the granted changelog into a reference and diff the live
|
||||
// database against it.
|
||||
Drift bool `json:"drift"`
|
||||
// Snapshot of the live schema as JSON.
|
||||
Snapshot bool `json:"snapshot"`
|
||||
// DryRunSQL: render the SQL an apply would run without running it.
|
||||
DryRunSQL bool `json:"dry_run_sql"`
|
||||
// NativeLint: the tool's own lint runs after the DBV verdict, as an
|
||||
// advisory signal (ADR-0070 §3), never as the verdict.
|
||||
NativeLint bool `json:"native_lint"`
|
||||
// Checksum is what the tool's history is keyed and checksummed by:
|
||||
// "changeset" (id+author+file), "file" (versioned script) or "directory"
|
||||
// (a sum file over the whole directory).
|
||||
Checksum string `json:"checksum"`
|
||||
// OnlineChange lists online schema-change tools the adapter drives
|
||||
// (pgroll, gh-ost, ...). None yet (ADR-0070 §5, 6–12 months).
|
||||
OnlineChange []string `json:"online_change"`
|
||||
}
|
||||
|
||||
// Command is one tool invocation: the image to run and the argv to exec in it.
|
||||
type Command struct {
|
||||
Image string
|
||||
Args []string
|
||||
}
|
||||
|
||||
// Adapter runs one migration tool.
|
||||
type Adapter interface {
|
||||
// Name is the --tool value that selects this adapter.
|
||||
Name() string
|
||||
Capabilities() Capabilities
|
||||
// Apply runs the judged files, in this order, against $DATABASE_URL.
|
||||
Apply(files []string) (Command, error)
|
||||
// Rollback undoes the last n changesets of file against $DATABASE_URL.
|
||||
Rollback(file string, n int) (Command, error)
|
||||
// Drift builds file into $REFERENCE_URL and diffs $DATABASE_URL against it.
|
||||
Drift(file string) (Command, error)
|
||||
// Snapshot prints the schema of $DATABASE_URL.
|
||||
Snapshot() (Command, error)
|
||||
}
|
||||
|
||||
// Images are the pinned images the adapters run. They stay declared in
|
||||
// main.go, where tools/ci/check-liquibase-pins.py and Renovate look for them.
|
||||
type Images struct {
|
||||
Liquibase string
|
||||
Flyway string
|
||||
Atlas string
|
||||
}
|
||||
|
||||
// Registry is the set of adapters, keyed by tool name.
|
||||
type Registry map[string]Adapter
|
||||
|
||||
// New returns every adapter the module has, running the given images.
|
||||
func New(images Images) Registry {
|
||||
r := Registry{}
|
||||
for _, a := range []Adapter{
|
||||
Liquibase{Image: images.Liquibase},
|
||||
Flyway{Image: images.Flyway},
|
||||
Atlas{Image: images.Atlas},
|
||||
} {
|
||||
r[a.Name()] = a
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// For returns the adapter for tool. An unknown tool is an error, never another
|
||||
// tool: until 2026-09-27 an unknown --tool fell through to atlas.
|
||||
func (r Registry) For(tool string) (Adapter, error) {
|
||||
a, ok := r[tool]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("--tool=%q is not a migration tool this module runs", tool)
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// Names lists the registered tools, sorted.
|
||||
func (r Registry) Names() []string {
|
||||
out := make([]string, 0, len(r))
|
||||
for name := range r {
|
||||
out = append(out, name)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func unsupported(tool, op string) error {
|
||||
return fmt.Errorf("%s %s: %w", tool, op, ErrUnsupported)
|
||||
}
|
||||
|
||||
// Liquibase is the default adapter (ADR-0070 §2: pinned below 5.0).
|
||||
type Liquibase struct{ Image string }
|
||||
|
||||
func (Liquibase) Name() string { return "liquibase" }
|
||||
|
||||
func (Liquibase) Capabilities() Capabilities {
|
||||
return Capabilities{
|
||||
Dialects: []string{"mysql", "oracle", "postgres", "tsql"},
|
||||
Rollback: true,
|
||||
Drift: true,
|
||||
Snapshot: true,
|
||||
Checksum: "changeset",
|
||||
OnlineChange: []string{},
|
||||
}
|
||||
}
|
||||
|
||||
// Apply runs each judged file as its own formatted-SQL changelog, in order:
|
||||
// there is no master changelog to point it at, and that is exactly the set the
|
||||
// engine saw. Files are positional arguments, never spliced into the script.
|
||||
func (l Liquibase) Apply(files []string) (Command, error) {
|
||||
return Command{Image: l.Image, Args: append([]string{"sh", "-c",
|
||||
`for f in "$@"; do liquibase --searchPath=/migrations --changelog-file="$f" --url="$DATABASE_URL" update || exit 1; done`,
|
||||
"sh"}, files...)}, nil
|
||||
}
|
||||
|
||||
// Rollback undoes the last n changesets with Liquibase's rollback-count.
|
||||
func (l Liquibase) Rollback(file string, n int) (Command, error) {
|
||||
return Command{Image: l.Image, Args: []string{"sh", "-c",
|
||||
`liquibase --searchPath=/migrations --changelog-file="$1" --url="$DATABASE_URL" rollback-count --count="$2"`,
|
||||
"sh", file, fmt.Sprintf("%d", n)}}, nil
|
||||
}
|
||||
|
||||
// Drift updates the empty reference database from the granted changelog
|
||||
// (mounted at /reference), then diffs the live database against it.
|
||||
func (l Liquibase) Drift(file string) (Command, error) {
|
||||
return Command{Image: l.Image, Args: []string{"sh", "-c",
|
||||
`liquibase --searchPath=/reference --changelog-file="$1" --url="$REFERENCE_URL" update >/dev/null && ` +
|
||||
`liquibase --url="$DATABASE_URL" --referenceUrl="$REFERENCE_URL" diff`,
|
||||
"sh", file}}, nil
|
||||
}
|
||||
|
||||
func (l Liquibase) Snapshot() (Command, error) {
|
||||
return Command{Image: l.Image, Args: []string{"sh", "-c",
|
||||
`liquibase --url="$DATABASE_URL" snapshot --snapshotFormat=json`}}, nil
|
||||
}
|
||||
|
||||
// Flyway applies a directory of versioned scripts. Placeholder replacement is
|
||||
// off: a ${...} in judged SQL must reach the database as written, not be
|
||||
// rewritten after the verdict.
|
||||
type Flyway struct{ Image string }
|
||||
|
||||
func (Flyway) Name() string { return "flyway" }
|
||||
|
||||
func (Flyway) Capabilities() Capabilities {
|
||||
return Capabilities{
|
||||
Dialects: []string{"mysql", "oracle", "postgres", "tsql"},
|
||||
Checksum: "file",
|
||||
OnlineChange: []string{},
|
||||
}
|
||||
}
|
||||
|
||||
func (f Flyway) Apply([]string) (Command, error) {
|
||||
return Command{Image: f.Image, Args: []string{"sh", "-c",
|
||||
`flyway -url="$DATABASE_URL" -locations=filesystem:/migrations -placeholderReplacement=false migrate`}}, nil
|
||||
}
|
||||
|
||||
func (Flyway) Rollback(string, int) (Command, error) {
|
||||
return Command{}, unsupported("flyway", "rollback")
|
||||
}
|
||||
func (Flyway) Drift(string) (Command, error) { return Command{}, unsupported("flyway", "drift") }
|
||||
func (Flyway) Snapshot() (Command, error) { return Command{}, unsupported("flyway", "snapshot") }
|
||||
|
||||
// Atlas is the Community Edition (Apache 2.0): PostgreSQL and MySQL only. Its
|
||||
// own lint (`atlas migrate lint`) runs in main.go after the DBV verdict.
|
||||
type Atlas struct{ Image string }
|
||||
|
||||
func (Atlas) Name() string { return "atlas" }
|
||||
|
||||
func (Atlas) Capabilities() Capabilities {
|
||||
return Capabilities{
|
||||
Dialects: []string{"mysql", "postgres"},
|
||||
NativeLint: true,
|
||||
Checksum: "directory",
|
||||
OnlineChange: []string{},
|
||||
}
|
||||
}
|
||||
|
||||
func (a Atlas) Apply([]string) (Command, error) {
|
||||
return Command{Image: a.Image, Args: []string{"sh", "-c",
|
||||
`atlas migrate apply --dir file:///migrations --url "$DATABASE_URL"`}}, nil
|
||||
}
|
||||
|
||||
func (Atlas) Rollback(string, int) (Command, error) {
|
||||
return Command{}, unsupported("atlas", "rollback")
|
||||
}
|
||||
func (Atlas) Drift(string) (Command, error) { return Command{}, unsupported("atlas", "drift") }
|
||||
func (Atlas) Snapshot() (Command, error) { return Command{}, unsupported("atlas", "snapshot") }
|
||||
@@ -0,0 +1,205 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"dagger/db-migration/verdict"
|
||||
)
|
||||
|
||||
var images = Images{Liquibase: "lb-image", Flyway: "fw-image", Atlas: "at-image"}
|
||||
|
||||
// The argv main.go built inline before #2135, copied verbatim from
|
||||
// origin/main 13a3918e2. Phase 1 promised no behaviour change; this is the
|
||||
// proof. Changing a script here is a behaviour change: review it as one.
|
||||
//
|
||||
// MUTATION-CHECK: drop `|| exit 1` from the Liquibase apply loop, or
|
||||
// `-placeholderReplacement=false` from Flyway → FAILS.
|
||||
func TestCommandsAreTheOnesTheModuleRanBefore(t *testing.T) {
|
||||
r := New(images)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
got func() (Command, error)
|
||||
want Command
|
||||
}{
|
||||
{"liquibase apply", func() (Command, error) { return r["liquibase"].Apply([]string{"a.sql", "b c.sql"}) },
|
||||
Command{"lb-image", []string{"sh", "-c",
|
||||
`for f in "$@"; do liquibase --searchPath=/migrations --changelog-file="$f" --url="$DATABASE_URL" update || exit 1; done`,
|
||||
"sh", "a.sql", "b c.sql"}}},
|
||||
{"liquibase rollback", func() (Command, error) { return r["liquibase"].Rollback("granted.sql", 3) },
|
||||
Command{"lb-image", []string{"sh", "-c",
|
||||
`liquibase --searchPath=/migrations --changelog-file="$1" --url="$DATABASE_URL" rollback-count --count="$2"`,
|
||||
"sh", "granted.sql", "3"}}},
|
||||
{"liquibase drift", func() (Command, error) { return r["liquibase"].Drift("granted.sql") },
|
||||
Command{"lb-image", []string{"sh", "-c",
|
||||
`liquibase --searchPath=/reference --changelog-file="$1" --url="$REFERENCE_URL" update >/dev/null && ` +
|
||||
`liquibase --url="$DATABASE_URL" --referenceUrl="$REFERENCE_URL" diff`,
|
||||
"sh", "granted.sql"}}},
|
||||
{"liquibase snapshot", func() (Command, error) { return r["liquibase"].Snapshot() },
|
||||
Command{"lb-image", []string{"sh", "-c",
|
||||
`liquibase --url="$DATABASE_URL" snapshot --snapshotFormat=json`}}},
|
||||
{"flyway apply", func() (Command, error) { return r["flyway"].Apply([]string{"V1__x.sql"}) },
|
||||
Command{"fw-image", []string{"sh", "-c",
|
||||
`flyway -url="$DATABASE_URL" -locations=filesystem:/migrations -placeholderReplacement=false migrate`}}},
|
||||
{"atlas apply", func() (Command, error) { return r["atlas"].Apply([]string{"1_x.sql"}) },
|
||||
Command{"at-image", []string{"sh", "-c",
|
||||
`atlas migrate apply --dir file:///migrations --url "$DATABASE_URL"`}}},
|
||||
} {
|
||||
got, err := tc.got()
|
||||
if err != nil {
|
||||
t.Errorf("%s: %v", tc.name, err)
|
||||
continue
|
||||
}
|
||||
if !reflect.DeepEqual(got, tc.want) {
|
||||
t.Errorf("%s:\n got %q\nwant %q", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A file name is an argument, never part of the script: a name carrying shell
|
||||
// syntax must not reach `sh -c`'s script string.
|
||||
func TestFileNamesNeverReachTheScript(t *testing.T) {
|
||||
evil := `x.sql"; touch /pwned; echo "`
|
||||
l := New(images)["liquibase"]
|
||||
for name, cmd := range map[string]func() (Command, error){
|
||||
"apply": func() (Command, error) { return l.Apply([]string{evil}) },
|
||||
"rollback": func() (Command, error) { return l.Rollback(evil, 1) },
|
||||
"drift": func() (Command, error) { return l.Drift(evil) },
|
||||
} {
|
||||
c, err := cmd()
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
if strings.Contains(c.Args[2], "pwned") {
|
||||
t.Errorf("%s: the file name reached the script: %q", name, c.Args[2])
|
||||
}
|
||||
if c.Args[3] != "sh" || c.Args[4] != evil {
|
||||
t.Errorf("%s: the file name is not the first positional argument: %q", name, c.Args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An operation an adapter does not declare fails with ErrUnsupported — it
|
||||
// never runs something else — and one it declares never does.
|
||||
func TestUnsupportedOperationsMatchTheCapabilities(t *testing.T) {
|
||||
for _, a := range New(images) {
|
||||
caps := a.Capabilities()
|
||||
for op, c := range map[string]struct {
|
||||
declared bool
|
||||
call func() (Command, error)
|
||||
}{
|
||||
"rollback": {caps.Rollback, func() (Command, error) { return a.Rollback("f.sql", 1) }},
|
||||
"drift": {caps.Drift, func() (Command, error) { return a.Drift("f.sql") }},
|
||||
"snapshot": {caps.Snapshot, func() (Command, error) { return a.Snapshot() }},
|
||||
} {
|
||||
cmd, err := c.call()
|
||||
if c.declared && err != nil {
|
||||
t.Errorf("%s declares %s but it fails: %v", a.Name(), op, err)
|
||||
}
|
||||
if !c.declared && (!errors.Is(err, ErrUnsupported) || cmd.Image != "" || cmd.Args != nil) {
|
||||
t.Errorf("%s does not declare %s, got %q, %v", a.Name(), op, cmd, err)
|
||||
}
|
||||
}
|
||||
if _, err := a.Apply([]string{"f.sql"}); err != nil {
|
||||
t.Errorf("%s apply: %v", a.Name(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every adapter runs its own pinned image, never another tool's.
|
||||
func TestEachAdapterRunsItsOwnImage(t *testing.T) {
|
||||
want := map[string]string{"liquibase": "lb-image", "flyway": "fw-image", "atlas": "at-image"}
|
||||
for name, a := range New(images) {
|
||||
c, _ := a.Apply([]string{"f.sql"})
|
||||
if c.Image != want[name] {
|
||||
t.Errorf("%s runs %q, want %q", name, c.Image, want[name])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --tool selects exactly one adapter; an unknown or misspelt one is an error,
|
||||
// not another tool (it fell through to atlas until 2026-09-27).
|
||||
func TestForRefusesAnUnknownTool(t *testing.T) {
|
||||
r := New(images)
|
||||
for _, tool := range []string{"liquibase", "flyway", "atlas"} {
|
||||
a, err := r.For(tool)
|
||||
if err != nil || a.Name() != tool {
|
||||
t.Errorf("For(%q) = %v, %v", tool, a, err)
|
||||
}
|
||||
}
|
||||
for _, tool := range []string{"", "none", "Liquibase", "liquibse", "sqitch"} {
|
||||
if a, err := r.For(tool); err == nil {
|
||||
t.Errorf("For(%q) = %v, want an error", tool, a.Name())
|
||||
}
|
||||
}
|
||||
if r["liquibase"] == nil || DefaultTool != "liquibase" {
|
||||
t.Errorf("the default adapter is %q and must be registered", DefaultTool)
|
||||
}
|
||||
}
|
||||
|
||||
// The adapters are exactly the tools --tool takes, minus "none" (which opts
|
||||
// out of governance and runs nothing).
|
||||
func TestAdaptersAreTheModulesTools(t *testing.T) {
|
||||
var tools []string
|
||||
for tool := range verdict.MigrationTools {
|
||||
if tool != "none" {
|
||||
tools = append(tools, tool)
|
||||
}
|
||||
}
|
||||
sort.Strings(tools)
|
||||
if got := New(images).Names(); !reflect.DeepEqual(got, tools) {
|
||||
t.Errorf("adapters %v, but --tool takes %v", got, tools)
|
||||
}
|
||||
}
|
||||
|
||||
// The declared dialects are the ones verdict.CheckTool accepts the tool for —
|
||||
// a declaration that disagreed would advertise a tool the module then refuses,
|
||||
// or hide one it runs.
|
||||
func TestDeclaredDialectsAreTheOnesCheckToolAccepts(t *testing.T) {
|
||||
for _, a := range New(images) {
|
||||
declared := map[string]bool{}
|
||||
for _, d := range a.Capabilities().Dialects {
|
||||
declared[d] = true
|
||||
}
|
||||
for _, d := range []string{"postgres", "mysql", "oracle", "tsql"} {
|
||||
accepted := verdict.CheckTool(a.Name(), d) == nil
|
||||
if accepted != declared[d] {
|
||||
t.Errorf("%s: dialect %s declared=%v, CheckTool accepts=%v", a.Name(), d, declared[d], accepted)
|
||||
}
|
||||
}
|
||||
if !sort.StringsAreSorted(a.Capabilities().Dialects) {
|
||||
t.Errorf("%s: dialects not sorted: %v", a.Name(), a.Capabilities().Dialects)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// capabilities.json is the contract the API's registry
|
||||
// (app/platform/services/db_engine_adapters.py) is tested against too.
|
||||
//
|
||||
// MUTATION-CHECK: flip Liquibase Rollback to false, or add an adapter without
|
||||
// a JSON entry → FAILS here; edit the JSON only → FAILS here and in the API test.
|
||||
func TestCapabilitiesMatchTheContract(t *testing.T) {
|
||||
raw, err := os.ReadFile("capabilities.json")
|
||||
if err != nil {
|
||||
t.Fatalf("capabilities.json is the cross-language contract and must exist: %v", err)
|
||||
}
|
||||
var contract map[string]Capabilities
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&contract); err != nil {
|
||||
t.Fatalf("capabilities.json: %v", err)
|
||||
}
|
||||
got := map[string]Capabilities{}
|
||||
for name, a := range New(images) {
|
||||
got[name] = a.Capabilities()
|
||||
}
|
||||
if !reflect.DeepEqual(got, contract) {
|
||||
t.Errorf("adapters declare\n %+v\nbut capabilities.json says\n %+v", got, contract)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
module dagger/db-migration
|
||||
|
||||
go 1.26.5
|
||||
|
||||
require (
|
||||
github.com/Khan/genqlient v0.8.1
|
||||
github.com/dagger/otel-go v1.43.0
|
||||
github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59
|
||||
github.com/vektah/gqlparser/v2 v2.5.32
|
||||
go.opentelemetry.io/otel v1.43.0
|
||||
go.opentelemetry.io/otel/trace v1.43.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/99designs/gqlgen v0.17.89 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
||||
github.com/sosodev/duration v1.4.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/log v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.43.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.43.0
|
||||
go.opentelemetry.io/otel/sdk/log v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
golang.org/x/net v0.51.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect
|
||||
google.golang.org/grpc v1.79.3 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
|
||||
replace go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc => go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp => go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/log => go.opentelemetry.io/otel/log v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/sdk/log => go.opentelemetry.io/otel/sdk/log v0.16.0
|
||||
@@ -0,0 +1,97 @@
|
||||
github.com/99designs/gqlgen v0.17.89 h1:KzEcxPiMgQoMw3m/E85atUEHyZyt0PbAflMia5Kw8z8=
|
||||
github.com/99designs/gqlgen v0.17.89/go.mod h1:GFqruTVGB7ZTdrf1uzOagpXbY7DrEt1pIxnTdhIbWvQ=
|
||||
github.com/Khan/genqlient v0.8.1 h1:wtOCc8N9rNynRLXN3k3CnfzheCUNKBcvXmVv5zt6WCs=
|
||||
github.com/Khan/genqlient v0.8.1/go.mod h1:R2G6DzjBvCbhjsEajfRjbWdVglSH/73kSivC9TLWVjU=
|
||||
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
|
||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/dagger/otel-go v1.43.0 h1:AYCnAamWmxtSxigWPTgC+8EWqiWPcDZEegh8y05gdJ8=
|
||||
github.com/dagger/otel-go v1.43.0/go.mod h1:83CTuXi70zcx1kaym5buqmb7RNzg1E9dEiQSFyLbLdU=
|
||||
github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59 h1:g6vfdGRyz6fAjfHz5FyYPZgHy8qcQ31fHrBl1iCOzxw=
|
||||
github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59/go.mod h1:jsdUJeYzcbyK1j/EqMGPrQgNYxl/Zfg06vvM9C/xXxs=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
|
||||
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
|
||||
github.com/sosodev/duration v1.4.0 h1:35ed0KiVFriGHHzZZJaZLgmTEEICIyt8Sx0RQfj9IjE=
|
||||
github.com/sosodev/duration v1.4.0/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERAikUR6SDg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/vektah/gqlparser/v2 v2.5.32 h1:k9QPJd4sEDTL+qB4ncPLflqTJ3MmjB9SrVzJrawpFSc=
|
||||
github.com/vektah/gqlparser/v2 v2.5.32/go.mod h1:c1I28gSOVNzlfc4WuDlqU7voQnsqI6OG2amkBAFmgts=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
|
||||
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0 h1:ZVg+kCXxd9LtAaQNKBxAvJ5NpMf7LpvEr4MIZqb0TMQ=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0/go.mod h1:hh0tMeZ75CCXrHd9OXRYxTlCAdxcXioWHFIpYw2rZu8=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0 h1:djrxvDxAe44mJUrKataUbOhCKhR3F8QCyWucO16hTQs=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0/go.mod h1:dt3nxpQEiSoKvfTVxp3TUg5fHPLhKtbcnN3Z1I1ePD0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.41.0 h1:VO3BL6OZXRQ1yQc8W6EVfJzINeJ35BkiHx4MYfoQf44=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.41.0/go.mod h1:qRDnJ2nv3CQXMK2HUd9K9VtvedsPAce3S+/4LZHjX/s=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.41.0 h1:MMrOAN8H1FrvDyq9UJ4lu5/+ss49Qgfgb7Zpm0m8ABo=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.41.0/go.mod h1:Na+2NNASJtF+uT4NxDe0G+NQb+bUgdPDfwxY/6JmS/c=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 h1:ao6Oe+wSebTlQ1OEht7jlYTzQKE+pnx/iNywFvTbuuI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0/go.mod h1:u3T6vz0gh/NVzgDgiwkgLxpsSF6PaPmo2il0apGJbls=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.41.0 h1:mq/Qcf28TWz719lE3/hMB4KkyDuLJIvgJnFGcd0kEUI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.41.0/go.mod h1:yk5LXEYhsL2htyDNJbEq7fWzNEigeEdV5xBF/Y+kAv0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 h1:inYW9ZhgqiDqh6BioM7DVHHzEGVq76Db5897WLGZ5Go=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0/go.mod h1:Izur+Wt8gClgMJqO/cZ8wdeeMryJ/xxiOVgFSSfpDTY=
|
||||
go.opentelemetry.io/otel/log v0.16.0 h1:DeuBPqCi6pQwtCK0pO4fvMB5eBq6sNxEnuTs88pjsN4=
|
||||
go.opentelemetry.io/otel/log v0.16.0/go.mod h1:rWsmqNVTLIA8UnwYVOItjyEZDbKIkMxdQunsIhpUMes=
|
||||
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
|
||||
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
|
||||
go.opentelemetry.io/otel/sdk/log v0.16.0 h1:e/b4bdlQwC5fnGtG3dlXUrNOnP7c8YLVSpSfEBIkTnI=
|
||||
go.opentelemetry.io/otel/sdk/log v0.16.0/go.mod h1:JKfP3T6ycy7QEuv3Hj8oKDy7KItrEkus8XJE6EoSzw4=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.16.0 h1:/XVkpZ41rVRTP4DfMgYv1nEtNmf65XPPyAdqV90TMy4=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.16.0/go.mod h1:iOOPgQr5MY9oac/F5W86mXdeyWZGleIx3uXO98X2R6Y=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=
|
||||
google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,722 @@
|
||||
// Package main implements the IntegraCI db-migration Dagger module.
|
||||
//
|
||||
// Judges a service's migration SQL with IntegraCI's DB-change engine (the DBV
|
||||
// policy engine behind the tenant's own policy, POST /api/v1/db-changes/analyze)
|
||||
// and applies migrations with the tenant's own tool: liquibase (default — the
|
||||
// engine the platform runs for its own database), flyway, or atlas. Which tool
|
||||
// a tenant uses is the tenant's choice; atlas here is one of those choices, not
|
||||
// the platform's (the platform retired atlas for its own schema in 2026-09).
|
||||
//
|
||||
// Verified 2026-09-26: `dagger functions` builds this module on engine v0.21.8.
|
||||
// Before that date it was marked an unverified scaffold, and its lint could not
|
||||
// fail for liquibase or flyway: `validate || true` swallowed every error, the
|
||||
// destructive check grepped the tool's output (which carries no SQL), and the
|
||||
// summary was POSTed to /services/{id}/migrations, which the API never served.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call lint --source . --dir migrations --api-url "$INTEGRACI_URL" --token env://INTEGRACI_TOKEN
|
||||
// dagger call apply --source . --dir migrations --db-url env://DATABASE_URL --api-url "$INTEGRACI_URL" --token env://INTEGRACI_TOKEN
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"dagger/db-migration/engine"
|
||||
"dagger/db-migration/internal/dagger"
|
||||
"dagger/db-migration/verdict"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// DbMigration is the IntegraCI database migration module.
|
||||
type DbMigration struct{}
|
||||
|
||||
// The images this module runs, pinned by tag AND digest (checked 2026-09-27):
|
||||
// a bare tag is a question to the registry on every run, and an air-gapped
|
||||
// mirror can only serve what it was given.
|
||||
const (
|
||||
// The Liquibase version the platform itself runs (apps/api/Dockerfile).
|
||||
// Its JDBC drivers: postgresql, mssql-jdbc (SQL Server), ojdbc8 (Oracle),
|
||||
// mariadb-java-client (MariaDB, and MySQL through a jdbc:mariadb: URL),
|
||||
// jcc (DB2), jaybird (Firebird), snowflake, sqlite, h2, hsqldb. Not
|
||||
// MySQL Connector/J: a jdbc:mysql: URL finds no driver.
|
||||
liquibaseImage = "liquibase/liquibase:4.31.1-alpine@sha256:d7e17e2d234835fe132c4c46ec1af7d7d490710e882db162abb15593c4948fe8"
|
||||
flywayImage = "flyway/flyway:10.22.0-alpine@sha256:94a81ca7db9a9f24fd8acd7463fa4560cb8f66aae2aa64485c27eb296f5851cf"
|
||||
// Atlas Community Edition (Apache 2.0). The standard arigaio/atlas image
|
||||
// is licensed under the proprietary Atlas MSA, and this module used it until
|
||||
// 2026-09-27. Community supports PostgreSQL, MySQL, MariaDB and SQLite —
|
||||
// not SQL Server or Oracle (https://atlasgo.io/community-edition).
|
||||
atlasImage = "arigaio/atlas:1.3.3-community-alpine@sha256:9d3161bf3bf2b0ce6d0f6b63471d0a341e664e87cccec90a12139ea2cba18575"
|
||||
// The throwaway database `atlas migrate lint` replays migrations on.
|
||||
atlasDevPostgresImage = "postgres:16.13-alpine@sha256:4e6e670bb069649261c9c18031f0aded7bb249a5b6664ddec29c013a89310d50"
|
||||
)
|
||||
|
||||
// engines are the migration-engine adapters (ADR-0070 §1), running the images
|
||||
// pinned above. An adapter builds the command; this file binds the secrets and
|
||||
// mounts only the judged files.
|
||||
var engines = engine.New(engine.Images{Liquibase: liquibaseImage, Flyway: flywayImage, Atlas: atlasImage})
|
||||
|
||||
// defaultAdapter is the adapter the platform's grants are written for, if it
|
||||
// drives the operation op. Asked before a grant is requested, so a default
|
||||
// that cannot drive it fails without spending a grant nobody reports.
|
||||
func defaultAdapter(drives func(engine.Capabilities) bool, op string) (engine.Adapter, error) {
|
||||
adapter, err := engines.For(engine.DefaultTool)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !drives(adapter.Capabilities()) {
|
||||
return nil, fmt.Errorf("%s %s: %w", adapter.Name(), op, engine.ErrUnsupported)
|
||||
}
|
||||
return adapter, nil
|
||||
}
|
||||
|
||||
// LintReport summarises a migration lint run.
|
||||
type LintReport struct {
|
||||
Tool string `json:"tool"`
|
||||
Dir string `json:"dir"`
|
||||
// Destructive and security-sensitive statements across all files.
|
||||
DestructiveFound int `json:"destructive_found"`
|
||||
DestructiveList []string `json:"destructive_list"`
|
||||
// The engine's verdict per migration file.
|
||||
Verdicts []FileVerdict `json:"verdicts"`
|
||||
// Output of the tool's own lint (atlas only; kept when it fails too).
|
||||
Report string `json:"report"`
|
||||
Skipped bool `json:"skipped,omitempty"`
|
||||
Pass bool `json:"pass"`
|
||||
}
|
||||
|
||||
// FileVerdict is the engine's verdict on one migration file.
|
||||
type FileVerdict struct {
|
||||
File string `json:"file"`
|
||||
Decision string `json:"decision"`
|
||||
Reasons []string `json:"reasons"`
|
||||
Rules []string `json:"rules"`
|
||||
RulesetVersion string `json:"ruleset_version"`
|
||||
}
|
||||
|
||||
// ApplyResult contains the output of a migration apply run.
|
||||
type ApplyResult struct {
|
||||
Tool string `json:"tool"`
|
||||
Dir string `json:"dir"`
|
||||
Applied int `json:"applied"`
|
||||
Pending int `json:"pending"`
|
||||
Report string `json:"report"`
|
||||
BlockedReason string `json:"blocked_reason,omitempty"`
|
||||
Skipped bool `json:"skipped,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// Lint judges every migration file with IntegraCI's DB-change engine and fails
|
||||
// on a change the tenant's policy blocks (or one needing approval, while
|
||||
// blocking is on). For atlas it also runs `atlas migrate lint`, and fails when
|
||||
// that does.
|
||||
//
|
||||
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
||||
// by default, keyed on its arguments, so a second call would return the first
|
||||
// call's verdict without judging, running or reporting anything.
|
||||
// +cache="never"
|
||||
func (m *DbMigration) Lint(
|
||||
ctx context.Context,
|
||||
// Source directory containing migrations
|
||||
source *dagger.Directory,
|
||||
// Migrations directory relative to source
|
||||
// +optional
|
||||
// +default="migrations"
|
||||
dir string,
|
||||
// Dev database URL atlas replays the migrations on — a secret, since a
|
||||
// DSN carries a password. Unset: a throwaway PostgreSQL is started for
|
||||
// this run (dialect postgres). The old default, docker://postgres/16/dev,
|
||||
// needs a Docker CLI inside the atlas container and never worked here.
|
||||
// +optional
|
||||
devURL *dagger.Secret,
|
||||
// Migration tool: liquibase | atlas | flyway | none
|
||||
// +optional
|
||||
// +default="liquibase"
|
||||
tool string,
|
||||
// Also fail on a change that needs approval (a blocked change always fails)
|
||||
// +optional
|
||||
// +default=true
|
||||
blockDestructive bool,
|
||||
// IntegraCI API URL — the engine that judges the SQL
|
||||
// +optional
|
||||
apiURL string,
|
||||
// IntegraCI API token
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// SQL dialect: postgres | mysql | oracle | tsql. Unset: the platform
|
||||
// judges in the engines of the service's databases when --service-id is
|
||||
// given, and as PostgreSQL otherwise
|
||||
// +optional
|
||||
dialect string,
|
||||
// Database engine instead of --dialect (postgres, mysql, sqlserver, oracle,
|
||||
// mongodb, snowflake, bigquery, spanner): the platform judges the SQL in
|
||||
// that engine's dialect, and one it has no rules for comes back unjudged,
|
||||
// needing an approver (GET /api/v1/db-engines)
|
||||
// +optional
|
||||
engine string,
|
||||
// Tenant environment id whose DB-change policy (and stage) applies
|
||||
// +optional
|
||||
environmentID string,
|
||||
// The service these migrations belong to. With --version, the platform
|
||||
// records its verdict for that release, which its deploy gate can require
|
||||
// +optional
|
||||
serviceID string,
|
||||
// The version being built: the image tag the deploy will carry
|
||||
// +optional
|
||||
version string,
|
||||
) (*LintReport, error) {
|
||||
report := &LintReport{
|
||||
Tool: tool,
|
||||
Dir: dir,
|
||||
DestructiveList: []string{},
|
||||
Verdicts: []FileVerdict{},
|
||||
Pass: true,
|
||||
}
|
||||
|
||||
target, err := verdict.ResolveTarget(engine, dialect)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := verdict.CheckTool(tool, target.ToolDialect()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// "none" disables DB migration governance — no-op skip.
|
||||
if tool == "none" {
|
||||
report.Skipped = true
|
||||
return report, nil
|
||||
}
|
||||
|
||||
if err := m.judge(ctx, source, dir, tool, apiURL, token, target, environmentID, serviceID, version, report); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The policy decides first. atlas lint REPLAYS the files on its dev
|
||||
// database, so a file the policy refuses must never reach it (review,
|
||||
// 2026-09-27: a blocked `COPY … TO PROGRAM` would otherwise run there).
|
||||
refused, err := verdict.Refused(judged(report), blockDestructive)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(refused) > 0 {
|
||||
report.Pass = false
|
||||
return report, fmt.Errorf("lint: %d migration file(s) refused by the DB-change policy: %s",
|
||||
len(refused), strings.Join(refused, "; "))
|
||||
}
|
||||
|
||||
if tool == "atlas" {
|
||||
rawOut, failed, err := m.atlasLint(ctx, source.Directory(dir), devURL, target.ToolDialect())
|
||||
report.Report = rawOut
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("atlas lint could not run: %w", err)
|
||||
}
|
||||
if failed {
|
||||
report.Pass = false
|
||||
return report, fmt.Errorf("atlas migrate lint reported errors:\n%s", rawOut)
|
||||
}
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// Apply runs the migrations against the target database. It judges them first
|
||||
// and refuses what the DB-change policy refuses: always a blocked change, and
|
||||
// one that needs approval unless blockDestructive is off. The tool sees ONLY
|
||||
// the judged directory — not the repo root, where a liquibase.properties or a
|
||||
// flyway config could point it at SQL nobody judged.
|
||||
//
|
||||
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
||||
// by default, keyed on its arguments, so a second call would return the first
|
||||
// call's verdict without judging, running or reporting anything.
|
||||
// +cache="never"
|
||||
func (m *DbMigration) Apply(
|
||||
ctx context.Context,
|
||||
// Source directory containing migrations
|
||||
source *dagger.Directory,
|
||||
// Migrations directory relative to source
|
||||
// +optional
|
||||
// +default="migrations"
|
||||
dir string,
|
||||
// Target database URL (DATABASE_URL) to apply migrations to
|
||||
// +optional
|
||||
dbURL *dagger.Secret,
|
||||
// Migration tool: liquibase | atlas | flyway | none
|
||||
// +optional
|
||||
// +default="liquibase"
|
||||
tool string,
|
||||
// Also refuse a change that needs approval (a blocked change is always refused)
|
||||
// +optional
|
||||
// +default=true
|
||||
blockDestructive bool,
|
||||
// IntegraCI API URL — the engine that judges the SQL
|
||||
// +optional
|
||||
apiURL string,
|
||||
// IntegraCI API token
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// SQL dialect: postgres | mysql | oracle | tsql. Unset: the platform
|
||||
// judges in the engines of the service's databases when --service-id is
|
||||
// given, and as PostgreSQL otherwise
|
||||
// +optional
|
||||
dialect string,
|
||||
// Database engine instead of --dialect (postgres, mysql, sqlserver, oracle,
|
||||
// mongodb, snowflake, bigquery, spanner): the platform judges the SQL in
|
||||
// that engine's dialect, and one it has no rules for comes back unjudged,
|
||||
// needing an approver (GET /api/v1/db-engines)
|
||||
// +optional
|
||||
engine string,
|
||||
// Tenant environment id whose DB-change policy (and stage) applies
|
||||
// +optional
|
||||
environmentID string,
|
||||
// The service these migrations belong to (with --version; see lint)
|
||||
// +optional
|
||||
serviceID string,
|
||||
// The version being built: the image tag the deploy will carry
|
||||
// +optional
|
||||
version string,
|
||||
) (*ApplyResult, error) {
|
||||
result := &ApplyResult{Tool: tool, Dir: dir}
|
||||
target, err := verdict.ResolveTarget(engine, dialect)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := verdict.CheckTool(tool, target.ToolDialect()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// "none" disables DB migration governance — no-op skip.
|
||||
if tool == "none" {
|
||||
result.Skipped = true
|
||||
result.Success = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Judge before touching the target DB — always.
|
||||
lint := &LintReport{DestructiveList: []string{}, Verdicts: []FileVerdict{}}
|
||||
if err := m.judge(ctx, source, dir, tool, apiURL, token, target, environmentID, serviceID, version, lint); err != nil {
|
||||
return nil, fmt.Errorf("pre-apply check failed: %w", err)
|
||||
}
|
||||
refused, err := verdict.Refused(judged(lint), blockDestructive)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("pre-apply check failed: %w", err)
|
||||
}
|
||||
if len(refused) > 0 {
|
||||
result.BlockedReason = strings.Join(refused, "; ")
|
||||
return result, fmt.Errorf("apply blocked: %s", result.BlockedReason)
|
||||
}
|
||||
files := make([]string, 0, len(lint.Verdicts))
|
||||
for _, v := range lint.Verdicts {
|
||||
files = append(files, v.File)
|
||||
}
|
||||
|
||||
rawOut, err := m.runApply(ctx, source.Directory(dir), tool, dbURL, files)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s apply failed: %w", tool, err)
|
||||
}
|
||||
result.Report = rawOut
|
||||
result.Applied = verdict.AppliedCount(tool, rawOut)
|
||||
result.Success = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Execute runs a batch the platform granted to this executor (plan §P5,
|
||||
// integraci_db_apply_execution = "delegated"). It asks for a single-use grant
|
||||
// for the dispatched batch digest, fetches the granted changelog, refuses it
|
||||
// unless its SHA-256 is the one the grant names, runs it with Liquibase against
|
||||
// --db-url, and reports the outcome once, so the platform's ledger records what
|
||||
// ran. The platform never connects to the database.
|
||||
//
|
||||
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
||||
// by default, keyed on its arguments, so a second call would return the first
|
||||
// call's verdict without judging, running or reporting anything.
|
||||
// +cache="never"
|
||||
func (m *DbMigration) Execute(
|
||||
ctx context.Context,
|
||||
// IntegraCI API URL
|
||||
apiURL string,
|
||||
// IntegraCI API token of this tenant, with write on db_devops
|
||||
apiToken *dagger.Secret,
|
||||
// DbInstance id the batch was dispatched for
|
||||
instanceID string,
|
||||
// Batch digest (changeset_sha256) from the dispatched apply or rollback
|
||||
digest string,
|
||||
// Target database URL — a secret, never on the command line
|
||||
dbURL *dagger.Secret,
|
||||
// Roll back the last N applied changesets instead of applying (the count
|
||||
// the dispatched rollback named); 0 applies
|
||||
// +optional
|
||||
// +default=0
|
||||
rollbackCount int,
|
||||
) (*ApplyResult, error) {
|
||||
api, err := apiToken.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading the API token: %w", err)
|
||||
}
|
||||
client := verdict.NewClient()
|
||||
grant, err := verdict.RequestGrant(ctx, client, apiURL, api, instanceID, digest, rollbackCount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
granted, err := verdict.FetchGranted(ctx, client, apiURL, api, *grant)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
file, err := granted.FileName()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
migrations := dag.Directory().WithNewFile(file, granted.Changelog)
|
||||
ref := "dagger-" + grant.ChangelogSHA256[:12]
|
||||
var out string
|
||||
var runErr error
|
||||
if rollbackCount > 0 {
|
||||
out, runErr = m.runRollback(ctx, migrations, file, dbURL, rollbackCount)
|
||||
} else {
|
||||
out, runErr = m.runApply(ctx, migrations, engine.DefaultTool, dbURL, []string{file})
|
||||
}
|
||||
outcome, message := "applied", "applied by the tenant's executor"
|
||||
if runErr != nil {
|
||||
outcome, message = "failed", runErr.Error()
|
||||
}
|
||||
if err := verdict.Report(ctx, client, apiURL, api, *grant, outcome, ref, message); err != nil {
|
||||
// The run happened; the ledger does not know. Say both.
|
||||
return nil, fmt.Errorf("%s, and %w", outcome, err)
|
||||
}
|
||||
if runErr != nil {
|
||||
return nil, fmt.Errorf("%s apply failed (reported): %w", engine.DefaultTool, runErr)
|
||||
}
|
||||
return &ApplyResult{Tool: engine.DefaultTool, Dir: "granted", Applied: len(granted.Changesets), Report: out, Success: true}, nil
|
||||
}
|
||||
|
||||
// judge sends every migration file to IntegraCI's DB-change engine and records
|
||||
// the verdicts in report. It fails closed: without an API to ask, with a
|
||||
// changelog format the engine cannot read, or with a file the API will not
|
||||
// take, nothing has judged the directory, so the step cannot pass.
|
||||
func (m *DbMigration) judge(
|
||||
ctx context.Context,
|
||||
source *dagger.Directory,
|
||||
dir, tool, apiURL string,
|
||||
token *dagger.Secret,
|
||||
target verdict.Target,
|
||||
environmentID, serviceID, version string,
|
||||
report *LintReport,
|
||||
) error {
|
||||
if apiURL == "" || token == nil {
|
||||
return fmt.Errorf("--api-url and --token are required: the verdict comes from IntegraCI's DB-change engine, and without it nothing judges the SQL")
|
||||
}
|
||||
migrations := source.Directory(dir)
|
||||
entries, err := migrations.Glob(ctx, "**/*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("listing %s: %w", dir, err)
|
||||
}
|
||||
sqlFiles, unanalysable := verdict.SplitMigrations(entries)
|
||||
if len(unanalysable) > 0 {
|
||||
return fmt.Errorf("the DB-change engine reads SQL files; it cannot judge these (changelogs, other suffixes, symlinks): %s "+
|
||||
"(use Liquibase formatted SQL, or --tool=none to opt out of governance)", strings.Join(unanalysable, ", "))
|
||||
}
|
||||
plain, err := token.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading the token: %w", err)
|
||||
}
|
||||
var env *string
|
||||
if environmentID != "" {
|
||||
env = &environmentID
|
||||
}
|
||||
service, release, err := verdict.Release(serviceID, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client := verdict.NewClient()
|
||||
for _, file := range sqlFiles {
|
||||
sql, err := migrations.File(file).Contents(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading %s: %w", file, err)
|
||||
}
|
||||
if err := verdict.Judgeable(file, sql); err != nil {
|
||||
return err
|
||||
}
|
||||
if tool == "liquibase" {
|
||||
if err := verdict.LiquibaseJudgeable(file, sql); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(sql) == "" {
|
||||
continue
|
||||
}
|
||||
name := file
|
||||
resp, err := verdict.Analyze(ctx, client, apiURL, plain, verdict.Request{
|
||||
SQL: sql, Dialect: target.Dialect, Engine: target.Engine, EnvironmentID: env,
|
||||
ServiceID: service, Version: release, File: &name,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("judging %s: %w", file, err)
|
||||
}
|
||||
v := FileVerdict(verdict.Of(file, resp))
|
||||
report.Verdicts = append(report.Verdicts, v)
|
||||
report.DestructiveFound += resp.DestructiveCount + resp.SecurityCount
|
||||
report.DestructiveList = append(report.DestructiveList, v.Rules...)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// judged converts the report's verdicts for the verdict package.
|
||||
func judged(report *LintReport) []verdict.FileVerdict {
|
||||
out := make([]verdict.FileVerdict, 0, len(report.Verdicts))
|
||||
for _, v := range report.Verdicts {
|
||||
out = append(out, verdict.FileVerdict(v))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// atlasLint runs atlas' own migration lint against a dev database — the given
|
||||
// one, or, with none given, a throwaway PostgreSQL started for this run. Like
|
||||
// runApply it sees the judged directory alone, with an empty working
|
||||
// directory, so an atlas.hcl in the repo cannot change what it reads. It
|
||||
// returns the lint's output and whether the lint failed; err is for a lint
|
||||
// that could not run at all.
|
||||
func (m *DbMigration) atlasLint(ctx context.Context, migrations *dagger.Directory, devURL *dagger.Secret, dialect string) (string, bool, error) {
|
||||
ctr := dag.Container().
|
||||
From(atlasImage).
|
||||
WithDirectory("/migrations", migrations).
|
||||
WithWorkdir("/work")
|
||||
if devURL != nil {
|
||||
ctr = ctr.WithSecretVariable("DEV_URL", devURL)
|
||||
} else {
|
||||
if dialect != "postgres" {
|
||||
return "", false, fmt.Errorf("--dev-url is required for atlas with dialect %q: only a PostgreSQL dev database is started for you", dialect)
|
||||
}
|
||||
nonce := make([]byte, 8)
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
dev := dag.Container().
|
||||
From(atlasDevPostgresImage).
|
||||
// Reachable only through this binding, for this run. Trust auth: no
|
||||
// password to leak. The nonce makes the service this run's own —
|
||||
// two identical definitions could otherwise share one database.
|
||||
WithEnvVariable("POSTGRES_HOST_AUTH_METHOD", "trust").
|
||||
WithEnvVariable("POSTGRES_DB", "dev").
|
||||
WithEnvVariable("INTEGRACI_LINT_RUN", hex.EncodeToString(nonce)).
|
||||
WithExposedPort(5432).
|
||||
AsService(dagger.ContainerAsServiceOpts{UseEntrypoint: true})
|
||||
ctr = ctr.
|
||||
WithServiceBinding("devdb", dev).
|
||||
WithEnvVariable("DEV_URL", "postgres://postgres@devdb:5432/dev?sslmode=disable")
|
||||
}
|
||||
run := ctr.WithExec([]string{"sh", "-c",
|
||||
`atlas migrate lint --dir file:///migrations --dev-url "$DEV_URL" --latest 1`,
|
||||
}, dagger.ContainerWithExecOpts{Expect: dagger.ReturnTypeAny})
|
||||
code, err := run.ExitCode(ctx)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
stdout, err := run.Stdout(ctx)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
stderr, err := run.Stderr(ctx)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return strings.TrimSpace(stdout + "\n" + stderr), code != 0, nil
|
||||
}
|
||||
|
||||
// runApply executes the tool-specific apply and returns its output. The tool
|
||||
// gets the judged directory alone, mounted at /migrations, and an empty
|
||||
// working directory, so no config file from the repo can widen what it runs.
|
||||
// The target database URL is a secret env var, never on the command line.
|
||||
// Liquibase runs each judged file as its own formatted-SQL changelog, in the
|
||||
// order they were judged: there is no master changelog to point it at, and
|
||||
// that is exactly the set the engine saw.
|
||||
func (m *DbMigration) runApply(ctx context.Context, migrations *dagger.Directory, tool string, dbURL *dagger.Secret, files []string) (string, error) {
|
||||
// verdict.CheckTool already refused an unknown tool; For refuses it again
|
||||
// rather than fall through to another tool.
|
||||
adapter, err := engines.For(tool)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cmd, err := adapter.Apply(files)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return dag.Container().
|
||||
From(cmd.Image).
|
||||
WithSecretVariable("DATABASE_URL", dbURL).
|
||||
WithDirectory("/migrations", migrations).
|
||||
WithWorkdir("/work").
|
||||
WithExec(cmd.Args).
|
||||
Stdout(ctx)
|
||||
}
|
||||
|
||||
// Drift checks the tenant's database for drift under a platform-issued drift
|
||||
// grant, and reports it once. The reference is NOT the executor's choice: the
|
||||
// grant names the instance's applied changelog, which is built into a
|
||||
// throwaway PostgreSQL (or into --reference-url, an EMPTY database of the same
|
||||
// engine, for another dialect) and diffed against the live database. Until
|
||||
// 2026-09-27 the executor passed any reference URL and the report took no
|
||||
// grant, so it proved nothing (plan §7, "self-attested").
|
||||
//
|
||||
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
||||
// by default, keyed on its arguments, so a second call would return the first
|
||||
// call's verdict without judging, running or reporting anything.
|
||||
// +cache="never"
|
||||
func (m *DbMigration) Drift(
|
||||
ctx context.Context,
|
||||
// IntegraCI API URL
|
||||
apiURL string,
|
||||
// IntegraCI API token of this tenant, with write on db_devops
|
||||
apiToken *dagger.Secret,
|
||||
// DbInstance id to report drift for
|
||||
instanceID string,
|
||||
// The live database URL (JDBC) — a secret
|
||||
dbURL *dagger.Secret,
|
||||
// A reference to this run (CI job URL or id), kept with the report
|
||||
executionRef string,
|
||||
// An EMPTY database of the live database's engine to build the reference
|
||||
// in (JDBC, a secret). Unset: a throwaway PostgreSQL for this run.
|
||||
// +optional
|
||||
referenceURL *dagger.Secret,
|
||||
) (*DriftResult, error) {
|
||||
// Before the grant: one the adapter cannot use would be spent unreported.
|
||||
adapter, err := defaultAdapter(func(c engine.Capabilities) bool { return c.Drift }, "drift")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
api, err := apiToken.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading the API token: %w", err)
|
||||
}
|
||||
client := verdict.NewClient()
|
||||
grant, err := verdict.RequestObservationGrant(ctx, client, apiURL, api, instanceID, "drift")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
granted, err := verdict.FetchGranted(ctx, client, apiURL, api, *grant)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
file, err := granted.FileName()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cmd, err := adapter.Drift(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctr := dag.Container().
|
||||
From(cmd.Image).
|
||||
WithSecretVariable("DATABASE_URL", dbURL).
|
||||
WithDirectory("/reference", dag.Directory().WithNewFile(file, granted.Changelog)).
|
||||
WithWorkdir("/work").
|
||||
// This grant's own run: never a cached diff from an earlier one.
|
||||
WithEnvVariable("INTEGRACI_DRIFT_GRANT", grant.JTI)
|
||||
if referenceURL != nil {
|
||||
ctr = ctr.WithSecretVariable("REFERENCE_URL", referenceURL)
|
||||
} else {
|
||||
ref := dag.Container().
|
||||
From(atlasDevPostgresImage).
|
||||
WithEnvVariable("POSTGRES_HOST_AUTH_METHOD", "trust").
|
||||
WithEnvVariable("POSTGRES_DB", "reference").
|
||||
WithEnvVariable("INTEGRACI_DRIFT_GRANT", grant.JTI).
|
||||
WithExposedPort(5432).
|
||||
AsService(dagger.ContainerAsServiceOpts{UseEntrypoint: true})
|
||||
ctr = ctr.
|
||||
WithServiceBinding("refdb", ref).
|
||||
WithEnvVariable("REFERENCE_URL", "jdbc:postgresql://refdb:5432/reference?user=postgres")
|
||||
}
|
||||
out, err := ctr.WithExec(cmd.Args).Stdout(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("building the reference or diffing against it failed: %w", err)
|
||||
}
|
||||
report := verdict.DriftReport{Drifted: verdict.Drifted(out), Diff: out, ExecutionRef: executionRef}
|
||||
if err := verdict.ReportDrift(ctx, client, apiURL, api, *grant, report); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &DriftResult{Drifted: report.Drifted, Report: out}, nil
|
||||
}
|
||||
|
||||
// Snapshot takes a schema snapshot of the tenant's database under a snapshot
|
||||
// grant and records it on the platform (its hash and size, as an in-process
|
||||
// snapshot is not stored either). Returns the snapshot JSON.
|
||||
//
|
||||
// Never cached (+cache="never"): Dagger caches a function's result for 7 days
|
||||
// by default, keyed on its arguments, so a second call would return the first
|
||||
// call's verdict without judging, running or reporting anything.
|
||||
// +cache="never"
|
||||
func (m *DbMigration) Snapshot(
|
||||
ctx context.Context,
|
||||
// IntegraCI API URL
|
||||
apiURL string,
|
||||
// IntegraCI API token of this tenant, with write on db_devops
|
||||
apiToken *dagger.Secret,
|
||||
// DbInstance id the snapshot is of
|
||||
instanceID string,
|
||||
// The live database URL (JDBC) — a secret
|
||||
dbURL *dagger.Secret,
|
||||
// A reference to this run (CI job URL or id)
|
||||
executionRef string,
|
||||
) (string, error) {
|
||||
// Before the grant: one the adapter cannot use would be spent unreported.
|
||||
adapter, err := defaultAdapter(func(c engine.Capabilities) bool { return c.Snapshot }, "snapshot")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
api, err := apiToken.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("reading the API token: %w", err)
|
||||
}
|
||||
client := verdict.NewClient()
|
||||
grant, err := verdict.RequestObservationGrant(ctx, client, apiURL, api, instanceID, "snapshot")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cmd, err := adapter.Snapshot()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
out, runErr := dag.Container().
|
||||
From(cmd.Image).
|
||||
WithSecretVariable("DATABASE_URL", dbURL).
|
||||
WithWorkdir("/work").
|
||||
// This grant's own run: never a cached snapshot from an earlier one.
|
||||
WithEnvVariable("INTEGRACI_SNAPSHOT_GRANT", grant.JTI).
|
||||
WithExec(cmd.Args).
|
||||
Stdout(ctx)
|
||||
outcome, message := "taken", ""
|
||||
if runErr != nil {
|
||||
outcome, message, out = "failed", runErr.Error(), ""
|
||||
}
|
||||
if err := verdict.ReportSnapshot(ctx, client, apiURL, api, *grant, outcome, out, executionRef, message); err != nil {
|
||||
return "", fmt.Errorf("%s, and %w", outcome, err)
|
||||
}
|
||||
if runErr != nil {
|
||||
return "", fmt.Errorf("%s snapshot failed (reported): %w", engine.DefaultTool, runErr)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DriftResult is what Drift found and reported.
|
||||
type DriftResult struct {
|
||||
Drifted bool
|
||||
Report string
|
||||
}
|
||||
|
||||
// runRollback undoes the last n changesets of the granted changelog with the
|
||||
// default adapter, against the judged file alone (see runApply).
|
||||
func (m *DbMigration) runRollback(ctx context.Context, migrations *dagger.Directory, file string, dbURL *dagger.Secret, n int) (string, error) {
|
||||
adapter, err := engines.For(engine.DefaultTool)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cmd, err := adapter.Rollback(file, n)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return dag.Container().
|
||||
From(cmd.Image).
|
||||
WithSecretVariable("DATABASE_URL", dbURL).
|
||||
WithDirectory("/migrations", migrations).
|
||||
WithWorkdir("/work").
|
||||
WithExec(cmd.Args).
|
||||
Stdout(ctx)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
// Liquibase prints one UPDATE SUMMARY per changelog it ran; "Run:" is the
|
||||
// number of changesets that summary applied.
|
||||
liquibaseRun = regexp.MustCompile(`(?m)^Run:\s+(\d+)\s*$`)
|
||||
// Flyway prints one line for the whole run.
|
||||
flywayApplied = regexp.MustCompile(`Successfully applied (\d+) migrations?`)
|
||||
)
|
||||
|
||||
// AppliedCount reads how many migrations an apply ran from the tool's own
|
||||
// summary. Each tool reports it differently, and a marker that fits one tool
|
||||
// counts nothing (or the wrong thing) in another: until 2026-09-27 this module
|
||||
// reported 0 for every Liquibase run and 1 for every Flyway run of any size.
|
||||
// An output without the tool's summary counts 0.
|
||||
func AppliedCount(tool, out string) int {
|
||||
count := 0
|
||||
switch tool {
|
||||
case "liquibase":
|
||||
for _, m := range liquibaseRun.FindAllStringSubmatch(out, -1) {
|
||||
n, _ := strconv.Atoi(m[1])
|
||||
count += n
|
||||
}
|
||||
case "flyway":
|
||||
for _, m := range flywayApplied.FindAllStringSubmatch(out, -1) {
|
||||
n, _ := strconv.Atoi(m[1])
|
||||
count += n
|
||||
}
|
||||
case "atlas":
|
||||
// One "-- migrating version <v>" line per file it applied.
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
if strings.HasPrefix(strings.TrimSpace(line), "-- migrating version ") {
|
||||
count++
|
||||
}
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package verdict
|
||||
|
||||
import "testing"
|
||||
|
||||
// The outputs below are what the pinned images printed on 2026-09-27
|
||||
// (liquibase 4.31.1-alpine, flyway 10.22.0-alpine, atlas 1.3.3-community-alpine),
|
||||
// trimmed to the lines that matter.
|
||||
|
||||
const liquibaseTwoChangelogs = `Liquibase Open Source 4.31.1 by Liquibase
|
||||
UPDATE SUMMARY
|
||||
Run: 2
|
||||
Previously run: 0
|
||||
Filtered out: 0
|
||||
-------------------------------
|
||||
Total change sets: 2
|
||||
Liquibase: Update has been successful. Rows affected: 4
|
||||
Liquibase Open Source 4.31.1 by Liquibase
|
||||
UPDATE SUMMARY
|
||||
Run: 1
|
||||
Previously run: 0
|
||||
Filtered out: 0
|
||||
-------------------------------
|
||||
Total change sets: 1
|
||||
`
|
||||
|
||||
// A changelog two of whose three changesets had already run.
|
||||
const liquibasePartlyRun = `UPDATE SUMMARY
|
||||
Run: 1
|
||||
Previously run: 2
|
||||
Filtered out: 0
|
||||
-------------------------------
|
||||
Total change sets: 3
|
||||
`
|
||||
|
||||
const flywayTwo = `Successfully validated 2 migrations (execution time 00:00.020s)
|
||||
Migrating schema "main" to version "1 - a"
|
||||
Migrating schema "main" to version "2 - b"
|
||||
Successfully applied 2 migrations to schema "main", now at version v2 (execution time 00:00.006s)
|
||||
`
|
||||
|
||||
const flywayNothing = `Successfully validated 2 migrations (execution time 00:00.041s)
|
||||
Current version of schema "main": 2
|
||||
Schema "main" is up to date. No migration necessary.
|
||||
`
|
||||
|
||||
const atlasTwo = `Migrating to version 20260927000002 (2 migrations in total):
|
||||
|
||||
-- migrating version 20260927000001
|
||||
-> CREATE TABLE t (id int);
|
||||
-- ok (1.2ms)
|
||||
|
||||
-- migrating version 20260927000002
|
||||
-> DROP TABLE t;
|
||||
-- ok (3.4ms)
|
||||
|
||||
-------------------------
|
||||
-- 11.18681ms
|
||||
-- 2 migrations
|
||||
-- 2 sql statements
|
||||
`
|
||||
|
||||
func TestAppliedCount(t *testing.T) {
|
||||
cases := []struct {
|
||||
tool, out string
|
||||
want int
|
||||
}{
|
||||
{"liquibase", liquibaseTwoChangelogs, 3},
|
||||
// "Previously run" and "Total change sets" are not what ran.
|
||||
{"liquibase", liquibasePartlyRun, 1},
|
||||
{"liquibase", "UPDATE SUMMARY\nRun: 0\nPreviously run: 5\n", 0},
|
||||
{"flyway", flywayTwo, 2},
|
||||
{"flyway", flywayNothing, 0},
|
||||
{"flyway", "Successfully applied 1 migration to schema \"main\"", 1},
|
||||
{"atlas", atlasTwo, 2},
|
||||
// One tool's markers count nothing for another.
|
||||
{"liquibase", flywayTwo, 0},
|
||||
{"flyway", atlasTwo, 0},
|
||||
{"atlas", liquibaseTwoChangelogs, 0},
|
||||
{"none", liquibaseTwoChangelogs, 0},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := AppliedCount(c.tool, c.out); got != c.want {
|
||||
t.Errorf("AppliedCount(%q) = %d, want %d", c.tool, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// liquibaseRunsUnjudged matches a formatted-SQL directive line that makes
|
||||
// Liquibase run, or skip, text the engine read as a comment:
|
||||
//
|
||||
// - precondition(s)/precondition-sql-check: runs the query in the comment
|
||||
// (measured 2026-09-27 on 4.31.1: `--precondition-sql-check expectedResult:0
|
||||
// WITH d AS (DELETE FROM users RETURNING 1) SELECT count(*) FROM d` is
|
||||
// judged "additive" — the engine sees a comment — and Liquibase executes it);
|
||||
// - include/includeAll: pull in files nobody sent to the engine;
|
||||
// - property: defines a ${…} value substituted after judging;
|
||||
// - validCheckSum: accepts an edited changeset without re-running the check;
|
||||
// - ignoreLines: skips judged lines, so what runs is not what was judged.
|
||||
//
|
||||
// The platform refuses the same set, and more, for changesets it renders itself
|
||||
// (apps/api/app/platform/services/db_apply_service.py, _LIQUIBASE_DIRECTIVE_LINE).
|
||||
// A tenant's own file keeps the lines a formatted-SQL changelog needs:
|
||||
// `--liquibase formatted sql`, `--changeset author:id [attributes]`,
|
||||
// `--rollback`, `--comment`.
|
||||
var liquibaseRunsUnjudged = regexp.MustCompile(
|
||||
`(?i)^\s*--\s*(?:preconditions?|precondition-[a-z-]+|include|includeall|property|validchecksum|ignorelines)\b`)
|
||||
|
||||
// lineEnds are line ends as Liquibase's reader sees them (Java readLine): a
|
||||
// lone \r ends a line too, so "SELECT 1;\r--precondition-sql-check …" is two
|
||||
// lines to Liquibase and must be two lines here.
|
||||
var lineEnds = regexp.MustCompile(`\r\n|\r|\n`)
|
||||
|
||||
// LiquibaseJudgeable refuses a formatted-SQL file holding a directive through
|
||||
// which Liquibase would run (or skip) text the engine did not judge.
|
||||
func LiquibaseJudgeable(file, sql string) error {
|
||||
for i, line := range lineEnds.Split(sql, -1) {
|
||||
if liquibaseRunsUnjudged.MatchString(line) {
|
||||
return fmt.Errorf("%s line %d is a Liquibase directive (%q) that runs or skips SQL the engine read as a comment; "+
|
||||
"the engine cannot judge it, so it is refused — write the check as its own changeset", file, i+1, line)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package verdict
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestLiquibaseJudgeable(t *testing.T) {
|
||||
refused := []string{
|
||||
"--liquibase formatted sql\n--changeset a:1\n--precondition-sql-check expectedResult:0 WITH d AS (DELETE FROM users RETURNING 1) SELECT count(*) FROM d\nCREATE TABLE t (id int);",
|
||||
"--preconditions onFail:MARK_RAN\nCREATE TABLE t (id int);",
|
||||
"--precondition-table-exists table:t",
|
||||
"--include file:other.sql",
|
||||
"--includeAll path:more/",
|
||||
"--property name:x value:y",
|
||||
"--validCheckSum: ANY",
|
||||
"--ignoreLines:start\nDROP TABLE t;\n--ignoreLines:end",
|
||||
" -- PRECONDITION-SQL-CHECK expectedResult:0 SELECT 1",
|
||||
// A lone \r ends a line for Liquibase.
|
||||
"SELECT 1;\r--precondition-sql-check expectedResult:0 SELECT 1",
|
||||
}
|
||||
for _, sql := range refused {
|
||||
if LiquibaseJudgeable("V1.sql", sql) == nil {
|
||||
t.Errorf("accepted %q", sql)
|
||||
}
|
||||
}
|
||||
// What a tenant's own formatted-SQL changelog legitimately holds.
|
||||
allowed := []string{
|
||||
"--liquibase formatted sql\n--changeset alice:1\nCREATE TABLE t (id int);\n--rollback DROP TABLE t;",
|
||||
"--changeset alice:2 splitStatements:false\nCREATE FUNCTION f() RETURNS int AS $$ SELECT 1 $$ LANGUAGE sql;",
|
||||
"--comment: adds the orders table\nCREATE TABLE orders (id int);",
|
||||
"-- a plain comment about preconditions in prose\nCREATE TABLE t (id int);",
|
||||
"CREATE TABLE includes (id int); -- not a directive",
|
||||
"",
|
||||
}
|
||||
for _, sql := range allowed {
|
||||
if err := LiquibaseJudgeable("V1.sql", sql); err != nil {
|
||||
t.Errorf("refused %q: %v", sql, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Grant is a single-use permission to run one batch (plan §P5): the batch
|
||||
// digest, the changelog's SHA-256, the stage and ruleset it was judged under,
|
||||
// an id and an expiry, all signed by Token.
|
||||
// apps/api/app/platform/services/db_execution.py mints it.
|
||||
type Grant struct {
|
||||
InstanceID string `json:"instance_id"`
|
||||
Digest string `json:"digest"`
|
||||
ChangelogSHA256 string `json:"changelog_sha256"`
|
||||
Stage string `json:"stage"`
|
||||
Ruleset string `json:"ruleset"`
|
||||
JTI string `json:"jti"`
|
||||
Exp int64 `json:"exp"`
|
||||
// Kind is "apply", or "rollback:<n>" to undo the last n changesets.
|
||||
Kind string `json:"kind"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// Granted is the changelog the platform hands out for a grant.
|
||||
type Granted struct {
|
||||
InstanceID string `json:"instance_id"`
|
||||
Digest string `json:"digest"`
|
||||
ChangelogSHA256 string `json:"changelog_sha256"`
|
||||
Changelog string `json:"changelog"`
|
||||
Changesets []string `json:"changesets"`
|
||||
// ChangelogName is the file name (without .sql) the platform applies this
|
||||
// schema's changelog under. Liquibase records a changeset by id, author AND
|
||||
// file name, so running it under any other name would run it again.
|
||||
ChangelogName string `json:"changelog_name"`
|
||||
}
|
||||
|
||||
var safeChangelogName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
|
||||
|
||||
// FileName is the changelog's file name, or an error when the platform named
|
||||
// something that is not a single safe path segment.
|
||||
func (g *Granted) FileName() (string, error) {
|
||||
if !safeChangelogName.MatchString(g.ChangelogName) || strings.Contains(g.ChangelogName, "..") {
|
||||
return "", fmt.Errorf("the granted changelog name %q is not a safe file name", g.ChangelogName)
|
||||
}
|
||||
return g.ChangelogName + ".sql", nil
|
||||
}
|
||||
|
||||
// ExecutionResult is the report of a delegated run.
|
||||
type ExecutionResult struct {
|
||||
Digest string `json:"digest"`
|
||||
ChangelogSHA256 string `json:"changelog_sha256"`
|
||||
Stage string `json:"stage"`
|
||||
Ruleset string `json:"ruleset"`
|
||||
JTI string `json:"jti"`
|
||||
Exp int64 `json:"exp"`
|
||||
Kind string `json:"kind"`
|
||||
Outcome string `json:"outcome"`
|
||||
ExecutionRef string `json:"execution_ref"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// The platform endpoints this client calls, as route templates. Kept in one
|
||||
// place because apps/api/tests/test_dagger_db_migration_paths_exist.py reads
|
||||
// them and checks each is a route the API serves: a fake server in these Go
|
||||
// tests would answer a path the API never had.
|
||||
const (
|
||||
GrantPath = "/api/v1/db-instances/{instance_id}/execution-grant"
|
||||
ChangelogPath = "/api/v1/db-executions/{instance_id}/changelog"
|
||||
ResultPath = "/api/v1/db-executions/{instance_id}/result"
|
||||
DriftReportPath = "/api/v1/db-instances/{instance_id}/drift-report"
|
||||
SnapshotPath = "/api/v1/db-executions/{instance_id}/snapshot"
|
||||
)
|
||||
|
||||
// endpoint fills a route template with the instance id.
|
||||
func endpoint(apiURL, template, instanceID string) string {
|
||||
return strings.TrimRight(apiURL, "/") + strings.Replace(template, "{instance_id}", url.PathEscape(instanceID), 1)
|
||||
}
|
||||
|
||||
// RequestGrant asks the platform for a single-use grant to run the batch with
|
||||
// this digest. The platform re-runs the gate first: a blocked batch, or one
|
||||
// needing an approval nobody recorded for this digest, gets no grant.
|
||||
func RequestGrant(ctx context.Context, client *http.Client, apiURL, apiToken, instanceID, digest string, rollbackCount int) (*Grant, error) {
|
||||
req0 := map[string]any{"digest": digest}
|
||||
if rollbackCount > 0 {
|
||||
req0["kind"] = "rollback"
|
||||
req0["count"] = rollbackCount
|
||||
}
|
||||
body, err := json.Marshal(req0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u := endpoint(apiURL, GrantPath, instanceID)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+apiToken)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("requesting a grant: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("requesting a grant: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
var g Grant
|
||||
if err := json.Unmarshal(raw, &g); err != nil {
|
||||
return nil, fmt.Errorf("the grant is not readable: %w", err)
|
||||
}
|
||||
wantKind := "apply"
|
||||
if rollbackCount > 0 {
|
||||
wantKind = fmt.Sprintf("rollback:%d", rollbackCount)
|
||||
}
|
||||
if g.Token == "" || g.JTI == "" || len(g.ChangelogSHA256) != 64 || g.Digest != digest || g.Kind != wantKind {
|
||||
return nil, fmt.Errorf("the platform answered with something that is not a grant for %s", digest)
|
||||
}
|
||||
return &g, nil
|
||||
}
|
||||
|
||||
// RequestObservationGrant asks for a single-use grant to observe the instance:
|
||||
// kind "drift" or "snapshot". The platform binds it to the instance's applied
|
||||
// state; for drift that state, as a changelog, is the reference to diff against.
|
||||
func RequestObservationGrant(ctx context.Context, client *http.Client, apiURL, apiToken, instanceID, kind string) (*Grant, error) {
|
||||
if kind != "drift" && kind != "snapshot" {
|
||||
return nil, fmt.Errorf("%q is not an observation grant", kind)
|
||||
}
|
||||
body, err := json.Marshal(map[string]any{"kind": kind})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint(apiURL, GrantPath, instanceID), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+apiToken)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("requesting a %s grant: %w", kind, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("requesting a %s grant: HTTP %d", kind, resp.StatusCode)
|
||||
}
|
||||
var g Grant
|
||||
if err := json.Unmarshal(raw, &g); err != nil {
|
||||
return nil, fmt.Errorf("the grant is not readable: %w", err)
|
||||
}
|
||||
if g.Token == "" || g.JTI == "" || len(g.Digest) != 64 || len(g.ChangelogSHA256) != 64 || g.Kind != kind {
|
||||
return nil, fmt.Errorf("the platform answered with something that is not a %s grant", kind)
|
||||
}
|
||||
return &g, nil
|
||||
}
|
||||
|
||||
// FetchGranted gets the granted changelog and REFUSES it unless its SHA-256 is
|
||||
// the one the grant names: what runs must be what the platform judged.
|
||||
func FetchGranted(ctx context.Context, client *http.Client, apiURL, apiToken string, g Grant) (*Granted, error) {
|
||||
q := url.Values{}
|
||||
q.Set("digest", g.Digest)
|
||||
q.Set("changelog_sha256", g.ChangelogSHA256)
|
||||
q.Set("stage", g.Stage)
|
||||
q.Set("ruleset", g.Ruleset)
|
||||
q.Set("jti", g.JTI)
|
||||
q.Set("kind", g.Kind)
|
||||
q.Set("exp", strconv.FormatInt(g.Exp, 10))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint(apiURL, ChangelogPath, g.InstanceID)+"?"+q.Encode(), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+apiToken)
|
||||
req.Header.Set("X-Execution-Token", g.Token)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetching the granted changelog: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("fetching the granted changelog: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
var out Granted
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, fmt.Errorf("the granted changelog is not readable: %w", err)
|
||||
}
|
||||
sum := sha256.Sum256([]byte(out.Changelog))
|
||||
if got := hex.EncodeToString(sum[:]); got != g.ChangelogSHA256 {
|
||||
return nil, fmt.Errorf("the changelog's SHA-256 is %s, the grant names %s: refusing to run it", got, g.ChangelogSHA256)
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// Report tells the platform what the run did.
|
||||
func Report(ctx context.Context, client *http.Client, apiURL, apiToken string, g Grant, outcome, ref, message string) error {
|
||||
if len(message) > 1000 {
|
||||
message = message[:1000]
|
||||
}
|
||||
body, err := json.Marshal(ExecutionResult{
|
||||
Digest: g.Digest, ChangelogSHA256: g.ChangelogSHA256, Stage: g.Stage, Ruleset: g.Ruleset, JTI: g.JTI, Exp: g.Exp, Kind: g.Kind,
|
||||
Outcome: outcome, ExecutionRef: ref, Message: message,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint(apiURL, ResultPath, g.InstanceID), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+apiToken)
|
||||
req.Header.Set("X-Execution-Token", g.Token)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reporting the outcome: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return fmt.Errorf("reporting the outcome: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DriftReport is a drift check the executor ran against its own database,
|
||||
// under a drift grant: its database against the grant's reference.
|
||||
type DriftReport struct {
|
||||
Drifted bool `json:"drifted"`
|
||||
Diff string `json:"diff"`
|
||||
ExecutionRef string `json:"execution_ref"`
|
||||
}
|
||||
|
||||
// Drifted reads Liquibase's diff output the way the platform's connector does:
|
||||
// a Missing, Unexpected or Changed section with an entry is drift.
|
||||
func Drifted(diff string) bool {
|
||||
for _, marker := range []string{"Missing ", "Unexpected ", "Changed "} {
|
||||
for _, line := range strings.Split(diff, "\n") {
|
||||
l := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(l, marker) && !strings.HasSuffix(l, ": NONE") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// grantFields are the signed fields a report repeats, with the token that signs them.
|
||||
func grantFields(g Grant) map[string]any {
|
||||
return map[string]any{
|
||||
"digest": g.Digest, "changelog_sha256": g.ChangelogSHA256, "stage": g.Stage,
|
||||
"ruleset": g.Ruleset, "jti": g.JTI, "exp": g.Exp, "kind": g.Kind,
|
||||
}
|
||||
}
|
||||
|
||||
// postGranted sends a report made under grant g, once.
|
||||
func postGranted(ctx context.Context, client *http.Client, apiURL, apiToken, template string, g Grant, fields map[string]any) error {
|
||||
body := grantFields(g)
|
||||
for k, v := range fields {
|
||||
body[k] = v
|
||||
}
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint(apiURL, template, g.InstanceID), bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+apiToken)
|
||||
req.Header.Set("X-Execution-Token", g.Token)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reporting the %s: %w", g.Kind, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return fmt.Errorf("reporting the %s: HTTP %d", g.Kind, resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReportDrift records the check on the platform under its drift grant.
|
||||
func ReportDrift(ctx context.Context, client *http.Client, apiURL, apiToken string, g Grant, r DriftReport) error {
|
||||
if len(r.Diff) > 8000 {
|
||||
r.Diff = r.Diff[:8000]
|
||||
}
|
||||
return postGranted(ctx, client, apiURL, apiToken, DriftReportPath, g, map[string]any{
|
||||
"drifted": r.Drifted, "diff": r.Diff, "execution_ref": r.ExecutionRef,
|
||||
})
|
||||
}
|
||||
|
||||
// ReportSnapshot records a snapshot under its snapshot grant: its SHA-256 and
|
||||
// size. The JSON stays with the executor.
|
||||
func ReportSnapshot(ctx context.Context, client *http.Client, apiURL, apiToken string, g Grant, outcome, snapshot, ref, message string) error {
|
||||
if len(message) > 1000 {
|
||||
message = message[:1000]
|
||||
}
|
||||
fields := map[string]any{"outcome": outcome, "execution_ref": ref, "snapshot_bytes": len(snapshot), "snapshot_sha256": ""}
|
||||
if snapshot != "" {
|
||||
sum := sha256.Sum256([]byte(snapshot))
|
||||
fields["snapshot_sha256"] = hex.EncodeToString(sum[:])
|
||||
}
|
||||
if message != "" {
|
||||
fields["message"] = message
|
||||
}
|
||||
return postGranted(ctx, client, apiURL, apiToken, SnapshotPath, g, fields)
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func sum(s string) string {
|
||||
h := sha256.Sum256([]byte(s))
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
func client() *http.Client { return &http.Client{Timeout: 5 * time.Second} }
|
||||
|
||||
func TestRequestGrantRefusesAnythingButAGrantForTheDigest(t *testing.T) {
|
||||
digest := strings.Repeat("d", 64)
|
||||
good := Grant{InstanceID: "i", Digest: digest, ChangelogSHA256: strings.Repeat("c", 64), Stage: "dev", Ruleset: "r", JTI: "abcdef012345", Exp: 1, Kind: "apply", Token: "t"}
|
||||
cases := map[string]Grant{
|
||||
"another digest": func() Grant { g := good; g.Digest = strings.Repeat("e", 64); return g }(),
|
||||
"no token": func() Grant { g := good; g.Token = ""; return g }(),
|
||||
"no id": func() Grant { g := good; g.JTI = ""; return g }(),
|
||||
"a rollback": func() Grant { g := good; g.Kind = "rollback:1"; return g }(),
|
||||
}
|
||||
for name, answer := range cases {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(answer)
|
||||
}))
|
||||
_, err := RequestGrant(context.Background(), client(), srv.URL, "api", "i", digest, 0)
|
||||
srv.Close()
|
||||
if err == nil {
|
||||
t.Fatalf("%s: accepted as a grant", name)
|
||||
}
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/db-instances/i/execution-grant" || r.Header.Get("Authorization") != "Bearer api" {
|
||||
t.Errorf("unexpected request %s %s", r.URL.Path, r.Header.Get("Authorization"))
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(good)
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, err := RequestGrant(context.Background(), client(), srv.URL, "api", "i", digest, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchGrantedRefusesAChangelogWithAnotherHash(t *testing.T) {
|
||||
changelog := "--liquibase formatted sql\nCREATE TABLE t (id int);\n"
|
||||
for name, served := range map[string]string{"same": changelog, "tampered": changelog + "DROP TABLE t;\n"} {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("X-Execution-Token") != "tok" || r.URL.Query().Get("jti") != "j1" {
|
||||
t.Errorf("the grant was not presented: %v", r.URL.Query())
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(Granted{Changelog: served})
|
||||
}))
|
||||
_, err := FetchGranted(context.Background(), client(), srv.URL, "api",
|
||||
Grant{InstanceID: "i", Digest: "d", ChangelogSHA256: sum(changelog), JTI: "j1", Token: "tok"})
|
||||
srv.Close()
|
||||
if (err == nil) != (name == "same") {
|
||||
t.Fatalf("%s: err=%v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportSendsEverySignedField(t *testing.T) {
|
||||
var got ExecutionResult
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewDecoder(r.Body).Decode(&got)
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}))
|
||||
defer srv.Close()
|
||||
g := Grant{InstanceID: "i", Digest: "d", ChangelogSHA256: "c", Stage: "prod", Ruleset: "r", JTI: "j", Exp: 9, Kind: "rollback:2", Token: "t"}
|
||||
if err := Report(context.Background(), client(), srv.URL, "api", g, "applied", "ref", "ok"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Stage != "prod" || got.Ruleset != "r" || got.JTI != "j" || got.Exp != 9 || got.Outcome != "applied" || got.Kind != "rollback:2" {
|
||||
t.Fatalf("report = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A rollback asks for a rollback grant of exactly that many changesets, and
|
||||
// refuses an apply grant (or a rollback of another count) handed back instead:
|
||||
// the executor must not run a batch it was not told to run.
|
||||
func TestRequestGrantForARollbackNamesTheKindAndCount(t *testing.T) {
|
||||
digest := strings.Repeat("d", 64)
|
||||
for _, answered := range []string{"rollback:2", "rollback:3", "apply"} {
|
||||
var asked map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewDecoder(r.Body).Decode(&asked)
|
||||
_ = json.NewEncoder(w).Encode(Grant{InstanceID: "i", Digest: digest, ChangelogSHA256: strings.Repeat("c", 64), JTI: "j", Kind: answered, Token: "t"})
|
||||
}))
|
||||
_, err := RequestGrant(context.Background(), client(), srv.URL, "api", "i", digest, 2)
|
||||
srv.Close()
|
||||
if asked["kind"] != "rollback" || asked["count"] != float64(2) {
|
||||
t.Fatalf("request = %v", asked)
|
||||
}
|
||||
if (err == nil) != (answered == "rollback:2") {
|
||||
t.Fatalf("answered %s: err=%v", answered, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchGrantedPresentsTheKind(t *testing.T) {
|
||||
changelog := "--liquibase formatted sql\n"
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("kind") != "rollback:1" {
|
||||
t.Errorf("kind not presented: %v", r.URL.Query())
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(Granted{Changelog: changelog})
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, err := FetchGranted(context.Background(), client(), srv.URL, "api",
|
||||
Grant{InstanceID: "i", Digest: "d", ChangelogSHA256: sum(changelog), JTI: "j", Kind: "rollback:1", Token: "t"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// The file name is the one the platform applies the schema under (Liquibase
|
||||
// keys a changeset on it), and never a path.
|
||||
func TestGrantedFileNameIsOneSafeSegment(t *testing.T) {
|
||||
for name, ok := range map[string]bool{
|
||||
"schema-0b7c2f9e-3a1d-4c55-9d7e-2f1a6b8c9d0e": true,
|
||||
"": false,
|
||||
"../etc/passwd": false,
|
||||
"a/b": false,
|
||||
"schema..x": false,
|
||||
"-flag": false,
|
||||
"name with space": false,
|
||||
} {
|
||||
file, err := (&Granted{ChangelogName: name}).FileName()
|
||||
if (err == nil) != ok {
|
||||
t.Fatalf("%q: err=%v", name, err)
|
||||
}
|
||||
if ok && file != name+".sql" {
|
||||
t.Fatalf("%q -> %q", name, file)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriftedReadsTheDiffSections(t *testing.T) {
|
||||
clean := "Diff Results:\nMissing Column(s): NONE\nUnexpected Table(s): NONE\nChanged Index(s): NONE\n"
|
||||
if Drifted(clean) {
|
||||
t.Fatal("a diff with nothing in any section is not drift")
|
||||
}
|
||||
if !Drifted("Diff Results:\nMissing Column(s): \n public.users.email\nUnexpected Table(s): NONE\n") {
|
||||
t.Fatal("a missing column is drift")
|
||||
}
|
||||
if !Drifted("Unexpected Table(s): scratch") {
|
||||
t.Fatal("an unexpected table is drift")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportDriftPostsUnderItsGrant(t *testing.T) {
|
||||
var got map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/api/v1/db-instances/i/drift-report" || r.Header.Get("Authorization") != "Bearer api" {
|
||||
t.Errorf("unexpected request %s", r.URL.Path)
|
||||
}
|
||||
if r.Header.Get("X-Execution-Token") != "tok" {
|
||||
t.Errorf("the drift report was sent without its grant's token")
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&got)
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}))
|
||||
defer srv.Close()
|
||||
g := Grant{InstanceID: "i", Digest: strings.Repeat("a", 64), ChangelogSHA256: strings.Repeat("b", 64), Stage: "prod", Ruleset: "r", JTI: "abc123def456", Exp: 9, Kind: "drift", Token: "tok"}
|
||||
if err := ReportDrift(context.Background(), client(), srv.URL, "api", g, DriftReport{Drifted: true, Diff: strings.Repeat("x", 9000), ExecutionRef: "ci-1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got["drifted"] != true || got["execution_ref"] != "ci-1" || len(got["diff"].(string)) != 8000 {
|
||||
t.Fatalf("report = %+v", got)
|
||||
}
|
||||
if got["jti"] != "abc123def456" || got["kind"] != "drift" || got["digest"] != g.Digest {
|
||||
t.Fatalf("the report does not repeat its grant's signed fields: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnObservationGrantIsDriftOrSnapshotAndIsChecked(t *testing.T) {
|
||||
if _, err := RequestObservationGrant(context.Background(), client(), "http://x", "api", "i", "apply"); err == nil {
|
||||
t.Fatal("an apply grant was asked for as an observation")
|
||||
}
|
||||
answer := `{"instance_id":"i","digest":"` + strings.Repeat("a", 64) + `","changelog_sha256":"` + strings.Repeat("b", 64) + `","stage":"prod","ruleset":"r","jti":"j1","exp":9,"kind":"%s","token":"t"}`
|
||||
for _, tc := range []struct {
|
||||
kind, answered string
|
||||
ok bool
|
||||
}{{"drift", "drift", true}, {"drift", "snapshot", false}, {"snapshot", "snapshot", true}} {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body["kind"] != tc.kind || body["digest"] != nil {
|
||||
t.Errorf("request = %+v", body)
|
||||
}
|
||||
_, _ = w.Write([]byte(strings.Replace(answer, "%s", tc.answered, 1)))
|
||||
}))
|
||||
_, err := RequestObservationGrant(context.Background(), client(), srv.URL, "api", "i", tc.kind)
|
||||
srv.Close()
|
||||
if (err == nil) != tc.ok {
|
||||
t.Errorf("%s answered as %s: err = %v", tc.kind, tc.answered, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestASnapshotIsReportedAsItsHashUnderItsGrant(t *testing.T) {
|
||||
var path, token string
|
||||
var got map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path, token = r.URL.Path, r.Header.Get("X-Execution-Token")
|
||||
_ = json.NewDecoder(r.Body).Decode(&got)
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}))
|
||||
defer srv.Close()
|
||||
g := Grant{InstanceID: "i", Kind: "snapshot", Token: "tok"}
|
||||
big := strings.Repeat("x", 3_000_000)
|
||||
if err := ReportSnapshot(context.Background(), client(), srv.URL, "api", g, "taken", big, "ci", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if path != "/api/v1/db-executions/i/snapshot" || token != "tok" {
|
||||
t.Fatalf("path %q token %q", path, token)
|
||||
}
|
||||
sum := sha256.Sum256([]byte(big))
|
||||
if got["snapshot_sha256"] != hex.EncodeToString(sum[:]) || got["snapshot_bytes"] != float64(len(big)) {
|
||||
t.Fatalf("report = %v", got["snapshot_bytes"])
|
||||
}
|
||||
if _, sent := got["snapshot"]; sent {
|
||||
t.Fatal("the snapshot JSON itself was sent")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAReleaseIsAServiceAndAVersionTogether(t *testing.T) {
|
||||
if _, _, err := Release("svc", ""); err == nil {
|
||||
t.Error("a service without a version was accepted")
|
||||
}
|
||||
if _, _, err := Release("", "abc123"); err == nil {
|
||||
t.Error("a version without a service was accepted")
|
||||
}
|
||||
s, v, err := Release("", "")
|
||||
if err != nil || s != nil || v != nil {
|
||||
t.Errorf("no release: got %v %v %v", s, v, err)
|
||||
}
|
||||
s, v, err = Release("svc", "abc123")
|
||||
if err != nil || *s != "svc" || *v != "abc123" {
|
||||
t.Errorf("a release: got %v %v %v", s, v, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The request names the release only when there is one, so a lint that names
|
||||
// none sends exactly what it sent before.
|
||||
func TestTheRequestCarriesTheReleaseOnlyWhenNamed(t *testing.T) {
|
||||
var seen []map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var got map[string]any
|
||||
_ = json.Unmarshal(body, &got)
|
||||
seen = append(seen, got)
|
||||
_, _ = w.Write([]byte(`{"decision":"allow","reasons":[],"violations":[]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
client := &http.Client{Timeout: 5 * time.Second}
|
||||
service, version, file := "svc", "abc123", "V1.sql"
|
||||
for _, req := range []Request{
|
||||
{SQL: "SELECT 1", Dialect: "postgres"},
|
||||
{SQL: "SELECT 1", Dialect: "postgres", ServiceID: &service, Version: &version, File: &file},
|
||||
} {
|
||||
if _, err := Analyze(context.Background(), client, srv.URL, "t", req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"service_id", "version", "file"} {
|
||||
if _, ok := seen[0][key]; ok {
|
||||
t.Errorf("a lint naming no release sent %q", key)
|
||||
}
|
||||
}
|
||||
if seen[1]["service_id"] != "svc" || seen[1]["version"] != "abc123" || seen[1]["file"] != "V1.sql" {
|
||||
t.Errorf("the release was not sent: %v", seen[1])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MigrationTools are the values --tool takes. The CI presets offer the same
|
||||
// set (ci_presets.DB_MIGRATION_TOOLS; a test in apps/api compares the two).
|
||||
var MigrationTools = map[string]bool{"liquibase": true, "flyway": true, "atlas": true, "none": true}
|
||||
|
||||
// CheckTool refuses a tool the module does not run, before anything runs.
|
||||
// Until 2026-09-27 any other value — a typo such as "liquibse" — fell through
|
||||
// to atlas and applied the directory with a tool nobody chose.
|
||||
//
|
||||
// It also refuses atlas for anything but PostgreSQL and MySQL: the module runs
|
||||
// the Atlas Community Edition, which migrates those two
|
||||
// (https://atlasgo.io/community-edition); SQL Server and Oracle keep their own
|
||||
// message, as they are the ones asked for most.
|
||||
func CheckTool(tool, dialect string) error {
|
||||
if !MigrationTools[tool] {
|
||||
return fmt.Errorf("--tool=%q is not one of liquibase, flyway, atlas, none", tool)
|
||||
}
|
||||
if tool == "atlas" && (dialect == "tsql" || dialect == "oracle") {
|
||||
return fmt.Errorf("atlas community edition does not support dialect %q (SQL Server and Oracle are in its proprietary build only); use liquibase", dialect)
|
||||
}
|
||||
if tool == "atlas" && !atlasDialects[dialect] {
|
||||
return fmt.Errorf("atlas community edition does not support %q; use liquibase or flyway", dialect)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// atlasDialects are what the Atlas Community Edition migrates.
|
||||
var atlasDialects = map[string]bool{"postgres": true, "mysql": true}
|
||||
|
||||
// DefaultDialect is what a local tool (atlas's dev database) runs when
|
||||
// neither --engine nor --dialect names one. --dialect itself has no default:
|
||||
// unset, it is not sent, and the platform judges the SQL in the engines of the
|
||||
// service's own databases (with --service-id) — a default "postgres" sent on
|
||||
// every call made that impossible.
|
||||
const DefaultDialect = "postgres"
|
||||
|
||||
// Target is what the platform is asked to judge the SQL as: the database
|
||||
// ENGINE when one is named — the platform then judges it in that engine's own
|
||||
// dialect, and one it has no rules for (MongoDB, Snowflake, ...) comes back
|
||||
// unjudged, needing an approver (GET /db-engines) — otherwise the SQL
|
||||
// dialect. Never both: the endpoint refuses a request naming both.
|
||||
type Target struct {
|
||||
Engine string
|
||||
Dialect string
|
||||
}
|
||||
|
||||
// ResolveTarget reads --engine and --dialect. Naming both is refused rather
|
||||
// than one of the two silently ignored.
|
||||
func ResolveTarget(engine, dialect string) (Target, error) {
|
||||
engine = strings.ToLower(strings.TrimSpace(engine))
|
||||
dialect = strings.TrimSpace(dialect)
|
||||
if engine == "" {
|
||||
return Target{Dialect: dialect}, nil
|
||||
}
|
||||
if dialect != "" {
|
||||
return Target{}, fmt.Errorf("give --engine or --dialect, not both (--engine=%q, --dialect=%q)", engine, dialect)
|
||||
}
|
||||
return Target{Engine: engine}, nil
|
||||
}
|
||||
|
||||
// ToolDialect is the dialect a migration TOOL works in on this runner (atlas
|
||||
// replays the files on a dev database of it). Only atlas reads it, and atlas
|
||||
// knows PostgreSQL and MySQL; any other engine is returned as it is, which
|
||||
// CheckTool refuses for atlas.
|
||||
func (t Target) ToolDialect() string {
|
||||
switch t.Engine {
|
||||
case "":
|
||||
if t.Dialect == "" {
|
||||
return DefaultDialect
|
||||
}
|
||||
return t.Dialect
|
||||
case "postgres", "postgresql":
|
||||
return "postgres"
|
||||
case "mysql", "mariadb":
|
||||
return "mysql"
|
||||
}
|
||||
return t.Engine
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package verdict
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCheckTool(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
tool, dialect string
|
||||
ok bool
|
||||
}{
|
||||
{"liquibase", "postgres", true},
|
||||
{"liquibase", "tsql", true},
|
||||
{"liquibase", "oracle", true},
|
||||
{"flyway", "mysql", true},
|
||||
{"atlas", "postgres", true},
|
||||
{"atlas", "mysql", true},
|
||||
{"none", "tsql", true},
|
||||
// A typo must fail, not fall through to some other tool.
|
||||
{"liquibse", "postgres", false},
|
||||
{"", "postgres", false},
|
||||
{"sqitch", "postgres", false},
|
||||
{"Liquibase", "postgres", false},
|
||||
// Atlas Community has no SQL Server or Oracle driver.
|
||||
{"atlas", "tsql", false},
|
||||
{"atlas", "oracle", false},
|
||||
} {
|
||||
err := CheckTool(c.tool, c.dialect)
|
||||
if (err == nil) != c.ok {
|
||||
t.Errorf("CheckTool(%q, %q) = %v, want ok=%v", c.tool, c.dialect, err, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --engine names what the platform judges the SQL as; with it, --dialect keeps
|
||||
// its default and is not sent (the endpoint refuses a request naming both).
|
||||
func TestResolveTarget(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
engine, dialect string
|
||||
want Target
|
||||
ok bool
|
||||
}{
|
||||
{"", "mysql", Target{Dialect: "mysql"}, true},
|
||||
{"", "", Target{}, true}, // neither: nothing sent, the platform decides
|
||||
{" SnowFlake ", "", Target{Engine: "snowflake"}, true},
|
||||
{"postgres", "postgres", Target{}, false},
|
||||
{"mongodb", "", Target{Engine: "mongodb"}, true},
|
||||
{"oracle", "tsql", Target{}, false},
|
||||
} {
|
||||
got, err := ResolveTarget(tc.engine, tc.dialect)
|
||||
if (err == nil) != tc.ok || got != tc.want {
|
||||
t.Errorf("ResolveTarget(%q, %q) = %+v, %v", tc.engine, tc.dialect, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAtlasRunsOnlyWhatItsCommunityEditionMigrates(t *testing.T) {
|
||||
for engine, ok := range map[string]bool{
|
||||
"postgres": true, "postgresql": true, "mysql": true, "mariadb": true,
|
||||
"snowflake": false, "mongodb": false, "sqlserver": false, "oracle": false,
|
||||
} {
|
||||
target, err := ResolveTarget(engine, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := CheckTool("atlas", target.ToolDialect()); (err == nil) != ok {
|
||||
t.Errorf("atlas on %s: err = %v", engine, err)
|
||||
}
|
||||
// The other tools bring the driver the tenant gives them.
|
||||
if err := CheckTool("liquibase", target.ToolDialect()); err != nil {
|
||||
t.Errorf("liquibase on %s: %v", engine, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Neither named: atlas's local dev database is PostgreSQL, as before.
|
||||
func TestToolDialectDefaultsToPostgres(t *testing.T) {
|
||||
if got := (Target{}).ToolDialect(); got != DefaultDialect {
|
||||
t.Fatalf("ToolDialect() = %q", got)
|
||||
}
|
||||
if err := CheckTool("atlas", (Target{}).ToolDialect()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
// Package verdict asks IntegraCI's DB-change engine to judge migration SQL.
|
||||
//
|
||||
// Kept out of package main: the Dagger-generated package panics at init without
|
||||
// a Dagger session, so tests in main cannot run under a plain `go test`.
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AnalyzePath is IntegraCI's DB-change policy endpoint: the DBV engine
|
||||
// (libs/dbv-policy) behind the tenant's own policy. The lint used to grep the
|
||||
// migration TOOL's output for keywords instead — liquibase/flyway `validate`
|
||||
// output carries no SQL, so it never found anything, and `|| true` made the
|
||||
// tool unable to fail the step at all.
|
||||
//
|
||||
// apps/api/tests/test_dagger_db_migration_lint_contract.py reads this constant
|
||||
// and the request field names below and checks the API really serves them.
|
||||
const AnalyzePath = "/api/v1/db-changes/analyze"
|
||||
|
||||
// MaxSQLBytes mirrors the endpoint's `sql` max_length (DbChangeAnalyzeRequest).
|
||||
const MaxSQLBytes = 200_000
|
||||
|
||||
// Request is the body of POST AnalyzePath.
|
||||
type Request struct {
|
||||
SQL string `json:"sql"`
|
||||
// Exactly one of the two (Target): the endpoint refuses both.
|
||||
Dialect string `json:"dialect,omitempty"`
|
||||
Engine string `json:"engine,omitempty"`
|
||||
EnvironmentID *string `json:"environment_id,omitempty"`
|
||||
// The release this file belongs to. With both set, the platform records
|
||||
// the verdict IT computed for (service, version), which its deploy gate
|
||||
// reads (DbChangePolicy.release_verdict).
|
||||
ServiceID *string `json:"service_id,omitempty"`
|
||||
Version *string `json:"version,omitempty"`
|
||||
File *string `json:"file,omitempty"`
|
||||
}
|
||||
|
||||
// Release names the release a lint judges: both or neither.
|
||||
func Release(serviceID, version string) (*string, *string, error) {
|
||||
if (serviceID == "") != (version == "") {
|
||||
return nil, nil, fmt.Errorf("--service-id and --version name a release together: give both or neither")
|
||||
}
|
||||
if serviceID == "" {
|
||||
return nil, nil, nil
|
||||
}
|
||||
return &serviceID, &version, nil
|
||||
}
|
||||
|
||||
// Violation is one finding of the engine, as the endpoint reports it.
|
||||
type Violation struct {
|
||||
RuleID string `json:"rule_id"`
|
||||
Severity string `json:"severity"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// Response is the part of the endpoint's verdict the lint reads.
|
||||
type Response struct {
|
||||
Decision string `json:"decision"`
|
||||
Reasons []string `json:"reasons"`
|
||||
DestructiveCount int `json:"destructive_count"`
|
||||
SecurityCount int `json:"security_count"`
|
||||
Violations []Violation `json:"violations"`
|
||||
RulesetVersion string `json:"ruleset_version"`
|
||||
}
|
||||
|
||||
// FileVerdict is the engine's verdict on one migration file.
|
||||
type FileVerdict struct {
|
||||
File string `json:"file"`
|
||||
Decision string `json:"decision"`
|
||||
Reasons []string `json:"reasons"`
|
||||
Rules []string `json:"rules"`
|
||||
RulesetVersion string `json:"ruleset_version"`
|
||||
}
|
||||
|
||||
// NewClient is the HTTP client the lint asks IntegraCI with. It follows no
|
||||
// redirect: Go keeps the Authorization header on a same-host redirect, even
|
||||
// one from https to http, and a 3xx is not a verdict anyway.
|
||||
func NewClient() *http.Client {
|
||||
return &http.Client{
|
||||
Timeout: 60 * time.Second,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Analyze asks IntegraCI to judge one script. Any answer that is not a
|
||||
// verdict — transport error, non-2xx, unreadable body, empty decision — is an
|
||||
// error: the lint cannot pass what nobody judged.
|
||||
func Analyze(ctx context.Context, client *http.Client, apiURL, token string, req Request) (*Response, error) {
|
||||
body, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
url := strings.TrimRight(apiURL, "/") + AnalyzePath
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err := client.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("POST %s: %w", AnalyzePath, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("POST %s: reading the answer: %w", AnalyzePath, err)
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
snippet := string(raw)
|
||||
if len(snippet) > 300 {
|
||||
snippet = snippet[:300]
|
||||
}
|
||||
hint := ""
|
||||
if resp.StatusCode == http.StatusUnprocessableEntity && req.Engine != "" {
|
||||
hint = " (a platform older than engine support refuses --engine; use --dialect until it is upgraded)"
|
||||
}
|
||||
return nil, fmt.Errorf("POST %s: HTTP %d: %s%s", AnalyzePath, resp.StatusCode, snippet, hint)
|
||||
}
|
||||
var out Response
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, fmt.Errorf("POST %s: not a verdict: %w", AnalyzePath, err)
|
||||
}
|
||||
if out.Decision == "" {
|
||||
return nil, fmt.Errorf("POST %s: the answer carries no decision", AnalyzePath)
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// Fails reports whether a decision fails the lint. `blocked` always does,
|
||||
// whatever `block` says; `requires_approval` does too while blocking is on,
|
||||
// because nobody can approve inside a CI step — the change goes through
|
||||
// IntegraCI's apply, where the approval is decided.
|
||||
func Fails(decision string, block bool) bool {
|
||||
switch decision {
|
||||
case "allow", "warn":
|
||||
return false
|
||||
case "requires_approval":
|
||||
return block
|
||||
default: // blocked, and any decision this module does not know
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// HasPlaceholder reports whether a script holds a `${…}` placeholder. Flyway
|
||||
// (by default, with built-ins such as `${flyway:filename}`) and Liquibase
|
||||
// substitute these AFTER the engine has judged the text and BEFORE they split
|
||||
// statements, so the SQL that runs is not the SQL that was judged: a file named
|
||||
// `V9__x');DROP TABLE users;--.sql` holding `SELECT ('${flyway:filename}');`
|
||||
// is one harmless literal to the engine and a DROP to flyway. A script with a
|
||||
// placeholder cannot be judged, so it is refused.
|
||||
func HasPlaceholder(sql string) bool {
|
||||
return strings.Contains(sql, "${")
|
||||
}
|
||||
|
||||
// Judgeable refuses a script the engine cannot be trusted to have judged: one
|
||||
// over the endpoint's size limit, or one with a placeholder the tool would
|
||||
// substitute afterwards.
|
||||
func Judgeable(file, sql string) error {
|
||||
if len(sql) > MaxSQLBytes {
|
||||
return fmt.Errorf("%s is %d bytes; the DB-change engine takes at most %d — split it", file, len(sql), MaxSQLBytes)
|
||||
}
|
||||
if HasPlaceholder(sql) {
|
||||
return fmt.Errorf("%s holds a ${…} placeholder: the tool substitutes it after the engine has judged the text, "+
|
||||
"so the SQL that would run is not the SQL judged — write the value out", file)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Refused lists the verdicts that fail the lint. Judging nothing is itself a
|
||||
// refusal: a directory with no SQL passed a lint that read nothing.
|
||||
func Refused(verdicts []FileVerdict, block bool) ([]string, error) {
|
||||
if len(verdicts) == 0 {
|
||||
return nil, fmt.Errorf("no migration was judged: the directory holds no SQL " +
|
||||
"(point --dir at the migrations, or use --tool=none to opt out of governance)")
|
||||
}
|
||||
refused := []string{}
|
||||
for _, v := range verdicts {
|
||||
if Fails(v.Decision, block) {
|
||||
refused = append(refused, fmt.Sprintf("%s: %s (%s)", v.File, v.Decision, strings.Join(v.Rules, ", ")))
|
||||
}
|
||||
}
|
||||
return refused, nil
|
||||
}
|
||||
|
||||
// notMigrations are the only non-SQL files a migrations directory may hold.
|
||||
// Anything else is a file some tool may run that the engine cannot read — an
|
||||
// XML/YAML/JSON changelog, a flyway `.pgsql` suffix set in the repo's config,
|
||||
// a Java migration — so a lint that skipped it would pass what it never judged.
|
||||
var (
|
||||
notMigrationExtensions = map[string]bool{".md": true, ".txt": true, ".rst": true}
|
||||
notMigrationNames = map[string]bool{".gitkeep": true, ".keep": true, "atlas.sum": true, "readme": true, "license": true}
|
||||
)
|
||||
|
||||
// SplitMigrations sorts a directory listing into the SQL the engine judges
|
||||
// and the files it cannot, which fail the step.
|
||||
func SplitMigrations(entries []string) (sqlFiles, unanalysable []string) {
|
||||
for _, e := range entries {
|
||||
if strings.HasSuffix(e, "/") {
|
||||
continue
|
||||
}
|
||||
base := strings.ToLower(path.Base(e))
|
||||
ext := path.Ext(base)
|
||||
switch {
|
||||
case ext == ".sql":
|
||||
sqlFiles = append(sqlFiles, e)
|
||||
case notMigrationExtensions[ext] || notMigrationNames[base]:
|
||||
default:
|
||||
unanalysable = append(unanalysable, e)
|
||||
}
|
||||
}
|
||||
sort.Slice(sqlFiles, func(i, j int) bool { return naturalLess(sqlFiles[i], sqlFiles[j]) })
|
||||
sort.Strings(unanalysable)
|
||||
return sqlFiles, unanalysable
|
||||
}
|
||||
|
||||
// naturalLess orders names with their digit runs compared as numbers, so
|
||||
// `V2.sql` comes before `V10.sql`: Liquibase applies the judged files one by
|
||||
// one in this order, and a lexical sort would run V10 first.
|
||||
func naturalLess(a, b string) bool {
|
||||
for a != "" && b != "" {
|
||||
da, db := digitPrefix(a), digitPrefix(b)
|
||||
if da != "" && db != "" {
|
||||
na, nb := strings.TrimLeft(da, "0"), strings.TrimLeft(db, "0")
|
||||
if len(na) != len(nb) {
|
||||
return len(na) < len(nb)
|
||||
}
|
||||
if na != nb {
|
||||
return na < nb
|
||||
}
|
||||
a, b = a[len(da):], b[len(db):]
|
||||
continue
|
||||
}
|
||||
if a[0] != b[0] {
|
||||
return a[0] < b[0]
|
||||
}
|
||||
a, b = a[1:], b[1:]
|
||||
}
|
||||
return len(a) < len(b)
|
||||
}
|
||||
|
||||
func digitPrefix(s string) string {
|
||||
i := 0
|
||||
for i < len(s) && s[i] >= '0' && s[i] <= '9' {
|
||||
i++
|
||||
}
|
||||
return s[:i]
|
||||
}
|
||||
|
||||
// Of condenses one answer for the report.
|
||||
func Of(file string, resp *Response) FileVerdict {
|
||||
rules := []string{}
|
||||
for _, v := range resp.Violations {
|
||||
if v.Severity != "info" {
|
||||
rules = append(rules, v.RuleID)
|
||||
}
|
||||
}
|
||||
return FileVerdict{
|
||||
File: file,
|
||||
Decision: resp.Decision,
|
||||
Reasons: resp.Reasons,
|
||||
Rules: rules,
|
||||
RulesetVersion: resp.RulesetVersion,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package verdict
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestAnalyzeSQLPostsTheScriptToTheEngineEndpoint(t *testing.T) {
|
||||
var got Request
|
||||
var path, auth string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path, auth = r.URL.Path, r.Header.Get("Authorization")
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(body, &got)
|
||||
_, _ = w.Write([]byte(`{"decision":"blocked","reasons":["1 destructive statement(s) → block"],` +
|
||||
`"destructive_count":1,"security_count":0,"ruleset_version":"2026.09.1",` +
|
||||
`"violations":[{"rule_id":"DBV-011","severity":"block","message":"UPDATE without WHERE"},` +
|
||||
`{"rule_id":"DBV-035","severity":"info","message":"no lock_timeout"}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
env := "env-1"
|
||||
resp, err := Analyze(context.Background(), srv.Client(), srv.URL+"/", "tok",
|
||||
Request{SQL: "UPDATE users SET admin = true;", Dialect: "postgres", EnvironmentID: &env})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if path != AnalyzePath || auth != "Bearer tok" {
|
||||
t.Fatalf("path=%q auth=%q", path, auth)
|
||||
}
|
||||
if got.SQL != "UPDATE users SET admin = true;" || got.Dialect != "postgres" || got.EnvironmentID == nil || *got.EnvironmentID != "env-1" {
|
||||
t.Fatalf("request body = %+v", got)
|
||||
}
|
||||
v := Of("V1__x.sql", resp)
|
||||
if v.Decision != "blocked" || strings.Join(v.Rules, ",") != "DBV-011" {
|
||||
t.Fatalf("verdict = %+v (info findings are not rules that failed it)", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnythingButAVerdictIsAnError(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
"forbidden": {http.StatusForbidden, `{"detail":"nope"}`},
|
||||
"server": {http.StatusBadGateway, `<html>bad gateway</html>`},
|
||||
"not json": {http.StatusOK, `<html>proxy login</html>`},
|
||||
"no decision": {http.StatusOK, `{"reasons":[]}`},
|
||||
// A verdict-shaped body on an error status (an intermediary replaying a
|
||||
// cached answer, say) is still not this request's verdict.
|
||||
"error status": {http.StatusServiceUnavailable, `{"decision":"allow"}`},
|
||||
}
|
||||
for name, c := range cases {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
_, _ = w.Write([]byte(c.body))
|
||||
}))
|
||||
_, err := Analyze(context.Background(), &http.Client{Timeout: 5 * time.Second}, srv.URL, "t", Request{SQL: "SELECT 1"})
|
||||
srv.Close()
|
||||
if err == nil {
|
||||
t.Fatalf("%s: an answer that is not a verdict must not pass", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhichDecisionsFailTheLint(t *testing.T) {
|
||||
cases := []struct {
|
||||
decision string
|
||||
block bool
|
||||
want bool
|
||||
}{
|
||||
{"allow", true, false},
|
||||
{"warn", true, false},
|
||||
{"requires_approval", true, true},
|
||||
{"requires_approval", false, false},
|
||||
{"blocked", true, true},
|
||||
{"blocked", false, true},
|
||||
{"something-new", true, true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := Fails(c.decision, c.block); got != c.want {
|
||||
t.Fatalf("Fails(%q, %v) = %v, want %v", c.decision, c.block, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangelogsTheEngineCannotReadAreNotSkippedQuietly(t *testing.T) {
|
||||
sqlFiles, unanalysable := SplitMigrations([]string{
|
||||
"V2__b.sql", "V1__a.SQL", "sub/", "sub/V3__c.sql", "db.changelog-master.xml",
|
||||
"changes.yaml", "README.md", "notes.txt", "atlas.sum", ".gitkeep",
|
||||
// A tool may run these (a flyway suffix set in the repo's config, a
|
||||
// Java migration); the engine cannot read them.
|
||||
"V4__drop.pgsql", "V5__Seed.java", "V6__x.sql.xml",
|
||||
})
|
||||
if strings.Join(sqlFiles, ",") != "V1__a.SQL,V2__b.sql,sub/V3__c.sql" {
|
||||
t.Fatalf("sql files = %v", sqlFiles)
|
||||
}
|
||||
if strings.Join(unanalysable, ",") != "V4__drop.pgsql,V5__Seed.java,V6__x.sql.xml,changes.yaml,db.changelog-master.xml" {
|
||||
t.Fatalf("unanalysable = %v", unanalysable)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefusedFollowsTheDecisionsAndRefusesAnEmptyJudgement(t *testing.T) {
|
||||
vs := []FileVerdict{
|
||||
{File: "V1.sql", Decision: "allow"},
|
||||
{File: "V2.sql", Decision: "requires_approval", Rules: []string{"DBV-030"}},
|
||||
{File: "V3.sql", Decision: "blocked", Rules: []string{"DBV-010"}},
|
||||
}
|
||||
got, err := Refused(vs, true)
|
||||
if err != nil || len(got) != 2 {
|
||||
t.Fatalf("block=true: %v %v", got, err)
|
||||
}
|
||||
// Turning blocking off only lets requires_approval through: `blocked` is
|
||||
// the tenant's policy, not the pipeline's to waive.
|
||||
got, err = Refused(vs, false)
|
||||
if err != nil || len(got) != 1 || !strings.HasPrefix(got[0], "V3.sql: blocked") {
|
||||
t.Fatalf("block=false: %v %v", got, err)
|
||||
}
|
||||
if _, err := Refused(nil, true); err == nil {
|
||||
t.Fatal("a lint that judged nothing must not pass")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheClientFollowsNoRedirect(t *testing.T) {
|
||||
hops := 0
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
hops++
|
||||
_, _ = w.Write([]byte(`{"decision":"allow"}`))
|
||||
}))
|
||||
defer target.Close()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, target.URL+AnalyzePath, http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, err := Analyze(context.Background(), NewClient(), srv.URL, "t", Request{SQL: "SELECT 1"}); err == nil {
|
||||
t.Fatal("a redirect is not a verdict")
|
||||
}
|
||||
if hops != 0 {
|
||||
t.Fatal("the token followed a redirect")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPlaceholderMakesAScriptUnjudgeable(t *testing.T) {
|
||||
if !HasPlaceholder("SELECT ('${flyway:filename}');") {
|
||||
t.Fatal("flyway placeholder not seen")
|
||||
}
|
||||
if !HasPlaceholder("CREATE TABLE ${schema}.t (id int);") {
|
||||
t.Fatal("liquibase property not seen")
|
||||
}
|
||||
if HasPlaceholder("SELECT '$1', $$body$$;") {
|
||||
t.Fatal("dollar quoting is not a placeholder")
|
||||
}
|
||||
if Judgeable("V9.sql", "SELECT ('${flyway:filename}');") == nil {
|
||||
t.Fatal("a script with a placeholder was judgeable")
|
||||
}
|
||||
if Judgeable("V1.sql", strings.Repeat("x", MaxSQLBytes+1)) == nil {
|
||||
t.Fatal("an oversized script was judgeable")
|
||||
}
|
||||
if err := Judgeable("V1.sql", "CREATE TABLE t (id int);"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationsAreOrderedByTheirNumbers(t *testing.T) {
|
||||
sqlFiles, _ := SplitMigrations([]string{"V10__c.sql", "V2__b.sql", "V1__a.sql", "V010__d.sql"})
|
||||
if got := strings.Join(sqlFiles, ","); got != "V1__a.sql,V2__b.sql,V10__c.sql,V010__d.sql" {
|
||||
t.Fatalf("order = %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestARequestNamesTheEngineOrTheDialectNeverBoth(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
target Target
|
||||
want string
|
||||
}{
|
||||
{Target{Engine: "snowflake"}, `{"sql":"x","engine":"snowflake"}`},
|
||||
{Target{Dialect: "mysql"}, `{"sql":"x","dialect":"mysql"}`},
|
||||
// Neither: the platform picks (the service's engines, or PostgreSQL).
|
||||
{Target{}, `{"sql":"x"}`},
|
||||
} {
|
||||
body, err := json.Marshal(Request{SQL: "x", Dialect: tc.target.Dialect, Engine: tc.target.Engine})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body) != tc.want {
|
||||
t.Errorf("%+v -> %s", tc.target, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A platform without engine support answers --engine with a 422; the step
|
||||
// says why instead of only relaying the body.
|
||||
func TestAn422ForAnEngineSaysThePlatformIsOlder(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
_, _ = w.Write([]byte(`{"detail":"extra fields not permitted"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
for engine, hinted := range map[string]bool{"snowflake": true, "": false} {
|
||||
_, err := Analyze(context.Background(), NewClient(), srv.URL, "t", Request{SQL: "x", Engine: engine, Dialect: "postgres"})
|
||||
if err == nil || strings.Contains(err.Error(), "older than engine support") != hinted {
|
||||
t.Errorf("engine %q: err = %v", engine, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
# IntegraCI — Deploy K8s Dagger Module
|
||||
|
||||
Deploy services to Kubernetes via Helm (helm upgrade --install / rollback).
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
dagger call deploy \
|
||||
--chart ./helm/my-service \
|
||||
--values ./values-staging.yaml \
|
||||
--namespace staging
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "deploy-k8s",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
// Package main implements the IntegraCI deploy-k8s Dagger module.
|
||||
//
|
||||
// Deploys services to Kubernetes via Helm + ArgoCD sync.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call deploy --chart ./helm/my-service --values ./values-staging.yaml --namespace staging
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"dagger/deploy-k-8-s/internal/dagger"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// DeployK8s is the IntegraCI Kubernetes deployment module.
|
||||
type DeployK8s struct{}
|
||||
|
||||
// DeployResult contains the output of a deployment.
|
||||
type DeployResult struct {
|
||||
Success bool `json:"success"`
|
||||
Namespace string `json:"namespace"`
|
||||
Release string `json:"release"`
|
||||
Revision string `json:"revision,omitempty"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// Deploy runs Helm upgrade/install to deploy a service.
|
||||
func (m *DeployK8s) Deploy(
|
||||
ctx context.Context,
|
||||
// Helm chart directory
|
||||
chart *dagger.Directory,
|
||||
// Values file
|
||||
// +optional
|
||||
values *dagger.File,
|
||||
// Release name
|
||||
// +optional
|
||||
// +default="app"
|
||||
release string,
|
||||
// Target namespace
|
||||
// +optional
|
||||
// +default="default"
|
||||
namespace string,
|
||||
// Container image to deploy
|
||||
// +optional
|
||||
image string,
|
||||
// Image tag
|
||||
// +optional
|
||||
// +default="latest"
|
||||
tag string,
|
||||
// Dry run mode
|
||||
// +optional
|
||||
dryRun bool,
|
||||
// Kubeconfig file used to authenticate against the cluster
|
||||
// +optional
|
||||
kubeconfig *dagger.Secret,
|
||||
// kube-context to target within the kubeconfig
|
||||
// +optional
|
||||
kubeContext string,
|
||||
) (*DeployResult, error) {
|
||||
helmArgs := []string{
|
||||
"upgrade", "--install", release,
|
||||
"/chart",
|
||||
"--namespace", namespace,
|
||||
"--create-namespace",
|
||||
"--wait",
|
||||
"--timeout", "5m",
|
||||
}
|
||||
|
||||
if image != "" {
|
||||
helmArgs = append(helmArgs, "--set", fmt.Sprintf("image.repository=%s", image))
|
||||
}
|
||||
if tag != "" {
|
||||
helmArgs = append(helmArgs, "--set", fmt.Sprintf("image.tag=%s", tag))
|
||||
}
|
||||
if dryRun {
|
||||
helmArgs = append(helmArgs, "--dry-run")
|
||||
}
|
||||
|
||||
container := dag.Container().
|
||||
From("alpine/helm:3.16").
|
||||
WithDirectory("/chart", chart)
|
||||
|
||||
if values != nil {
|
||||
container = container.WithFile("/values.yaml", values)
|
||||
helmArgs = append(helmArgs, "-f", "/values.yaml")
|
||||
}
|
||||
if kubeconfig != nil {
|
||||
container = container.
|
||||
WithMountedSecret("/kube/config", kubeconfig).
|
||||
WithEnvVariable("KUBECONFIG", "/kube/config")
|
||||
}
|
||||
if kubeContext != "" {
|
||||
helmArgs = append(helmArgs, "--kube-context", kubeContext)
|
||||
}
|
||||
|
||||
out, err := container.WithExec(helmArgs).Stdout(ctx)
|
||||
if err != nil {
|
||||
return &DeployResult{
|
||||
Success: false,
|
||||
Namespace: namespace,
|
||||
Release: release,
|
||||
Message: fmt.Sprintf("Helm deploy failed: %v", err),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &DeployResult{
|
||||
Success: true,
|
||||
Namespace: namespace,
|
||||
Release: release,
|
||||
Message: out,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Rollback performs a Helm rollback to a previous revision.
|
||||
func (m *DeployK8s) Rollback(
|
||||
ctx context.Context,
|
||||
// Release name
|
||||
release string,
|
||||
// Target namespace
|
||||
namespace string,
|
||||
// Revision to rollback to (0 = previous)
|
||||
// +optional
|
||||
// +default=0
|
||||
revision int,
|
||||
// Kubeconfig file used to authenticate against the cluster
|
||||
// +optional
|
||||
kubeconfig *dagger.Secret,
|
||||
// kube-context to target within the kubeconfig
|
||||
// +optional
|
||||
kubeContext string,
|
||||
) (*DeployResult, error) {
|
||||
args := []string{"rollback", release, "--namespace", namespace, "--wait"}
|
||||
if revision > 0 {
|
||||
args = append(args, fmt.Sprintf("%d", revision))
|
||||
}
|
||||
if kubeContext != "" {
|
||||
args = append(args, "--kube-context", kubeContext)
|
||||
}
|
||||
|
||||
container := dag.Container().
|
||||
From("alpine/helm:3.16")
|
||||
|
||||
if kubeconfig != nil {
|
||||
container = container.
|
||||
WithMountedSecret("/kube/config", kubeconfig).
|
||||
WithEnvVariable("KUBECONFIG", "/kube/config")
|
||||
}
|
||||
|
||||
out, err := container.WithExec(args).Stdout(ctx)
|
||||
if err != nil {
|
||||
return &DeployResult{
|
||||
Success: false,
|
||||
Namespace: namespace,
|
||||
Release: release,
|
||||
Message: fmt.Sprintf("Rollback failed: %v", err),
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &DeployResult{
|
||||
Success: true,
|
||||
Namespace: namespace,
|
||||
Release: release,
|
||||
Message: out,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
/dagger.gen.go linguist-generated
|
||||
/internal/dagger/** linguist-generated
|
||||
/internal/telemetry/** linguist-generated
|
||||
@@ -0,0 +1,4 @@
|
||||
/dagger.gen.go
|
||||
/internal/dagger
|
||||
/internal/telemetry
|
||||
/.env
|
||||
@@ -0,0 +1,50 @@
|
||||
# e2e-test (Dagger module)
|
||||
|
||||
> **Verified 2026-07-16**: dagger v0.21.7 `develop` + `go build` + `dagger
|
||||
> functions` pass. Generated code (`dagger.gen.go`, `internal/`) is
|
||||
> gitignored; run `dagger develop` to regenerate.
|
||||
|
||||
Runs web end-to-end tests (Playwright or Cypress) against a target
|
||||
`baseURL`, uploads the report artifact, and POSTs results to the IntegraCI
|
||||
API. Mirrors the structure and idioms of the `security-scan` module.
|
||||
|
||||
## Functions
|
||||
|
||||
### `run`
|
||||
|
||||
| Param | Required | Default | Description |
|
||||
| ------------ | -------- | -------------------- | --------------------------------------------- |
|
||||
| `source` | yes | — | Source directory containing the e2e suite |
|
||||
| `base-url` | yes | — | Base URL the tests run against |
|
||||
| `tool` | no | `playwright` | Test runner: `playwright` or `cypress` |
|
||||
| `report-path`| no | `playwright-report` | Report artifact path inside the source |
|
||||
| `api-url` | no | — | IntegraCI API URL for posting results |
|
||||
| `token` | no | — | JWT token for API authentication |
|
||||
| `service-id` | no | — | Service ID to link test results |
|
||||
|
||||
Results are POSTed to the API only when `api-url`, `token`, and
|
||||
`service-id` are all supplied.
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
# Playwright (default)
|
||||
dagger call run --source . --base-url https://staging.example.com --tool playwright
|
||||
|
||||
# Cypress, with result posting
|
||||
dagger call run \
|
||||
--source . \
|
||||
--base-url https://staging.example.com \
|
||||
--tool cypress \
|
||||
--api-url http://localhost:8000 \
|
||||
--token "$TOKEN" \
|
||||
--service-id "$SVC_ID"
|
||||
```
|
||||
|
||||
## Before you trust this
|
||||
|
||||
```bash
|
||||
dagger develop # generate the Dagger Go SDK bindings
|
||||
dagger functions # confirm `run` is registered with the expected params
|
||||
dagger call run --source . --base-url https://example.com # smoke test
|
||||
```
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "e2e-test",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
module dagger/e-2-e-test
|
||||
|
||||
go 1.26.4
|
||||
|
||||
require (
|
||||
github.com/Khan/genqlient v0.8.1
|
||||
github.com/dagger/otel-go v1.43.0
|
||||
github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59
|
||||
github.com/vektah/gqlparser/v2 v2.5.32
|
||||
go.opentelemetry.io/otel v1.43.0
|
||||
go.opentelemetry.io/otel/trace v1.43.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/99designs/gqlgen v0.17.89 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
||||
github.com/sosodev/duration v1.4.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/log v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.43.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.43.0
|
||||
go.opentelemetry.io/otel/sdk/log v0.17.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // indirect
|
||||
google.golang.org/grpc v1.82.1 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
|
||||
replace go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc => go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp => go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/log => go.opentelemetry.io/otel/log v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/sdk/log => go.opentelemetry.io/otel/sdk/log v0.16.0
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
github.com/99designs/gqlgen v0.17.89 h1:KzEcxPiMgQoMw3m/E85atUEHyZyt0PbAflMia5Kw8z8=
|
||||
github.com/99designs/gqlgen v0.17.89/go.mod h1:GFqruTVGB7ZTdrf1uzOagpXbY7DrEt1pIxnTdhIbWvQ=
|
||||
github.com/Khan/genqlient v0.8.1 h1:wtOCc8N9rNynRLXN3k3CnfzheCUNKBcvXmVv5zt6WCs=
|
||||
github.com/Khan/genqlient v0.8.1/go.mod h1:R2G6DzjBvCbhjsEajfRjbWdVglSH/73kSivC9TLWVjU=
|
||||
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
|
||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/dagger/otel-go v1.43.0 h1:AYCnAamWmxtSxigWPTgC+8EWqiWPcDZEegh8y05gdJ8=
|
||||
github.com/dagger/otel-go v1.43.0/go.mod h1:83CTuXi70zcx1kaym5buqmb7RNzg1E9dEiQSFyLbLdU=
|
||||
github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59 h1:g6vfdGRyz6fAjfHz5FyYPZgHy8qcQ31fHrBl1iCOzxw=
|
||||
github.com/dagger/querybuilder v0.0.0-20260402040506-574a5e81cb59/go.mod h1:jsdUJeYzcbyK1j/EqMGPrQgNYxl/Zfg06vvM9C/xXxs=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
|
||||
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
|
||||
github.com/sosodev/duration v1.4.0 h1:35ed0KiVFriGHHzZZJaZLgmTEEICIyt8Sx0RQfj9IjE=
|
||||
github.com/sosodev/duration v1.4.0/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERAikUR6SDg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/vektah/gqlparser/v2 v2.5.32 h1:k9QPJd4sEDTL+qB4ncPLflqTJ3MmjB9SrVzJrawpFSc=
|
||||
github.com/vektah/gqlparser/v2 v2.5.32/go.mod h1:c1I28gSOVNzlfc4WuDlqU7voQnsqI6OG2amkBAFmgts=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
|
||||
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0 h1:ZVg+kCXxd9LtAaQNKBxAvJ5NpMf7LpvEr4MIZqb0TMQ=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0/go.mod h1:hh0tMeZ75CCXrHd9OXRYxTlCAdxcXioWHFIpYw2rZu8=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0 h1:djrxvDxAe44mJUrKataUbOhCKhR3F8QCyWucO16hTQs=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0/go.mod h1:dt3nxpQEiSoKvfTVxp3TUg5fHPLhKtbcnN3Z1I1ePD0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.41.0 h1:VO3BL6OZXRQ1yQc8W6EVfJzINeJ35BkiHx4MYfoQf44=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.41.0/go.mod h1:qRDnJ2nv3CQXMK2HUd9K9VtvedsPAce3S+/4LZHjX/s=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.41.0 h1:MMrOAN8H1FrvDyq9UJ4lu5/+ss49Qgfgb7Zpm0m8ABo=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.41.0/go.mod h1:Na+2NNASJtF+uT4NxDe0G+NQb+bUgdPDfwxY/6JmS/c=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 h1:ao6Oe+wSebTlQ1OEht7jlYTzQKE+pnx/iNywFvTbuuI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0/go.mod h1:u3T6vz0gh/NVzgDgiwkgLxpsSF6PaPmo2il0apGJbls=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.41.0 h1:mq/Qcf28TWz719lE3/hMB4KkyDuLJIvgJnFGcd0kEUI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.41.0/go.mod h1:yk5LXEYhsL2htyDNJbEq7fWzNEigeEdV5xBF/Y+kAv0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 h1:inYW9ZhgqiDqh6BioM7DVHHzEGVq76Db5897WLGZ5Go=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0/go.mod h1:Izur+Wt8gClgMJqO/cZ8wdeeMryJ/xxiOVgFSSfpDTY=
|
||||
go.opentelemetry.io/otel/log v0.16.0 h1:DeuBPqCi6pQwtCK0pO4fvMB5eBq6sNxEnuTs88pjsN4=
|
||||
go.opentelemetry.io/otel/log v0.16.0/go.mod h1:rWsmqNVTLIA8UnwYVOItjyEZDbKIkMxdQunsIhpUMes=
|
||||
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
|
||||
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
|
||||
go.opentelemetry.io/otel/sdk/log v0.16.0 h1:e/b4bdlQwC5fnGtG3dlXUrNOnP7c8YLVSpSfEBIkTnI=
|
||||
go.opentelemetry.io/otel/sdk/log v0.16.0/go.mod h1:JKfP3T6ycy7QEuv3Hj8oKDy7KItrEkus8XJE6EoSzw4=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.16.0 h1:/XVkpZ41rVRTP4DfMgYv1nEtNmf65XPPyAdqV90TMy4=
|
||||
go.opentelemetry.io/otel/sdk/log/logtest v0.16.0/go.mod h1:iOOPgQr5MY9oac/F5W86mXdeyWZGleIx3uXO98X2R6Y=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 h1:yQugLulqltosq0B/f8l4w9VryjV+N/5gcW0jQ3N8Qec=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478/go.mod h1:C6ADNqOxbgdUUeRTU+LCHDPB9ttAMCTff6auwCVa4uc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 h1:RmoJA1ujG+/lRGNfUnOMfhCy5EipVMyvUE+KNbPbTlw=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=
|
||||
google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE=
|
||||
google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,240 @@
|
||||
// Verified 2026-07-16: dagger v0.21.7 develop + go build + dagger functions
|
||||
// pass. Generated code (dagger.gen.go, internal/) is gitignored; run
|
||||
// 'dagger develop' to regenerate.
|
||||
//
|
||||
// Package main implements the IntegraCI e2e-test Dagger module.
|
||||
//
|
||||
// Runs web end-to-end tests (Playwright or Cypress) against a target
|
||||
// baseURL, uploads the report artifact, and POSTs results to the
|
||||
// IntegraCI API.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call run --source . --base-url https://staging.example.com --tool playwright
|
||||
// dagger call run --source . --base-url https://staging.example.com --tool cypress --api-url http://localhost:8000 --token $TOKEN --service-id $SVC_ID
|
||||
// dagger call run --source . --base-url https://staging.example.com --tool selenium --command "pytest -m e2e"
|
||||
// dagger call run --source . --base-url https://staging.example.com --tool none
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"dagger/e-2-e-test/internal/dagger"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// E2eTest is the IntegraCI web end-to-end testing module.
|
||||
type E2eTest struct{}
|
||||
|
||||
// E2EResult contains the output of an end-to-end test run.
|
||||
type E2EResult struct {
|
||||
Tool string `json:"tool"`
|
||||
BaseURL string `json:"base_url"`
|
||||
ExitCode int `json:"exit_code"`
|
||||
Output string `json:"output"`
|
||||
ReportPath string `json:"report_path,omitempty"`
|
||||
ReportSize int `json:"report_size"`
|
||||
Posted bool `json:"posted"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// Run executes a web end-to-end test suite against baseURL using either
|
||||
// Playwright (default) or Cypress, uploads the report artifact, and
|
||||
// optionally POSTs the results to the IntegraCI API.
|
||||
func (m *E2eTest) Run(
|
||||
ctx context.Context,
|
||||
// Source directory containing the e2e test suite
|
||||
source *dagger.Directory,
|
||||
// Base URL the tests run against
|
||||
baseURL string,
|
||||
// Test runner to use: "playwright" | "cypress" | "selenium" | "none"
|
||||
// +optional
|
||||
// +default="playwright"
|
||||
tool string,
|
||||
// Command to run for the selenium tool (engine-agnostic; no official action)
|
||||
// +optional
|
||||
// +default="pytest -m e2e"
|
||||
command string,
|
||||
// Path inside the source the report artifact is written to
|
||||
// +optional
|
||||
// +default="playwright-report"
|
||||
reportPath string,
|
||||
// IntegraCI API URL for posting results
|
||||
// +optional
|
||||
apiURL string,
|
||||
// JWT token for API authentication
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// Service ID to link test results
|
||||
// +optional
|
||||
serviceID string,
|
||||
) (*E2EResult, error) {
|
||||
result := &E2EResult{
|
||||
Tool: tool,
|
||||
BaseURL: baseURL,
|
||||
ReportPath: reportPath,
|
||||
}
|
||||
|
||||
var (
|
||||
output string
|
||||
report string
|
||||
err error
|
||||
)
|
||||
|
||||
switch strings.ToLower(strings.TrimSpace(tool)) {
|
||||
case "none":
|
||||
// No-op skip, mirroring the adapter's _comment_skip intent.
|
||||
result.Tool = "none"
|
||||
result.Output = "Web E2E disabled (tool=none)"
|
||||
result.Success = true
|
||||
return result, nil
|
||||
case "cypress":
|
||||
output, report, err = m.runCypress(ctx, source, baseURL, reportPath)
|
||||
case "selenium":
|
||||
output, report, err = m.runSelenium(ctx, source, baseURL, command)
|
||||
case "", "playwright":
|
||||
result.Tool = "playwright"
|
||||
output, report, err = m.runPlaywright(ctx, source, baseURL, reportPath)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported tool %q: use \"playwright\", \"cypress\", \"selenium\" or \"none\"", tool)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s run failed: %w", result.Tool, err)
|
||||
}
|
||||
|
||||
result.Output = output
|
||||
result.ReportSize = len(report)
|
||||
result.Success = true
|
||||
|
||||
// POST results to the IntegraCI API when API params are supplied.
|
||||
if apiURL != "" && token != nil && serviceID != "" {
|
||||
if err := m.postResults(ctx, apiURL, token, serviceID, result); err != nil {
|
||||
return result, fmt.Errorf("post results: %w", err)
|
||||
}
|
||||
result.Posted = true
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// runPlaywright installs Playwright browsers and runs the suite against
|
||||
// baseURL, then reads the report artifact back out of the container.
|
||||
func (m *E2eTest) runPlaywright(
|
||||
ctx context.Context,
|
||||
source *dagger.Directory,
|
||||
baseURL string,
|
||||
reportPath string,
|
||||
) (string, string, error) {
|
||||
runner := dag.Container().
|
||||
From("mcr.microsoft.com/playwright:v1.44.0-jammy").
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src").
|
||||
WithEnvVariable("BASE_URL", baseURL).
|
||||
WithExec([]string{"npm", "ci"}).
|
||||
WithExec([]string{"npx", "playwright", "install", "--with-deps"}).
|
||||
WithExec([]string{"npx", "playwright", "test"})
|
||||
|
||||
output, err := runner.Stdout(ctx)
|
||||
if err != nil {
|
||||
return output, "", fmt.Errorf("playwright test: %w", err)
|
||||
}
|
||||
|
||||
report, rerr := runner.File("/src/" + reportPath + "/index.html").Contents(ctx)
|
||||
if rerr != nil {
|
||||
// Report artifact is best-effort; absence is not fatal.
|
||||
report = ""
|
||||
}
|
||||
|
||||
return output, report, nil
|
||||
}
|
||||
|
||||
// runCypress installs dependencies and runs the Cypress suite against
|
||||
// baseURL, then reads the report artifact back out of the container.
|
||||
func (m *E2eTest) runCypress(
|
||||
ctx context.Context,
|
||||
source *dagger.Directory,
|
||||
baseURL string,
|
||||
reportPath string,
|
||||
) (string, string, error) {
|
||||
runner := dag.Container().
|
||||
From("cypress/included:13.11.0").
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src").
|
||||
WithEnvVariable("CYPRESS_BASE_URL", baseURL).
|
||||
WithExec([]string{"npm", "ci"}).
|
||||
WithExec([]string{"cypress", "run", "--config", "baseUrl=" + baseURL})
|
||||
|
||||
output, err := runner.Stdout(ctx)
|
||||
if err != nil {
|
||||
return output, "", fmt.Errorf("cypress run: %w", err)
|
||||
}
|
||||
|
||||
report, rerr := runner.File("/src/" + reportPath).Contents(ctx)
|
||||
if rerr != nil {
|
||||
report = ""
|
||||
}
|
||||
|
||||
return output, report, nil
|
||||
}
|
||||
|
||||
// runSelenium runs a configurable test command (default "pytest -m e2e")
|
||||
// against baseURL. Selenium has no official CI action, so the canonical
|
||||
// recipe is to run the project's own command inside a Python image with a
|
||||
// Selenium runtime. The baseURL is exposed via BASE_URL for the suite.
|
||||
func (m *E2eTest) runSelenium(
|
||||
ctx context.Context,
|
||||
source *dagger.Directory,
|
||||
baseURL string,
|
||||
command string,
|
||||
) (string, string, error) {
|
||||
cmd := strings.TrimSpace(command)
|
||||
if cmd == "" {
|
||||
cmd = "pytest -m e2e"
|
||||
}
|
||||
|
||||
output, err := dag.Container().
|
||||
From("python:3.12-slim").
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src").
|
||||
WithEnvVariable("BASE_URL", baseURL).
|
||||
WithExec([]string{"sh", "-c", cmd}).
|
||||
Stdout(ctx)
|
||||
if err != nil {
|
||||
return output, "", fmt.Errorf("selenium command: %w", err)
|
||||
}
|
||||
|
||||
return output, "", nil
|
||||
}
|
||||
|
||||
// postResults POSTs the E2E result summary to the IntegraCI API. Mirrors
|
||||
// the security-scan post-to-API pattern: a small curl invocation inside a
|
||||
// throwaway container so no host network access is required.
|
||||
func (m *E2eTest) postResults(
|
||||
ctx context.Context,
|
||||
apiURL string,
|
||||
token *dagger.Secret,
|
||||
serviceID string,
|
||||
result *E2EResult,
|
||||
) error {
|
||||
payload := fmt.Sprintf(
|
||||
`{"service_id":%q,"tool":%q,"base_url":%q,"success":%t,"report_size":%d}`,
|
||||
serviceID, result.Tool, result.BaseURL, result.Success, result.ReportSize,
|
||||
)
|
||||
|
||||
_, err := dag.Container().
|
||||
From("curlimages/curl:8.10.1").
|
||||
WithSecretVariable("API_TOKEN", token).
|
||||
WithExec([]string{
|
||||
"sh", "-c",
|
||||
"curl -sS -X POST " +
|
||||
"-H \"Authorization: Bearer $API_TOKEN\" " +
|
||||
"-H \"Content-Type: application/json\" " +
|
||||
"-d '" + payload + "' " +
|
||||
strings.TrimRight(apiURL, "/") + "/api/v1/e2e-results",
|
||||
}).
|
||||
Stdout(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("curl post: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
# iac-scan
|
||||
|
||||
> **UNVERIFIED SCAFFOLD** — run `dagger develop` + `dagger functions` + test
|
||||
> against a matching Dagger engine (engineVersion `v0.21.7`) before use. The
|
||||
> Go in `main.go` has NOT been compiled or validated by Dagger codegen in
|
||||
> this environment (`dagger develop` is unavailable, and the `dag` global
|
||||
> plus the `*Directory` / `*Container` / `*Secret` / `*File` types are
|
||||
> generated). Do not assume it works as-is.
|
||||
|
||||
IntegraCI IaC (Infrastructure-as-Code) security scanning Dagger module. Runs
|
||||
[Trivy](https://trivy.dev/) (`trivy config`) — or optionally
|
||||
[Checkov](https://www.checkov.io/) — over a source directory containing
|
||||
Terraform / Helm / Dockerfile / Kubernetes manifests, counts
|
||||
misconfigurations by severity, and optionally POSTs the result to the
|
||||
IntegraCI API.
|
||||
|
||||
It mirrors the structure and idioms of the sibling `sast-scan` module.
|
||||
|
||||
## Functions
|
||||
|
||||
### `scan`
|
||||
|
||||
Runs an IaC misconfiguration scan and returns a `ScanResult`.
|
||||
|
||||
| Param | Required | Default | Description |
|
||||
| ------------ | -------- | --------- | ------------------------------------------------- |
|
||||
| `source` | yes | — | Source directory to scan (Terraform/Helm/K8s/…) |
|
||||
| `tool` | no | `trivy` | IaC tool: `trivy` \| `checkov` \| `none` |
|
||||
| `api-url` | no | — | IntegraCI API URL for posting results |
|
||||
| `token` | no | — | JWT token for API authentication |
|
||||
| `service-id` | no | — | Service ID to link scan results |
|
||||
| `version` | no | — | Commit SHA / image tag the scan applies to |
|
||||
|
||||
When `tool=none`, the scan is skipped and a result with `skipped=true` is
|
||||
returned. Results are POSTed to the generic scan-ingest endpoint
|
||||
(`POST /api/v1/scans`, `scan_type="iac"`) only when both `api-url` and
|
||||
`token` are set. The per-severity counts populate the typed columns; the
|
||||
`iac_critical` / `iac_high` counters are mirrored into `report_data`, which is
|
||||
where the deploy OPA gate reads them (`golden_standard.rego`
|
||||
`scan_results.iac_critical` / `iac_high`).
|
||||
|
||||
## Usage
|
||||
|
||||
> These commands are illustrative and have NOT been run here. Verify against
|
||||
> a live Dagger engine first.
|
||||
|
||||
```sh
|
||||
# Scan and post results to the IntegraCI API
|
||||
dagger call scan \
|
||||
--source . \
|
||||
--api-url http://localhost:8000 \
|
||||
--token "$TOKEN" \
|
||||
--service-id "$SVC_ID"
|
||||
|
||||
# Scan with Checkov instead of Trivy
|
||||
dagger call scan --source . --tool checkov
|
||||
|
||||
# Scan only (no API post)
|
||||
dagger call scan --source .
|
||||
|
||||
# Skip scanning
|
||||
dagger call scan --source . --tool none
|
||||
```
|
||||
|
||||
## Verifying the scaffold
|
||||
|
||||
```sh
|
||||
dagger develop # generate the SDK + codegen
|
||||
dagger functions # confirm the 'scan' function is exposed
|
||||
gofmt -l main.go # confirm formatting (should print nothing)
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "iac-scan",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
// Package main implements the IntegraCI iac-scan Dagger module.
|
||||
//
|
||||
// Runs Infrastructure-as-Code (IaC) security scanning over a source directory
|
||||
// (Terraform / Helm / Dockerfile / Kubernetes manifests), counts
|
||||
// misconfigurations by severity, and optionally POSTs the result to the
|
||||
// IntegraCI API. Engine-agnostic: callable from any CI engine via
|
||||
// `dagger call`.
|
||||
//
|
||||
// Supported tools (each runs the vendor's canonical CLI inside its official
|
||||
// container image):
|
||||
//
|
||||
// trivy aquasec/trivy trivy config --format json .
|
||||
// checkov bridgecrew/checkov checkov -d . -o json
|
||||
// none no-op skip
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call scan --source . --api-url http://localhost:8000 --token env:TOKEN --service-id $SVC_ID
|
||||
// dagger call scan --source . --tool checkov
|
||||
// dagger call scan --source . --tool none
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"dagger/iac-scan/internal/dagger"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// IacScan is the IntegraCI Infrastructure-as-Code scanning module.
|
||||
type IacScan struct{}
|
||||
|
||||
// ScanResult contains the output of an IaC scan.
|
||||
type ScanResult struct {
|
||||
Tool string `json:"tool"`
|
||||
Findings int `json:"findings"`
|
||||
Critical int `json:"critical"`
|
||||
High int `json:"high"`
|
||||
Medium int `json:"medium"`
|
||||
Low int `json:"low"`
|
||||
Report string `json:"report,omitempty"`
|
||||
Skipped bool `json:"skipped"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// Scan runs an IaC misconfiguration pass over the source directory with the
|
||||
// selected tool, counts findings by severity, and optionally POSTs the result
|
||||
// to the IntegraCI API. Mirrors sast-scan.Scan's reporting contract.
|
||||
func (m *IacScan) Scan(
|
||||
ctx context.Context,
|
||||
// Source directory to scan (Terraform / Helm / Dockerfile / K8s manifests)
|
||||
source *dagger.Directory,
|
||||
// IaC tool: trivy | checkov | none
|
||||
// +optional
|
||||
// +default="trivy"
|
||||
tool string,
|
||||
// IntegraCI API URL for posting results
|
||||
// +optional
|
||||
apiURL string,
|
||||
// JWT token for API authentication
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// Service ID to link scan results
|
||||
// +optional
|
||||
serviceID string,
|
||||
// Version (commit SHA / image tag) the scan applies to
|
||||
// +optional
|
||||
version string,
|
||||
) (*ScanResult, error) {
|
||||
result := &ScanResult{Tool: tool}
|
||||
|
||||
var (
|
||||
report string
|
||||
err error
|
||||
)
|
||||
|
||||
switch strings.ToLower(tool) {
|
||||
case "none":
|
||||
result.Skipped = true
|
||||
result.Success = true
|
||||
return result, nil
|
||||
case "trivy":
|
||||
report, err = m.runTrivyConfig(ctx, source)
|
||||
case "checkov":
|
||||
report, err = m.runCheckov(ctx, source)
|
||||
default:
|
||||
return nil, fmt.Errorf(
|
||||
"unsupported iac tool %q (expected one of: trivy, checkov, none)",
|
||||
tool,
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s iac scan failed: %w", tool, err)
|
||||
}
|
||||
|
||||
result.Report = report
|
||||
result.Critical = countSeverity(report, "CRITICAL")
|
||||
result.High = countSeverity(report, "HIGH")
|
||||
result.Medium = countSeverity(report, "MEDIUM")
|
||||
result.Low = countSeverity(report, "LOW")
|
||||
result.Findings = result.Critical + result.High + result.Medium + result.Low
|
||||
|
||||
// POST results to the IntegraCI API when configured. Skipped silently
|
||||
// when apiURL or token is empty so local runs still work.
|
||||
if apiURL != "" && token != nil {
|
||||
if err := m.postResults(ctx, apiURL, token, serviceID, version, result); err != nil {
|
||||
return nil, fmt.Errorf("posting results to API failed: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
result.Success = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// runTrivyConfig runs "trivy config" over the source directory in JSON mode.
|
||||
// Trivy exits non-zero when misconfigurations are present; we force
|
||||
// --exit-code 0 and read the JSON report rather than relying on the exit code.
|
||||
func (m *IacScan) runTrivyConfig(ctx context.Context, source *dagger.Directory) (string, error) {
|
||||
const reportPath = "/tmp/iac-report.json"
|
||||
report, err := dag.Container().
|
||||
From("aquasec/trivy:0.58.1").
|
||||
// Persist Trivy's misconfig/policy DB across runs (avoids re-downloading it).
|
||||
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src").
|
||||
WithExec([]string{
|
||||
"trivy", "config",
|
||||
"--format", "json",
|
||||
"--output", reportPath,
|
||||
"--exit-code", "0",
|
||||
".",
|
||||
}).
|
||||
File(reportPath).
|
||||
Contents(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read trivy config JSON output: %w", err)
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// runCheckov runs Checkov over the source directory in JSON mode. Checkov
|
||||
// exits non-zero when failed checks are present, so we tolerate the exit code
|
||||
// and read the JSON emitted on stdout.
|
||||
func (m *IacScan) runCheckov(ctx context.Context, source *dagger.Directory) (string, error) {
|
||||
c := dag.Container().
|
||||
From("bridgecrew/checkov:3.2.334").
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src").
|
||||
WithExec([]string{"sh", "-c", "checkov -d . -o json --compact || true"})
|
||||
return c.Stdout(ctx)
|
||||
}
|
||||
|
||||
// countSeverity tallies findings of a given severity level from an IaC scan
|
||||
// report. Both Trivy (`"Severity": "HIGH"`) and Checkov (`"severity": "HIGH"`)
|
||||
// emit uppercase severity strings under a severity key; we count occurrences
|
||||
// of that key/value pair, tolerant of the optional space after the colon.
|
||||
// Zero-dep, matching the license-scan / sast-scan substring approach.
|
||||
func countSeverity(report, level string) int {
|
||||
total := 0
|
||||
for _, key := range []string{`"Severity"`, `"severity"`} {
|
||||
for _, sep := range []string{":", ": "} {
|
||||
total += strings.Count(report, key+sep+`"`+level+`"`)
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// postResults sends the IaC scan result to the IntegraCI generic scan-ingest
|
||||
// endpoint. Shape matches api/app/schemas/scan.py ScanResultCreate: the
|
||||
// per-severity misconfig counts populate the typed columns, and the
|
||||
// iac_critical / iac_high counters are mirrored into report_data (the fields
|
||||
// the deploy OPA gate reads — see deploy_policy_gate.py _build_scan_results).
|
||||
func (m *IacScan) postResults(
|
||||
ctx context.Context,
|
||||
apiURL string,
|
||||
token *dagger.Secret,
|
||||
serviceID string,
|
||||
version string,
|
||||
result *ScanResult,
|
||||
) error {
|
||||
payload := map[string]any{
|
||||
"service_id": serviceID,
|
||||
"version": version,
|
||||
"scan_type": "iac",
|
||||
"scanner": result.Tool,
|
||||
"report_format": "json",
|
||||
"findings_count": result.Findings,
|
||||
"critical_count": result.Critical,
|
||||
"high_count": result.High,
|
||||
"medium_count": result.Medium,
|
||||
"low_count": result.Low,
|
||||
"report_data": map[string]any{
|
||||
"iac_critical": result.Critical,
|
||||
"iac_high": result.High,
|
||||
},
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal scan payload: %w", err)
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/scans"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
tokenStr, err := token.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read token secret: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+tokenStr)
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("API post to %s failed: %w", endpoint, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("API post to %s returned %d", endpoint, resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# IntegraCI — License Scan Dagger Module
|
||||
|
||||
Scan dependency licenses and fail on blocked licenses (GPL/AGPL/SSPL).
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
dagger call scan-fs --source . --strict
|
||||
dagger call scan-image --image ghcr.io/org/svc:1.2.3 --blocklist GPL-2.0,GPL-3.0,AGPL-3.0
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "license-scan",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
// Package main implements the IntegraCI license-scan Dagger module.
|
||||
//
|
||||
// Runs Trivy in license mode (S-05). Outputs a JSON license report and
|
||||
// fails the pipeline when any blocked license (default GPL/AGPL/SSPL) is
|
||||
// found in the dependency tree. Result can be POSTed to the IntegraCI
|
||||
// /api/v1/scans endpoint with scan_type=license.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call scan-fs --source . --strict
|
||||
// dagger call scan-image --image ghcr.io/org/svc:1.2.3 --blocklist GPL-2.0,GPL-3.0,AGPL-3.0
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"dagger/license-scan/internal/dagger"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// LicenseScan is the IntegraCI Trivy license scanning module.
|
||||
type LicenseScan struct{}
|
||||
|
||||
// LicenseResult contains the output of a license scan.
|
||||
type LicenseResult struct {
|
||||
Success bool `json:"success"`
|
||||
Target string `json:"target"`
|
||||
BlockedHits []string `json:"blocked_hits"`
|
||||
Report string `json:"report,omitempty"`
|
||||
}
|
||||
|
||||
const defaultBlocklist = "GPL-2.0,GPL-3.0,AGPL-1.0,AGPL-3.0,SSPL-1.0"
|
||||
|
||||
// ScanFs runs Trivy filesystem license scan against a source directory.
|
||||
func (m *LicenseScan) ScanFs(
|
||||
ctx context.Context,
|
||||
// Source directory to scan
|
||||
source *dagger.Directory,
|
||||
// Comma-separated list of blocked SPDX license IDs
|
||||
// +optional
|
||||
// +default="GPL-2.0,GPL-3.0,AGPL-1.0,AGPL-3.0,SSPL-1.0"
|
||||
blocklist string,
|
||||
// Strict mode: fail on any blocked license hit
|
||||
// +optional
|
||||
// +default=true
|
||||
strict bool,
|
||||
) (*LicenseResult, error) {
|
||||
if blocklist == "" {
|
||||
blocklist = defaultBlocklist
|
||||
}
|
||||
|
||||
report, err := dag.Container().
|
||||
From("aquasec/trivy:0.58.1").
|
||||
// Persist Trivy's vulnerability DB across runs (avoids re-downloading it).
|
||||
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
|
||||
WithDirectory("/src", source).
|
||||
WithWorkdir("/src").
|
||||
WithExec([]string{
|
||||
"trivy", "fs",
|
||||
"--scanners", "license",
|
||||
"--license-full",
|
||||
"--format", "json",
|
||||
"--output", "/tmp/license-report.json",
|
||||
"--exit-code", "0",
|
||||
".",
|
||||
}).
|
||||
File("/tmp/license-report.json").
|
||||
Contents(ctx)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trivy license scan failed: %w", err)
|
||||
}
|
||||
|
||||
hits := findBlockedLicenses(report, strings.Split(blocklist, ","))
|
||||
result := &LicenseResult{
|
||||
Target: "filesystem",
|
||||
Report: report,
|
||||
BlockedHits: hits,
|
||||
Success: len(hits) == 0 || !strict,
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ScanImage runs Trivy license scan against a container image reference.
|
||||
func (m *LicenseScan) ScanImage(
|
||||
ctx context.Context,
|
||||
// Image reference (e.g. ghcr.io/org/service:tag)
|
||||
image string,
|
||||
// Comma-separated list of blocked SPDX license IDs
|
||||
// +optional
|
||||
// +default="GPL-2.0,GPL-3.0,AGPL-1.0,AGPL-3.0,SSPL-1.0"
|
||||
blocklist string,
|
||||
// Strict mode: fail on any blocked license hit
|
||||
// +optional
|
||||
// +default=true
|
||||
strict bool,
|
||||
) (*LicenseResult, error) {
|
||||
if blocklist == "" {
|
||||
blocklist = defaultBlocklist
|
||||
}
|
||||
|
||||
report, err := dag.Container().
|
||||
From("aquasec/trivy:0.58.1").
|
||||
// Persist Trivy's vulnerability DB across runs (avoids re-downloading it).
|
||||
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
|
||||
WithExec([]string{
|
||||
"trivy", "image",
|
||||
"--scanners", "license",
|
||||
"--license-full",
|
||||
"--format", "json",
|
||||
"--output", "/tmp/license-report.json",
|
||||
"--exit-code", "0",
|
||||
image,
|
||||
}).
|
||||
File("/tmp/license-report.json").
|
||||
Contents(ctx)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("trivy license scan failed: %w", err)
|
||||
}
|
||||
|
||||
hits := findBlockedLicenses(report, strings.Split(blocklist, ","))
|
||||
result := &LicenseResult{
|
||||
Target: image,
|
||||
Report: report,
|
||||
BlockedHits: hits,
|
||||
Success: len(hits) == 0 || !strict,
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// findBlockedLicenses returns the unique blocked license IDs found in the JSON report.
|
||||
func findBlockedLicenses(report string, blocklist []string) []string {
|
||||
seen := map[string]bool{}
|
||||
hits := []string{}
|
||||
for _, lic := range blocklist {
|
||||
needle := strings.TrimSpace(lic)
|
||||
if needle == "" {
|
||||
continue
|
||||
}
|
||||
// Trivy's license report includes "Name":"<SPDX>" entries.
|
||||
token := fmt.Sprintf(`"Name":%q`, needle)
|
||||
if strings.Contains(report, token) && !seen[needle] {
|
||||
seen[needle] = true
|
||||
hits = append(hits, needle)
|
||||
}
|
||||
}
|
||||
return hits
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# IntegraCI — Malware Scan Dagger Module
|
||||
|
||||
Scan a source tree for known malware signatures (ClamAV) and, optionally, post
|
||||
the result back as the `malware` leg of the vendor code-ingest quarantine gate.
|
||||
|
||||
This closes the last leg of the quarantine suite
|
||||
(`sast` / `secret` / `sca` / `license` / `malware`) — without it the gate can
|
||||
never reach `passed`.
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
# scan only
|
||||
dagger call scan --source .
|
||||
|
||||
# skip (governance opt-out)
|
||||
dagger call scan --source . --tool none
|
||||
|
||||
# scan + report to the quarantine gate
|
||||
dagger call scan --source . \
|
||||
--ingest-id <uuid> \
|
||||
--api-url https://api.example.com \
|
||||
--token env://INTEGRACI_TOKEN
|
||||
```
|
||||
|
||||
Infected files map to the `critical` severity bucket, so any hit fails the gate.
|
||||
|
||||
## Notes
|
||||
|
||||
- ClamAV ships a bundled signature DB in its official image, so no rules to
|
||||
author. The signature DB is cached across runs.
|
||||
- ClamAV runs as a pulled runtime container image (not bundled into the
|
||||
IntegraCI distribution), the same posture as the other scanner modules.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "malware-scan",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
// Package main implements the IntegraCI malware-scan Dagger module.
|
||||
//
|
||||
// Closes the last leg of the vendor code-ingest quarantine suite
|
||||
// (sast/secret/sca/license/malware). The quarantine gate
|
||||
// (api/app/security/services/code_ingest.py) requires every leg to report
|
||||
// clean before a vendor repo can be adopted; the other four legs have
|
||||
// scanner modules, malware did not — so the gate could never reach "passed".
|
||||
//
|
||||
// Scans a source directory for known malware signatures with ClamAV (its
|
||||
// official image ships a bundled signature DB, so no rules to author) and
|
||||
// can POST the result back to the quarantine as scanner="malware".
|
||||
//
|
||||
// ClamAV is invoked as a runtime container image (not bundled/linked into the
|
||||
// IntegraCI distribution), the same posture as the other scanner modules that
|
||||
// pull tool images (e.g. trufflehog in secret-scan).
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call scan --source .
|
||||
// dagger call scan --source . --tool none
|
||||
// dagger call scan --source . --ingest-id <uuid> --api-url https://api.example --token env://INTEGRACI_TOKEN
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"dagger/malware-scan/internal/dagger"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// MalwareScan is the IntegraCI malware-scanning module.
|
||||
type MalwareScan struct{}
|
||||
|
||||
// MalwareResult is the normalised output of a malware scan.
|
||||
type MalwareResult struct {
|
||||
Tool string `json:"tool"` // clamav | none
|
||||
Skipped bool `json:"skipped"` // true for the "none" no-op branch
|
||||
Findings int `json:"findings"` // number of infected files detected
|
||||
Report string `json:"report"` // raw scanner stdout
|
||||
Pass bool `json:"pass"` // false when malware was detected
|
||||
Error string `json:"error,omitempty"` // failure detail, if any
|
||||
}
|
||||
|
||||
// Scan runs the selected malware scanner over the source tree and, when
|
||||
// quarantine coordinates are supplied, posts the result back as the
|
||||
// scanner="malware" leg of the code-ingest gate.
|
||||
//
|
||||
// The scanner exits non-zero when infected files are found; we swallow that
|
||||
// exit, capture the report, and surface Pass/Findings ourselves so the caller
|
||||
// (any CI engine) decides how to gate.
|
||||
func (m *MalwareScan) Scan(
|
||||
ctx context.Context,
|
||||
// Source directory to scan
|
||||
source *dagger.Directory,
|
||||
// Tool: clamav | none
|
||||
// +optional
|
||||
// +default="clamav"
|
||||
tool string,
|
||||
// Quarantine ingest id to POST results to (omit to skip posting)
|
||||
// +optional
|
||||
ingestID string,
|
||||
// IntegraCI API base URL (required to POST results)
|
||||
// +optional
|
||||
apiURL string,
|
||||
// Bearer token secret (required to POST results)
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
) (*MalwareResult, error) {
|
||||
var result *MalwareResult
|
||||
switch tool {
|
||||
case "none":
|
||||
// Mirrors the governance skip branch used by the other scan modules.
|
||||
result = &MalwareResult{Tool: "none", Skipped: true, Pass: true}
|
||||
case "clamav", "":
|
||||
result = runClamAV(ctx, source)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported malware-scan tool: %q (want clamav|none)", tool)
|
||||
}
|
||||
|
||||
if ingestID != "" && apiURL != "" && token != nil {
|
||||
if err := postIngestResult(ctx, apiURL, token, ingestID, result); err != nil {
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// runClamAV runs `clamscan -r --infected /src`. The clamav/clamav image
|
||||
// bundles a signature DB, so the scan works without a freshclam update.
|
||||
// clamscan exits 1 when infected files are found; we swallow that and count
|
||||
// the "FOUND" lines (one per infected file) ourselves.
|
||||
func runClamAV(ctx context.Context, source *dagger.Directory) *MalwareResult {
|
||||
out, _ := dag.Container().
|
||||
From("clamav/clamav:1.4").
|
||||
// Persist the signature DB across runs (avoids re-downloading it).
|
||||
WithMountedCache("/var/lib/clamav", dag.CacheVolume("clamav-db")).
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src").
|
||||
WithExec([]string{"clamscan", "-r", "--infected", "/src"}).
|
||||
Stdout(ctx)
|
||||
|
||||
result := &MalwareResult{Tool: "clamav", Report: out}
|
||||
// clamscan prints one "<file>: <Signature> FOUND" line per infected file.
|
||||
result.Findings = strings.Count(out, "FOUND")
|
||||
result.Pass = result.Findings == 0
|
||||
if !result.Pass {
|
||||
result.Error = fmt.Sprintf("clamav: %d infected file(s) detected", result.Findings)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// postIngestResult reports the malware leg to the quarantine gate. Shape
|
||||
// matches api/app/security/schemas/code_ingest.py ScanResultReport: infected
|
||||
// files map to the critical severity bucket so any hit fails the gate.
|
||||
func postIngestResult(
|
||||
ctx context.Context,
|
||||
apiURL string,
|
||||
token *dagger.Secret,
|
||||
ingestID string,
|
||||
result *MalwareResult,
|
||||
) error {
|
||||
payload := map[string]any{
|
||||
"scanner": "malware",
|
||||
"critical": result.Findings,
|
||||
"high": 0,
|
||||
"medium": 0,
|
||||
"low": 0,
|
||||
}
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal scan payload: %w", err)
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/code-ingest/" + ingestID + "/scan-result"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
tokenStr, err := token.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read token secret: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+tokenStr)
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("API post to %s failed: %w", endpoint, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("API post to %s returned %d", endpoint, resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
# IntegraCI — Mobile Android Dagger Module
|
||||
|
||||
Build, test, sign, and distribute Android apps.
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
dagger call build --source . --variant release
|
||||
dagger call test --source . --task testReleaseUnitTest
|
||||
dagger call sign --aab build/app-release.aab --keystore $KEYSTORE
|
||||
dagger call distribute --aab build/app-release.aab --track internal
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "mobile-android",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,822 @@
|
||||
// Package main implements the IntegraCI mobile-android Dagger module.
|
||||
//
|
||||
// Wraps Gradle + Fastlane (supply) to:
|
||||
// - Build .apk / .aab from a Gradle project
|
||||
// - Sign with a keystore fetched from OpenBao (passed in as a secret)
|
||||
// - Publish the artifact to a raw (non-OCI) repository such as Nexus
|
||||
// - Distribute to Play Store via Fastlane `supply`
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call build --source . --variant release export --path ./mobile-out
|
||||
// dagger call test --source . --task testReleaseUnitTest
|
||||
// dagger call sign --artifact ./mobile-out/app.aab --keystore file:ks.jks … export --path signed.aab
|
||||
// dagger call publish-raw --artifact ./mobile-out/app.aab --url http://nexus:8081 --repository raw-hosted …
|
||||
// dagger call distribute --aab ./mobile-out/app.aab --track internal --service-account-json env:SA
|
||||
//
|
||||
// ── Why every exec here is allowed to FAIL ────────────────────────────────────
|
||||
// Every command in this module used to end in `|| true`, and success was then
|
||||
// inferred by grepping stdout for "build failed" / "fail" / "error". That is a
|
||||
// gate that cannot fail: Gradle writes its failure banner to stderr under many
|
||||
// configurations, so a broken build produced a green result, an APK path that
|
||||
// pointed at nothing, and a pipeline that reported success having produced no
|
||||
// artifact. Dagger already fails an exec on a non-zero exit code — the fix is to
|
||||
// stop suppressing it and to surface the output with `execDetail` so the reason
|
||||
// is visible without scrolling the engine log.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"dagger/mobile-android/internal/dagger"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MobileAndroid is the IntegraCI Android pipeline module.
|
||||
type MobileAndroid struct{}
|
||||
|
||||
// AndroidBuildMetadata is what the build could learn about the artifact it
|
||||
// produced. “VersionCode“ is not cosmetic: the Play Store promote API
|
||||
// addresses a release BY version code, so a distribute step that does not have
|
||||
// it cannot do anything at all.
|
||||
type AndroidBuildMetadata struct {
|
||||
ApplicationID string `json:"application_id,omitempty"`
|
||||
VersionName string `json:"version_name,omitempty"`
|
||||
VersionCode int `json:"version_code,omitempty"`
|
||||
APKName string `json:"apk_name,omitempty"`
|
||||
AABName string `json:"aab_name,omitempty"`
|
||||
}
|
||||
|
||||
// AndroidTestResult summarises a Gradle unit-test run.
|
||||
type AndroidTestResult struct {
|
||||
Task string `json:"task"`
|
||||
Logs string `json:"logs,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// execDetail turns Dagger's bare `exit code: N` into the output that explains
|
||||
// it. Copied deliberately from the standard-build module: the two modules fail
|
||||
// in the same way and a caller should read the same shape of error from both.
|
||||
func execDetail(err error) string {
|
||||
var exec *dagger.ExecError
|
||||
if !errors.As(err, &exec) {
|
||||
return err.Error()
|
||||
}
|
||||
out := strings.TrimSpace(exec.Stderr)
|
||||
if out == "" {
|
||||
out = strings.TrimSpace(exec.Stdout)
|
||||
}
|
||||
const maxDetail = 4000
|
||||
if len(out) > maxDetail {
|
||||
out = "…" + out[len(out)-maxDetail:]
|
||||
}
|
||||
if out == "" {
|
||||
return err.Error()
|
||||
}
|
||||
return fmt.Sprintf("exit code %d\n%s", exec.ExitCode, out)
|
||||
}
|
||||
|
||||
// variantTask capitalises a Gradle variant for task names ("release" ->
|
||||
// "Release"). `strings.Title` is deprecated and word-splits on every space,
|
||||
// which is wrong for a variant name; this does the one thing that is needed.
|
||||
func variantTask(variant string) string {
|
||||
v := strings.ToLower(strings.TrimSpace(variant))
|
||||
if v == "" {
|
||||
return "Release"
|
||||
}
|
||||
return strings.ToUpper(v[:1]) + v[1:]
|
||||
}
|
||||
|
||||
// gradleImage returns the base container with a JDK + the Android SDK.
|
||||
//
|
||||
// `compileSdk` and `buildTools` are parameters, not constants: the SDK platform
|
||||
// a project compiles against is a property of THAT project. This module pinned
|
||||
// `android-34` / `build-tools;34.0.0` while an onboarding app declared
|
||||
// `compileSdk = 36`, and — because the sdkmanager line ended in `|| true` — the
|
||||
// image was built without the platform the build needs and failed much later
|
||||
// with a message about a missing package rather than about the SDK.
|
||||
// signerImage is the SMALLEST image that can sign an artefact: a JDK (for
|
||||
// jarsigner) plus Android build-tools (for apksigner). No `platforms`, no
|
||||
// `platform-tools` — signing reads a finished artefact and needs neither.
|
||||
//
|
||||
// WHY THIS IS NOT gradleImage. Sign used to reuse the build image, which
|
||||
// installs the compile platform as well. MEASURED 2026-09-06 in a cold
|
||||
// container: the build image's SDK install is **458 MB / 291 s**, this one is
|
||||
// **299 MB / 226 s** — and `apksigner` is present in both. That saving is paid
|
||||
// on EVERY build, because the managed Jenkins agent runs the engine on an
|
||||
// EmptyDir with `podRetention: Never`, so no cache volume survives the build
|
||||
// (see the note in gradleImage).
|
||||
//
|
||||
// The cache volume is keyed on build-tools ALONE, deliberately. Sign has no
|
||||
// compileSdk parameter and used to pass a hardcoded "34" into gradleImage's
|
||||
// key, so a project on compileSdk 36 got a SECOND SDK volume that shared
|
||||
// nothing with its own build. One key per thing actually installed.
|
||||
// defaultJDKImage is pinned BY DIGEST, not by tag, and that is an air-gap
|
||||
// requirement rather than a style preference.
|
||||
//
|
||||
// Measured 2026-09-07: with the engine's network cut but its content store warm
|
||||
// from a previous build, `From("eclipse-temurin:17-jdk")` still failed::
|
||||
//
|
||||
// failed to resolve image "docker.io/library/eclipse-temurin:17-jdk":
|
||||
// Head "https://registry-1.docker.io/v2/library/eclipse-temurin/manifests/17-jdk":
|
||||
// dial tcp: lookup registry-1.docker.io: i/o timeout
|
||||
//
|
||||
// A TAG is mutable, so BuildKit must ask the registry which digest it points at
|
||||
// today -- every build, even when the bytes are already local. A DIGEST is the
|
||||
// content address: it resolves from the local store and needs no registry.
|
||||
//
|
||||
// The build therefore could not even START on an air-gapped agent, before any
|
||||
// SDK or dependency question arose. Pinning also removes a reproducibility hole
|
||||
// that has nothing to do with air-gap: a tag can move between two builds of the
|
||||
// same commit.
|
||||
//
|
||||
// To move to a newer JDK image: `docker pull eclipse-temurin:<tag>` then
|
||||
// `docker inspect --format '{{index .RepoDigests 0}}'`. This is the multi-arch
|
||||
// manifest-list digest, so it stays correct on any platform.
|
||||
const defaultJDKImage = "eclipse-temurin@sha256:a27c79d44326d5f689668df5fedfee487652066d2a91e172747056cc7fbee6fc"
|
||||
|
||||
// defaultJDKVersion is the JDK the digest above actually contains. Kept beside
|
||||
// it so the two cannot drift silently: a caller asking for a different JDK gets
|
||||
// the mutable tag and, with it, the registry round-trip described above.
|
||||
const defaultJDKVersion = "17"
|
||||
|
||||
// jdkImage returns the digest-pinned base for the default JDK and a plain tag
|
||||
// for anything else. A caller pinning a different JDK accepts the registry
|
||||
// round-trip that comes with a mutable reference -- see defaultJDKImage.
|
||||
func jdkImage(jdkVersion string) string {
|
||||
if jdkVersion == "" || jdkVersion == defaultJDKVersion {
|
||||
return defaultJDKImage
|
||||
}
|
||||
return fmt.Sprintf("eclipse-temurin:%s-jdk", jdkVersion)
|
||||
}
|
||||
|
||||
// defaultBuildTools is a comma-separated LIST because the project, not this
|
||||
// module, decides which Build-Tools version Gradle asks for: the Android Gradle
|
||||
// plugin picks a default from its own version. When the requested package is
|
||||
// missing, AGP DOWNLOADS it mid-build from dl.google.com -- measured 2026-09-07
|
||||
// on the sibling Flutter lane, which pulled 33.0.1 despite 34.0.0 being
|
||||
// installed explicitly. That is a silent network dependency in the middle of
|
||||
// the longest stage, and on an air-gapped agent a build that dies after twenty
|
||||
// minutes with a message about a licence.
|
||||
//
|
||||
// Paired with `android.builder.sdkDownload=false` (written into
|
||||
// GRADLE_USER_HOME by Build): a missing package then fails immediately and by
|
||||
// name, and the name goes into --build-tools.
|
||||
const defaultBuildTools = "34.0.0"
|
||||
|
||||
// buildToolsList splits the comma-separated --build-tools into the versions to
|
||||
// install plus a slug safe for a cache-volume key.
|
||||
func buildToolsList(raw string) (versions []string, slug string) {
|
||||
for _, v := range strings.Split(raw, ",") {
|
||||
v = strings.TrimSpace(v)
|
||||
if v == "" {
|
||||
continue
|
||||
}
|
||||
versions = append(versions, v)
|
||||
}
|
||||
if len(versions) == 0 {
|
||||
versions = []string{defaultBuildTools}
|
||||
}
|
||||
return versions, strings.Join(versions, "_")
|
||||
}
|
||||
|
||||
func (m *MobileAndroid) signerImage(jdkVersion, buildTools string) *dagger.Container {
|
||||
if jdkVersion == "" {
|
||||
jdkVersion = "17"
|
||||
}
|
||||
if buildTools == "" {
|
||||
buildTools = defaultBuildTools
|
||||
}
|
||||
tools, toolsSlug := buildToolsList(buildTools)
|
||||
pkgs := ""
|
||||
for _, v := range tools {
|
||||
pkgs += " 'build-tools;" + v + "'"
|
||||
}
|
||||
return dag.Container().
|
||||
From(jdkImage(jdkVersion)).
|
||||
WithExec([]string{"sh", "-c", "apt-get update && apt-get install -y --no-install-recommends zip unzip wget && rm -rf /var/lib/apt/lists/*"}).
|
||||
WithEnvVariable("ANDROID_HOME", "/opt/android-sdk").
|
||||
WithEnvVariable("ANDROID_SDK_ROOT", "/opt/android-sdk").
|
||||
WithMountedCache("/opt/android-sdk", dag.CacheVolume("android-buildtools-"+toolsSlug)).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
"if [ ! -x \"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager\" ]; then",
|
||||
" mkdir -p \"$ANDROID_HOME/cmdline-tools\"",
|
||||
" cd \"$ANDROID_HOME/cmdline-tools\"",
|
||||
" wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip -O cli.zip",
|
||||
" unzip -q cli.zip",
|
||||
" rm -rf latest && mv cmdline-tools latest",
|
||||
" rm cli.zip",
|
||||
"fi",
|
||||
}, "\n")}).
|
||||
WithEnvVariable("PATH", "/opt/android-sdk/cmdline-tools/latest/bin:/opt/android-sdk/build-tools/"+buildTools+":${PATH}", dagger.ContainerWithEnvVariableOpts{Expand: true}).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
// SIGPIPE (141) on success — same reason as gradleImage.
|
||||
"yes | sdkmanager --licenses > /dev/null 2>&1 || true",
|
||||
"sdkmanager" + pkgs,
|
||||
}, "\n")})
|
||||
}
|
||||
|
||||
func (m *MobileAndroid) gradleImage(jdkVersion, compileSdk, buildTools string) *dagger.Container {
|
||||
if jdkVersion == "" {
|
||||
jdkVersion = "17"
|
||||
}
|
||||
if compileSdk == "" {
|
||||
compileSdk = "34"
|
||||
}
|
||||
if buildTools == "" {
|
||||
buildTools = defaultBuildTools
|
||||
}
|
||||
tools, toolsSlug := buildToolsList(buildTools)
|
||||
pkgs := ""
|
||||
for _, v := range tools {
|
||||
pkgs += " 'build-tools;" + v + "'"
|
||||
}
|
||||
return dag.Container().
|
||||
From(jdkImage(jdkVersion)).
|
||||
WithExec([]string{"sh", "-c", "apt-get update && apt-get install -y --no-install-recommends git unzip wget curl && rm -rf /var/lib/apt/lists/*"}).
|
||||
WithEnvVariable("ANDROID_HOME", "/opt/android-sdk").
|
||||
WithEnvVariable("ANDROID_SDK_ROOT", "/opt/android-sdk").
|
||||
// The SDK is public and pinned by version, so the volume is shared.
|
||||
//
|
||||
// NOTE ON WHAT THIS ACTUALLY SAVES. On the managed Jenkins agent it saves
|
||||
// NOTHING: that pod runs the engine as a sidecar with `/var/lib/dagger` on
|
||||
// an EmptyDir and `podRetention: Never`, so every cache volume dies with
|
||||
// the build and the SDK is re-downloaded each time. The mount earns its
|
||||
// place on a long-lived engine (a customer's own, or a future shared
|
||||
// runner) and is harmless otherwise — but do not read it as a per-build
|
||||
// speed-up here.
|
||||
//
|
||||
// It is also WRITABLE while the tenant's own `./gradlew` runs, and keyed
|
||||
// with no tenant component. "Public and immutable" is an assumption about
|
||||
// the contents, not an enforcement: on a persistent engine a build task
|
||||
// that overwrites `$ANDROID_HOME/build-tools/*/aapt2` poisons every later
|
||||
// build on that engine. Keying it per tenant, or mounting it read-only for
|
||||
// the build exec, is the fix when that engine exists.
|
||||
//
|
||||
// The DEPENDENCY cache is a different matter and is opt-in per tenant —
|
||||
// see `cacheKey` on Build.
|
||||
WithMountedCache("/opt/android-sdk", dag.CacheVolume("android-sdk-"+compileSdk+"-"+toolsSlug)).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
// Idempotent: the cache volume may already hold a complete SDK.
|
||||
"if [ ! -x \"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager\" ]; then",
|
||||
" mkdir -p \"$ANDROID_HOME/cmdline-tools\"",
|
||||
" cd \"$ANDROID_HOME/cmdline-tools\"",
|
||||
" wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip -O cli.zip",
|
||||
" unzip -q cli.zip",
|
||||
" rm -rf latest && mv cmdline-tools latest",
|
||||
" rm cli.zip",
|
||||
"fi",
|
||||
}, "\n")}).
|
||||
WithEnvVariable("PATH", "/opt/android-sdk/cmdline-tools/latest/bin:/opt/android-sdk/platform-tools:/opt/android-sdk/build-tools/"+buildTools+":${PATH}", dagger.ContainerWithEnvVariableOpts{Expand: true}).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
// `yes |` closes the pipe once sdkmanager stops reading, which makes
|
||||
// sdkmanager exit 141 (SIGPIPE) on success. That is not a failure, so
|
||||
// the licence step is the one place a non-zero status is tolerated —
|
||||
// and only for that specific, understood reason.
|
||||
"yes | sdkmanager --licenses > /dev/null 2>&1 || true",
|
||||
// This one is NOT tolerated: without the platform the project compiles
|
||||
// against, nothing downstream can work.
|
||||
fmt.Sprintf("sdkmanager 'platform-tools' 'platforms;android-%s'%s", compileSdk, pkgs),
|
||||
}, "\n")})
|
||||
}
|
||||
|
||||
// Build runs `./gradlew assemble<Variant>` (APK) and `bundle<Variant>` (AAB) and
|
||||
// returns a directory holding the artifacts under STABLE names.
|
||||
//
|
||||
// It returns a `*dagger.Directory`, not a struct of path strings. The previous
|
||||
// version returned `APKPath: "app/build/outputs/apk/release/app-release.apk"` —
|
||||
// a name it CONSTRUCTED rather than found — so nothing ever left the container,
|
||||
// and for any project that renames its outputs the guess was simply wrong. One
|
||||
// of the applications this platform onboards renames its APK to
|
||||
// `my app name-release_1.2.3_45.apk`, spaces and all. The artifacts are
|
||||
// therefore located by glob and copied to `/out/app.apk` and `/out/app.aab`, so
|
||||
// the caller has one predictable name to sign and publish; `/out/metadata.json`
|
||||
// carries the original names alongside the version identifiers.
|
||||
func (m *MobileAndroid) Build(
|
||||
ctx context.Context,
|
||||
// +defaultPath="."
|
||||
source *dagger.Directory,
|
||||
// release / debug / staging — any variant the project defines
|
||||
// +optional
|
||||
// +default="release"
|
||||
variant string,
|
||||
// Build the .aab bundle in addition to the .apk
|
||||
// +optional
|
||||
// +default=true
|
||||
bundle bool,
|
||||
// JDK version to build with
|
||||
// +optional
|
||||
// +default="17"
|
||||
jdk string,
|
||||
// Android SDK platform to install (the project's compileSdk)
|
||||
// +optional
|
||||
// +default="34"
|
||||
compileSdk string,
|
||||
// Android build-tools version to install
|
||||
// +optional
|
||||
// Android Build-Tools to install: a COMMA-SEPARATED LIST. Add the
|
||||
// version the project's AGP asks for when the build reports it missing
|
||||
// -- with `android.builder.sdkDownload=false` in force it names the
|
||||
// package instead of silently fetching it.
|
||||
// +default="34.0.0"
|
||||
buildTools string,
|
||||
// Opt-in Gradle dependency cache, namespaced by this key. Leave EMPTY to
|
||||
// disable caching entirely. A Gradle dependency cache can hold artifacts
|
||||
// pulled from a tenant's private Maven repository, so it is never shared
|
||||
// across tenants implicitly — pass the tenant id to get a per-tenant cache.
|
||||
// +optional
|
||||
cacheKey string,
|
||||
// Extra flags appended to the Gradle invocation, e.g.
|
||||
// "-Dorg.gradle.jvmargs=-Xmx900m -Dorg.gradle.workers.max=1" to fit a small
|
||||
// build agent.
|
||||
// +optional
|
||||
gradleArgs string,
|
||||
) (*dagger.Directory, error) {
|
||||
v := variantTask(variant)
|
||||
lower := strings.ToLower(strings.TrimSpace(variant))
|
||||
if lower == "" {
|
||||
lower = "release"
|
||||
}
|
||||
tasks := []string{fmt.Sprintf("assemble%s", v)}
|
||||
if bundle {
|
||||
tasks = append(tasks, fmt.Sprintf("bundle%s", v))
|
||||
}
|
||||
|
||||
// EVALUATE THE TOOLCHAIN BEFORE THE BUILD, so a toolchain failure says so.
|
||||
//
|
||||
// Dagger is lazy: without this, every failure in the whole chain surfaces
|
||||
// from the build exec below and is wrapped as "flutter build (release)
|
||||
// failed". Measured 2026-09-07 with --build-tools=99.0.0, which cannot
|
||||
// install: the operator was told the Flutter BUILD failed and handed
|
||||
// sdkmanager's "Warning: Failed to find package 'build-tools;99.0.0'" --
|
||||
// the right clue attached to the wrong stage.
|
||||
//
|
||||
// (sdkmanager exits 1 for a package that does not exist, and installs
|
||||
// NOTHING when a bad version is listed alongside a good one -- both
|
||||
// measured -- so the failure itself is already reliable. What was missing
|
||||
// was saying which stage produced it.)
|
||||
toolchain := m.gradleImage(jdk, compileSdk, buildTools)
|
||||
if _, err := toolchain.Sync(ctx); err != nil {
|
||||
return nil, fmt.Errorf("preparing the Android toolchain failed: %s", execDetail(err))
|
||||
}
|
||||
c := toolchain.WithMountedDirectory("/src", source)
|
||||
|
||||
// Set whether or not the dependency cache is SHARED: this is also where the
|
||||
// air-gap switch below has to live, and the module must not write a property
|
||||
// into the tenant's checked-out repository to set it.
|
||||
c = c.WithEnvVariable("GRADLE_USER_HOME", "/gradle-home")
|
||||
if strings.TrimSpace(cacheKey) != "" {
|
||||
c = c.WithMountedCache("/gradle-home", dag.CacheVolume("gradle-deps-"+cacheKey))
|
||||
}
|
||||
c = c.WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
"mkdir -p \"$GRADLE_USER_HOME\"",
|
||||
"grep -q '^android.builder.sdkDownload=' \"$GRADLE_USER_HOME/gradle.properties\" 2>/dev/null ||",
|
||||
" echo 'android.builder.sdkDownload=false' >> \"$GRADLE_USER_HOME/gradle.properties\"",
|
||||
}, "\n")})
|
||||
|
||||
// `--no-daemon` matters on a constrained agent: a Gradle daemon outlives the
|
||||
// build and holds its heap, which on a memory-capped container is the
|
||||
// difference between a completed build and an OOM kill of the next stage.
|
||||
build := c.WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
// DELETE THE PREVIOUS BUILD'S OUTPUT FIRST -- same reason as the sibling
|
||||
// Flutter module: the source comes from a Jenkins workspace, workspaces
|
||||
// are reused, and the collect step below takes the FIRST .apk/.aab it
|
||||
// finds. Scoped to the Gradle output directories the glob actually
|
||||
// reads, so no other part of the checkout is touched.
|
||||
"find /src -maxdepth 3 -type d -path '*/build/outputs' -exec rm -rf {} + 2>/dev/null || true",
|
||||
"cd /src",
|
||||
"chmod +x ./gradlew",
|
||||
fmt.Sprintf("./gradlew %s --no-daemon %s", strings.Join(tasks, " "), gradleArgs),
|
||||
}, "\n")})
|
||||
|
||||
if _, err := build.Stdout(ctx); err != nil {
|
||||
return nil, fmt.Errorf("gradle %s failed: %s", strings.Join(tasks, " "), execDetail(err))
|
||||
}
|
||||
|
||||
// Collect by glob. `-print -quit` takes the first match; a project with
|
||||
// multiple modules should name the one it wants via `variant`.
|
||||
collect := fmt.Sprintf(`set -eu
|
||||
# /out is EMPTIED first, not just created.
|
||||
#
|
||||
# The build exec above ran the project's own Gradle/Flutter scripts as root in
|
||||
# this same container, so anything it chose to write to /out is still here and
|
||||
# would be exported as if this module had produced it. That matters because the
|
||||
# pipeline decides what to publish by FILENAME: a repo that plants
|
||||
# /out/signed-app.aab during its build would get an artefact no Sign stage ever
|
||||
# touched uploaded to the tenant's registry, and reported as signed.
|
||||
#
|
||||
# Emptying the directory makes the export contain exactly what the lines below
|
||||
# put there. It costs nothing: /out is this module's own output staging area,
|
||||
# never a mount and never the caller's directory.
|
||||
rm -rf /out
|
||||
mkdir -p /out
|
||||
apk="$(find /src -path '*/build/outputs/apk/%[1]s/*.apk' -print -quit 2>/dev/null || true)"
|
||||
aab="$(find /src -path '*/build/outputs/bundle/%[1]s/*.aab' -print -quit 2>/dev/null || true)"
|
||||
if [ -z "$apk" ] && [ -z "$aab" ]; then
|
||||
echo "no .apk or .aab found under */build/outputs/**/%[1]s/ after a successful gradle run" >&2
|
||||
exit 1
|
||||
fi
|
||||
apk_name=""
|
||||
aab_name=""
|
||||
if [ -n "$apk" ]; then cp "$apk" /out/app.apk; apk_name="$(basename "$apk" | tr -cd 'A-Za-z0-9._ -')"; fi
|
||||
if [ -n "$aab" ]; then cp "$aab" /out/app.aab; aab_name="$(basename "$aab" | tr -cd 'A-Za-z0-9._ -')"; fi
|
||||
# aapt2 is the authority on what the built artifact actually declares — reading
|
||||
# it back from the binary cannot drift from the build the way parsing Gradle
|
||||
# files can. Only an APK carries a readable badging block, so a bundle-only
|
||||
# build leaves the version fields empty rather than guessing.
|
||||
app_id=""; ver_name=""; ver_code=""
|
||||
if [ -f /out/app.apk ]; then
|
||||
badging="$(aapt2 dump badging /out/app.apk 2>/dev/null || true)"
|
||||
app_id="$(printf '%%s' "$badging" | sed -n "s/^package: name='\([^']*\)'.*/\1/p" | head -1 | tr -cd 'A-Za-z0-9._-')"
|
||||
ver_code="$(printf '%%s' "$badging" | sed -n "s/^package:.*versionCode='\([^']*\)'.*/\1/p" | head -1 | tr -cd '0-9')"
|
||||
# SANITISED, and this is the module the finding was written against.
|
||||
# version_name is read back out by the pipeline and used as a PATH SEGMENT in
|
||||
# the upload (tenant/service/version/...) and as a VALUE in the report JSON.
|
||||
# An app that declares versionName ../../otherteam/prod/9.9 would have its
|
||||
# artefact land on another team's path -- curl normalises dot segments, it
|
||||
# does not reject them -- and one containing a quote would rewrite the report
|
||||
# body. ver_code is interpolated UNQUOTED as "version_code":$ver_code, so it
|
||||
# is held to digits only.
|
||||
ver_name="$(printf '%%s' "$badging" | sed -n "s/^package:.*versionName='\([^']*\)'.*/\1/p" | head -1 | tr -cd 'A-Za-z0-9._-')"
|
||||
fi
|
||||
: "${ver_code:=0}"
|
||||
cat > /out/metadata.json <<JSON
|
||||
{"application_id":"$app_id","version_name":"$ver_name","version_code":$ver_code,"apk_name":"$apk_name","aab_name":"$aab_name"}
|
||||
JSON
|
||||
cat /out/metadata.json
|
||||
`, lower)
|
||||
|
||||
out := build.WithExec([]string{"sh", "-c", collect})
|
||||
if _, err := out.Stdout(ctx); err != nil {
|
||||
return nil, fmt.Errorf("collecting android artifacts: %s", execDetail(err))
|
||||
}
|
||||
return out.Directory("/out"), nil
|
||||
}
|
||||
|
||||
// Metadata re-reads `/out/metadata.json` from a directory produced by Build.
|
||||
//
|
||||
// The distribute step needs the version code, and it runs in a different
|
||||
// invocation from the build — so the number has to survive as data rather than
|
||||
// as a variable in someone's shell.
|
||||
func (m *MobileAndroid) Metadata(
|
||||
ctx context.Context,
|
||||
// Directory produced by `build`
|
||||
artifacts *dagger.Directory,
|
||||
) (*AndroidBuildMetadata, error) {
|
||||
raw, err := artifacts.File("metadata.json").Contents(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading metadata.json: %w", err)
|
||||
}
|
||||
meta := &AndroidBuildMetadata{}
|
||||
if err := json.Unmarshal([]byte(raw), meta); err != nil {
|
||||
return nil, fmt.Errorf("parsing metadata.json (%q): %w", raw, err)
|
||||
}
|
||||
return meta, nil
|
||||
}
|
||||
|
||||
// Test runs Gradle JVM unit tests and FAILS when they fail.
|
||||
//
|
||||
// The previous version marked the run failed when the log merely CONTAINED the
|
||||
// substring "fail" — a test named `…_fails_when_empty` was enough to turn a
|
||||
// green run red — and could not see a real failure that wrote only to stderr.
|
||||
// Gradle's own exit code answers the question exactly.
|
||||
func (m *MobileAndroid) Test(
|
||||
ctx context.Context,
|
||||
// +defaultPath="."
|
||||
source *dagger.Directory,
|
||||
// +optional
|
||||
// +default="testReleaseUnitTest"
|
||||
task string,
|
||||
// +optional
|
||||
// +default="17"
|
||||
jdk string,
|
||||
// +optional
|
||||
// +default="34"
|
||||
compileSdk string,
|
||||
// +optional
|
||||
// +default="34.0.0"
|
||||
buildTools string,
|
||||
// +optional
|
||||
cacheKey string,
|
||||
// +optional
|
||||
gradleArgs string,
|
||||
) (*AndroidTestResult, error) {
|
||||
c := m.gradleImage(jdk, compileSdk, buildTools).WithMountedDirectory("/src", source)
|
||||
if strings.TrimSpace(cacheKey) != "" {
|
||||
c = c.WithEnvVariable("GRADLE_USER_HOME", "/gradle-home").
|
||||
WithMountedCache("/gradle-home", dag.CacheVolume("gradle-deps-"+cacheKey))
|
||||
}
|
||||
logs, err := c.WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
"cd /src",
|
||||
"chmod +x ./gradlew",
|
||||
fmt.Sprintf("./gradlew %s --no-daemon %s", task, gradleArgs),
|
||||
}, "\n")}).Stdout(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gradle %s failed: %s", task, execDetail(err))
|
||||
}
|
||||
return &AndroidTestResult{Task: task, Logs: logs, Success: true}, nil
|
||||
}
|
||||
|
||||
// Sign signs an APK/AAB with apksigner and returns the SIGNED FILE.
|
||||
//
|
||||
// Returning a file rather than a path string is the whole point: the caller
|
||||
// exports it and publishes that, instead of publishing whatever happened to be
|
||||
// sitting at a path the module guessed.
|
||||
//
|
||||
// An AAB is signed with jarsigner, not apksigner — apksigner only understands
|
||||
// the APK format and rejects a bundle. The previous version sent both through
|
||||
// apksigner and swallowed the resulting error.
|
||||
func (m *MobileAndroid) Sign(
|
||||
ctx context.Context,
|
||||
// .apk or .aab to sign
|
||||
artifact *dagger.File,
|
||||
// JKS / PKCS12 keystore (binary)
|
||||
keystore *dagger.Secret,
|
||||
keystorePassword *dagger.Secret,
|
||||
keyAlias string,
|
||||
keyPassword *dagger.Secret,
|
||||
// +optional
|
||||
// +default="17"
|
||||
jdk string,
|
||||
// +optional
|
||||
// +default="34.0.0"
|
||||
buildTools string,
|
||||
) (*dagger.File, error) {
|
||||
name, err := artifact.Name(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading artifact name: %w", err)
|
||||
}
|
||||
// IN and OUT are DIFFERENT PATHS, and that is load-bearing.
|
||||
//
|
||||
// Both signers default to signing IN PLACE, and `WithMountedFile` puts the
|
||||
// artifact on its own mount — so an in-place sign fails on the rename across
|
||||
// that mount point, not on anything to do with the key. MEASURED: jarsigner
|
||||
// answered `attempt to rename /work/app.aab to /work/app.aab.orig failed`,
|
||||
// and it took a real run to see it because the mount only exists at runtime.
|
||||
//
|
||||
// Writing to a separate path fixes it for both signers AND makes the verify
|
||||
// meaningful: it now runs against exactly the bytes this function returns,
|
||||
// rather than against a path that may or may not have been rewritten.
|
||||
base := "app.apk"
|
||||
isBundle := strings.HasSuffix(strings.ToLower(name), ".aab")
|
||||
if isBundle {
|
||||
base = "app.aab"
|
||||
}
|
||||
in := "/work/in/" + base
|
||||
out := "/work/out/" + base
|
||||
|
||||
signCmd := strings.Join([]string{
|
||||
"apksigner sign --ks /work/keystore.jks",
|
||||
"--ks-pass env:KEYSTORE_PASSWORD",
|
||||
"--key-pass env:KEY_PASSWORD",
|
||||
"--ks-key-alias \"$KEY_ALIAS\"",
|
||||
"--out", out,
|
||||
in,
|
||||
}, " ")
|
||||
verifyCmd := fmt.Sprintf("apksigner verify --print-certs %s", out)
|
||||
// STRIP FIRST, then sign. Empty for an APK; the whole point for a bundle.
|
||||
prepare := "true"
|
||||
if isBundle {
|
||||
// `jarsigner -signedjar` ADDS a signer, it does not replace one, and
|
||||
// Gradle has already signed this bundle -- with the ANDROID DEBUG KEY
|
||||
// when the project declares no signingConfig. Measured 2026-09-07 on the
|
||||
// sibling Flutter lane: the signed .aab carried BOTH
|
||||
// META-INF/RELEASE-.SF and META-INF/ANDROIDD.SF, and
|
||||
// `jarsigner -verify -certs` reported both identities. The APK path does
|
||||
// not need this because apksigner rebuilds the v1 block -- which is
|
||||
// exactly why the defect survived: the two formats behave differently
|
||||
// under the same-looking call.
|
||||
//
|
||||
// Stripping happens on a COPY: `zip -d` rewrites the archive in place,
|
||||
// and `in` is a Dagger mount, where in-place rewrites fail the same way
|
||||
// in-place signing does.
|
||||
prepare = strings.Join([]string{
|
||||
"mkdir -p /work/strip",
|
||||
"cp " + in + " /work/strip/" + base,
|
||||
"zip -q -d /work/strip/" + base + " 'META-INF/*.SF' 'META-INF/*.RSA' 'META-INF/*.DSA' 'META-INF/*.EC' >/dev/null 2>&1 || true",
|
||||
}, "\n")
|
||||
signCmd = strings.Join([]string{
|
||||
"jarsigner -keystore /work/keystore.jks",
|
||||
"-storepass:env KEYSTORE_PASSWORD",
|
||||
"-keypass:env KEY_PASSWORD",
|
||||
"-sigalg SHA256withRSA -digestalg SHA-256",
|
||||
"-signedjar", out,
|
||||
"/work/strip/" + base, "\"$KEY_ALIAS\"",
|
||||
}, " ")
|
||||
verifyCmd = fmt.Sprintf("jarsigner -verify -certs %s", out)
|
||||
}
|
||||
|
||||
// TWO GATES ON THE RESULT, both inside the container that produced it: the
|
||||
// artefact must carry ONE signer, and that signer must not be the debug
|
||||
// identity. Checked here rather than by whoever looks at the artefact later,
|
||||
// because by then it has been published.
|
||||
//
|
||||
// The signer count is asked in the way each FORMAT answers it, which is not
|
||||
// pedantry. A bundle is a JAR, so one signer means exactly one
|
||||
// META-INF/*.SF. An APK is not: v2/v3 signatures live in the APK Signing
|
||||
// Block, and apksigner omits the v1 (META-INF) block entirely when the
|
||||
// project's minSdk is 24 or higher. Counting .SF files on an APK would
|
||||
// therefore REFUSE a perfectly good modern release -- the gate would fire on
|
||||
// the projects most likely to be shipping.
|
||||
//
|
||||
// For the APK it counts the "Signer #N certificate DN:" lines rather than
|
||||
// apksigner's "Number of signers:" summary: that summary is printed only
|
||||
// under --verbose, and the first version of this gate grepped for it,
|
||||
// counted 0, and refused a correctly signed APK. Also measured, also only
|
||||
// visible by running it.
|
||||
countCmd := "apksigner verify --print-certs " + out + " 2>/dev/null | grep -c '^Signer #[0-9]* certificate DN:' || true"
|
||||
expectation := "exactly one signer certificate"
|
||||
if isBundle {
|
||||
countCmd = "unzip -l " + out + " | awk '{print $NF}' | grep -ciE '^META-INF/.*[.]SF$' || true"
|
||||
expectation = "exactly one META-INF/*.SF block"
|
||||
}
|
||||
assertCmd := strings.Join([]string{
|
||||
"signers=\"$(" + countCmd + ")\"",
|
||||
"if [ \"$signers\" != \"1\" ]; then",
|
||||
" echo \"REFUSING: the signed artefact does not show " + expectation + " (got $signers).\" >&2",
|
||||
" echo \"More than one means an earlier signature survived; zero means nothing signed it.\" >&2",
|
||||
" exit 1",
|
||||
"fi",
|
||||
"if " + verifyCmd + " 2>&1 | grep -q 'CN=Android Debug'; then",
|
||||
" echo \"REFUSING: the signed artefact still carries the ANDROID DEBUG identity.\" >&2",
|
||||
" echo \"The debug key is public and anyone can re-sign with it, so an artefact\" >&2",
|
||||
" echo \"bearing it is not release-signed no matter what else verifies.\" >&2",
|
||||
" exit 1",
|
||||
"fi",
|
||||
}, "\n")
|
||||
|
||||
c := m.signerImage(jdk, buildTools).
|
||||
WithMountedFile(in, artifact).
|
||||
WithMountedSecret("/work/keystore.jks", keystore).
|
||||
WithSecretVariable("KEYSTORE_PASSWORD", keystorePassword).
|
||||
WithSecretVariable("KEY_PASSWORD", keyPassword).
|
||||
WithEnvVariable("KEY_ALIAS", keyAlias).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
"mkdir -p /work/out",
|
||||
prepare,
|
||||
signCmd,
|
||||
// Verifying is not ceremony. `apksigner sign` can exit 0 having
|
||||
// produced an artifact no store will accept (wrong scheme, missing
|
||||
// v2 block); the verify is what turns that into a failed stage here
|
||||
// rather than a rejected upload an hour later.
|
||||
verifyCmd,
|
||||
assertCmd,
|
||||
}, "\n")})
|
||||
|
||||
if _, err := c.Stdout(ctx); err != nil {
|
||||
return nil, fmt.Errorf("signing %s failed: %s", name, execDetail(err))
|
||||
}
|
||||
return c.File(out), nil
|
||||
}
|
||||
|
||||
// PublishRaw uploads a built artifact to a RAW (non-OCI) repository — Nexus,
|
||||
// Artifactory generic, or anything else that takes an HTTP PUT.
|
||||
//
|
||||
// This is what stores a mobile artifact. There is no connector action for it and
|
||||
// there should not be: a connector is how the CONTROL PLANE manages a registry,
|
||||
// while an upload is something the BUILD does. Nexus serves raw content under
|
||||
// its path-based layout (`{url}/repository/{repo}/{path}`), which is reachable
|
||||
// by an ordinary HTTP client — unlike `docker push`, which needs a dedicated
|
||||
// connector port because the docker client pings `/v2/` at the host root.
|
||||
//
|
||||
// Returns the URL the artifact now lives at, so the caller can record it.
|
||||
func (m *MobileAndroid) PublishRaw(
|
||||
ctx context.Context,
|
||||
// The file to upload
|
||||
artifact *dagger.File,
|
||||
// Registry base URL, e.g. http://nexus.tools.svc:8081
|
||||
url string,
|
||||
// Raw repository name, e.g. "mobile-artifacts"
|
||||
repository string,
|
||||
// Path within the repository, e.g. "acme/field-app/1.3.74/app.aab"
|
||||
path string,
|
||||
// Registry username
|
||||
username string,
|
||||
// Registry password
|
||||
password *dagger.Secret,
|
||||
// Accept a self-signed / plain-HTTP endpoint. A managed registry on a
|
||||
// private cluster with no ingress host has no certificate to present.
|
||||
// +optional
|
||||
insecure bool,
|
||||
) (string, error) {
|
||||
base := strings.TrimRight(strings.TrimSpace(url), "/")
|
||||
repo := strings.Trim(strings.TrimSpace(repository), "/")
|
||||
rel := strings.TrimLeft(strings.TrimSpace(path), "/")
|
||||
if base == "" || repo == "" || rel == "" {
|
||||
return "", fmt.Errorf("publish-raw needs --url, --repository and --path (got url=%q repository=%q path=%q)", url, repo, rel)
|
||||
}
|
||||
// A dot segment walks out of the tenant prefix. curl NORMALISES `..`, it does
|
||||
// not reject it, so `<tenant>/<svc>/1.0/../../<other>/x` resolves to another
|
||||
// tenant's path in a shared raw repository — and that prefix is the only
|
||||
// isolation the upload has. The caller sanitises the version it builds this
|
||||
// from; this refuses independently, because a module is used by more than
|
||||
// the one template that ships with it.
|
||||
for _, seg := range strings.Split(rel, "/") {
|
||||
if seg == ".." {
|
||||
return "", fmt.Errorf("publish-raw refuses a '..' segment in --path (got %q)", rel)
|
||||
}
|
||||
}
|
||||
// The REPOSITORY name too, and for the same reason. It sits one segment
|
||||
// above the tenant prefix in the URL, so `--repository=..` yields
|
||||
// `<base>/repository/../<tenant>/…` which curl normalises to
|
||||
// `<base>/<tenant>/…` — out of the repository namespace entirely. Unlike
|
||||
// the tenant and service segments, this value is not platform-resolved: it
|
||||
// comes from the caller's spec, so the module cannot assume the template
|
||||
// vetted it.
|
||||
if repo == "." || repo == ".." || strings.Trim(repo, ".") == "" {
|
||||
return "", fmt.Errorf("publish-raw refuses a dot segment as --repository (got %q)", repository)
|
||||
}
|
||||
target := fmt.Sprintf("%s/repository/%s/%s", base, repo, rel)
|
||||
|
||||
// The URL travels as an ENVIRONMENT VARIABLE, never interpolated into the
|
||||
// command string.
|
||||
//
|
||||
// It used to be pasted in with `%q`, which escapes `"` and `\` and leaves
|
||||
// `$` and backticks intact — and the result sat in a shell double-quoted
|
||||
// position. Any `$(…)` reaching `url`, `repository` or `path` therefore
|
||||
// executed in THIS container, which is the one holding REG_PASS. And these
|
||||
// values are reachable: `path` is built from the artefact's own
|
||||
// `versionName`, read out of a binary the build just produced.
|
||||
//
|
||||
// `"$UPLOAD_URL"` is quoted and a parameter expansion's RESULT is not
|
||||
// re-scanned for substitutions, so the value cannot become code however it
|
||||
// is shaped.
|
||||
//
|
||||
// `--fail-with-body` turns an HTTP 4xx/5xx into a non-zero exit AND still
|
||||
// prints what the server said. Without a failure flag curl exits 0 on a 401
|
||||
// and the pipeline records a publish that never happened.
|
||||
script := `set -eu
|
||||
if [ -n "${REG_INSECURE:-}" ]; then
|
||||
curl --fail-with-body -sS --insecure -u "$REG_USER:$REG_PASS" --upload-file /work/artifact "$UPLOAD_URL"
|
||||
else
|
||||
curl --fail-with-body -sS -u "$REG_USER:$REG_PASS" --upload-file /work/artifact "$UPLOAD_URL"
|
||||
fi
|
||||
echo
|
||||
echo "published: $UPLOAD_URL"`
|
||||
|
||||
c := dag.Container().
|
||||
From("curlimages/curl:8.11.1").
|
||||
WithMountedFile("/work/artifact", artifact).
|
||||
WithEnvVariable("REG_USER", username).
|
||||
WithEnvVariable("UPLOAD_URL", target).
|
||||
WithSecretVariable("REG_PASS", password)
|
||||
if insecure {
|
||||
c = c.WithEnvVariable("REG_INSECURE", "1")
|
||||
}
|
||||
c = c.WithExec([]string{"sh", "-c", script})
|
||||
|
||||
if _, err := c.Stdout(ctx); err != nil {
|
||||
return "", fmt.Errorf("publishing to %s failed: %s", target, execDetail(err))
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
// Distribute uploads the AAB to Play Console using Fastlane `supply`.
|
||||
func (m *MobileAndroid) Distribute(
|
||||
ctx context.Context,
|
||||
aab *dagger.File,
|
||||
// internal | alpha | beta | production
|
||||
// +optional
|
||||
// +default="internal"
|
||||
track string,
|
||||
// Service-account JSON for the Play Developer API
|
||||
serviceAccountJSON *dagger.Secret,
|
||||
packageName string,
|
||||
) (string, error) {
|
||||
c := dag.Container().
|
||||
From("ruby:3.3-slim").
|
||||
WithExec([]string{"sh", "-c", "apt-get update && apt-get install -y --no-install-recommends git curl && rm -rf /var/lib/apt/lists/*"}).
|
||||
WithExec([]string{"gem", "install", "fastlane", "--no-document"}).
|
||||
WithMountedFile("/work/app.aab", aab).
|
||||
WithMountedSecret("/work/sa.json", serviceAccountJSON).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
strings.Join([]string{
|
||||
"fastlane run supply",
|
||||
fmt.Sprintf("track:%s", track),
|
||||
fmt.Sprintf("package_name:%s", packageName),
|
||||
"aab:/work/app.aab",
|
||||
"json_key:/work/sa.json",
|
||||
"skip_upload_apk:true",
|
||||
"skip_upload_metadata:true",
|
||||
"skip_upload_images:true",
|
||||
"skip_upload_screenshots:true",
|
||||
}, " "),
|
||||
}, "\n")})
|
||||
|
||||
out, err := c.Stdout(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("play store upload to %s failed: %s", track, execDetail(err))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
# IntegraCI — Mobile Flutter Dagger Module
|
||||
|
||||
Build, test, sign and publish Flutter apps.
|
||||
|
||||
Separate from `mobile-android` on purpose: Flutter owns its own Gradle
|
||||
invocation, puts artefacts under `build/app/outputs/flutter-apk/`, and tests
|
||||
with the Dart runner. A Flutter repo handed the native Android module is given a
|
||||
Gradle project it does not have at its root.
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
dagger call build --source . --flutter-version 3.24.5 export --path ./mobile-out
|
||||
dagger call test --source .
|
||||
dagger call sign --artifact ./mobile-out/app.aab --keystore file:ks.jks \
|
||||
--keystore-password env:KS --key-alias upload --key-password env:KP \
|
||||
export --path ./mobile-out/signed-app.aab
|
||||
dagger call publish-raw --artifact ./mobile-out/signed-app.aab \
|
||||
--url http://nexus:8081 --repository mobile-artifacts \
|
||||
--path acme/app/1.0.0/app.aab --username ci --password env:PW
|
||||
```
|
||||
|
||||
`--flutter-version` is a property of the REPO. One application onboarded through
|
||||
this platform is pinned to `sdk: ">=2.15.1 <3.0.0"` and cannot build on a modern
|
||||
stable channel at all; pinning here is what lets that be stated rather than
|
||||
discovered.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "mobile-flutter",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,720 @@
|
||||
// Package main implements the IntegraCI mobile-flutter Dagger module.
|
||||
//
|
||||
// Flutter is not "Android with extra steps": the toolchain owns the Gradle
|
||||
// invocation, the artefact paths differ from a native project
|
||||
// (`build/app/outputs/flutter-apk/…` rather than `app/build/outputs/apk/…`),
|
||||
// and `flutter test` is a Dart runner, not a Gradle task. A Flutter repo handed
|
||||
// the native Android module is given a Gradle project it does not have at its
|
||||
// root — which is why this is a module of its own rather than a flag on that
|
||||
// one.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call build --source . export --path ./mobile-out
|
||||
// dagger call test --source .
|
||||
// dagger call sign --artifact ./mobile-out/app.aab --keystore file:ks.jks … export --path signed.aab
|
||||
// dagger call publish-raw --artifact ./mobile-out/app.aab --url http://nexus:8081 --repository raw-hosted …
|
||||
//
|
||||
// Every exec here is allowed to FAIL. See the sibling mobile-android module for
|
||||
// why that sentence needs writing down: both modules used to end every command
|
||||
// in `|| true` and infer success by grepping stdout, which cannot fail.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"dagger/mobile-flutter/internal/dagger"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MobileFlutter is the IntegraCI Flutter pipeline module.
|
||||
type MobileFlutter struct{}
|
||||
|
||||
// FlutterBuildMetadata is what the build could learn about its own artefact.
|
||||
type FlutterBuildMetadata struct {
|
||||
ApplicationID string `json:"application_id,omitempty"`
|
||||
VersionName string `json:"version_name,omitempty"`
|
||||
VersionCode int `json:"version_code,omitempty"`
|
||||
APKName string `json:"apk_name,omitempty"`
|
||||
AABName string `json:"aab_name,omitempty"`
|
||||
}
|
||||
|
||||
// FlutterTestResult summarises a `flutter test` run.
|
||||
type FlutterTestResult struct {
|
||||
Logs string `json:"logs,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
func execDetail(err error) string {
|
||||
var exec *dagger.ExecError
|
||||
if !errors.As(err, &exec) {
|
||||
return err.Error()
|
||||
}
|
||||
out := strings.TrimSpace(exec.Stderr)
|
||||
if out == "" {
|
||||
out = strings.TrimSpace(exec.Stdout)
|
||||
}
|
||||
const maxDetail = 4000
|
||||
if len(out) > maxDetail {
|
||||
out = "…" + out[len(out)-maxDetail:]
|
||||
}
|
||||
if out == "" {
|
||||
return err.Error()
|
||||
}
|
||||
return fmt.Sprintf("exit code %d\n%s", exec.ExitCode, out)
|
||||
}
|
||||
|
||||
// flutterImage returns a container with the Flutter SDK + Android SDK.
|
||||
//
|
||||
// `flutterVersion` is a REQUIRED-ish parameter with a conservative default
|
||||
// rather than "latest": a Flutter major upgrade changes the Dart language
|
||||
// version, and one of the applications this platform onboards is pinned to
|
||||
// `sdk: ">=2.15.1 <3.0.0"` — it cannot build on a modern channel at all. The
|
||||
// version a repo needs is a property of that repo.
|
||||
// signerImage is the SMALLEST image that can sign an artefact: a JDK (for
|
||||
// jarsigner) plus Android build-tools (for apksigner).
|
||||
//
|
||||
// WHY NOT flutterImage. Sign used to reuse the build image, which downloads the
|
||||
// entire Flutter SDK — **661 MB compressed** (measured 2026-09-06) — plus the
|
||||
// Android compile platform. Signing invokes neither `flutter` nor anything from
|
||||
// a platform: it reads a finished .apk/.aab. And the managed Jenkins agent runs
|
||||
// the engine on an EmptyDir with `podRetention: Never`, so no cache volume
|
||||
// survives the build and that download is paid EVERY time.
|
||||
func (m *MobileFlutter) signerImage(jdkVersion, buildTools string) *dagger.Container {
|
||||
if jdkVersion == "" {
|
||||
jdkVersion = "17"
|
||||
}
|
||||
if buildTools == "" {
|
||||
buildTools = defaultBuildTools
|
||||
}
|
||||
tools, toolsSlug := buildToolsList(buildTools)
|
||||
pkgs := ""
|
||||
for _, v := range tools {
|
||||
pkgs += " 'build-tools;" + v + "'"
|
||||
}
|
||||
return dag.Container().
|
||||
From(jdkImage(jdkVersion)).
|
||||
WithExec([]string{"sh", "-c", "apt-get update && apt-get install -y --no-install-recommends zip unzip wget && rm -rf /var/lib/apt/lists/*"}).
|
||||
WithEnvVariable("ANDROID_HOME", "/opt/android-sdk").
|
||||
WithEnvVariable("ANDROID_SDK_ROOT", "/opt/android-sdk").
|
||||
WithMountedCache("/opt/android-sdk", dag.CacheVolume("android-buildtools-"+toolsSlug)).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
"if [ ! -x \"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager\" ]; then",
|
||||
" mkdir -p \"$ANDROID_HOME/cmdline-tools\"",
|
||||
" cd \"$ANDROID_HOME/cmdline-tools\"",
|
||||
" wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip -O cli.zip",
|
||||
" unzip -q cli.zip",
|
||||
" rm -rf latest && mv cmdline-tools latest",
|
||||
" rm cli.zip",
|
||||
"fi",
|
||||
}, "\n")}).
|
||||
WithEnvVariable("PATH", "/opt/android-sdk/cmdline-tools/latest/bin:/opt/android-sdk/build-tools/"+tools[0]+":${PATH}", dagger.ContainerWithEnvVariableOpts{Expand: true}).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
"yes | sdkmanager --licenses > /dev/null 2>&1 || true",
|
||||
"sdkmanager" + pkgs,
|
||||
}, "\n")})
|
||||
}
|
||||
|
||||
// defaultJDKImage is pinned BY DIGEST, not by tag, and that is an air-gap
|
||||
// requirement rather than a style preference.
|
||||
//
|
||||
// Measured 2026-09-07: with the engine's network cut but its content store warm
|
||||
// from a previous build, `From("eclipse-temurin:17-jdk")` still failed::
|
||||
//
|
||||
// failed to resolve image "docker.io/library/eclipse-temurin:17-jdk":
|
||||
// Head "https://registry-1.docker.io/v2/library/eclipse-temurin/manifests/17-jdk":
|
||||
// dial tcp: lookup registry-1.docker.io: i/o timeout
|
||||
//
|
||||
// A TAG is mutable, so BuildKit must ask the registry which digest it points at
|
||||
// today -- every build, even when the bytes are already local. A DIGEST is the
|
||||
// content address: it resolves from the local store and needs no registry.
|
||||
//
|
||||
// The build therefore could not even START on an air-gapped agent, before any
|
||||
// SDK or dependency question arose. Pinning also removes a reproducibility hole
|
||||
// that has nothing to do with air-gap: a tag can move between two builds of the
|
||||
// same commit.
|
||||
//
|
||||
// To move to a newer JDK image: `docker pull eclipse-temurin:<tag>` then
|
||||
// `docker inspect --format '{{index .RepoDigests 0}}'`. This is the multi-arch
|
||||
// manifest-list digest, so it stays correct on any platform.
|
||||
const defaultJDKImage = "eclipse-temurin@sha256:a27c79d44326d5f689668df5fedfee487652066d2a91e172747056cc7fbee6fc"
|
||||
|
||||
// defaultJDKVersion is the JDK the digest above actually contains. Kept beside
|
||||
// it so the two cannot drift silently: a caller asking for a different JDK gets
|
||||
// the mutable tag and, with it, the registry round-trip described above.
|
||||
const defaultJDKVersion = "17"
|
||||
|
||||
// jdkImage returns the digest-pinned base for the default JDK and a plain tag
|
||||
// for anything else. A caller pinning a different JDK accepts the registry
|
||||
// round-trip that comes with a mutable reference -- see defaultJDKImage.
|
||||
func jdkImage(jdkVersion string) string {
|
||||
if jdkVersion == "" || jdkVersion == defaultJDKVersion {
|
||||
return defaultJDKImage
|
||||
}
|
||||
return fmt.Sprintf("eclipse-temurin:%s-jdk", jdkVersion)
|
||||
}
|
||||
|
||||
// defaultBuildTools is a LIST, and the second entry is the point of it.
|
||||
//
|
||||
// 34.0.0 is what this module's own tooling uses (`aapt2` in the collect step,
|
||||
// `apksigner` in Sign). 33.0.1 is what the Android Gradle plugin pinned by
|
||||
// Flutter 3.24.5's project template (AGP 8.1.0) asks for while the build runs.
|
||||
// Installing only the first is what made a real build reach out to
|
||||
// dl.google.com twenty minutes in -- fine on this box, fatal on an air-gapped
|
||||
// agent. Both are small (~60MB each) next to the SDKs already being installed.
|
||||
//
|
||||
// A project on a different AGP will want a different one; that is why this is a
|
||||
// parameter rather than a constant, and why `android.builder.sdkDownload=false`
|
||||
// is set as well: the build then FAILS naming the package instead of fetching
|
||||
// it, so the answer arrives in one line rather than after an air-gapped
|
||||
// deployment fails in production.
|
||||
const defaultBuildTools = "34.0.0,33.0.1"
|
||||
|
||||
// buildToolsList splits the comma-separated --build-tools into the versions to
|
||||
// install, plus a slug safe to use in a cache-volume key.
|
||||
//
|
||||
// A LIST, not one version, because the project decides which one Gradle asks
|
||||
// for and the module cannot see that decision. AGP picks a default from its own
|
||||
// version -- AGP 8.1.0, which Flutter 3.24.5's template pins, wants 33.0.1 --
|
||||
// and when the requested package is missing the Android Gradle plugin
|
||||
// DOWNLOADS it mid-build. Measured 2026-09-07 on a real Flutter release build::
|
||||
//
|
||||
// Checking the license for package Android SDK Build-Tools 33.0.1 ...
|
||||
// Installing Android SDK Build-Tools 33.0.1 in /opt/android-sdk/build-tools/33.0.1
|
||||
//
|
||||
// That is a silent network dependency in the middle of the longest stage, and
|
||||
// on an air-gapped agent it is a build that fails after twenty minutes with a
|
||||
// message about a licence. Listing the versions makes the toolchain explicit;
|
||||
// `android.builder.sdkDownload=false` (written into GRADLE_USER_HOME by Build)
|
||||
// makes a missing one fail
|
||||
// immediately and by name instead of being fetched.
|
||||
func buildToolsList(raw string) (versions []string, slug string) {
|
||||
for _, v := range strings.Split(raw, ",") {
|
||||
v = strings.TrimSpace(v)
|
||||
if v == "" {
|
||||
continue
|
||||
}
|
||||
versions = append(versions, v)
|
||||
}
|
||||
if len(versions) == 0 {
|
||||
versions = []string{defaultBuildTools}
|
||||
}
|
||||
return versions, strings.Join(versions, "_")
|
||||
}
|
||||
|
||||
func (m *MobileFlutter) flutterImage(flutterVersion, compileSdk, buildTools string) *dagger.Container {
|
||||
if flutterVersion == "" {
|
||||
flutterVersion = "3.24.5"
|
||||
}
|
||||
if compileSdk == "" {
|
||||
compileSdk = "34"
|
||||
}
|
||||
if buildTools == "" {
|
||||
buildTools = defaultBuildTools
|
||||
}
|
||||
tools, toolsSlug := buildToolsList(buildTools)
|
||||
pkgs := ""
|
||||
for _, v := range tools {
|
||||
pkgs += " 'build-tools;" + v + "'"
|
||||
}
|
||||
return dag.Container().
|
||||
From(defaultJDKImage).
|
||||
WithExec([]string{"sh", "-c", "apt-get update && apt-get install -y --no-install-recommends git unzip wget curl xz-utils && rm -rf /var/lib/apt/lists/*"}).
|
||||
WithEnvVariable("ANDROID_HOME", "/opt/android-sdk").
|
||||
WithEnvVariable("ANDROID_SDK_ROOT", "/opt/android-sdk").
|
||||
WithEnvVariable("FLUTTER_HOME", "/opt/flutter").
|
||||
// Both SDKs are public and pinned, so these volumes are shared.
|
||||
//
|
||||
// Same two caveats as the sibling mobile-android module. (1) On the managed
|
||||
// Jenkins agent this saves NOTHING: that pod runs the engine as a sidecar
|
||||
// with /var/lib/dagger on an EmptyDir and podRetention Never, so every
|
||||
// cache volume dies with the build. (2) On an engine where it DOES persist,
|
||||
// the mount is writable while the tenant's own build runs and is keyed with
|
||||
// no tenant component — "immutable" is an assumption about the contents,
|
||||
// not an enforcement. The Pub/Gradle DEPENDENCY caches are opt-in per
|
||||
// tenant (see cacheKey) because those can hold private packages.
|
||||
WithMountedCache("/opt/android-sdk", dag.CacheVolume("android-sdk-"+compileSdk+"-"+toolsSlug)).
|
||||
WithMountedCache("/opt/flutter", dag.CacheVolume("flutter-sdk-"+flutterVersion)).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
"if [ ! -x \"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager\" ]; then",
|
||||
" mkdir -p \"$ANDROID_HOME/cmdline-tools\"",
|
||||
" cd \"$ANDROID_HOME/cmdline-tools\"",
|
||||
" wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip -O cli.zip",
|
||||
" unzip -q cli.zip && rm -rf latest && mv cmdline-tools latest && rm cli.zip",
|
||||
"fi",
|
||||
"if [ ! -x \"$FLUTTER_HOME/bin/flutter\" ]; then",
|
||||
" rm -rf \"$FLUTTER_HOME\"/*",
|
||||
fmt.Sprintf(" wget -q https://storage.googleapis.com/flutter_infra_release/releases/stable/linux/flutter_linux_%s-stable.tar.xz -O /tmp/f.tar.xz", flutterVersion),
|
||||
" tar -xJf /tmp/f.tar.xz -C /opt && rm /tmp/f.tar.xz",
|
||||
"fi",
|
||||
}, "\n")}).
|
||||
// The FIRST listed version is the one on PATH: `aapt2` in the collect
|
||||
// step has to resolve to something, and the extra versions exist for
|
||||
// Gradle to find by path, not for us to call.
|
||||
WithEnvVariable("PATH", "/opt/flutter/bin:/opt/android-sdk/cmdline-tools/latest/bin:/opt/android-sdk/platform-tools:/opt/android-sdk/build-tools/"+tools[0]+":${PATH}", dagger.ContainerWithEnvVariableOpts{Expand: true}).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
// SIGPIPE (141) on success — see the sibling module. This is the only
|
||||
// tolerated non-zero status in this file.
|
||||
"yes | sdkmanager --licenses > /dev/null 2>&1 || true",
|
||||
fmt.Sprintf("sdkmanager 'platform-tools' 'platforms;android-%s'%s", compileSdk, pkgs),
|
||||
// Flutter refuses to run from a directory owned by another user.
|
||||
"git config --global --add safe.directory /opt/flutter",
|
||||
"flutter --version",
|
||||
}, "\n")})
|
||||
}
|
||||
|
||||
// Build runs `flutter build apk` and `flutter build appbundle`, returning a
|
||||
// directory with the artefacts under stable names plus `metadata.json`.
|
||||
func (m *MobileFlutter) Build(
|
||||
ctx context.Context,
|
||||
// +defaultPath="."
|
||||
source *dagger.Directory,
|
||||
// +optional
|
||||
// +default="release"
|
||||
buildMode string,
|
||||
// Also build the .aab
|
||||
// +optional
|
||||
// +default=true
|
||||
bundle bool,
|
||||
// Flutter SDK version — a property of the REPO, not of this module.
|
||||
// +optional
|
||||
// +default="3.24.5"
|
||||
flutterVersion string,
|
||||
// +optional
|
||||
// +default="34"
|
||||
compileSdk string,
|
||||
// +optional
|
||||
// Android Build-Tools to install: a COMMA-SEPARATED LIST.
|
||||
//
|
||||
// The default carries two because the Android Gradle plugin picks its
|
||||
// own version at build time and downloads it if absent -- measured
|
||||
// 2026-09-07: AGP 8.1.0 (what Flutter 3.24.5 pins) pulled 33.0.1 from
|
||||
// dl.google.com even though 34.0.0 was installed. Pre-installing both
|
||||
// removes that network call; `android.builder.sdkDownload=false` turns
|
||||
// any remaining one into an immediate, named failure.
|
||||
// +default="34.0.0,33.0.1"
|
||||
buildTools string,
|
||||
// Per-tenant Pub/Gradle dependency cache. Empty ⇒ no dependency cache.
|
||||
// +optional
|
||||
cacheKey string,
|
||||
// Extra flags for the flutter build invocation.
|
||||
// +optional
|
||||
buildArgs string,
|
||||
) (*dagger.Directory, error) {
|
||||
mode := strings.ToLower(strings.TrimSpace(buildMode))
|
||||
if mode == "" {
|
||||
mode = "release"
|
||||
}
|
||||
|
||||
// EVALUATE THE TOOLCHAIN BEFORE THE BUILD, so a toolchain failure says so.
|
||||
//
|
||||
// Dagger is lazy: without this, every failure in the whole chain surfaces
|
||||
// from the build exec below and is wrapped as "flutter build (release)
|
||||
// failed". Measured 2026-09-07 with --build-tools=99.0.0, which cannot
|
||||
// install: the operator was told the Flutter BUILD failed and handed
|
||||
// sdkmanager's "Warning: Failed to find package 'build-tools;99.0.0'" --
|
||||
// the right clue attached to the wrong stage.
|
||||
//
|
||||
// (sdkmanager exits 1 for a package that does not exist, and installs
|
||||
// NOTHING when a bad version is listed alongside a good one -- both
|
||||
// measured -- so the failure itself is already reliable. What was missing
|
||||
// was saying which stage produced it.)
|
||||
toolchain := m.flutterImage(flutterVersion, compileSdk, buildTools)
|
||||
if _, err := toolchain.Sync(ctx); err != nil {
|
||||
return nil, fmt.Errorf("preparing the Flutter/Android toolchain failed: %s", execDetail(err))
|
||||
}
|
||||
c := toolchain.WithMountedDirectory("/src", source)
|
||||
|
||||
// GRADLE_USER_HOME is set whether or not a dependency cache is shared,
|
||||
// because it is also where the air-gap switch below has to live -- Gradle
|
||||
// reads `$GRADLE_USER_HOME/gradle.properties` for every build, and the
|
||||
// module must not write into the tenant's checked-out repository to set a
|
||||
// property.
|
||||
c = c.WithEnvVariable("GRADLE_USER_HOME", "/gradle-home").
|
||||
WithEnvVariable("PUB_CACHE", "/pub-cache")
|
||||
if strings.TrimSpace(cacheKey) != "" {
|
||||
// SHARED and persistent: reuse across this tenant's builds. Keyed with
|
||||
// the tenant component precisely because these hold resolved
|
||||
// dependencies, which can be private packages.
|
||||
c = c.WithMountedCache("/pub-cache", dag.CacheVolume("pub-cache-"+cacheKey)).
|
||||
WithMountedCache("/gradle-home", dag.CacheVolume("gradle-deps-"+cacheKey))
|
||||
}
|
||||
|
||||
// STOP GRADLE FETCHING ANDROID PACKAGES MID-BUILD.
|
||||
//
|
||||
// Without this the Android Gradle plugin installs whatever SDK package it
|
||||
// finds missing, from dl.google.com, in the middle of the build. Measured
|
||||
// 2026-09-07: a release build downloaded Build-Tools 33.0.1 even though
|
||||
// 34.0.0 had been installed explicitly. Three things are wrong with that,
|
||||
// in ascending order: the toolchain is no longer the one the module
|
||||
// declared; the build silently depends on the public internet; and on an
|
||||
// air-gapped agent it fails after twenty minutes with a message about a
|
||||
// licence rather than about a missing package.
|
||||
//
|
||||
// `false` makes it fail immediately and say which package it wanted, which
|
||||
// is then added to --build-tools. Written into GRADLE_USER_HOME rather than
|
||||
// the project so nothing in the tenant's repository is modified.
|
||||
c = c.WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
"mkdir -p \"$GRADLE_USER_HOME\"",
|
||||
"grep -q '^android.builder.sdkDownload=' \"$GRADLE_USER_HOME/gradle.properties\" 2>/dev/null ||",
|
||||
" echo 'android.builder.sdkDownload=false' >> \"$GRADLE_USER_HOME/gradle.properties\"",
|
||||
}, "\n")})
|
||||
|
||||
steps := []string{
|
||||
"set -eu",
|
||||
// DELETE THE PREVIOUS BUILD'S OUTPUT FIRST.
|
||||
//
|
||||
// The source arrives from the agent's WORKSPACE, and Jenkins reuses
|
||||
// workspaces between builds -- so `build/` from the previous commit is
|
||||
// uploaded and mounted along with the code. The collect step then globs
|
||||
// for an .apk/.aab and takes the FIRST match (`-print -quit`), which can
|
||||
// be last week's artefact. A stale artefact that gets signed, reported
|
||||
// and published is worse than a failed build: everything downstream
|
||||
// looks correct.
|
||||
//
|
||||
// Scoped to exactly what collect globs over, so nothing else in the
|
||||
// tenant's checkout is touched. The mount is the container's view; the
|
||||
// agent's workspace on disk is not modified.
|
||||
"rm -rf /src/build",
|
||||
"cd /src",
|
||||
"flutter pub get",
|
||||
fmt.Sprintf("flutter build apk --%s %s", mode, buildArgs),
|
||||
}
|
||||
if bundle {
|
||||
steps = append(steps, fmt.Sprintf("flutter build appbundle --%s %s", mode, buildArgs))
|
||||
}
|
||||
build := c.WithExec([]string{"sh", "-c", strings.Join(steps, "\n")})
|
||||
if _, err := build.Stdout(ctx); err != nil {
|
||||
return nil, fmt.Errorf("flutter build (%s) failed: %s", mode, execDetail(err))
|
||||
}
|
||||
|
||||
collect := `set -eu
|
||||
# /out is EMPTIED first, not just created.
|
||||
#
|
||||
# The build exec above ran the project's own Gradle/Flutter scripts as root in
|
||||
# this same container, so anything it chose to write to /out is still here and
|
||||
# would be exported as if this module had produced it. That matters because the
|
||||
# pipeline decides what to publish by FILENAME: a repo that plants
|
||||
# /out/signed-app.aab during its build would get an artefact no Sign stage ever
|
||||
# touched uploaded to the tenant's registry, and reported as signed.
|
||||
#
|
||||
# Emptying the directory makes the export contain exactly what the lines below
|
||||
# put there. It costs nothing: /out is this module's own output staging area,
|
||||
# never a mount and never the caller's directory.
|
||||
rm -rf /out
|
||||
mkdir -p /out
|
||||
apk="$(find /src/build -path '*/flutter-apk/*.apk' -print -quit 2>/dev/null || true)"
|
||||
[ -n "$apk" ] || apk="$(find /src/build -path '*/outputs/apk/*/*.apk' -print -quit 2>/dev/null || true)"
|
||||
aab="$(find /src/build -path '*/outputs/bundle/*/*.aab' -print -quit 2>/dev/null || true)"
|
||||
if [ -z "$apk" ] && [ -z "$aab" ]; then
|
||||
echo "no .apk or .aab under /src/build after a successful flutter build" >&2
|
||||
exit 1
|
||||
fi
|
||||
apk_name=""; aab_name=""
|
||||
if [ -n "$apk" ]; then cp "$apk" /out/app.apk; apk_name="$(basename "$apk" | tr -cd 'A-Za-z0-9._ -')"; fi
|
||||
if [ -n "$aab" ]; then cp "$aab" /out/app.aab; aab_name="$(basename "$aab" | tr -cd 'A-Za-z0-9._ -')"; fi
|
||||
app_id=""; ver_name=""; ver_code=""
|
||||
if [ -f /out/app.apk ]; then
|
||||
badging="$(aapt2 dump badging /out/app.apk 2>/dev/null || true)"
|
||||
app_id="$(printf '%s' "$badging" | sed -n "s/^package: name='\([^']*\)'.*/\1/p" | head -1 | tr -cd 'A-Za-z0-9._-')"
|
||||
ver_code="$(printf '%s' "$badging" | sed -n "s/^package:.*versionCode='\([^']*\)'.*/\1/p" | head -1 | tr -cd '0-9')"
|
||||
# SANITISED: version_name becomes a PATH SEGMENT in the upload and a VALUE in
|
||||
# the report JSON. ../../otherteam/prod/9.9 would land the artefact on another
|
||||
# team's path (curl normalises dot segments, it does not reject them), and a
|
||||
# quote would rewrite the report body. The charset excludes slash,
|
||||
# double-quote and backslash.
|
||||
ver_name="$(printf '%s' "$badging" | sed -n "s/^package:.*versionName='\([^']*\)'.*/\1/p" | head -1 | tr -cd 'A-Za-z0-9._-')"
|
||||
fi
|
||||
: "${ver_code:=0}"
|
||||
cat > /out/metadata.json <<JSON
|
||||
{"application_id":"$app_id","version_name":"$ver_name","version_code":$ver_code,"apk_name":"$apk_name","aab_name":"$aab_name"}
|
||||
JSON
|
||||
cat /out/metadata.json
|
||||
`
|
||||
out := build.WithExec([]string{"sh", "-c", collect})
|
||||
if _, err := out.Stdout(ctx); err != nil {
|
||||
return nil, fmt.Errorf("collecting flutter artifacts: %s", execDetail(err))
|
||||
}
|
||||
return out.Directory("/out"), nil
|
||||
}
|
||||
|
||||
// Metadata re-reads the metadata a Build produced.
|
||||
func (m *MobileFlutter) Metadata(
|
||||
ctx context.Context,
|
||||
artifacts *dagger.Directory,
|
||||
) (*FlutterBuildMetadata, error) {
|
||||
raw, err := artifacts.File("metadata.json").Contents(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading metadata.json: %w", err)
|
||||
}
|
||||
meta := &FlutterBuildMetadata{}
|
||||
if err := json.Unmarshal([]byte(raw), meta); err != nil {
|
||||
return nil, fmt.Errorf("parsing metadata.json (%q): %w", raw, err)
|
||||
}
|
||||
return meta, nil
|
||||
}
|
||||
|
||||
// Test runs `flutter test` and fails when the suite fails.
|
||||
func (m *MobileFlutter) Test(
|
||||
ctx context.Context,
|
||||
// +defaultPath="."
|
||||
source *dagger.Directory,
|
||||
// +optional
|
||||
// +default="3.24.5"
|
||||
flutterVersion string,
|
||||
// +optional
|
||||
// +default="34"
|
||||
compileSdk string,
|
||||
// +optional
|
||||
// +default="34.0.0"
|
||||
buildTools string,
|
||||
// +optional
|
||||
cacheKey string,
|
||||
) (*FlutterTestResult, error) {
|
||||
c := m.flutterImage(flutterVersion, compileSdk, buildTools).WithMountedDirectory("/src", source)
|
||||
if strings.TrimSpace(cacheKey) != "" {
|
||||
c = c.WithEnvVariable("PUB_CACHE", "/pub-cache").
|
||||
WithMountedCache("/pub-cache", dag.CacheVolume("pub-cache-"+cacheKey))
|
||||
}
|
||||
logs, err := c.WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"set -eu",
|
||||
"cd /src",
|
||||
"flutter pub get",
|
||||
"flutter analyze",
|
||||
"flutter test",
|
||||
}, "\n")}).Stdout(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("flutter analyze/test failed: %s", execDetail(err))
|
||||
}
|
||||
return &FlutterTestResult{Logs: logs, Success: true}, nil
|
||||
}
|
||||
|
||||
// Sign signs the built artefact and returns the SIGNED FILE.
|
||||
//
|
||||
// An .aab goes through jarsigner and an .apk through apksigner: apksigner only
|
||||
// understands the APK container and rejects a bundle outright.
|
||||
func (m *MobileFlutter) Sign(
|
||||
ctx context.Context,
|
||||
artifact *dagger.File,
|
||||
keystore *dagger.Secret,
|
||||
keystorePassword *dagger.Secret,
|
||||
keyAlias string,
|
||||
keyPassword *dagger.Secret,
|
||||
// JDK that runs jarsigner. Signing does not care which JDK built the app —
|
||||
// this exists so the parameter list matches the sibling mobile-android
|
||||
// module, whose Sign has carried it since it was written.
|
||||
// +optional
|
||||
// +default="17"
|
||||
jdk string,
|
||||
// +optional
|
||||
// +default="34.0.0"
|
||||
buildTools string,
|
||||
) (*dagger.File, error) {
|
||||
name, err := artifact.Name(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading artifact name: %w", err)
|
||||
}
|
||||
// IN and OUT are DIFFERENT PATHS — see the same note in mobile-android's
|
||||
// Sign. Both signers default to signing IN PLACE, and the artifact arrives
|
||||
// on its own `WithMountedFile` mount, so an in-place sign dies renaming
|
||||
// across that mount point (MEASURED: `attempt to rename /work/app.aab to
|
||||
// /work/app.aab.orig failed`) — a failure that has nothing to do with the
|
||||
// key and only appears in a real run.
|
||||
base := "app.apk"
|
||||
isBundle := strings.HasSuffix(strings.ToLower(name), ".aab")
|
||||
if isBundle {
|
||||
base = "app.aab"
|
||||
}
|
||||
in := "/work/in/" + base
|
||||
out := "/work/out/" + base
|
||||
|
||||
signCmd := strings.Join([]string{
|
||||
"apksigner sign --ks /work/keystore.jks",
|
||||
"--ks-pass env:KEYSTORE_PASSWORD",
|
||||
"--key-pass env:KEY_PASSWORD",
|
||||
"--ks-key-alias \"$KEY_ALIAS\"",
|
||||
"--out", out,
|
||||
in,
|
||||
}, " ")
|
||||
verifyCmd := fmt.Sprintf("apksigner verify --print-certs %s", out)
|
||||
// STRIP FIRST, then sign. Empty for an APK; the whole point for a bundle.
|
||||
prepare := "true"
|
||||
if isBundle {
|
||||
// A .aab is signed as a JAR, and `jarsigner -signedjar` ADDS a signer;
|
||||
// it does not replace one. Gradle already signed this bundle -- with the
|
||||
// ANDROID DEBUG KEY when the project declares no signingConfig -- so
|
||||
// signing on top left BOTH signers in place. Measured 2026-09-07 on a
|
||||
// bundle this module built and then signed::
|
||||
//
|
||||
// META-INF/RELEASE-.SF <- ours
|
||||
// META-INF/RELEASE-.RSA
|
||||
// META-INF/ANDROIDD.SF <- Gradle's debug key, still there
|
||||
// META-INF/ANDROIDD.RSA
|
||||
//
|
||||
// and `jarsigner -verify -certs` duly reported both
|
||||
// "CN=IntegraCI Release Proof" and "C=US, O=Android, CN=Android Debug".
|
||||
// A release bundle that still carries a debug signature is not a release
|
||||
// bundle: the debug key is public, so a second valid signer means the
|
||||
// artefact's provenance is not what the pipeline claims.
|
||||
//
|
||||
// The APK path does not need this -- apksigner rebuilds the v1 block and
|
||||
// the debug entry is gone -- which is exactly why the defect survived:
|
||||
// the two formats behave differently under the same-looking call.
|
||||
//
|
||||
// Stripping happens on a COPY. `zip -d` rewrites the archive in place,
|
||||
// and `in` is a Dagger mount, where in-place rewrites fail the same way
|
||||
// in-place signing does.
|
||||
prepare = strings.Join([]string{
|
||||
"mkdir -p /work/strip",
|
||||
"cp " + in + " /work/strip/" + base,
|
||||
"zip -q -d /work/strip/" + base + " 'META-INF/*.SF' 'META-INF/*.RSA' 'META-INF/*.DSA' 'META-INF/*.EC' >/dev/null 2>&1 || true",
|
||||
}, "\n")
|
||||
signCmd = strings.Join([]string{
|
||||
"jarsigner -keystore /work/keystore.jks",
|
||||
"-storepass:env KEYSTORE_PASSWORD",
|
||||
"-keypass:env KEY_PASSWORD",
|
||||
"-sigalg SHA256withRSA -digestalg SHA-256",
|
||||
"-signedjar", out,
|
||||
"/work/strip/" + base, "\"$KEY_ALIAS\"",
|
||||
}, " ")
|
||||
verifyCmd = fmt.Sprintf("jarsigner -verify -certs %s", out)
|
||||
}
|
||||
|
||||
// TWO GATES ON THE RESULT, both inside the container that produced it.
|
||||
//
|
||||
// Signing that "succeeded" is not the property anyone actually wants; the
|
||||
// property is that the artefact carries ONE signer and that it is not the
|
||||
// debug identity. Checked here rather than left to whoever looks at the
|
||||
// artefact later, because by then it has been published.
|
||||
//
|
||||
// The signer count is asked in the way each FORMAT answers it, which is not
|
||||
// pedantry. A bundle is a JAR, so one signer means exactly one
|
||||
// META-INF/*.SF. An APK is not: v2/v3 signatures live in the APK Signing
|
||||
// Block, and apksigner omits the v1 (META-INF) block entirely when the
|
||||
// project's minSdk is 24 or higher. Counting .SF files on an APK would
|
||||
// therefore REFUSE a perfectly good modern release -- the gate would fire on
|
||||
// the projects most likely to be shipping.
|
||||
//
|
||||
// For the APK it counts the "Signer #N certificate DN:" lines rather than
|
||||
// apksigner's "Number of signers:" summary: that summary is printed only
|
||||
// under --verbose, and the first version of this gate grepped for it,
|
||||
// counted 0, and refused a correctly signed APK. Also measured, also only
|
||||
// visible by running it.
|
||||
countCmd := "apksigner verify --print-certs " + out + " 2>/dev/null | grep -c '^Signer #[0-9]* certificate DN:' || true"
|
||||
expectation := "exactly one signer certificate"
|
||||
if isBundle {
|
||||
countCmd = "unzip -l " + out + " | awk '{print $NF}' | grep -ciE '^META-INF/.*[.]SF$' || true"
|
||||
expectation = "exactly one META-INF/*.SF block"
|
||||
}
|
||||
assertCmd := strings.Join([]string{
|
||||
"signers=\"$(" + countCmd + ")\"",
|
||||
"if [ \"$signers\" != \"1\" ]; then",
|
||||
" echo \"REFUSING: the signed artefact does not show " + expectation + " (got $signers).\" >&2",
|
||||
" echo \"More than one means an earlier signature survived; zero means nothing signed it.\" >&2",
|
||||
" exit 1",
|
||||
"fi",
|
||||
"if " + verifyCmd + " 2>&1 | grep -q 'CN=Android Debug'; then",
|
||||
" echo \"REFUSING: the signed artefact still carries the ANDROID DEBUG identity.\" >&2",
|
||||
" echo \"The debug key is public and anyone can re-sign with it, so an artefact\" >&2",
|
||||
" echo \"bearing it is not release-signed no matter what else verifies.\" >&2",
|
||||
" exit 1",
|
||||
"fi",
|
||||
}, "\n")
|
||||
|
||||
c := m.signerImage(jdk, buildTools).
|
||||
WithMountedFile(in, artifact).
|
||||
WithMountedSecret("/work/keystore.jks", keystore).
|
||||
WithSecretVariable("KEYSTORE_PASSWORD", keystorePassword).
|
||||
WithSecretVariable("KEY_PASSWORD", keyPassword).
|
||||
WithEnvVariable("KEY_ALIAS", keyAlias).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{"set -eu", "mkdir -p /work/out", prepare, signCmd, verifyCmd, assertCmd}, "\n")})
|
||||
|
||||
if _, err := c.Stdout(ctx); err != nil {
|
||||
return nil, fmt.Errorf("signing %s failed: %s", name, execDetail(err))
|
||||
}
|
||||
return c.File(out), nil
|
||||
}
|
||||
|
||||
// PublishRaw uploads the artefact to a raw (non-OCI) repository such as Nexus.
|
||||
//
|
||||
// Identical in shape to the mobile-android module's: a Dagger module is its own
|
||||
// deployable unit and cannot import a sibling, so the two carry the same twenty
|
||||
// lines rather than a shared package that neither could resolve.
|
||||
func (m *MobileFlutter) PublishRaw(
|
||||
ctx context.Context,
|
||||
artifact *dagger.File,
|
||||
url string,
|
||||
repository string,
|
||||
path string,
|
||||
username string,
|
||||
password *dagger.Secret,
|
||||
// +optional
|
||||
insecure bool,
|
||||
) (string, error) {
|
||||
base := strings.TrimRight(strings.TrimSpace(url), "/")
|
||||
repo := strings.Trim(strings.TrimSpace(repository), "/")
|
||||
rel := strings.TrimLeft(strings.TrimSpace(path), "/")
|
||||
if base == "" || repo == "" || rel == "" {
|
||||
return "", fmt.Errorf("publish-raw needs --url, --repository and --path (got url=%q repository=%q path=%q)", url, repo, rel)
|
||||
}
|
||||
// A dot segment walks out of the tenant prefix. curl NORMALISES `..`, it does
|
||||
// not reject it, so `<tenant>/<svc>/1.0/../../<other>/x` resolves to another
|
||||
// tenant's path in a shared raw repository — and that prefix is the only
|
||||
// isolation the upload has. The caller sanitises the version it builds this
|
||||
// from; this refuses independently, because a module is used by more than
|
||||
// the one template that ships with it.
|
||||
for _, seg := range strings.Split(rel, "/") {
|
||||
if seg == ".." {
|
||||
return "", fmt.Errorf("publish-raw refuses a '..' segment in --path (got %q)", rel)
|
||||
}
|
||||
}
|
||||
// The REPOSITORY name too, and for the same reason. It sits one segment
|
||||
// above the tenant prefix in the URL, so `--repository=..` yields
|
||||
// `<base>/repository/../<tenant>/…` which curl normalises to
|
||||
// `<base>/<tenant>/…` — out of the repository namespace entirely. Unlike
|
||||
// the tenant and service segments, this value is not platform-resolved: it
|
||||
// comes from the caller's spec, so the module cannot assume the template
|
||||
// vetted it.
|
||||
if repo == "." || repo == ".." || strings.Trim(repo, ".") == "" {
|
||||
return "", fmt.Errorf("publish-raw refuses a dot segment as --repository (got %q)", repository)
|
||||
}
|
||||
target := fmt.Sprintf("%s/repository/%s/%s", base, repo, rel)
|
||||
|
||||
// The URL travels as an ENVIRONMENT VARIABLE, never interpolated into the
|
||||
// command string — see the sibling mobile-android module for the whole
|
||||
// reasoning. Short version: `%q` leaves `$` and backticks intact, the result
|
||||
// sat in a shell double-quoted position, and `path` is built from the
|
||||
// artefact's own `versionName`. `"$UPLOAD_URL"` is quoted and an expansion's
|
||||
// result is not re-scanned, so the value cannot become code.
|
||||
script := `set -eu
|
||||
if [ -n "${REG_INSECURE:-}" ]; then
|
||||
curl --fail-with-body -sS --insecure -u "$REG_USER:$REG_PASS" --upload-file /work/artifact "$UPLOAD_URL"
|
||||
else
|
||||
curl --fail-with-body -sS -u "$REG_USER:$REG_PASS" --upload-file /work/artifact "$UPLOAD_URL"
|
||||
fi
|
||||
echo
|
||||
echo "published: $UPLOAD_URL"`
|
||||
|
||||
c := dag.Container().
|
||||
From("curlimages/curl:8.11.1").
|
||||
WithMountedFile("/work/artifact", artifact).
|
||||
WithEnvVariable("REG_USER", username).
|
||||
WithEnvVariable("UPLOAD_URL", target).
|
||||
WithSecretVariable("REG_PASS", password)
|
||||
if insecure {
|
||||
c = c.WithEnvVariable("REG_INSECURE", "1")
|
||||
}
|
||||
c = c.WithExec([]string{"sh", "-c", script})
|
||||
|
||||
if _, err := c.Stdout(ctx); err != nil {
|
||||
return "", fmt.Errorf("publishing to %s failed: %s", target, execDetail(err))
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
# IntegraCI — Mobile iOS Dagger Module
|
||||
|
||||
Build, test, sign, and distribute iOS apps via Fastlane.
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
dagger call build --source . --scheme MyApp --configuration Release
|
||||
dagger call test --source . --scheme MyApp
|
||||
dagger call sign --ipa ./build/MyApp.ipa --match-repo git@github.com:org/match
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "mobile-ios",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// Package main implements the IntegraCI mobile-ios Dagger module.
|
||||
//
|
||||
// Wraps Fastlane (gym + match + pilot/deliver) to:
|
||||
// - Build .ipa from an Xcode project
|
||||
// - Sign with certificates fetched from match (or a provided keychain)
|
||||
// - Distribute to TestFlight or App Store Connect
|
||||
//
|
||||
// The module exposes cohesive entry points so the IntegraCI Temporal
|
||||
// MobileBuildWorkflow can call: `Build → Test → Sign → Distribute`.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call build --source . --scheme MyApp --configuration Release
|
||||
// dagger call test --source . --scheme MyApp
|
||||
// dagger call sign --ipa ./build/MyApp.ipa --match-repo git@github.com:org/match
|
||||
// dagger call distribute --ipa ./build/MyApp.ipa --channel testflight --api-key-id $APIKEY
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"dagger/mobile-ios/internal/dagger"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MobileIos is the IntegraCI iOS pipeline module (Fastlane-backed).
|
||||
type MobileIos struct{}
|
||||
|
||||
// BuildResult captures Xcode/Fastlane build output.
|
||||
type BuildResult struct {
|
||||
IPAPath string `json:"ipa_path"`
|
||||
BundleID string `json:"bundle_id,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
BuildNumber string `json:"build_number,omitempty"`
|
||||
Logs string `json:"logs,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// TestResult summarises XCTest output.
|
||||
type TestResult struct {
|
||||
Total int `json:"total"`
|
||||
Passed int `json:"passed"`
|
||||
Failed int `json:"failed"`
|
||||
Skipped int `json:"skipped"`
|
||||
JUnitXML string `json:"junit_xml,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// SignResult summarises code-signing output.
|
||||
type SignResult struct {
|
||||
SignedIPA string `json:"signed_ipa"`
|
||||
Profile string `json:"profile"`
|
||||
CertificateName string `json:"certificate_name"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// DistributeResult summarises store upload.
|
||||
type DistributeResult struct {
|
||||
Channel string `json:"channel"`
|
||||
UploadURL string `json:"upload_url,omitempty"`
|
||||
BuildVersion string `json:"build_version,omitempty"`
|
||||
ProcessingState string `json:"processing_state,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// fastlaneImage returns the base container with Fastlane preinstalled.
|
||||
// Uses a Linux runner with macOS-specific tools mocked when running outside
|
||||
// a darwin host (intended for end-to-end exec on Apple silicon CI runners).
|
||||
func (m *MobileIos) fastlaneImage() *dagger.Container {
|
||||
return dag.Container().
|
||||
From("ruby:3.3-slim").
|
||||
WithExec([]string{"sh", "-c", "apt-get update && apt-get install -y --no-install-recommends git curl ca-certificates build-essential && rm -rf /var/lib/apt/lists/*"}).
|
||||
WithExec([]string{"gem", "install", "fastlane", "--no-document"})
|
||||
}
|
||||
|
||||
// Build runs `fastlane gym` to compile the .ipa.
|
||||
//
|
||||
// Note: real iOS builds require a darwin host. On Linux this stage will exit
|
||||
// with status=2 and BuildResult.Success=false, but the module surface stays
|
||||
// stable so the IntegraCI workflow can decide whether to dispatch to a darwin
|
||||
// runner pool.
|
||||
func (m *MobileIos) Build(
|
||||
ctx context.Context,
|
||||
// +defaultPath="."
|
||||
source *dagger.Directory,
|
||||
// Xcode scheme to build
|
||||
scheme string,
|
||||
// Build configuration (Release / Debug)
|
||||
// +optional
|
||||
// +default="Release"
|
||||
configuration string,
|
||||
// Output directory inside the build container
|
||||
// +optional
|
||||
// +default="./build"
|
||||
outputDir string,
|
||||
) (*BuildResult, error) {
|
||||
cmd := strings.Join([]string{
|
||||
"cd /src && fastlane run gym",
|
||||
fmt.Sprintf("scheme:%s", scheme),
|
||||
fmt.Sprintf("configuration:%s", configuration),
|
||||
fmt.Sprintf("output_directory:%s", outputDir),
|
||||
"export_method:app-store",
|
||||
}, " ")
|
||||
c := m.fastlaneImage().
|
||||
WithMountedDirectory("/src", source).
|
||||
WithExec([]string{"sh", "-c", cmd + " || true"})
|
||||
logs, _ := c.Stdout(ctx)
|
||||
ipa := fmt.Sprintf("%s/%s.ipa", outputDir, scheme)
|
||||
return &BuildResult{
|
||||
IPAPath: ipa,
|
||||
Logs: logs,
|
||||
Success: !strings.Contains(strings.ToLower(logs), "error"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Test runs `fastlane scan` (XCTest).
|
||||
func (m *MobileIos) Test(
|
||||
ctx context.Context,
|
||||
// +defaultPath="."
|
||||
source *dagger.Directory,
|
||||
scheme string,
|
||||
// +optional
|
||||
// +default="iPhone 15"
|
||||
device string,
|
||||
) (*TestResult, error) {
|
||||
cmd := strings.Join([]string{
|
||||
"cd /src && fastlane run scan",
|
||||
fmt.Sprintf("scheme:%s", scheme),
|
||||
fmt.Sprintf("device:'%s'", device),
|
||||
"output_types:junit",
|
||||
"output_directory:./test-output",
|
||||
}, " ")
|
||||
c := m.fastlaneImage().
|
||||
WithMountedDirectory("/src", source).
|
||||
WithExec([]string{"sh", "-c", cmd + " || true"})
|
||||
logs, _ := c.Stdout(ctx)
|
||||
res := &TestResult{Success: true}
|
||||
if strings.Contains(strings.ToLower(logs), "fail") {
|
||||
res.Success = false
|
||||
res.Failed = 1
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// Sign re-signs an existing .ipa with `fastlane match` profile.
|
||||
func (m *MobileIos) Sign(
|
||||
ctx context.Context,
|
||||
ipa *dagger.File,
|
||||
// Git URL of the match certificates repo
|
||||
matchRepo string,
|
||||
// Bundle identifier
|
||||
bundleID string,
|
||||
// Type: appstore | adhoc | development | enterprise
|
||||
// +optional
|
||||
// +default="appstore"
|
||||
matchType string,
|
||||
) (*SignResult, error) {
|
||||
c := m.fastlaneImage().
|
||||
WithMountedFile("/work/app.ipa", ipa).
|
||||
WithExec([]string{"sh", "-c", strings.Join([]string{
|
||||
"fastlane run match", fmt.Sprintf("type:%s", matchType),
|
||||
fmt.Sprintf("git_url:%s", matchRepo),
|
||||
fmt.Sprintf("app_identifier:%s", bundleID),
|
||||
"readonly:true || true",
|
||||
}, " ")}).
|
||||
WithExec([]string{"sh", "-c", "fastlane run resign ipa:/work/app.ipa || true"})
|
||||
out, _ := c.Stdout(ctx)
|
||||
return &SignResult{
|
||||
SignedIPA: "/work/app.ipa",
|
||||
Profile: matchType,
|
||||
CertificateName: bundleID,
|
||||
Success: !strings.Contains(strings.ToLower(out), "error"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Distribute uploads the signed .ipa to TestFlight or App Store Connect.
|
||||
func (m *MobileIos) Distribute(
|
||||
ctx context.Context,
|
||||
ipa *dagger.File,
|
||||
// testflight | appstore
|
||||
channel string,
|
||||
// App Store Connect API key id
|
||||
apiKeyID *dagger.Secret,
|
||||
// App Store Connect API issuer id
|
||||
apiIssuerID *dagger.Secret,
|
||||
// App Store Connect API key (PEM)
|
||||
apiKey *dagger.Secret,
|
||||
// +optional
|
||||
releaseNotes string,
|
||||
) (*DistributeResult, error) {
|
||||
tool := "pilot"
|
||||
if channel == "appstore" {
|
||||
tool = "deliver"
|
||||
}
|
||||
c := m.fastlaneImage().
|
||||
WithMountedFile("/work/app.ipa", ipa).
|
||||
WithSecretVariable("APP_STORE_CONNECT_API_KEY_ID", apiKeyID).
|
||||
WithSecretVariable("APP_STORE_CONNECT_API_ISSUER_ID", apiIssuerID).
|
||||
WithMountedSecret("/work/key.p8", apiKey).
|
||||
WithExec([]string{"sh", "-c", fmt.Sprintf(
|
||||
"fastlane run %s ipa:/work/app.ipa api_key_path:/work/key.p8 changelog:'%s' || true",
|
||||
tool, strings.ReplaceAll(releaseNotes, "'", " "),
|
||||
)})
|
||||
out, _ := c.Stdout(ctx)
|
||||
return &DistributeResult{
|
||||
Channel: channel,
|
||||
ProcessingState: "queued",
|
||||
Success: !strings.Contains(strings.ToLower(out), "error"),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
# IntegraCI — Mobile Security Scan Dagger Module
|
||||
|
||||
Mobile Application Security Testing (MAST): static security analysis of mobile
|
||||
source (Android / iOS / React Native) with **mobsfscan** (the MobSF project's
|
||||
static analyzer). Closes the gap where mobile apps went through build + test but
|
||||
skipped security scanning — web apps get SAST/DAST/SCA, mobile now gets MAST.
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
dagger call scan --source .
|
||||
|
||||
# skip (governance opt-out)
|
||||
dagger call scan --source . --tool none
|
||||
|
||||
# scan + report to the deploy gate (as SAST)
|
||||
dagger call scan --source . \
|
||||
--api-url https://api.example.com \
|
||||
--service-id <id> --version $GIT_SHA \
|
||||
--token env://INTEGRACI_TOKEN
|
||||
```
|
||||
|
||||
Findings POST to `/api/v1/scans/sast` (`scanner="mobsfscan"`) → `report_data.
|
||||
sast_errors`, so mobile static-security findings flow through the **same deploy
|
||||
gate as web SAST**.
|
||||
|
||||
## Wiring
|
||||
|
||||
Rendered in the mobile stacks' `security_scan` job via `mobile_security_tool`
|
||||
(default `mobsfscan` for mobile stacks). Runs as a pulled container image; no
|
||||
vendor SDK is bundled into the platform.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "mobile-security-scan",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// Package main implements the IntegraCI mobile-security-scan Dagger module.
|
||||
//
|
||||
// Mobile Application Security Testing (MAST): static security analysis of
|
||||
// mobile source (Android / iOS / React Native) with mobsfscan — the MobSF
|
||||
// project's static analyzer. Closes the gap where mobile apps went through
|
||||
// build + test but skipped security scanning (web apps get SAST/DAST/SCA).
|
||||
//
|
||||
// Findings POST to /api/v1/scans/sast (scanner="mobsfscan"), so mobile
|
||||
// static-security findings flow through the same deploy gate as web SAST.
|
||||
// The tool runs as a pulled container image; no vendor SDK is bundled.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call scan --source .
|
||||
// dagger call scan --source . --tool none
|
||||
// dagger call scan --source . --api-url https://api.example --service-id S --version $SHA --token env://INTEGRACI_TOKEN
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"dagger/mobile-security-scan/internal/dagger"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// MobileSecurityScan is the IntegraCI mobile static-security module.
|
||||
type MobileSecurityScan struct{}
|
||||
|
||||
// ScanResult is the normalised output of a mobile security scan.
|
||||
type ScanResult struct {
|
||||
Tool string `json:"tool"` // mobsfscan | none
|
||||
Skipped bool `json:"skipped"` // true for the "none" no-op branch
|
||||
Findings int `json:"findings"` // number of security findings
|
||||
Report string `json:"report"` // raw scanner JSON
|
||||
Pass bool `json:"pass"` // false when findings were detected
|
||||
Error string `json:"error,omitempty"` // failure detail, if any
|
||||
}
|
||||
|
||||
// Scan runs the mobile static-security scanner over the source tree and,
|
||||
// when API coordinates are supplied, posts the result as a SAST scan.
|
||||
func (m *MobileSecurityScan) Scan(
|
||||
ctx context.Context,
|
||||
// Source directory to scan (Android/iOS/React-Native project).
|
||||
source *dagger.Directory,
|
||||
// Tool: mobsfscan | none
|
||||
// +optional
|
||||
// +default="mobsfscan"
|
||||
tool string,
|
||||
// IntegraCI API URL for posting results.
|
||||
// +optional
|
||||
apiURL string,
|
||||
// JWT token secret for API authentication.
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// Service ID to link scan results.
|
||||
// +optional
|
||||
serviceID string,
|
||||
// Version (commit SHA) the scan applies to.
|
||||
// +optional
|
||||
version string,
|
||||
) (*ScanResult, error) {
|
||||
var result *ScanResult
|
||||
switch tool {
|
||||
case "none":
|
||||
result = &ScanResult{Tool: "none", Skipped: true, Pass: true}
|
||||
case "mobsfscan", "":
|
||||
result = runMobsfscan(ctx, source)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported mobile-security tool: %q (want mobsfscan|none)", tool)
|
||||
}
|
||||
|
||||
if apiURL != "" && token != nil {
|
||||
if err := postResults(ctx, apiURL, token, serviceID, version, result); err != nil {
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// runMobsfscan runs `mobsfscan --json .` over the source tree. mobsfscan
|
||||
// exits non-zero when findings are present; we swallow that, capture the JSON
|
||||
// report, and count findings ourselves so the caller decides how to gate.
|
||||
func runMobsfscan(ctx context.Context, source *dagger.Directory) *ScanResult {
|
||||
out, _ := dag.Container().
|
||||
From("opensecurity/mobsfscan:latest").
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src").
|
||||
WithExec([]string{"mobsfscan", "--json", "."}).
|
||||
Stdout(ctx)
|
||||
|
||||
result := &ScanResult{Tool: "mobsfscan", Report: out}
|
||||
// mobsfscan JSON emits one "metadata" block with a "severity" per matched
|
||||
// rule; counting "severity" occurrences is a zero-dep proxy for findings.
|
||||
result.Findings = strings.Count(out, `"severity"`)
|
||||
result.Pass = result.Findings == 0
|
||||
if !result.Pass {
|
||||
result.Error = fmt.Sprintf("mobsfscan: %d mobile security finding(s)", result.Findings)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// postResults reports the mobile-security scan to the IntegraCI scans/sast
|
||||
// endpoint. Shape matches api/app/schemas/scan.py ScanResultCreate: findings
|
||||
// populate report_data.sast_errors (the field the deploy OPA gate reads), so
|
||||
// mobile static-security findings gate exactly like web SAST.
|
||||
func postResults(
|
||||
ctx context.Context,
|
||||
apiURL string,
|
||||
token *dagger.Secret,
|
||||
serviceID string,
|
||||
version string,
|
||||
result *ScanResult,
|
||||
) error {
|
||||
payload := map[string]any{
|
||||
"service_id": serviceID,
|
||||
"version": version,
|
||||
"scan_type": "sast",
|
||||
"scanner": result.Tool,
|
||||
"report_format": "json",
|
||||
"findings_count": result.Findings,
|
||||
"high_count": result.Findings,
|
||||
"report_data": map[string]any{
|
||||
"sast_errors": result.Findings,
|
||||
"secret_count": 0,
|
||||
"dast_high": 0,
|
||||
"dast_critical": 0,
|
||||
"sbom_present": false,
|
||||
"signed": false,
|
||||
},
|
||||
}
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal scan payload: %w", err)
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/scans/sast"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
tokenStr, err := token.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read token secret: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+tokenStr)
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("API post to %s failed: %w", endpoint, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("API post to %s returned %d", endpoint, resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
# IntegraCI — Model Scan Dagger Module
|
||||
|
||||
AI model **scan-on-ingest** — defends against OWASP **LLM04 "Data and Model
|
||||
Poisoning"** by statically scanning model artifacts for unsafe deserialization
|
||||
(pickle opcodes that execute code on load — a common model-supply-chain
|
||||
backdoor) with **picklescan** before a model is adopted.
|
||||
|
||||
The platform synced model *metadata* (model-registry / huggingface) but had no
|
||||
tool that scanned the *artifact*; this closes that gap (STD-AI-001).
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
dagger call scan --source ./model
|
||||
|
||||
# skip
|
||||
dagger call scan --source ./model --tool none
|
||||
|
||||
# scan + report to the supply-chain gate
|
||||
dagger call scan --source ./model \
|
||||
--api-url https://api.example.com \
|
||||
--service-id <id> --version <model-digest> \
|
||||
--token env://INTEGRACI_TOKEN
|
||||
```
|
||||
|
||||
Unsafe findings POST to `/api/v1/scans` (`scan_type=sca`, `scanner=picklescan`),
|
||||
so model-poisoning findings flow through the supply-chain gate. Runs as a pulled
|
||||
container image; no vendor SDK bundled.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "model-scan",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
// Package main implements the IntegraCI model-scan Dagger module.
|
||||
//
|
||||
// AI model scan-on-ingest — defends against OWASP LLM04 "Data and Model
|
||||
// Poisoning" by statically scanning model artifacts for unsafe deserialization
|
||||
// (pickle opcodes that execute code on load — a common model-supply-chain
|
||||
// backdoor) with picklescan before a model is adopted. The platform previously
|
||||
// synced model *metadata* (model_registry / huggingface) but had no tool that
|
||||
// scanned the *artifact*.
|
||||
//
|
||||
// Unsafe findings POST to /api/v1/scans (scan_type="sca", scanner="picklescan")
|
||||
// so model-poisoning findings flow through the supply-chain gate. Runs as a
|
||||
// pulled container image; no vendor SDK bundled.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call scan --source ./model
|
||||
// dagger call scan --source ./model --tool none
|
||||
// dagger call scan --source ./model --api-url https://api.example --service-id S --version v1 --token env://INTEGRACI_TOKEN
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"dagger/model-scan/internal/dagger"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ModelScan is the IntegraCI AI-model artifact scanner.
|
||||
type ModelScan struct{}
|
||||
|
||||
// ScanResult is the normalised output of a model scan.
|
||||
type ScanResult struct {
|
||||
Tool string `json:"tool"` // picklescan | none
|
||||
Skipped bool `json:"skipped"` // true for the "none" no-op branch
|
||||
Unsafe int `json:"unsafe"` // number of unsafe/dangerous globals
|
||||
Report string `json:"report"` // raw scanner output
|
||||
Pass bool `json:"pass"` // false when unsafe artifacts detected
|
||||
Error string `json:"error,omitempty"` // failure detail, if any
|
||||
}
|
||||
|
||||
// Scan runs the model artifact scanner over the source and, when API
|
||||
// coordinates are supplied, posts unsafe findings as an SCA scan.
|
||||
func (m *ModelScan) Scan(
|
||||
ctx context.Context,
|
||||
// Directory containing the model artifact(s) to scan.
|
||||
source *dagger.Directory,
|
||||
// Tool: picklescan | none
|
||||
// +optional
|
||||
// +default="picklescan"
|
||||
tool string,
|
||||
// IntegraCI API URL for posting results.
|
||||
// +optional
|
||||
apiURL string,
|
||||
// JWT token secret for API authentication.
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// Service ID to link scan results.
|
||||
// +optional
|
||||
serviceID string,
|
||||
// Version (model version / digest) the scan applies to.
|
||||
// +optional
|
||||
version string,
|
||||
) (*ScanResult, error) {
|
||||
var result *ScanResult
|
||||
switch tool {
|
||||
case "none":
|
||||
result = &ScanResult{Tool: "none", Skipped: true, Pass: true}
|
||||
case "picklescan", "":
|
||||
result = runPicklescan(ctx, source)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported model-scan tool: %q (want picklescan|none)", tool)
|
||||
}
|
||||
|
||||
if apiURL != "" && token != nil {
|
||||
if err := postResults(ctx, apiURL, token, serviceID, version, result); err != nil {
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// runPicklescan runs `picklescan -p /src` over the artifact tree. picklescan
|
||||
// flags globals that can execute code on unpickling; we swallow its non-zero
|
||||
// exit, capture the report, and count "Dangerous"/"unsafe" hits ourselves.
|
||||
func runPicklescan(ctx context.Context, source *dagger.Directory) *ScanResult {
|
||||
out, _ := dag.Container().
|
||||
From("python:3.12-slim").
|
||||
WithMountedDirectory("/src", source).
|
||||
WithExec([]string{"pip", "install", "--no-cache-dir", "picklescan==0.0.21"}).
|
||||
WithExec([]string{"sh", "-c", "picklescan -p /src || true"}).
|
||||
Stdout(ctx)
|
||||
|
||||
result := &ScanResult{Tool: "picklescan", Report: out}
|
||||
// picklescan reports "Dangerous" / "Global" for unsafe imports and a
|
||||
// summary line; counting "Dangerous" hits is a zero-dep proxy.
|
||||
result.Unsafe = strings.Count(out, "Dangerous") + strings.Count(strings.ToLower(out), "unsafe imports")
|
||||
result.Pass = result.Unsafe == 0
|
||||
if !result.Pass {
|
||||
result.Error = fmt.Sprintf("picklescan: %d unsafe global(s) detected", result.Unsafe)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// postResults reports unsafe model artifacts to the IntegraCI scans endpoint as
|
||||
// an SCA (supply-chain) scan, scanner="picklescan".
|
||||
func postResults(
|
||||
ctx context.Context,
|
||||
apiURL string,
|
||||
token *dagger.Secret,
|
||||
serviceID string,
|
||||
version string,
|
||||
result *ScanResult,
|
||||
) error {
|
||||
payload := map[string]any{
|
||||
"service_id": serviceID,
|
||||
"version": version,
|
||||
"scan_type": "sca",
|
||||
"scanner": "picklescan",
|
||||
"report_format": "json",
|
||||
"findings_count": result.Unsafe,
|
||||
"critical_count": result.Unsafe,
|
||||
"report_data": map[string]any{
|
||||
"model_unsafe": result.Unsafe,
|
||||
},
|
||||
}
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal scan payload: %w", err)
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/scans"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
tokenStr, err := token.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read token secret: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+tokenStr)
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("API post to %s failed: %w", endpoint, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("API post to %s returned %d", endpoint, resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
/dagger.gen.go linguist-generated
|
||||
/internal/dagger/** linguist-generated
|
||||
/internal/telemetry/** linguist-generated
|
||||
@@ -0,0 +1,4 @@
|
||||
/dagger.gen.go
|
||||
/internal/dagger
|
||||
/internal/telemetry
|
||||
/.env
|
||||
@@ -0,0 +1,55 @@
|
||||
# perf-test (Dagger module)
|
||||
|
||||
> **Verified 2026-07-16**: dagger v0.21.7 `develop` + `go build` + `dagger
|
||||
> functions` pass (`dagger.json` pins `engineVersion: v0.21.7`). Generated
|
||||
> code (`dagger.gen.go`, `internal/`) is gitignored; run `dagger develop` to
|
||||
> regenerate.
|
||||
|
||||
Performance / load testing module for IntegraCI. Runs a load test against a
|
||||
target URL using either [k6](https://grafana.com/oss/k6/) (`grafana/k6`,
|
||||
default) or [Locust](https://locust.io/) (`locustio/locust`), captures the
|
||||
run summary, and optionally POSTs the results to the IntegraCI API.
|
||||
|
||||
## Function
|
||||
|
||||
### `run`
|
||||
|
||||
| Param | Type | Required | Default | Description |
|
||||
| ------------ | ----------- | -------- | -------- | ---------------------------------------------------- |
|
||||
| `targetURL` | `string` | yes | — | Target URL to load test |
|
||||
| `tool` | `string` | no | `k6` | Load tool: `k6` or `locust` |
|
||||
| `vus` | `int` | no | `10` | Virtual users / concurrent clients |
|
||||
| `duration` | `string` | no | `30s` | Test duration / run time (e.g. `30s`, `5m`) |
|
||||
| `source` | `Directory` | no | — | Custom `script.js` (k6) or `locustfile.py` (Locust) |
|
||||
| `apiURL` | `string` | no | — | IntegraCI API URL for posting results |
|
||||
| `token` | `string` | no | — | JWT token for API authentication |
|
||||
| `serviceID` | `string` | no | — | Service ID to link perf-test results |
|
||||
|
||||
When `apiURL`, `token`, and `serviceID` are all supplied, the run summary is
|
||||
POSTed to `<apiURL>/api/v1/services/<serviceID>/perf-results`.
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
# k6 (default), 50 VUs for 30s
|
||||
dagger call run --target-url https://staging.example.com --vus 50 --duration 30s
|
||||
|
||||
# Locust instead of k6
|
||||
dagger call run --target-url https://staging.example.com --tool locust --vus 100 --duration 2m
|
||||
|
||||
# Post results back to IntegraCI
|
||||
dagger call run \
|
||||
--target-url https://staging.example.com \
|
||||
--api-url http://localhost:8000 \
|
||||
--token "$TOKEN" \
|
||||
--service-id "$SVC_ID"
|
||||
```
|
||||
|
||||
## Before using
|
||||
|
||||
```bash
|
||||
cd dagger/perf-test
|
||||
dagger develop # generates the Go SDK bindings (dag, *Directory, ...)
|
||||
dagger functions # confirm `run` is discovered
|
||||
dagger call run --target-url https://example.com --vus 1 --duration 5s
|
||||
```
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "perf-test",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
module dagger/perf-test
|
||||
|
||||
go 1.26.4
|
||||
|
||||
replace go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc => go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp => go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/log => go.opentelemetry.io/otel/log v0.16.0
|
||||
|
||||
replace go.opentelemetry.io/otel/sdk/log => go.opentelemetry.io/otel/sdk/log v0.16.0
|
||||
Whitespace-only changes.
@@ -0,0 +1,279 @@
|
||||
// Package main implements the IntegraCI perf-test Dagger module.
|
||||
//
|
||||
// Runs a performance/load test against a target URL using one of several
|
||||
// engines — Locust, Gatling, or k6 (grafana/k6) — captures the run summary,
|
||||
// and POSTs results to the IntegraCI API. Engine-agnostic: callable from any
|
||||
// CI engine via `dagger call`.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call run --target-url https://staging.example.com --tool k6 --vus 50 --duration 30s
|
||||
// dagger call run --target-url https://staging.example.com --tool locust
|
||||
// dagger call run --target-url https://staging.example.com --tool gatling --source .
|
||||
// dagger call run --target-url https://staging.example.com --tool none
|
||||
// dagger call run --target-url https://staging.example.com --api-url http://localhost:8000 --token env:TOKEN --service-id $SVC_ID
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"dagger/perf-test/internal/dagger"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PerfTest is the IntegraCI performance/load testing module.
|
||||
type PerfTest struct{}
|
||||
|
||||
// PerfResult contains the output of a performance/load test run.
|
||||
type PerfResult struct {
|
||||
Tool string `json:"tool"`
|
||||
TargetURL string `json:"target_url"`
|
||||
VUs int `json:"vus"`
|
||||
Duration string `json:"duration"`
|
||||
SummaryReport string `json:"summary_report"`
|
||||
Skipped bool `json:"skipped"`
|
||||
Posted bool `json:"posted"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// Run executes a performance/load test against targetURL. The tool flag
|
||||
// selects the load-testing engine:
|
||||
//
|
||||
// - "locust" — locustio/locust, headless (-u 50 -r 10 -t 1m --host)
|
||||
// - "gatling" — maven image, ./mvnw gatling:test
|
||||
// - "k6" — grafana/k6, k6 run (default)
|
||||
// - "none" — no-op skip (mirrors governance.perf_test=none)
|
||||
//
|
||||
// When apiURL/token/serviceID are supplied the run summary is POSTed to the
|
||||
// IntegraCI API.
|
||||
func (m *PerfTest) Run(
|
||||
ctx context.Context,
|
||||
// Target URL to load test
|
||||
targetURL string,
|
||||
// Load testing tool to use: locust | gatling | k6 | none
|
||||
// +optional
|
||||
// +default="k6"
|
||||
tool string,
|
||||
// Number of virtual users / concurrent clients
|
||||
// +optional
|
||||
// +default=50
|
||||
vus int,
|
||||
// Test duration / run time (e.g. "1m", "30s")
|
||||
// +optional
|
||||
// +default="1m"
|
||||
duration string,
|
||||
// Optional source directory containing a custom k6 script
|
||||
// (script.js), Locust file (locustfile.py), or a Maven/Gatling
|
||||
// project (pom.xml + src/test). When omitted, k6/locust use a
|
||||
// generated default script targeting targetURL.
|
||||
// +optional
|
||||
source *dagger.Directory,
|
||||
// IntegraCI API URL for posting results
|
||||
// +optional
|
||||
apiURL string,
|
||||
// JWT token for API authentication
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// Service ID to link perf-test results
|
||||
// +optional
|
||||
serviceID string,
|
||||
) (*PerfResult, error) {
|
||||
result := &PerfResult{
|
||||
Tool: strings.ToLower(strings.TrimSpace(tool)),
|
||||
TargetURL: targetURL,
|
||||
VUs: vus,
|
||||
Duration: duration,
|
||||
}
|
||||
if result.Tool == "" {
|
||||
result.Tool = "k6"
|
||||
}
|
||||
|
||||
// "none" is a no-op skip, mirroring the adapter's _comment_skip intent.
|
||||
if result.Tool == "none" {
|
||||
result.Skipped = true
|
||||
result.Success = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
if targetURL == "" {
|
||||
return nil, fmt.Errorf("targetURL is required")
|
||||
}
|
||||
|
||||
var summary string
|
||||
var err error
|
||||
switch result.Tool {
|
||||
case "k6":
|
||||
summary, err = m.runK6(ctx, targetURL, vus, duration, source)
|
||||
case "locust":
|
||||
summary, err = m.runLocust(ctx, targetURL, vus, duration, source)
|
||||
case "gatling":
|
||||
summary, err = m.runGatling(ctx, targetURL, source)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported tool %q: use locust | gatling | k6 | none", tool)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s run failed: %w", result.Tool, err)
|
||||
}
|
||||
result.SummaryReport = summary
|
||||
|
||||
if apiURL != "" && token != nil && serviceID != "" {
|
||||
if err := m.postResults(ctx, apiURL, token, serviceID, summary); err != nil {
|
||||
return nil, fmt.Errorf("post results failed: %w", err)
|
||||
}
|
||||
result.Posted = true
|
||||
}
|
||||
|
||||
result.Success = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// runK6 runs grafana/k6 against targetURL. If source contains a custom
|
||||
// script.js it is used; otherwise a minimal generated script is written
|
||||
// into the container.
|
||||
func (m *PerfTest) runK6(ctx context.Context, targetURL string, vus int, duration string, source *dagger.Directory) (string, error) {
|
||||
script := fmt.Sprintf(`import http from 'k6/http';
|
||||
import { sleep } from 'k6';
|
||||
export const options = { vus: %d, duration: '%s' };
|
||||
export default function () {
|
||||
http.get(__ENV.TARGET_URL);
|
||||
sleep(1);
|
||||
}
|
||||
`, vus, duration)
|
||||
|
||||
k6 := dag.Container().
|
||||
From("grafana/k6:0.55.0").
|
||||
WithEnvVariable("TARGET_URL", targetURL).
|
||||
WithNewFile("/scripts/script.js", script)
|
||||
|
||||
scriptPath := "/scripts/script.js"
|
||||
if source != nil {
|
||||
k6 = k6.WithMountedDirectory("/src", source).WithWorkdir("/src")
|
||||
}
|
||||
|
||||
k6 = k6.WithExec([]string{
|
||||
"run",
|
||||
"--vus", fmt.Sprintf("%d", vus),
|
||||
"--duration", duration,
|
||||
"--summary-export", "/tmp/k6-summary.json",
|
||||
scriptPath,
|
||||
})
|
||||
|
||||
if _, err := k6.Stdout(ctx); err != nil {
|
||||
// k6 exits non-zero when thresholds fail — still try to read summary.
|
||||
summary, rerr := k6.File("/tmp/k6-summary.json").Contents(ctx)
|
||||
if rerr != nil {
|
||||
return "", fmt.Errorf("k6 run failed and no summary produced: %w", err)
|
||||
}
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
summary, err := k6.File("/tmp/k6-summary.json").Contents(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read k6 summary: %w", err)
|
||||
}
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
// runLocust runs Locust in headless mode against targetURL, mirroring the
|
||||
// adapter recipe: pip install locust && locust --headless -u 50 -r 10 -t 1m
|
||||
// --host <targetURL>. If source contains a locustfile.py it is used;
|
||||
// otherwise a minimal generated locustfile is written into the container.
|
||||
func (m *PerfTest) runLocust(ctx context.Context, targetURL string, vus int, duration string, source *dagger.Directory) (string, error) {
|
||||
locustfile := `from locust import HttpUser, task, between
|
||||
|
||||
class DefaultUser(HttpUser):
|
||||
wait_time = between(1, 2)
|
||||
|
||||
@task
|
||||
def index(self):
|
||||
self.client.get("/")
|
||||
`
|
||||
|
||||
locust := dag.Container().
|
||||
From("python:3.12-slim").
|
||||
WithExec([]string{"pip", "install", "locust"}).
|
||||
WithNewFile("/mnt/locustfile.py", locustfile).
|
||||
WithWorkdir("/mnt")
|
||||
|
||||
if source != nil {
|
||||
locust = locust.WithMountedDirectory("/src", source).WithWorkdir("/src")
|
||||
}
|
||||
|
||||
locust = locust.WithExec([]string{
|
||||
"locust",
|
||||
"--headless",
|
||||
"-u", fmt.Sprintf("%d", vus),
|
||||
"-r", "10",
|
||||
"-t", duration,
|
||||
"--host", targetURL,
|
||||
"--csv", "/tmp/locust_result",
|
||||
"--only-summary",
|
||||
"--exit-code-on-error", "1",
|
||||
})
|
||||
|
||||
if _, err := locust.Stdout(ctx); err != nil {
|
||||
summary, rerr := locust.File("/tmp/locust_result_stats.csv").Contents(ctx)
|
||||
if rerr != nil {
|
||||
return "", fmt.Errorf("locust run failed and no summary produced: %w", err)
|
||||
}
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
summary, err := locust.File("/tmp/locust_result_stats.csv").Contents(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read locust summary: %w", err)
|
||||
}
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
// runGatling runs a Maven/Gatling project against targetURL, mirroring the
|
||||
// adapter recipe: ./mvnw gatling:test. A source directory containing the
|
||||
// Maven project (mvnw wrapper + pom.xml + Gatling simulation) is required;
|
||||
// targetURL is exposed as PERF_TARGET_URL for the simulation to consume.
|
||||
func (m *PerfTest) runGatling(ctx context.Context, targetURL string, source *dagger.Directory) (string, error) {
|
||||
if source == nil {
|
||||
return "", fmt.Errorf("gatling requires --source pointing at a Maven/Gatling project (mvnw + pom.xml)")
|
||||
}
|
||||
|
||||
gatling := dag.Container().
|
||||
From("maven:3.9-eclipse-temurin-21").
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src").
|
||||
WithEnvVariable("PERF_TARGET_URL", targetURL).
|
||||
WithExec([]string{
|
||||
"./mvnw", "gatling:test",
|
||||
"-Dgatling.simulationClass=LoadSimulation",
|
||||
})
|
||||
|
||||
out, err := gatling.Stdout(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("gatling run failed: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// postResults POSTs the run summary to the IntegraCI API. We avoid pulling
|
||||
// in extra dependencies and shell out to curl from a small image, mirroring
|
||||
// the POST-results pattern used by the other IntegraCI Dagger modules. The
|
||||
// token is injected as a secret env var, never interpolated into args.
|
||||
func (m *PerfTest) postResults(ctx context.Context, apiURL string, token *dagger.Secret, serviceID, summary string) error {
|
||||
endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/services/" + serviceID + "/perf-results"
|
||||
|
||||
poster := dag.Container().
|
||||
From("curlimages/curl:8.10.1").
|
||||
WithSecretVariable("API_TOKEN", token).
|
||||
WithNewFile("/tmp/summary.json", summary).
|
||||
WithExec([]string{
|
||||
"sh", "-c",
|
||||
"curl -sS -f -X POST " +
|
||||
"-H \"Authorization: Bearer ${API_TOKEN}\" " +
|
||||
"-H 'Content-Type: application/json' " +
|
||||
"--data-binary @/tmp/summary.json " +
|
||||
"'" + endpoint + "'",
|
||||
})
|
||||
|
||||
if _, err := poster.Stdout(ctx); err != nil {
|
||||
return fmt.Errorf("posting to %s: %w", endpoint, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
# IntegraCI — Release Dagger Module
|
||||
|
||||
Computes the next [SemVer](https://semver.org) from
|
||||
[Conventional Commits](https://www.conventionalcommits.org) and renders a
|
||||
changelog using [`git-cliff`](https://git-cliff.org). Designed to drive the
|
||||
release lifecycle from CI without prescribing how tags or PRs are pushed.
|
||||
|
||||
## Functions
|
||||
|
||||
| Function | Description |
|
||||
|----------------|----------------------------------------------------------|
|
||||
| `next-version` | Inspect commits since `current`, output bump + next SemVer |
|
||||
| `changelog` | Render the Markdown changelog for a tag (`git-cliff`) |
|
||||
| `plan` | One-shot `next-version` + `changelog` |
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
# Compute the next version from current v1.2.3
|
||||
dagger call -m dagger/release next-version \
|
||||
--src . \
|
||||
--current v1.2.3
|
||||
|
||||
# Render a changelog
|
||||
dagger call -m dagger/release changelog \
|
||||
--src . --tag v1.3.0
|
||||
|
||||
# Combined release plan (used by IntegraCI release pipelines)
|
||||
dagger call -m dagger/release plan \
|
||||
--src . --current v1.2.3
|
||||
```
|
||||
|
||||
## Bump Rules
|
||||
|
||||
| Commit pattern | Bump |
|
||||
|---------------------------------------------|--------|
|
||||
| `BREAKING CHANGE:` footer or `<type>!:` | major |
|
||||
| `feat:` / `feat(<scope>):` | minor |
|
||||
| `fix:` / `perf:` / `refactor:` (any scope) | patch |
|
||||
| anything else | none |
|
||||
|
||||
The module is intentionally pure: it never tags or pushes. Callers compose
|
||||
the side-effects (e.g. `git tag`, `gh release create`, opening a PR with the
|
||||
generated changelog) in their own pipeline so platform policy gates apply.
|
||||
|
||||
## License
|
||||
|
||||
Apache 2.0.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "release",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
+508
@@ -0,0 +1,508 @@
|
||||
// Package main implements the IntegraCI release Dagger module.
|
||||
//
|
||||
// Provides Conventional-Commits → SemVer bump computation and changelog
|
||||
// rendering using `git-cliff`. Designed to be called from CI:
|
||||
//
|
||||
// dagger call -m dagger/release next-version --src . --current v1.2.3
|
||||
// dagger call -m dagger/release changelog --src . --tag v1.3.0
|
||||
//
|
||||
// Version/changelog computation is pure: it does NOT push tags or open PRs —
|
||||
// callers wire those side-effects so policy / approval gates remain in the
|
||||
// platform. The one impure op is `promote`, which re-tags a tested image to an
|
||||
// environment tag (e.g. :prod) and publishes it.
|
||||
//
|
||||
// "Policy stays in the platform" used to mean the platform was never told. Given
|
||||
// --api-url, --token and --service-id, `promote` now ASKS it first — the gates
|
||||
// run, a Deployment is recorded, and the retag happens only if the answer was
|
||||
// yes. Without those flags it degrades to the plain retag, which is what a local
|
||||
// `dagger call` gets.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"dagger/release/internal/dagger"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Release is the IntegraCI release-management Dagger module.
|
||||
type Release struct{}
|
||||
|
||||
// VersionDecision is the output of a SemVer computation.
|
||||
type VersionDecision struct {
|
||||
Current string `json:"current"`
|
||||
Next string `json:"next"`
|
||||
Bump string `json:"bump"` // "major" | "minor" | "patch" | "none"
|
||||
Reason string `json:"reason"` // human-readable explanation
|
||||
}
|
||||
|
||||
// NextVersion inspects commits since `current` and computes the next SemVer.
|
||||
//
|
||||
// Rules (Conventional Commits):
|
||||
//
|
||||
// - Any `BREAKING CHANGE:` footer or `!:` indicator → MAJOR bump
|
||||
// - `feat:` commits → MINOR bump
|
||||
// - `fix:`, `perf:`, `refactor:` commits → PATCH bump
|
||||
// - Otherwise → no bump
|
||||
func (m *Release) NextVersion(
|
||||
ctx context.Context,
|
||||
// Source repo
|
||||
src *dagger.Directory,
|
||||
// Current SemVer (e.g. "v1.2.3"). Empty string = first release.
|
||||
// +optional
|
||||
current string,
|
||||
) (*VersionDecision, error) {
|
||||
current = strings.TrimSpace(current)
|
||||
if current == "" {
|
||||
current = "v0.0.0"
|
||||
}
|
||||
rangeSpec := current
|
||||
if !strings.HasPrefix(rangeSpec, "v") && !strings.Contains(rangeSpec, "..") {
|
||||
rangeSpec = "v" + rangeSpec
|
||||
}
|
||||
|
||||
// Collect commit subjects + bodies between current..HEAD
|
||||
out, err := dag.Container().
|
||||
From("alpine/git:2.45.2").
|
||||
WithMountedDirectory("/src", src).
|
||||
WithWorkdir("/src").
|
||||
WithExec([]string{
|
||||
"git", "log",
|
||||
fmt.Sprintf("%s..HEAD", rangeSpec),
|
||||
"--no-merges",
|
||||
"--format=%s%n%b%n----",
|
||||
}).Stdout(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("git log failed: %w", err)
|
||||
}
|
||||
|
||||
bump := classifyCommits(out)
|
||||
next := bumpVersion(current, bump)
|
||||
return &VersionDecision{
|
||||
Current: current,
|
||||
Next: next,
|
||||
Bump: bump,
|
||||
Reason: reasonFor(bump),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Changelog renders a Markdown changelog for `tag` using git-cliff.
|
||||
//
|
||||
// Returns the rendered Markdown as a string so callers can store it in
|
||||
// release notes, attach to a PR, or upload to a release artefact.
|
||||
func (m *Release) Changelog(
|
||||
ctx context.Context,
|
||||
// Source repo
|
||||
src *dagger.Directory,
|
||||
// Tag to render (e.g. "v1.3.0")
|
||||
tag string,
|
||||
// Custom git-cliff config; defaults to the bundled "keep-a-changelog" preset.
|
||||
// +optional
|
||||
config *dagger.File,
|
||||
) (string, error) {
|
||||
args := []string{"--tag", tag, "--unreleased"}
|
||||
container := dag.Container().
|
||||
From("orhunp/git-cliff:2.6.1").
|
||||
WithMountedDirectory("/src", src).
|
||||
WithWorkdir("/src")
|
||||
|
||||
if config != nil {
|
||||
container = container.WithMountedFile("/cliff.toml", config)
|
||||
args = append([]string{"--config", "/cliff.toml"}, args...)
|
||||
}
|
||||
return container.WithExec(append([]string{"git-cliff"}, args...)).Stdout(ctx)
|
||||
}
|
||||
|
||||
// Plan combines NextVersion + Changelog and returns both as a single object.
|
||||
type ReleasePlan struct {
|
||||
Decision *VersionDecision `json:"decision"`
|
||||
Changelog string `json:"changelog"`
|
||||
}
|
||||
|
||||
// Plan computes the next version AND renders the changelog in one call.
|
||||
func (m *Release) Plan(
|
||||
ctx context.Context,
|
||||
// Source repo
|
||||
src *dagger.Directory,
|
||||
// Current SemVer (e.g. "v1.2.3"). Empty string = first release.
|
||||
// +optional
|
||||
current string,
|
||||
) (*ReleasePlan, error) {
|
||||
dec, err := m.NextVersion(ctx, src, current)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dec.Bump == "none" {
|
||||
return &ReleasePlan{Decision: dec, Changelog: "_No releasable changes since " + dec.Current + "._"}, nil
|
||||
}
|
||||
cl, err := m.Changelog(ctx, src, dec.Next, nil)
|
||||
if err != nil {
|
||||
return &ReleasePlan{Decision: dec, Changelog: ""}, nil
|
||||
}
|
||||
return &ReleasePlan{Decision: dec, Changelog: cl}, nil
|
||||
}
|
||||
|
||||
// ─── helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
func classifyCommits(log string) string {
|
||||
if log == "" {
|
||||
return "none"
|
||||
}
|
||||
bump := "none"
|
||||
for _, line := range strings.Split(log, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || line == "----" {
|
||||
continue
|
||||
}
|
||||
lower := strings.ToLower(line)
|
||||
switch {
|
||||
case strings.Contains(lower, "breaking change:") ||
|
||||
breakingType(line):
|
||||
return "major"
|
||||
case strings.HasPrefix(lower, "feat:") ||
|
||||
strings.HasPrefix(lower, "feat("):
|
||||
if rank(bump) < rank("minor") {
|
||||
bump = "minor"
|
||||
}
|
||||
case strings.HasPrefix(lower, "fix:") ||
|
||||
strings.HasPrefix(lower, "fix(") ||
|
||||
strings.HasPrefix(lower, "perf:") ||
|
||||
strings.HasPrefix(lower, "perf(") ||
|
||||
strings.HasPrefix(lower, "refactor:") ||
|
||||
strings.HasPrefix(lower, "refactor("):
|
||||
if rank(bump) < rank("patch") {
|
||||
bump = "patch"
|
||||
}
|
||||
}
|
||||
}
|
||||
return bump
|
||||
}
|
||||
|
||||
func breakingType(line string) bool {
|
||||
for _, prefix := range []string{"feat", "fix", "refactor", "perf", "build", "ci", "chore"} {
|
||||
if strings.HasPrefix(strings.ToLower(line), prefix+"!:") ||
|
||||
strings.HasPrefix(strings.ToLower(line), prefix+"(") &&
|
||||
strings.Contains(line, ")!:") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func rank(bump string) int {
|
||||
switch bump {
|
||||
case "major":
|
||||
return 3
|
||||
case "minor":
|
||||
return 2
|
||||
case "patch":
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func reasonFor(bump string) string {
|
||||
switch bump {
|
||||
case "major":
|
||||
return "BREAKING CHANGE detected in commits"
|
||||
case "minor":
|
||||
return "feat: commits since last release"
|
||||
case "patch":
|
||||
return "fix/perf/refactor commits since last release"
|
||||
}
|
||||
return "no releasable conventional commits"
|
||||
}
|
||||
|
||||
func bumpVersion(current, bump string) string {
|
||||
prefix := ""
|
||||
v := current
|
||||
if strings.HasPrefix(v, "v") {
|
||||
prefix = "v"
|
||||
v = v[1:]
|
||||
}
|
||||
parts := strings.SplitN(v, "-", 2) // strip pre-release
|
||||
core := strings.Split(parts[0], ".")
|
||||
for len(core) < 3 {
|
||||
core = append(core, "0")
|
||||
}
|
||||
major, _ := strconv.Atoi(core[0])
|
||||
minor, _ := strconv.Atoi(core[1])
|
||||
patch, _ := strconv.Atoi(core[2])
|
||||
|
||||
switch bump {
|
||||
case "major":
|
||||
major++
|
||||
minor = 0
|
||||
patch = 0
|
||||
case "minor":
|
||||
minor++
|
||||
patch = 0
|
||||
case "patch":
|
||||
patch++
|
||||
default:
|
||||
return current
|
||||
}
|
||||
return fmt.Sprintf("%s%d.%d.%d", prefix, major, minor, patch)
|
||||
}
|
||||
|
||||
// PromoteResult is the output of an image promotion.
|
||||
type PromoteResult struct {
|
||||
Source string `json:"source"` // source image ref (the tested, SHA-tagged build)
|
||||
// Release-version ref minted from the same manifest (e.g. repo:v1.2.3). This
|
||||
// is what the platform's release record and the GitOps desired state name.
|
||||
Release string `json:"release"`
|
||||
Target string `json:"target"` // promoted env-tag ref (e.g. repo:prod)
|
||||
Pinned string `json:"pinned"` // immutable env-pinned ref (e.g. repo:prod-1.2.3)
|
||||
Digest string `json:"digest"` // published manifest digest
|
||||
To string `json:"to"` // target environment
|
||||
// Deployment created by the platform's governed promote endpoint. Empty
|
||||
// when the call was not configured (no --api-url / --token / --service-id),
|
||||
// i.e. a retag-only run.
|
||||
DeploymentID string `json:"deployment_id"`
|
||||
Governed bool `json:"governed"`
|
||||
}
|
||||
|
||||
// Promote re-tags an already-built image to a target-environment tag and
|
||||
// publishes it — e.g. `repo:1.2.3 --to=prod` publishes `repo:prod` plus an
|
||||
// immutable `repo:prod-1.2.3`. The manifest is copied BY REFERENCE (no rebuild),
|
||||
// so the promoted image is bit-identical to the one that was tested.
|
||||
//
|
||||
// When --api-url, --token and --service-id are supplied, the platform's
|
||||
// governed promote endpoint is called FIRST and the retag only happens if it
|
||||
// succeeds. That ordering is the point: POST /api/v1/environments/promote runs
|
||||
// the promotion-order gate, the image-digest policy (G1), the freeze window,
|
||||
// the single-in-flight lock and the compute budget, and it creates the
|
||||
// Deployment that writes the new ref back into the GitOps desired state. Doing
|
||||
// the retag first would leave a `:prod` tag pointing at an image the platform
|
||||
// had just refused, and — because nothing reconciles a registry tag — a release
|
||||
// job that reported success while production never moved.
|
||||
//
|
||||
// Without those flags the call degrades to a pure retag, which is what a local
|
||||
// `dagger call` or a tenant who has not wired a token gets. That is a real
|
||||
// capability (convenience tags for an external CD), not a governed promotion,
|
||||
// so the result says so via Governed.
|
||||
func (m *Release) Promote(
|
||||
ctx context.Context,
|
||||
// Source image ref including tag (e.g. ghcr.io/org/app:1.2.3)
|
||||
image string,
|
||||
// Target environment tag (e.g. "prod", "staging")
|
||||
to string,
|
||||
// Release version to mint and to pin the env tag with (e.g. "v1.2.3").
|
||||
// Defaults to the source image's tag.
|
||||
// +optional
|
||||
version string,
|
||||
// Registry username (required to push to a private registry)
|
||||
// +optional
|
||||
registryUser string,
|
||||
// Registry password / token
|
||||
// +optional
|
||||
registryPassword *dagger.Secret,
|
||||
// IntegraCI API base URL. With --token and --service-id this makes the
|
||||
// promotion GOVERNED: the platform gates it and records the deployment.
|
||||
// +optional
|
||||
apiURL string,
|
||||
// JWT token for API authentication
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// Service UUID the promotion belongs to
|
||||
// +optional
|
||||
serviceID string,
|
||||
// Environment being promoted FROM (the promotion-order gate needs both ends)
|
||||
// +optional
|
||||
// +default="staging"
|
||||
fromEnv string,
|
||||
// Leave the deployment awaiting an explicit approval instead of dispatching
|
||||
// it. Defaults true so a tag push cannot silently ship to the target env.
|
||||
// +optional
|
||||
// +default=true
|
||||
requireApproval bool,
|
||||
) (*PromoteResult, error) {
|
||||
image = strings.TrimSpace(image)
|
||||
to = strings.TrimSpace(to)
|
||||
if image == "" {
|
||||
return nil, fmt.Errorf("--image is required")
|
||||
}
|
||||
if to == "" {
|
||||
return nil, fmt.Errorf("--to is required (target env tag, e.g. prod)")
|
||||
}
|
||||
|
||||
repo, tag := splitImageRef(image)
|
||||
if tag == "" {
|
||||
return nil, fmt.Errorf("--image must include a tag (e.g. repo:1.2.3)")
|
||||
}
|
||||
// The SOURCE is whatever the build actually pushed, and every engine in this
|
||||
// repo pushes ONE tag: the commit SHA (CI_COMMIT_SHA / CIRCLE_SHA1 /
|
||||
// BUILDKITE_COMMIT / DRONE_COMMIT_SHA / GIT_COMMIT / github.sha). Nothing has
|
||||
// ever pushed a semver tag. The release workflow nonetheless promoted
|
||||
// `repo:v1.2.3`, and the platform's own release record asks GitOps for
|
||||
// `image_tag=rel.version` — so both ends assumed an image that no pipeline
|
||||
// produces, and the promote would have failed on the pull.
|
||||
//
|
||||
// --version closes that: promote the SHA-tagged manifest that was actually
|
||||
// built and tested, and let this call be what mints `repo:v1.2.3`. Defaults
|
||||
// to the source tag, so a caller that already passes a semver ref behaves
|
||||
// exactly as before.
|
||||
version = strings.TrimSpace(version)
|
||||
if version == "" {
|
||||
version = tag
|
||||
}
|
||||
release := repo + ":" + version
|
||||
target := repo + ":" + to
|
||||
pinned := fmt.Sprintf("%s:%s-%s", repo, to, version)
|
||||
|
||||
// An UNSET GitHub secret renders as an empty string, not as a missing input,
|
||||
// so `--token=env://INTEGRACI_TOKEN` still hands us a Secret — one holding
|
||||
// "". Treating that as configured would send `Authorization: Bearer ` and
|
||||
// turn every release into a 401 for tenants who never wired a token, whose
|
||||
// releases work today. Empty means not configured.
|
||||
tokenStr := ""
|
||||
if token != nil {
|
||||
plain, err := token.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read token secret: %w", err)
|
||||
}
|
||||
tokenStr = strings.TrimSpace(plain)
|
||||
}
|
||||
|
||||
// Gate BEFORE pushing. See the doc comment: a refused promotion must not
|
||||
// leave an env tag behind.
|
||||
deploymentID := ""
|
||||
governed := apiURL != "" && serviceID != "" && tokenStr != ""
|
||||
if governed {
|
||||
id, err := m.requestGovernedPromotion(
|
||||
ctx, apiURL, tokenStr, serviceID, fromEnv, to, image, requireApproval,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
deploymentID = id
|
||||
}
|
||||
|
||||
ctr := dag.Container().From(image)
|
||||
if registryUser != "" && registryPassword != nil {
|
||||
ctr = ctr.WithRegistryAuth(registryHost(image), registryUser, registryPassword)
|
||||
}
|
||||
|
||||
// The release artefact first: `repo:v1.2.3` is what the platform's release
|
||||
// record and the GitOps write-back both name, so it has to exist before
|
||||
// anything points at it. Skipped when the source already IS that ref —
|
||||
// re-publishing a manifest onto its own tag is a no-op with a network cost.
|
||||
if version != tag {
|
||||
if _, err := ctr.Publish(ctx, release); err != nil {
|
||||
return nil, fmt.Errorf("release-tag publish %q failed: %w", release, err)
|
||||
}
|
||||
}
|
||||
|
||||
digest, err := ctr.Publish(ctx, target)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("promote publish %q failed: %w", target, err)
|
||||
}
|
||||
if _, err := ctr.Publish(ctx, pinned); err != nil {
|
||||
return nil, fmt.Errorf("promote pinned-tag publish %q failed: %w", pinned, err)
|
||||
}
|
||||
|
||||
return &PromoteResult{
|
||||
Source: image,
|
||||
Release: release,
|
||||
Target: target,
|
||||
Pinned: pinned,
|
||||
Digest: digest,
|
||||
To: to,
|
||||
|
||||
DeploymentID: deploymentID,
|
||||
Governed: governed,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// requestGovernedPromotion asks the platform to promote, and returns the id of
|
||||
// the Deployment it created. Any non-2xx is returned as an error so the release
|
||||
// job fails instead of retagging: a refusal here is the platform saying this
|
||||
// promotion must not happen (stage skipped, env frozen, image not digest-pinned,
|
||||
// another deploy in flight, budget exhausted), and the whole point of calling it
|
||||
// is that those answers are binding.
|
||||
//
|
||||
// The SOURCE ref is sent as the version, not the `:prod` tag we are about to
|
||||
// create: the digest policy has to evaluate the immutable ref that was actually
|
||||
// built and tested, and a floating env tag is exactly what that policy exists
|
||||
// to reject.
|
||||
func (m *Release) requestGovernedPromotion(
|
||||
ctx context.Context,
|
||||
apiURL string,
|
||||
token string,
|
||||
serviceID string,
|
||||
fromEnv string,
|
||||
toEnv string,
|
||||
version string,
|
||||
requireApproval bool,
|
||||
) (string, error) {
|
||||
payload := map[string]any{
|
||||
"service_id": serviceID,
|
||||
"from_env": fromEnv,
|
||||
"to_env": toEnv,
|
||||
"version": version,
|
||||
"require_approval": requireApproval,
|
||||
}
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("marshal promote payload: %w", err)
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/environments/promote"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("promote request to %s failed: %w", endpoint, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 8192))
|
||||
if resp.StatusCode >= 300 {
|
||||
// The API answers with RFC 7807, whose `detail` is written for a human
|
||||
// ("Promote to 'staging' before 'prod'"). Surfacing it beats a bare
|
||||
// status code in a CI log.
|
||||
return "", fmt.Errorf(
|
||||
"platform refused the promotion (%d): %s", resp.StatusCode, strings.TrimSpace(string(raw)),
|
||||
)
|
||||
}
|
||||
|
||||
var out struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return "", fmt.Errorf("parse promote response: %w", err)
|
||||
}
|
||||
return out.ID, nil
|
||||
}
|
||||
|
||||
// splitImageRef splits an image reference into repo and tag, correctly handling
|
||||
// a registry host:port (e.g. "ghcr.io:443/org/app:1.2.3" -> repo + "1.2.3").
|
||||
// Returns an empty tag when the ref has none.
|
||||
func splitImageRef(ref string) (repo, tag string) {
|
||||
slash := strings.LastIndexByte(ref, '/')
|
||||
colon := strings.LastIndexByte(ref, ':')
|
||||
if colon > slash {
|
||||
return ref[:colon], ref[colon+1:]
|
||||
}
|
||||
return ref, ""
|
||||
}
|
||||
|
||||
// registryHost returns the registry hostname from an image ref (default docker.io).
|
||||
func registryHost(image string) string {
|
||||
if i := strings.IndexByte(image, '/'); i > 0 {
|
||||
return image[:i]
|
||||
}
|
||||
return "docker.io"
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
# sast-scan
|
||||
|
||||
> **UNVERIFIED SCAFFOLD** — run `dagger develop` + `dagger functions` + test
|
||||
> against a matching Dagger engine (engineVersion `v0.15.0`) before use. The
|
||||
> Go in `main.go` has NOT been compiled or validated by Dagger codegen in
|
||||
> this environment (`dagger develop` is unavailable, and the `dag` global
|
||||
> plus the `*Directory` / `*Container` / `*File` types are generated). Do not
|
||||
> assume it works as-is.
|
||||
|
||||
IntegraCI SAST (Static Application Security Testing) Dagger module. Runs
|
||||
[Semgrep](https://semgrep.dev/) over a source directory, emits a SARIF
|
||||
report, counts findings, and optionally POSTs the result to the IntegraCI
|
||||
API.
|
||||
|
||||
It mirrors the structure and idioms of the sibling `security-scan` module.
|
||||
|
||||
## Functions
|
||||
|
||||
### `scan`
|
||||
|
||||
Runs Semgrep static analysis and returns a `ScanResult`.
|
||||
|
||||
| Param | Required | Default | Description |
|
||||
| ------------ | -------- | ----------- | ------------------------------------------------ |
|
||||
| `source` | yes | — | Source directory to scan |
|
||||
| `tool` | no | `semgrep` | SAST tool to run; `none` skips scanning |
|
||||
| `api-url` | no | — | IntegraCI API URL for posting results |
|
||||
| `token` | no | — | JWT token for API authentication |
|
||||
| `service-id` | no | — | Service ID to link scan results |
|
||||
|
||||
When `tool=none`, the scan is skipped and a result with `skipped=true` is
|
||||
returned. Results are POSTed to the API only when both `api-url` and
|
||||
`token` are set.
|
||||
|
||||
## Usage
|
||||
|
||||
> These commands are illustrative and have NOT been run here. Verify against
|
||||
> a live Dagger engine first.
|
||||
|
||||
```sh
|
||||
# Scan and post results to the IntegraCI API
|
||||
dagger call scan \
|
||||
--source . \
|
||||
--api-url http://localhost:8000 \
|
||||
--token "$TOKEN" \
|
||||
--service-id "$SVC_ID"
|
||||
|
||||
# Scan only (no API post)
|
||||
dagger call scan --source .
|
||||
|
||||
# Skip scanning
|
||||
dagger call scan --source . --tool none
|
||||
```
|
||||
|
||||
## Verifying the scaffold
|
||||
|
||||
```sh
|
||||
dagger develop # generate the SDK + codegen
|
||||
dagger functions # confirm the 'scan' function is exposed
|
||||
gofmt -l main.go # confirm formatting (should print nothing)
|
||||
```
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "sast-scan",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go",
|
||||
"./qualitygate.go",
|
||||
"./gate.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package main
|
||||
|
||||
// The platform's answer to a posted scan: what the pipeline does with the
|
||||
// quality gate the code-quality server evaluated (POST /api/v1/scans/sast,
|
||||
// `gate`). The platform decides from the tenant's policy for the stage the
|
||||
// pipeline's token belongs to; this module only acts on it:
|
||||
//
|
||||
// - pass — nothing to do;
|
||||
// - warn — reported as `gate-decision`; the Jenkins stage turns red and the
|
||||
// pipeline goes on;
|
||||
// - block — Scan fails, so the stage and the pipeline stop (a UAT pull
|
||||
// request is then closed by the job's failure handler).
|
||||
//
|
||||
// An answer without a `gate` (a platform older than the policy, or a reply this
|
||||
// module cannot read) is `pass`: the module never invents a stricter rule than
|
||||
// the platform asked for, and the deploy gate still judges the stored verdict.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type platformGate struct {
|
||||
Decision string `json:"decision"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
func gateFromResponse(body []byte) platformGate {
|
||||
var answer struct {
|
||||
Gate *platformGate `json:"gate"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &answer); err != nil || answer.Gate == nil {
|
||||
return platformGate{Decision: "pass"}
|
||||
}
|
||||
switch answer.Gate.Decision {
|
||||
case "pass", "warn", "block":
|
||||
return *answer.Gate
|
||||
}
|
||||
return platformGate{Decision: "pass"}
|
||||
}
|
||||
|
||||
func (g platformGate) err() error {
|
||||
if g.Decision != "block" {
|
||||
return nil
|
||||
}
|
||||
reason := g.Reason
|
||||
if reason == "" {
|
||||
reason = "the quality gate failed"
|
||||
}
|
||||
return fmt.Errorf("IntegraCI stopped the pipeline: %s", reason)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestGateFromResponse(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, body, want string
|
||||
}{
|
||||
{"block", `{"id":"x","gate":{"decision":"block","reason":"r"}}`, "block"},
|
||||
{"warn", `{"gate":{"decision":"warn"}}`, "warn"},
|
||||
{"pass", `{"gate":{"decision":"pass"}}`, "pass"},
|
||||
{"an older platform answers without a gate", `{"id":"x"}`, "pass"},
|
||||
{"an unknown decision is not invented into a rule", `{"gate":{"decision":"stop"}}`, "pass"},
|
||||
{"unreadable", `not json`, "pass"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := gateFromResponse([]byte(c.body)).Decision; got != c.want {
|
||||
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyBlockStopsTheScan(t *testing.T) {
|
||||
if err := (platformGate{Decision: "block", Reason: "gate failed (uat: block)"}).err(); err == nil {
|
||||
t.Fatal("block must fail the scan")
|
||||
}
|
||||
for _, d := range []string{"pass", "warn", ""} {
|
||||
if err := (platformGate{Decision: d}).err(); err != nil {
|
||||
t.Errorf("%q must not fail the scan: %v", d, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user