diff --git a/.integraci/modules-732ec6c83925 b/.integraci/modules-732ec6c83925 new file mode 100644 index 0000000..501da86 --- /dev/null +++ b/.integraci/modules-732ec6c83925 @@ -0,0 +1 @@ +732ec6c83925 \ No newline at end of file diff --git a/README.md b/README.md index 42e4c21..98e7316 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,200 @@ -# integraci-dagger-modules +# Dagger modules -IntegraCI build modules — published by the platform, upgraded in place \ No newline at end of file +The build/scan/deploy logic every CI engine calls. A template renders a +`dagger call --mod=/ --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=/ --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. diff --git a/SHA256SUMS b/SHA256SUMS new file mode 100644 index 0000000..0a4cc84 --- /dev/null +++ b/SHA256SUMS @@ -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 diff --git a/ai-code-review/README.md b/ai-code-review/README.md new file mode 100644 index 0000000..97de0cf --- /dev/null +++ b/ai-code-review/README.md @@ -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 diff --git a/ai-code-review/dagger.json b/ai-code-review/dagger.json new file mode 100644 index 0000000..b19a841 --- /dev/null +++ b/ai-code-review/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "ai-code-review", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/ai-code-review/main.go b/ai-code-review/main.go new file mode 100644 index 0000000..a725f8e --- /dev/null +++ b/ai-code-review/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/..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("\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 +} diff --git a/container-paas-deploy/README.md b/container-paas-deploy/README.md new file mode 100644 index 0000000..778bde7 --- /dev/null +++ b/container-paas-deploy/README.md @@ -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 +``` diff --git a/container-paas-deploy/dagger.json b/container-paas-deploy/dagger.json new file mode 100644 index 0000000..d8336e8 --- /dev/null +++ b/container-paas-deploy/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "container-paas-deploy", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/container-paas-deploy/main.go b/container-paas-deploy/main.go new file mode 100644 index 0000000..adac6a7 --- /dev/null +++ b/container-paas-deploy/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 +} diff --git a/contract-test/.gitattributes b/contract-test/.gitattributes new file mode 100644 index 0000000..d3384f5 --- /dev/null +++ b/contract-test/.gitattributes @@ -0,0 +1,3 @@ +/dagger.gen.go linguist-generated +/internal/dagger/** linguist-generated +/internal/telemetry/** linguist-generated diff --git a/contract-test/.gitignore b/contract-test/.gitignore new file mode 100644 index 0000000..3342715 --- /dev/null +++ b/contract-test/.gitignore @@ -0,0 +1,4 @@ +/dagger.gen.go +/internal/dagger +/internal/telemetry +/.env diff --git a/contract-test/README.md b/contract-test/README.md new file mode 100644 index 0000000..6bff276 --- /dev/null +++ b/contract-test/README.md @@ -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. diff --git a/contract-test/dagger.json b/contract-test/dagger.json new file mode 100644 index 0000000..4c5310c --- /dev/null +++ b/contract-test/dagger.json @@ -0,0 +1,10 @@ +{ + "name": "contract-test", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "include": [ + "./main.go" + ] +} diff --git a/contract-test/go.mod b/contract-test/go.mod new file mode 100644 index 0000000..18f8b31 --- /dev/null +++ b/contract-test/go.mod @@ -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 diff --git a/contract-test/go.sum b/contract-test/go.sum new file mode 100644 index 0000000..1336182 --- /dev/null +++ b/contract-test/go.sum @@ -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= diff --git a/contract-test/main.go b/contract-test/main.go new file mode 100644 index 0000000..280b4db --- /dev/null +++ b/contract-test/main.go @@ -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 +} diff --git a/cosign/README.md b/cosign/README.md new file mode 100644 index 0000000..0279978 --- /dev/null +++ b/cosign/README.md @@ -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 (`[: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 `.sig` and `.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 `@` (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. diff --git a/cosign/attestation/attestation.go b/cosign/attestation/attestation.go new file mode 100644 index 0000000..7c46e16 --- /dev/null +++ b/cosign/attestation/attestation.go @@ -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 +} diff --git a/cosign/attestation/attestation_test.go b/cosign/attestation/attestation_test.go new file mode 100644 index 0000000..c5f8f08 --- /dev/null +++ b/cosign/attestation/attestation_test.go @@ -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) + } + } +} diff --git a/cosign/attestation/gate.go b/cosign/attestation/gate.go new file mode 100644 index 0000000..4878bde --- /dev/null +++ b/cosign/attestation/gate.go @@ -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 +} diff --git a/cosign/attestation/gate_test.go b/cosign/attestation/gate_test.go new file mode 100644 index 0000000..e873b85 --- /dev/null +++ b/cosign/attestation/gate_test.go @@ -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) + } + } +} diff --git a/cosign/attestation/tlog.go b/cosign/attestation/tlog.go new file mode 100644 index 0000000..273ce35 --- /dev/null +++ b/cosign/attestation/tlog.go @@ -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 +} diff --git a/cosign/attestation/tlog_test.go b/cosign/attestation/tlog_test.go new file mode 100644 index 0000000..49a36f3 --- /dev/null +++ b/cosign/attestation/tlog_test.go @@ -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) + } +} diff --git a/cosign/attestation/verify.go b/cosign/attestation/verify.go new file mode 100644 index 0000000..474aeff --- /dev/null +++ b/cosign/attestation/verify.go @@ -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 `@`. + SourceRepo string +} + +// VerifiedProvenance describes the statement that satisfied the expectation. +type VerifiedProvenance struct { + BuilderID string + SourceURI string + Subjects []string // "@sha256:" 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= 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 @ 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 "@". "…/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 +} diff --git a/cosign/attestation/verify_test.go b/cosign/attestation/verify_test.go new file mode 100644 index 0000000..c84a1fa --- /dev/null +++ b/cosign/attestation/verify_test.go @@ -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) + } + } +} diff --git a/cosign/dagger.json b/cosign/dagger.json new file mode 100644 index 0000000..06add76 --- /dev/null +++ b/cosign/dagger.json @@ -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" + ] +} diff --git a/cosign/main.go b/cosign/main.go new file mode 100644 index 0000000..76ca78d --- /dev/null +++ b/cosign/main.go @@ -0,0 +1,1217 @@ +// Package main implements the IntegraCI Cosign Dagger module. +// +// Signs container images with Cosign (Sigstore) using either keyless OIDC +// (recommended for CI) or a key pair stored in OpenBao. Verification uses the +// same modes. Outputs: signature reference, transparency log entry URL. +// +// Usage (sign with keyless): +// +// dagger call sign \ +// --image ghcr.io/integraci/payments-api:1.2.3 \ +// --keyless \ +// --identity-token env:ACTIONS_ID_TOKEN_REQUEST_TOKEN +// +// Usage (sign with key from OpenBao): +// +// dagger call sign \ +// --image ghcr.io/integraci/payments-api:1.2.3 \ +// --private-key file:cosign.key \ +// --password env:COSIGN_PASSWORD +// +// Usage (verify): +// +// dagger call verify --image ghcr.io/integraci/payments-api:1.2.3 --public-key file:cosign.pub +package main + +import ( + "context" + "crypto/sha256" + "dagger/cosign/attestation" + "dagger/cosign/internal/dagger" + _ "embed" + "encoding/hex" + "fmt" + "os" + "strings" + "time" +) + +// gatePolicy is the attestation gate, byte-identical to +// infra/policies/bundles/attestation-gate/attestation_gate.rego (a test in +// apps/api/tests/test_supply_chain_phase2.py keeps the two in step). +// +//go:embed policy/attestation_gate.rego +var gatePolicy string + +// opaImage evaluates the gate. Tag-pinned, the same version the platform's +// own OPA runs; no digest is pinned because none was looked up (#2143). +const opaImage = "openpolicyagent/opa:1.0.0" + +// daggerEngineVersion is the engine every module's dagger.json pins; recorded +// as the provenance builder version. Before #2143 this said v0.15.0. +const daggerEngineVersion = "v0.21.7" + +// Cosign is the IntegraCI artifact signing module. +type Cosign struct{} + +// SignResult contains the output of a signing operation. +type SignResult struct { + Image string `json:"image"` + Signature string `json:"signature"` // Cosign signature reference (e.g., image:tag.sig) + TransparencyLog string `json:"transparency_log"` // Rekor entry URL (keyless mode) + BundlePath string `json:"bundle_path,omitempty"` + Success bool `json:"success"` + KeylessIdentity string `json:"keyless_identity,omitempty"` + // Notice is set when the call relied on a deprecated default (see + // attestation.LegacyKeylessNotice); also printed to stderr. + Notice string `json:"notice,omitempty"` +} + +// VerifyResult contains the output of a verification operation. +type VerifyResult struct { + Image string `json:"image"` + Verified bool `json:"verified"` + Subjects []string `json:"subjects,omitempty"` // Subject identities from cert (keyless) + Error string `json:"error,omitempty"` +} + +// cosignContainer returns a fresh Cosign container with an isolated home so +// runs don't pollute each other's keychain / SIGSTORE_* state. +func (m *Cosign) cosignContainer() *dagger.Container { + return dag.Container(). + From("gcr.io/projectsigstore/cosign:v2.4.1"). + WithEnvVariable("HOME", "/tmp/cosign-home"). + WithEnvVariable("COSIGN_YES", "true") // non-interactive +} + +// Sign signs a container image with Cosign. +// +// Mode selection: +// - If keyless == true: use OIDC identity (Fulcio + Rekor). Requires ambient +// OIDC token (GitHub Actions, GitLab CI) or --identity-token override. +// - Else: use the supplied --private-key (file or env). Optional --password. +func (m *Cosign) Sign( + ctx context.Context, + // Full image reference including digest or tag (e.g. ghcr.io/org/app:1.0.0) + image string, + // Use keyless signing via Fulcio/Rekor (recommended for CI) + // +optional + keyless bool, + // Private key (Cosign-format) for keyed signing + // +optional + privateKey *dagger.Secret, + // Password for the private key (if encrypted) + // +optional + password *dagger.Secret, + // Identity token (OIDC) override — when not running on a supported CI + // +optional + identityToken *dagger.Secret, + // Registry username (for pushing the .sig artifact) + // +optional + registryUser string, + // Registry password / token + // +optional + registryPassword *dagger.Secret, + // Annotations to attach (key=value, comma-separated) + // +optional + annotations string, + // Upload the keyed signature to the PUBLIC Sigstore Rekor (off by default: + // an entry there is public and permanent) + // +optional + publicRekor bool, + // Private Rekor to upload to instead (https; wins over --public-rekor) + // +optional + rekorURL string, + // Public key (PEM) of the private Rekor at --rekor-url + // +optional + rekorPublicKey *dagger.Secret, +) (*SignResult, error) { + if image == "" { + return nil, fmt.Errorf("--image is required") + } + if !keyless && privateKey == nil { + return nil, fmt.Errorf("either --keyless or --private-key must be provided") + } + tlog, err := signTlog(keyless, rekorURL, publicRekor) + if err != nil { + return nil, err + } + + c := withRekorPublicKey(m.cosignContainer(), rekorPublicKey) + + // Registry auth (so we can push the signature artifact) + if registryUser != "" && registryPassword != nil { + c = c. + WithSecretVariable("REG_PASSWORD", registryPassword). + WithExec([]string{ + "sh", "-c", + fmt.Sprintf("cosign login %s -u %s -p $REG_PASSWORD", + registryHost(image), registryUser), + }) + } + + args := []string{"cosign", "sign"} + + if annotations != "" { + for _, kv := range strings.Split(annotations, ",") { + kv = strings.TrimSpace(kv) + if kv == "" { + continue + } + args = append(args, "-a", kv) + } + } + + result := &SignResult{Image: image} + + if keyless { + // Use Sigstore Public Good Instance for Fulcio + Rekor. + c = c.WithEnvVariable("COSIGN_EXPERIMENTAL", "1") + if identityToken != nil { + c = c.WithSecretVariable("COSIGN_IDENTITY_TOKEN", identityToken) + args = append(args, "--identity-token", "$COSIGN_IDENTITY_TOKEN") + } + // Joined into `sh -c` below: CheckRekorURL's charset keeps it inert. + args = append(args, tlog...) + args = append(args, image) + out, err := c.WithExec([]string{"sh", "-c", strings.Join(args, " ")}).Stderr(ctx) + if err != nil { + return nil, fmt.Errorf("cosign keyless sign failed: %w", err) + } + result.TransparencyLog = extractRekorURL(out) + result.KeylessIdentity = extractIdentity(out) + } else { + c = c.WithMountedSecret("/tmp/cosign.key", privateKey) + if password != nil { + c = c.WithSecretVariable("COSIGN_PASSWORD", password) + } + args = append(args, "--key", "/tmp/cosign.key") + args = append(args, tlog...) + args = append(args, image) + if _, err := c.WithExec(args).Sync(ctx); err != nil { + return nil, fmt.Errorf("cosign keyed sign failed: %w", err) + } + } + + result.Signature = signatureRef(image) + result.Success = true + return result, nil +} + +// SignMethod is the engine-agnostic signing entrypoint. It dispatches to the +// requested signing backend so ANY CI engine can sign an image via a single +// `dagger call sign-method` invocation, mirroring +// security_pipeline_adapter.build_signing_step. +// +// Supported methods: +// - cosign: Sigstore cosign. KEYED with --key (the default rendered +// pipelines use since 2026-10-18; no transparency-log upload unless +// --public-rekor / --rekor-url). KEYLESS only with --keyless: the signing +// identity and digest go to the PUBLIC Sigstore Rekor unless --rekor-url +// names a private one. With neither flag the call behaves as it always did +// (keyless) and prints a deprecation notice: pipelines rendered before +// 2026-10-18 make exactly that call and must keep working. +// - notation: NotaryProject `notation sign` (COSE) using the supplied key. +// - gpg: GPG detached-sign of the image manifest. +// - in-toto: in-toto CLI attestation (link metadata) over the manifest. +// - none: no-op skip (mirrors the adapter's _comment_skip). +// +// Usage (keyed cosign — the default): +// +// dagger call sign-method --method cosign --image-ref ghcr.io/org/app:1.0.0 --key env://COSIGN_PRIVATE_KEY +// +// Usage (keyless cosign against a private Rekor): +// +// dagger call sign-method --method cosign --image-ref ghcr.io/org/app:1.0.0 --keyless \ +// --identity-token env://SIGSTORE_ID_TOKEN \ +// --rekor-url https://rekor.example.internal --rekor-public-key env://COSIGN_REKOR_PUBLIC_KEY +func (m *Cosign) SignMethod( + ctx context.Context, + // Signing method: cosign | notation | gpg | in-toto | none + // +optional + // +default="cosign" + method string, + // Full image reference including digest or tag + imageRef string, + // Signing key material. Interpretation depends on method: + // cosign -> Cosign private key (keyless when omitted) + // notation-> signing key (PEM) + // gpg -> ASCII-armored GPG private key to import + // in-toto -> in-toto functionary signing key (PEM) + // +optional + key *dagger.Secret, + // cosign only: upload a keyed signature to the PUBLIC Sigstore Rekor (off + // by default) + // +optional + publicRekor bool, + // cosign only: private Rekor to use instead (https; wins over --public-rekor) + // +optional + rekorURL string, + // cosign only: sign KEYLESS (Fulcio certificate + transparency log). The + // entry is PUBLIC unless --rekor-url names a private Rekor. Mutually + // exclusive with --key. + // +optional + keyless bool, + // cosign keyless only: OIDC identity token for Fulcio. Handed to cosign + // through SIGSTORE_ID_TOKEN, never on the command line (argv is visible in + // Dagger traces). Without it cosign looks for an ambient provider, which a + // Dagger container does not inherit from the CI runner. + // +optional + identityToken *dagger.Secret, + // cosign keyed only: password of an encrypted private key. Without it an + // empty password is assumed (cosign would otherwise wait on a terminal). + // +optional + password *dagger.Secret, + // cosign only: public key (PEM) of the private Rekor at --rekor-url. cosign + // checks the log entry it gets back against it. + // +optional + rekorPublicKey *dagger.Secret, +) (*SignResult, error) { + if method == "" { + method = "cosign" + } + if method != "cosign" && (keyless || identityToken != nil || rekorPublicKey != nil) { + return nil, fmt.Errorf("--keyless, --identity-token and --rekor-public-key apply to --method cosign only") + } + if method != "none" && imageRef == "" { + return nil, fmt.Errorf("--image-ref is required") + } + + switch method { + case "none": + // No-op skip, mirroring the adapter's _comment_skip intent. + return &SignResult{ + Image: imageRef, + Success: true, + }, nil + + case "cosign": + mode, legacy, err := attestation.SignMethodMode(key != nil, keyless) + if err != nil { + return nil, err + } + if mode == "keyed" && identityToken != nil { + return nil, fmt.Errorf("--identity-token is for keyless signing; keyed signing uses --key") + } + tlog, err := signTlog(mode == "keyless", rekorURL, publicRekor) + if err != nil { + return nil, err + } + c := withRekorPublicKey(m.cosignContainer(), rekorPublicKey) + if mode == "keyless" { + notice := "" + if legacy { + // Printed so it lands in the CI log of every pipeline that still + // relies on the old default, whether or not it is ever re-rendered. + notice = attestation.LegacyKeylessNotice + fmt.Fprintln(os.Stderr, notice) + } + // Keyless OIDC (Fulcio + Rekor). + c = c.WithEnvVariable("COSIGN_EXPERIMENTAL", "1") + if identityToken != nil { + c = c.WithSecretVariable("SIGSTORE_ID_TOKEN", identityToken) + } + args := append([]string{"cosign", "sign", "--yes"}, tlog...) + out, err := c.WithExec(append(args, imageRef)).Stderr(ctx) + if err != nil { + return nil, fmt.Errorf("cosign keyless sign failed: %w", err) + } + return &SignResult{ + Image: imageRef, + Signature: signatureRef(imageRef), + TransparencyLog: extractRekorURL(out), + KeylessIdentity: extractIdentity(out), + Success: true, + Notice: notice, + }, nil + } + // Keyed signing via env://COSIGN_PRIVATE_KEY. + c = c.WithSecretVariable("COSIGN_PRIVATE_KEY", key) + if password != nil { + c = c.WithSecretVariable("COSIGN_PASSWORD", password) + } else { + c = c.WithEnvVariable("COSIGN_PASSWORD", "") + } + args := append([]string{"cosign", "sign", "--yes", "--key", "env://COSIGN_PRIVATE_KEY"}, tlog...) + if _, err := c.WithExec(append(args, imageRef)).Sync(ctx); err != nil { + return nil, fmt.Errorf("cosign keyed sign failed: %w", err) + } + return &SignResult{ + Image: imageRef, + Signature: signatureRef(imageRef), + Success: true, + }, nil + + case "notation": + if key == nil { + return nil, fmt.Errorf("--key is required for notation signing") + } + // NotaryProject notation CLI: sign with a COSE signature. + c := dag.Container(). + From("notaryproject/notation:v1.3.1"). + WithEnvVariable("HOME", "/tmp/notation-home"). + WithMountedSecret("/tmp/notation.key", key) + if _, err := c.WithExec([]string{ + "notation", "sign", + "--signature-format", "cose", + "--key", "/tmp/notation.key", + imageRef, + }).Sync(ctx); err != nil { + return nil, fmt.Errorf("notation sign failed: %w", err) + } + return &SignResult{ + Image: imageRef, + Signature: imageRef + " (notation cose signature)", + Success: true, + }, nil + + case "gpg": + if key == nil { + return nil, fmt.Errorf("--key is required for gpg signing") + } + // Import the GPG key, inspect the manifest, and produce a detached + // armored signature over it. + c := dag.Container(). + From("alpine:3.20"). + WithExec([]string{"apk", "add", "--no-cache", "gnupg", "skopeo"}). + WithMountedSecret("/tmp/gpg.key", key). + WithEnvVariable("CACHEBUST", imageRef) + script := strings.Join([]string{ + "gpg --batch --import /tmp/gpg.key", + fmt.Sprintf("skopeo inspect --raw docker://%s > manifest.json", imageRef), + "gpg --batch --yes --detach-sign --armor manifest.json", + }, " && ") + if _, err := c.WithExec([]string{"sh", "-c", script}).Sync(ctx); err != nil { + return nil, fmt.Errorf("gpg sign failed: %w", err) + } + return &SignResult{ + Image: imageRef, + Signature: imageRef + " (gpg detached manifest.json.asc)", + Success: true, + }, nil + + case "in-toto": + if key == nil { + return nil, fmt.Errorf("--key is required for in-toto attestation") + } + // in-toto CLI: record a link-metadata attestation over the image. + c := dag.Container(). + From("python:3.12-slim"). + WithExec([]string{"pip", "install", "--no-cache-dir", "in-toto"}). + WithMountedSecret("/tmp/intoto.key", key). + WithEnvVariable("CACHEBUST", imageRef) + script := strings.Join([]string{ + fmt.Sprintf(`in-toto-run --step-name sign --key /tmp/intoto.key --products "%s" --no-command`, imageRef), + }, " && ") + if _, err := c.WithExec([]string{"sh", "-c", script}).Sync(ctx); err != nil { + return nil, fmt.Errorf("in-toto attestation failed: %w", err) + } + return &SignResult{ + Image: imageRef, + Signature: imageRef + " (in-toto link attestation)", + Success: true, + }, nil + + default: + return nil, fmt.Errorf("unsupported signing method: %q (want cosign|notation|gpg|in-toto|none)", method) + } +} + +// Verify checks that an image carries a valid Cosign signature. +func (m *Cosign) Verify( + ctx context.Context, + image string, + // Public key for keyed verification + // +optional + publicKey *dagger.Secret, + // Expect a keyless signature; --identity-regex / --issuer-regex required if so. + // +optional + keyless bool, + // Regex for the signing identity (e.g. ".+@integraci\\.io") + // +optional + identityRegex string, + // Regex for the OIDC issuer (e.g. "https://token\\.actions\\.githubusercontent\\.com") + // +optional + issuerRegex string, + // Keyed: the signature was uploaded to the PUBLIC Rekor (same choice as + // at signing; without it the key alone is checked) + // +optional + publicRekor bool, + // Private Rekor the signature was uploaded to (https) + // +optional + rekorURL string, + // Public key (PEM) of the private Rekor at --rekor-url; required with it + // (the log entry's SET is checked against this key) + // +optional + rekorPublicKey *dagger.Secret, +) (*VerifyResult, error) { + if image == "" { + return nil, fmt.Errorf("--image is required") + } + tlog, err := verifyTlog(keyless, rekorURL, publicRekor) + if err != nil { + return nil, err + } + if err := attestation.CheckRekorPublicKey(rekorURL, rekorPublicKey != nil); err != nil { + return nil, err + } + c := withRekorPublicKey(m.cosignContainer(), rekorPublicKey) + args := []string{"cosign", "verify"} + + if keyless { + c = c.WithEnvVariable("COSIGN_EXPERIMENTAL", "1") + if identityRegex == "" || issuerRegex == "" { + return nil, fmt.Errorf("--identity-regex and --issuer-regex required for keyless verify") + } + if err := attestation.CheckRegex("--identity-regex", identityRegex); err != nil { + return nil, err + } + if err := attestation.CheckRegex("--issuer-regex", issuerRegex); err != nil { + return nil, err + } + // Anchored to the whole value (#2435): cosign matches anywhere. + args = append(args, + "--certificate-identity-regexp", attestation.AnchorRegex(identityRegex), + "--certificate-oidc-issuer-regexp", attestation.AnchorRegex(issuerRegex), + ) + } else { + if publicKey == nil { + return nil, fmt.Errorf("--public-key required for keyed verify") + } + c = c.WithMountedSecret("/tmp/cosign.pub", publicKey) + args = append(args, "--key", "/tmp/cosign.pub") + } + args = append(args, tlog...) + args = append(args, image) + + out, err := c.WithExec(args).Stdout(ctx) + if err != nil { + return &VerifyResult{Image: image, Verified: false, Error: err.Error()}, nil + } + return &VerifyResult{ + Image: image, + Verified: true, + Subjects: extractSubjects(out), + }, nil +} + +// AttestProvenance generates an SLSA Build Level 3 provenance predicate +// (in-toto attestation) and attaches it to the image. The predicate is +// built in-process from the supplied build metadata so it is consistent +// regardless of the underlying CI provider. +// +// SLSA L3 requires: +// - Build platform is hardened (e.g. ephemeral GitHub Actions runner +// or Dagger engine in an isolated VM). +// - Provenance is signed by the build platform (we sign with Cosign +// keyless using the workflow's OIDC identity). +// - Provenance is non-falsifiable (the OIDC subject is bound to the +// workflow ref + commit SHA — verifiable at consumption time). +// +// The predicate type is `https://slsa.dev/provenance/v1` (SLSA v1.0). +// +// Usage (from a GitHub Actions release job): +// +// dagger 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)" \ +// --build-type https://actions.github.io/buildtypes/workflow/v1 \ +// --invocation-id ${{ github.run_id }} \ +// --keyless +// +// Usage (attach the statement standard-build `evidence` wrote — preferred, +// so the archived evidence and the registry attestation are one set): +// +// dagger call attest-provenance \ +// --image registry.example/team/orders:abc@sha256: \ +// --predicate evidence/provenance.intoto.json --keyless +func (m *Cosign) AttestProvenance( + ctx context.Context, + // Image reference pinned to a digest: [:tag]@sha256:<64 hex> + image string, + // SLSA `builder.id` — fully-qualified workflow ref. For GitHub Actions: + // "https://github.com///.github/workflows/.yml@" + // Required unless --predicate is given. + // +optional + builderID string, + // SLSA `buildType` — e.g. "https://actions.github.io/buildtypes/workflow/v1" + // +optional + // +default="https://actions.github.io/buildtypes/workflow/v1" + buildType string, + // VCS source URI — "git+https://github.com//@". + // Required unless --predicate is given. + // +optional + sourceURI string, + // Full source commit id (40 or 64 hex; a `sha1:`/`sha256:` prefix is + // tolerated) — pinpoints the exact commit. Required unless --predicate. + // +optional + sourceDigest string, + // Build invocation ID (e.g. GitHub Actions run_id) for traceability. + // +optional + invocationID string, + // Build start time in RFC3339. Defaults to now (the attest time — pass the + // real value from CI when it matters). + // +optional + startedOn string, + // Build finish time in RFC3339. Defaults to now. + // +optional + finishedOn string, + // Use keyless OIDC signing (recommended for CI). + // +optional + keyless bool, + // Private key for keyed signing. + // +optional + privateKey *dagger.Secret, + // in-toto Statement (SLSA v1 provenance) written by standard-build + // `evidence` — provenance.intoto.json. When given, its predicate is what + // is attached, after checking its subject is --image's digest; --image + // must then be digest-pinned, and the builder/source flags are ignored. + // +optional + predicate *dagger.File, + // Registry username, so cosign can push the attestation to a private + // registry. Paired with --registry-password. + // +optional + registryUsername string, + // Registry password/token for --registry-username. + // +optional + registryPassword *dagger.Secret, + // The registry is served over plain HTTP / self-signed TLS (same opt-in + // as standard-build's --registry-insecure) + // +optional + registryInsecure bool, + // Upload a keyed attestation to the PUBLIC Sigstore Rekor. Off by default: + // the entry publishes the provenance (registry and git hosts, repository + // paths, CI job URL, commit) permanently. + // +optional + publicRekor bool, + // Private Rekor to upload to instead (https; wins over --public-rekor) + // +optional + rekorURL string, + // Public key (PEM) of the private Rekor at --rekor-url + // +optional + rekorPublicKey *dagger.Secret, +) (*SignResult, error) { + if image == "" { + return nil, fmt.Errorf("--image is required") + } + tlog, err := signTlog(keyless, rekorURL, publicRekor) + if err != nil { + return nil, err + } + // Digest-pinned on BOTH paths. cosign resolves a tag at attest time, so a + // tag pushed again between build and attest would sign provenance about + // another build's image — the gap `standard-build evidence` refuses too. + if _, err := attestation.ImageDigest(image); err != nil { + return nil, fmt.Errorf("--image: %w", err) + } + if predicate == nil && builderID == "" { + return nil, fmt.Errorf("--builder-id is required (must be a stable, verifiable URI)") + } + if predicate == nil && (sourceURI == "" || sourceDigest == "") { + return nil, fmt.Errorf("--source-uri and --source-digest are required") + } + if buildType == "" { + buildType = "https://actions.github.io/buildtypes/workflow/v1" + } + + var predicateBody []byte + if predicate != nil { + // Attach the statement standard-build's `evidence` wrote, byte for + // byte its predicate — so what a verifier pulls from the registry is + // what was archived with the build. Only after checking the statement + // is about THIS digest. + raw, err := predicate.Contents(ctx) + if err != nil { + return nil, fmt.Errorf("reading --predicate: %w", err) + } + predicateBody, err = attestation.PredicateFromStatement([]byte(raw), image) + if err != nil { + return nil, err + } + } else { + var err error + predicateBody, err = attestation.ProvenancePredicate(attestation.ProvenanceInput{ + BuilderID: builderID, + BuildType: buildType, + SourceURI: sourceURI, + SourceDigest: sourceDigest, + InvocationID: invocationID, + StartedOn: startedOn, + FinishedOn: finishedOn, + EngineVersion: daggerEngineVersion, + Now: time.Now(), + }) + if err != nil { + return nil, err + } + } + + c, err := withRegistryAuth(ctx, withRekorPublicKey(m.cosignContainer(), rekorPublicKey), image, registryUsername, registryPassword) + if err != nil { + return nil, err + } + c = c.WithNewFile("/tmp/provenance.json", string(predicateBody)) + + args := []string{ + "cosign", "attest", + "--type", "slsaprovenance1", + "--predicate", "/tmp/provenance.json", + } + args = append(args, insecureRegistryArgs(registryInsecure)...) + + if keyless { + c = c.WithEnvVariable("COSIGN_EXPERIMENTAL", "1") + } else { + if privateKey == nil { + return nil, fmt.Errorf("--private-key required when not keyless") + } + // An empty COSIGN_PASSWORD is what a key generated with an empty + // password needs; without it cosign asks a terminal there is none of. + c = c.WithMountedSecret("/tmp/cosign.key", privateKey). + WithEnvVariable("COSIGN_PASSWORD", "") + args = append(args, "--key", "/tmp/cosign.key") + } + args = append(args, tlog...) + args = append(args, image) + + out, err := c.WithExec(args).Stderr(ctx) + if err != nil { + return nil, fmt.Errorf("cosign attest provenance failed: %w", err) + } + return &SignResult{ + Image: image, + Signature: image + ".att (slsaprovenance1)", + TransparencyLog: extractRekorURL(out), + KeylessIdentity: extractIdentity(out), + Success: true, + }, nil +} + +// VerifyProvenance verifies that an image carries an SLSA v1 provenance +// attestation that was issued by the expected builder. This is the +// gate consumers (e.g. Argo CD admission controller) should call before +// promoting an image to production. +// +// cosign checks the signature; this then decodes each DSSE envelope and +// requires one in-toto statement whose subject is --image's digest, whose +// runDetails.builder.id equals --expected-builder-id exactly, and whose source +// (first resolvedDependency) is --expected-source-repo pinned to a commit (see +// attestation.VerifyProvenanceOutput). +// +// builder.id is only a string inside what was signed, so the trust anchor is +// the SIGNER: by default the certificate identity must equal +// --expected-builder-id (for GitHub Actions keyless signing both are +// `https://github.com///.github/workflows/.yml@`). A +// broad --identity-regex replaces that binding — then any workflow it admits +// can claim the builder id. +func (m *Cosign) VerifyProvenance( + ctx context.Context, + // Image reference pinned to a digest: [:tag]@sha256:<64 hex> + image string, + // Expected builder.id — must match exactly, and by default is also the + // exact certificate identity the attestation must be signed by. + expectedBuilderID string, + // Expected source repository URI (without ref or commit digest). + expectedSourceRepo string, + // Cert-identity regex for the OIDC subject (keyless). Replaces the default + // exact identity (= --expected-builder-id); anchor it (^…$). + // +optional + identityRegex string, + // OIDC issuer regex (keyless). Matched against the WHOLE issuer: it is + // anchored (^(?:…)$) before cosign sees it (#2435). + // +optional + // +default="https://token\\.actions\\.githubusercontent\\.com" + issuerRegex string, + // Private Rekor the attestation was logged in (https). Without it cosign + // checks the public Sigstore Rekor, which a keyless signature needs. + // +optional + rekorURL string, + // Public key (PEM) of the private Rekor at --rekor-url; required with it + // +optional + rekorPublicKey *dagger.Secret, +) (*VerifyResult, error) { + if image == "" { + return nil, fmt.Errorf("--image is required") + } + if expectedBuilderID == "" || expectedSourceRepo == "" { + return nil, fmt.Errorf("--expected-builder-id and --expected-source-repo are required") + } + tlog, err := attestation.KeylessTlogArgs(rekorURL) + if err != nil { + return nil, err + } + if err := attestation.CheckRekorPublicKey(rekorURL, rekorPublicKey != nil); err != nil { + return nil, err + } + if err := attestation.CheckRegex("--issuer-regex", issuerRegex); err != nil { + return nil, err + } + if err := attestation.CheckRegex("--identity-regex", identityRegex); err != nil { + return nil, err + } + // The statement's subject is compared with this digest, and a tag could + // move between this check and the deploy it gates. + if _, err := attestation.ImageDigest(image); err != nil { + return nil, fmt.Errorf("--image: %w", err) + } + if issuerRegex == "" { + issuerRegex = `https://token\.actions\.githubusercontent\.com` + } + + c := withRekorPublicKey(m.cosignContainer(), rekorPublicKey).WithEnvVariable("COSIGN_EXPERIMENTAL", "1") + // Before #2337 an empty regex passed no identity flag at all, which cosign + // v2 refuses for keyless verification — so the gate could not pass. Now the + // signer is bound to the builder the statement must name. + args := attestation.VerifyAttestationArgs(image, expectedBuilderID, identityRegex, issuerRegex) + // The image stays the last argument; the log flags go before it. + args = append(append(args[:len(args)-1:len(args)-1], tlog...), image) + + // Both refusals below are errors, so `dagger call verify-provenance` exits + // non-zero: a gate written as `verify-provenance … && deploy` must stop. + // Before #2337 they returned Verified:false with a nil error — exit 0 — + // and only a caller that parsed .verified was protected. + out, err := c.WithExec(args).Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("provenance of %s not verified: cosign: %w", image, err) + } + + // Decide on what the signed statement SAYS, field by field. Before #2337 + // this was strings.Contains over the raw output — but cosign prints DSSE + // envelopes whose payload is base64, so the builder id never appeared in + // plain text, and a substring match would also have accepted a prefix of + // the expected repo or the id quoted anywhere in the statement. + vp, err := attestation.VerifyProvenanceOutput([]byte(out), attestation.ProvenanceExpectation{ + Image: image, + BuilderID: expectedBuilderID, + SourceRepo: expectedSourceRepo, + }) + if err != nil { + return nil, fmt.Errorf("provenance of %s not verified: %w", image, err) + } + + return &VerifyResult{ + Image: image, + Verified: true, + Subjects: vp.Subjects, + }, nil +} + +// withRegistryAuth logs cosign into the image's registry by mounting a +// docker config.json as a secret. No shell and no argv carries the username or +// password (compare Sign's `cosign login` line). Both empty = no auth, which +// is the existing behaviour; exactly one of them is refused. +func withRegistryAuth( + ctx context.Context, + c *dagger.Container, + image, username string, + password *dagger.Secret, +) (*dagger.Container, error) { + if username == "" && password == nil { + return c, nil + } + if username == "" || password == nil { + return nil, fmt.Errorf("--registry-username and --registry-password go together") + } + plain, err := password.Plaintext(ctx) + if err != nil { + return nil, fmt.Errorf("reading --registry-password: %w", err) + } + host := attestation.RegistryHost(image) + cfg, err := attestation.RegistryAuthConfig(host, username, plain) + if err != nil { + return nil, err + } + // Named by host and username only. The config holds the password, and a + // secret's NAME can surface in traces, so it must not be derived from it. + sum := sha256.Sum256([]byte(host + "\x00" + username)) + secret := dag.SetSecret("cosign-registry-auth-"+hex.EncodeToString(sum[:8]), string(cfg)) + // DOCKER_CONFIG, not $HOME/.docker: a mount under HOME would create HOME + // owned by root, and cosign keeps its TUF cache there. Owned by 65532, the + // nonroot user of the cosign image (harmless if it runs as root). + return c. + WithEnvVariable("DOCKER_CONFIG", "/tmp/docker-auth"). + WithMountedSecret("/tmp/docker-auth/config.json", secret, cosignOwned), nil +} + +// insecureRegistryArgs are cosign's flags for a registry without trusted TLS. +func insecureRegistryArgs(insecure bool) []string { + if !insecure { + return nil + } + return []string{"--allow-insecure-registry", "--allow-http-registry"} +} + +// cosignOwned makes a mounted secret readable by the cosign image's nonroot +// user (65532). +var cosignOwned = dagger.ContainerWithMountedSecretOpts{Owner: "65532"} + +// SignBlob signs a file with cosign `sign-blob` and returns a directory +// holding `.sig` (base64 signature) and `.bundle` (signature, +// certificate and transparency-log entry, for an offline verify-blob). +// +// Written for the SHA256SUMS that standard-build `evidence` emits (#2143 +// phase 2). An unsigned SHA256SUMS detects CORRUPTION only: anyone who can +// change a file can rewrite its line too. Signed, it detects TAMPERING: +// +// cosign verify-blob --key cosign.pub \ +// --signature SHA256SUMS.sig --bundle SHA256SUMS.bundle SHA256SUMS +// sha256sum -c --strict SHA256SUMS +// +// Keyed signing does NOT upload to a transparency log unless asked for +// (--public-rekor, or --rekor-url for a private Rekor; owner decision +// 2026-10-11), so it works air-gapped. Without a log entry, verify with +// `cosign verify-blob --insecure-ignore-tlog=true …`: the key alone is the +// trust anchor then. Keyless signing still needs a log (public unless +// --rekor-url). +func (m *Cosign) SignBlob( + ctx context.Context, + // The file to sign + blob *dagger.File, + // Base name for the outputs (plain file name) + // +optional + // +default="SHA256SUMS" + name string, + // Use keyless OIDC signing + // +optional + keyless bool, + // Private key for keyed signing + // +optional + privateKey *dagger.Secret, + // Password for the private key (if encrypted) + // +optional + password *dagger.Secret, + // Upload a keyed signature to the PUBLIC Sigstore Rekor (off by default) + // +optional + publicRekor bool, + // Private Rekor to upload to instead (https; wins over --public-rekor) + // +optional + rekorURL string, + // Public key (PEM) of the private Rekor at --rekor-url + // +optional + rekorPublicKey *dagger.Secret, +) (*dagger.Directory, error) { + if name == "" { + name = "SHA256SUMS" + } + tlog, err := signTlog(keyless, rekorURL, publicRekor) + if err != nil { + return nil, err + } + if err := attestation.CheckBlobName(name); err != nil { + return nil, err + } + if blob == nil { + return nil, fmt.Errorf("--blob is required") + } + c := withRekorPublicKey(m.cosignContainer(), rekorPublicKey).WithMountedFile("/tmp/blob", blob) + args := []string{ + "cosign", "sign-blob", "--yes", + "--output-signature", "/tmp/out/" + name + ".sig", + "--bundle", "/tmp/out/" + name + ".bundle", + } + if keyless { + c = c.WithEnvVariable("COSIGN_EXPERIMENTAL", "1") + } else { + if privateKey == nil { + return nil, fmt.Errorf("either --keyless or --private-key must be provided") + } + c = c.WithMountedSecret("/tmp/cosign.key", privateKey, cosignOwned) + if password != nil { + c = c.WithSecretVariable("COSIGN_PASSWORD", password) + } else { + c = c.WithEnvVariable("COSIGN_PASSWORD", "") + } + args = append(args, "--key", "/tmp/cosign.key") + } + args = append(args, tlog...) + args = append(args, "/tmp/blob") + out := c. + WithDirectory("/tmp/out", dag.Directory(), dagger.ContainerWithDirectoryOpts{Owner: "65532"}). + WithExec(args) + if _, err := out.Sync(ctx); err != nil { + return nil, fmt.Errorf("cosign sign-blob failed: %w", err) + } + return dag.Directory(). + WithFile(name+".sig", out.File("/tmp/out/"+name+".sig")). + WithFile(name+".bundle", out.File("/tmp/out/"+name+".bundle")), nil +} + +// GateResult is the attestation gate's decision for one digest. +type GateResult struct { + Image string `json:"image"` + Allowed bool `json:"allowed"` + Deny []string `json:"deny,omitempty"` + // Notes are cosign failures that left a predicate type with no verified + // envelope (no attestation, wrong key, registry unreachable). The gate + // then denies; the note says why. + Notes []string `json:"notes,omitempty"` +} + +// VerifyAttestationGate is the attestation-verifying gate (#2143 phase 2). +// +// cosign verifies the signatures (`verify-attestation --key`), then the +// attestation-gate OPA policy judges the decoded statements: SLSA v1 +// provenance whose subject IS --image's digest, whose builder.id exactly +// equals one of --trusted-builder, and which pins a full commit; plus an SBOM +// attestation about the same digest when --require-sbom is set. +// +// It returns an ERROR when the gate denies, so a CI stage that calls it fails. +// Unlike verify-provenance it never substring-matches cosign's raw output. +// +// Usage: +// +// dagger call verify-attestation-gate \ +// --image=registry.example/team/orders:abc@sha256: \ +// --public-key=env://COSIGN_PUB --trusted-builder=https://ci.example/job/orders/ +func (m *Cosign) VerifyAttestationGate( + ctx context.Context, + // Image reference pinned to a digest: [:tag]@sha256:<64 hex> + image string, + // Cosign public key the attestations must verify against + publicKey *dagger.Secret, + // builder.id values to trust, exact match. Repeat for more than one. + trustedBuilder []string, + // Also require a CycloneDX SBOM attestation about the digest + // +optional + requireSbom bool, + // Registry username for pulling attestations from a private registry + // +optional + registryUsername string, + // Registry password/token for --registry-username + // +optional + registryPassword *dagger.Secret, + // The registry is served over plain HTTP / self-signed TLS + // +optional + registryInsecure bool, + // The attestations were uploaded to the PUBLIC Rekor (the choice made at + // attest time); without it, and without --rekor-url, the key alone is checked + // +optional + publicRekor bool, + // Private Rekor the attestations were uploaded to (https) + // +optional + rekorURL string, + // Public key (PEM) of the private Rekor at --rekor-url; required with it + // +optional + rekorPublicKey *dagger.Secret, +) (*GateResult, error) { + if _, err := attestation.ImageDigest(image); err != nil { + return nil, fmt.Errorf("--image: %w", err) + } + if publicKey == nil { + return nil, fmt.Errorf("--public-key is required") + } + tlog, err := attestation.VerifyTlogArgs(rekorURL, publicRekor) + if err != nil { + return nil, err + } + if err := attestation.CheckRekorPublicKey(rekorURL, rekorPublicKey != nil); err != nil { + return nil, err + } + c, err := withRegistryAuth(ctx, withRekorPublicKey(m.cosignContainer(), rekorPublicKey), image, registryUsername, registryPassword) + if err != nil { + return nil, err + } + c = c.WithMountedSecret("/tmp/cosign.pub", publicKey, cosignOwned) + + types := []string{"slsaprovenance1"} + if requireSbom { + types = append(types, "cyclonedx") + } + result := &GateResult{Image: image} + var envelopes []string + for _, typ := range types { + args := []string{"cosign", "verify-attestation", "--key", "/tmp/cosign.pub", "--type", typ} + args = append(args, insecureRegistryArgs(registryInsecure)...) + args = append(args, tlog...) + out, err := c.WithExec(append(args, image)).Stdout(ctx) + if err != nil { + // Fail closed: no verified envelope for this type. The policy + // denies; the note keeps cosign's reason. + result.Notes = append(result.Notes, fmt.Sprintf("cosign verify-attestation --type %s: %v", typ, err)) + continue + } + envelopes = append(envelopes, out) + } + + input, err := attestation.GateInput(image, strings.Join(envelopes, "\n"), trustedBuilder, requireSbom) + if err != nil { + return nil, err + } + opaOut, err := dag.Container(). + From(opaImage). + WithNewFile("/policy/attestation_gate.rego", gatePolicy). + WithNewFile("/input.json", string(input)). + WithExec([]string{ + "/opa", "eval", "--format", "json", + "--data", "/policy", "--input", "/input.json", + attestation.GatePolicyQuery, + }). + Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("opa eval failed: %w", err) + } + allowed, deny, err := attestation.GateVerdict([]byte(opaOut)) + if err != nil { + return nil, err + } + result.Allowed = allowed + result.Deny = deny + if !allowed { + msg := strings.Join(deny, "; ") + if len(result.Notes) > 0 { + msg += " (" + strings.Join(result.Notes, "; ") + ")" + } + return result, fmt.Errorf("attestation gate denied %s: %s", image, msg) + } + return result, nil +} + +// AttestSBOM attaches an SBOM (CycloneDX/SPDX) to the image as a Cosign +// attestation — e.g. the sbom.cdx.json `standard-build evidence` wrote. +// --image must be pinned to a digest. +func (m *Cosign) AttestSBOM( + ctx context.Context, + image string, + // SBOM file (CycloneDX JSON) + sbom *dagger.File, + // Predicate type — "cyclonedx" or "spdxjson" + // +optional + // +default="cyclonedx" + predicateType string, + // +optional + keyless bool, + // +optional + privateKey *dagger.Secret, + // Upload a keyed attestation to the PUBLIC Sigstore Rekor (off by default) + // +optional + publicRekor bool, + // Private Rekor to upload to instead (https; wins over --public-rekor) + // +optional + rekorURL string, + // Public key (PEM) of the private Rekor at --rekor-url + // +optional + rekorPublicKey *dagger.Secret, +) (*SignResult, error) { + if predicateType == "" { + predicateType = "cyclonedx" + } + tlog, err := signTlog(keyless, rekorURL, publicRekor) + if err != nil { + return nil, err + } + // Same rule as attest-provenance: the SBOM is about one digest. + if _, err := attestation.ImageDigest(image); err != nil { + return nil, fmt.Errorf("--image: %w", err) + } + c := withRekorPublicKey(m.cosignContainer(), rekorPublicKey).WithMountedFile("/tmp/sbom.json", sbom) + + args := []string{ + "cosign", "attest", + "--type", predicateType, + "--predicate", "/tmp/sbom.json", + } + if keyless { + c = c.WithEnvVariable("COSIGN_EXPERIMENTAL", "1") + } else { + if privateKey == nil { + return nil, fmt.Errorf("--private-key required when not keyless") + } + c = c.WithMountedSecret("/tmp/cosign.key", privateKey) + args = append(args, "--key", "/tmp/cosign.key") + } + args = append(args, tlog...) + args = append(args, image) + + if _, err := c.WithExec(args).Sync(ctx); err != nil { + return nil, fmt.Errorf("cosign attest failed: %w", err) + } + return &SignResult{ + Image: image, + Signature: image + ".att", + Success: true, + }, nil +} + +// ───── helpers ───── + +// signTlog picks the transparency-log flags for a signing call (see +// attestation/tlog.go): keyed signing uploads nowhere unless asked; keyless +// needs a log and keeps the public one unless a private Rekor is named. +func signTlog(keyless bool, rekorURL string, publicRekor bool) ([]string, error) { + if keyless { + return attestation.KeylessTlogArgs(rekorURL) + } + return attestation.SignTlogArgs(rekorURL, publicRekor) +} + +// withRekorPublicKey mounts a private Rekor's public key and points cosign at +// it (SIGSTORE_REKOR_PUBLIC_KEY is a path). nil leaves the container as is, so +// cosign keeps the public Sigstore keys from its TUF root. +func withRekorPublicKey(c *dagger.Container, key *dagger.Secret) *dagger.Container { + if key == nil { + return c + } + return c. + WithMountedSecret(attestation.RekorPublicKeyPath, key, cosignOwned). + WithEnvVariable("SIGSTORE_REKOR_PUBLIC_KEY", attestation.RekorPublicKeyPath) +} + +// verifyTlog is signTlog's counterpart for verification. +func verifyTlog(keyless bool, rekorURL string, publicRekor bool) ([]string, error) { + if keyless { + return attestation.KeylessTlogArgs(rekorURL) + } + return attestation.VerifyTlogArgs(rekorURL, publicRekor) +} + +// signatureRef returns the OCI reference Cosign uses for the .sig artifact. +// Cosign convention: replace the tag with `sha256-.sig`. +func signatureRef(image string) string { + // We don't resolve the digest here — let consumers query the registry if + // they need the canonical reference. Returning a human-readable hint. + return image + " (sig artifact at .sig tag)" +} + +func registryHost(image string) string { + if i := strings.IndexByte(image, '/'); i > 0 { + return image[:i] + } + return "docker.io" +} + +func extractRekorURL(out string) string { + const marker = "tlog entry created with index:" + if idx := strings.Index(out, marker); idx >= 0 { + rest := out[idx+len(marker):] + if nl := strings.IndexByte(rest, '\n'); nl > 0 { + id := strings.TrimSpace(rest[:nl]) + return "https://search.sigstore.dev/?logIndex=" + id + } + } + return "" +} + +func extractIdentity(out string) string { + const marker = "Certificate subject:" + for _, line := range strings.Split(out, "\n") { + if strings.HasPrefix(strings.TrimSpace(line), marker) { + return strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), marker)) + } + } + return "" +} + +func extractSubjects(out string) []string { + var subjects []string + for _, line := range strings.Split(out, "\n") { + if strings.Contains(line, "Subject:") { + parts := strings.SplitN(line, "Subject:", 2) + if len(parts) == 2 { + subjects = append(subjects, strings.TrimSpace(parts[1])) + } + } + } + return subjects +} diff --git a/cosign/policy/attestation_gate.rego b/cosign/policy/attestation_gate.rego new file mode 100644 index 0000000..07470a7 --- /dev/null +++ b/cosign/policy/attestation_gate.rego @@ -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 --type +# 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": "", "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"], "")}) + 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), +} diff --git a/dast-scan/README.md b/dast-scan/README.md new file mode 100644 index 0000000..9f8671d --- /dev/null +++ b/dast-scan/README.md @@ -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). diff --git a/dast-scan/dagger.json b/dast-scan/dagger.json new file mode 100644 index 0000000..1d586c8 --- /dev/null +++ b/dast-scan/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "dast-scan", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/dast-scan/main.go b/dast-scan/main.go new file mode 100644 index 0000000..57a0ce9 --- /dev/null +++ b/dast-scan/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) +} diff --git a/db-migration/.gitattributes b/db-migration/.gitattributes new file mode 100644 index 0000000..d3384f5 --- /dev/null +++ b/db-migration/.gitattributes @@ -0,0 +1,3 @@ +/dagger.gen.go linguist-generated +/internal/dagger/** linguist-generated +/internal/telemetry/** linguist-generated diff --git a/db-migration/.gitignore b/db-migration/.gitignore new file mode 100644 index 0000000..3342715 --- /dev/null +++ b/db-migration/.gitignore @@ -0,0 +1,4 @@ +/dagger.gen.go +/internal/dagger +/internal/telemetry +/.env diff --git a/db-migration/README.md b/db-migration/README.md new file mode 100644 index 0000000..b734c50 --- /dev/null +++ b/db-migration/README.md @@ -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/`. diff --git a/db-migration/dagger.json b/db-migration/dagger.json new file mode 100644 index 0000000..9acad26 --- /dev/null +++ b/db-migration/dagger.json @@ -0,0 +1,12 @@ +{ + "name": "db-migration", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "include": [ + "./main.go", + "./engine/**", + "./verdict/**" + ] +} diff --git a/db-migration/engine/capabilities.json b/db-migration/engine/capabilities.json new file mode 100644 index 0000000..42a3c9b --- /dev/null +++ b/db-migration/engine/capabilities.json @@ -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": [] + } +} diff --git a/db-migration/engine/engine.go b/db-migration/engine/engine.go new file mode 100644 index 0000000..96f4389 --- /dev/null +++ b/db-migration/engine/engine.go @@ -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") } diff --git a/db-migration/engine/engine_test.go b/db-migration/engine/engine_test.go new file mode 100644 index 0000000..30f7357 --- /dev/null +++ b/db-migration/engine/engine_test.go @@ -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) + } +} diff --git a/db-migration/go.mod b/db-migration/go.mod new file mode 100644 index 0000000..feb19a7 --- /dev/null +++ b/db-migration/go.mod @@ -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 diff --git a/db-migration/go.sum b/db-migration/go.sum new file mode 100644 index 0000000..4bb39e6 --- /dev/null +++ b/db-migration/go.sum @@ -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= diff --git a/db-migration/main.go b/db-migration/main.go new file mode 100644 index 0000000..a5e9fe9 --- /dev/null +++ b/db-migration/main.go @@ -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) +} diff --git a/db-migration/verdict/applied.go b/db-migration/verdict/applied.go new file mode 100644 index 0000000..493c83d --- /dev/null +++ b/db-migration/verdict/applied.go @@ -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 " line per file it applied. + for _, line := range strings.Split(out, "\n") { + if strings.HasPrefix(strings.TrimSpace(line), "-- migrating version ") { + count++ + } + } + } + return count +} diff --git a/db-migration/verdict/applied_test.go b/db-migration/verdict/applied_test.go new file mode 100644 index 0000000..df6776e --- /dev/null +++ b/db-migration/verdict/applied_test.go @@ -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) + } + } +} diff --git a/db-migration/verdict/directives.go b/db-migration/verdict/directives.go new file mode 100644 index 0000000..1c5d7af --- /dev/null +++ b/db-migration/verdict/directives.go @@ -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 +} diff --git a/db-migration/verdict/directives_test.go b/db-migration/verdict/directives_test.go new file mode 100644 index 0000000..3ea09ac --- /dev/null +++ b/db-migration/verdict/directives_test.go @@ -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) + } + } +} diff --git a/db-migration/verdict/execution.go b/db-migration/verdict/execution.go new file mode 100644 index 0000000..4dcfc80 --- /dev/null +++ b/db-migration/verdict/execution.go @@ -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:" 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) +} diff --git a/db-migration/verdict/execution_test.go b/db-migration/verdict/execution_test.go new file mode 100644 index 0000000..c5457dc --- /dev/null +++ b/db-migration/verdict/execution_test.go @@ -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") + } +} diff --git a/db-migration/verdict/release_test.go b/db-migration/verdict/release_test.go new file mode 100644 index 0000000..1e80a2e --- /dev/null +++ b/db-migration/verdict/release_test.go @@ -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]) + } +} diff --git a/db-migration/verdict/tools.go b/db-migration/verdict/tools.go new file mode 100644 index 0000000..3b45793 --- /dev/null +++ b/db-migration/verdict/tools.go @@ -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 +} diff --git a/db-migration/verdict/tools_test.go b/db-migration/verdict/tools_test.go new file mode 100644 index 0000000..3a1346f --- /dev/null +++ b/db-migration/verdict/tools_test.go @@ -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) + } +} diff --git a/db-migration/verdict/verdict.go b/db-migration/verdict/verdict.go new file mode 100644 index 0000000..71ff7c9 --- /dev/null +++ b/db-migration/verdict/verdict.go @@ -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, + } +} diff --git a/db-migration/verdict/verdict_test.go b/db-migration/verdict/verdict_test.go new file mode 100644 index 0000000..20bc09e --- /dev/null +++ b/db-migration/verdict/verdict_test.go @@ -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, `bad gateway`}, + "not json": {http.StatusOK, `proxy login`}, + "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) + } + } +} diff --git a/deploy-k8s/README.md b/deploy-k8s/README.md new file mode 100644 index 0000000..e141e3e --- /dev/null +++ b/deploy-k8s/README.md @@ -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 +``` diff --git a/deploy-k8s/dagger.json b/deploy-k8s/dagger.json new file mode 100644 index 0000000..5643060 --- /dev/null +++ b/deploy-k8s/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "deploy-k8s", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/deploy-k8s/main.go b/deploy-k8s/main.go new file mode 100644 index 0000000..2b763c7 --- /dev/null +++ b/deploy-k8s/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 +} diff --git a/e2e-test/.gitattributes b/e2e-test/.gitattributes new file mode 100644 index 0000000..d3384f5 --- /dev/null +++ b/e2e-test/.gitattributes @@ -0,0 +1,3 @@ +/dagger.gen.go linguist-generated +/internal/dagger/** linguist-generated +/internal/telemetry/** linguist-generated diff --git a/e2e-test/.gitignore b/e2e-test/.gitignore new file mode 100644 index 0000000..3342715 --- /dev/null +++ b/e2e-test/.gitignore @@ -0,0 +1,4 @@ +/dagger.gen.go +/internal/dagger +/internal/telemetry +/.env diff --git a/e2e-test/README.md b/e2e-test/README.md new file mode 100644 index 0000000..79b14b2 --- /dev/null +++ b/e2e-test/README.md @@ -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 +``` diff --git a/e2e-test/dagger.json b/e2e-test/dagger.json new file mode 100644 index 0000000..c9b2a1d --- /dev/null +++ b/e2e-test/dagger.json @@ -0,0 +1,10 @@ +{ + "name": "e2e-test", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "include": [ + "./main.go" + ] +} diff --git a/e2e-test/go.mod b/e2e-test/go.mod new file mode 100644 index 0000000..8049581 --- /dev/null +++ b/e2e-test/go.mod @@ -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 diff --git a/e2e-test/go.sum b/e2e-test/go.sum new file mode 100644 index 0000000..1336182 --- /dev/null +++ b/e2e-test/go.sum @@ -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= diff --git a/e2e-test/main.go b/e2e-test/main.go new file mode 100644 index 0000000..86470e3 --- /dev/null +++ b/e2e-test/main.go @@ -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 +} diff --git a/iac-scan/README.md b/iac-scan/README.md new file mode 100644 index 0000000..2cf47bb --- /dev/null +++ b/iac-scan/README.md @@ -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) +``` diff --git a/iac-scan/dagger.json b/iac-scan/dagger.json new file mode 100644 index 0000000..a84df89 --- /dev/null +++ b/iac-scan/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "iac-scan", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/iac-scan/main.go b/iac-scan/main.go new file mode 100644 index 0000000..417f7ab --- /dev/null +++ b/iac-scan/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 +} diff --git a/license-scan/README.md b/license-scan/README.md new file mode 100644 index 0000000..0770b47 --- /dev/null +++ b/license-scan/README.md @@ -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 +``` diff --git a/license-scan/dagger.json b/license-scan/dagger.json new file mode 100644 index 0000000..33e93a8 --- /dev/null +++ b/license-scan/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "license-scan", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/license-scan/main.go b/license-scan/main.go new file mode 100644 index 0000000..b2b6dba --- /dev/null +++ b/license-scan/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":"" entries. + token := fmt.Sprintf(`"Name":%q`, needle) + if strings.Contains(report, token) && !seen[needle] { + seen[needle] = true + hits = append(hits, needle) + } + } + return hits +} diff --git a/malware-scan/README.md b/malware-scan/README.md new file mode 100644 index 0000000..2b93b1c --- /dev/null +++ b/malware-scan/README.md @@ -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 \ + --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. diff --git a/malware-scan/dagger.json b/malware-scan/dagger.json new file mode 100644 index 0000000..e352d83 --- /dev/null +++ b/malware-scan/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "malware-scan", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/malware-scan/main.go b/malware-scan/main.go new file mode 100644 index 0000000..231df16 --- /dev/null +++ b/malware-scan/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 --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 ": 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 +} diff --git a/mobile-android/README.md b/mobile-android/README.md new file mode 100644 index 0000000..b132d4c --- /dev/null +++ b/mobile-android/README.md @@ -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 +``` diff --git a/mobile-android/dagger.json b/mobile-android/dagger.json new file mode 100644 index 0000000..8f109d5 --- /dev/null +++ b/mobile-android/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "mobile-android", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/mobile-android/main.go b/mobile-android/main.go new file mode 100644 index 0000000..a6f2824 --- /dev/null +++ b/mobile-android/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:` 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` (APK) and `bundle` (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 </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 `//1.0/../..//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 + // `/repository/..//…` which curl normalises to + // `//…` — 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 +} diff --git a/mobile-flutter/README.md b/mobile-flutter/README.md new file mode 100644 index 0000000..44cb6fa --- /dev/null +++ b/mobile-flutter/README.md @@ -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. diff --git a/mobile-flutter/dagger.json b/mobile-flutter/dagger.json new file mode 100644 index 0000000..0e04fd4 --- /dev/null +++ b/mobile-flutter/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "mobile-flutter", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/mobile-flutter/main.go b/mobile-flutter/main.go new file mode 100644 index 0000000..392abcc --- /dev/null +++ b/mobile-flutter/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:` 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 </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 `//1.0/../..//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 + // `/repository/..//…` which curl normalises to + // `//…` — 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 +} diff --git a/mobile-ios/README.md b/mobile-ios/README.md new file mode 100644 index 0000000..c794846 --- /dev/null +++ b/mobile-ios/README.md @@ -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 +``` diff --git a/mobile-ios/dagger.json b/mobile-ios/dagger.json new file mode 100644 index 0000000..a3ca4dc --- /dev/null +++ b/mobile-ios/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "mobile-ios", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/mobile-ios/main.go b/mobile-ios/main.go new file mode 100644 index 0000000..fdbf01c --- /dev/null +++ b/mobile-ios/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 +} diff --git a/mobile-security-scan/README.md b/mobile-security-scan/README.md new file mode 100644 index 0000000..4ea6591 --- /dev/null +++ b/mobile-security-scan/README.md @@ -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 --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. diff --git a/mobile-security-scan/dagger.json b/mobile-security-scan/dagger.json new file mode 100644 index 0000000..481b0ff --- /dev/null +++ b/mobile-security-scan/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "mobile-security-scan", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/mobile-security-scan/main.go b/mobile-security-scan/main.go new file mode 100644 index 0000000..ff41aec --- /dev/null +++ b/mobile-security-scan/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 +} diff --git a/model-scan/README.md b/model-scan/README.md new file mode 100644 index 0000000..3fad7a3 --- /dev/null +++ b/model-scan/README.md @@ -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 --version \ + --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. diff --git a/model-scan/dagger.json b/model-scan/dagger.json new file mode 100644 index 0000000..14e68ae --- /dev/null +++ b/model-scan/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "model-scan", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/model-scan/main.go b/model-scan/main.go new file mode 100644 index 0000000..2609fb3 --- /dev/null +++ b/model-scan/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 +} diff --git a/perf-test/.gitattributes b/perf-test/.gitattributes new file mode 100644 index 0000000..d3384f5 --- /dev/null +++ b/perf-test/.gitattributes @@ -0,0 +1,3 @@ +/dagger.gen.go linguist-generated +/internal/dagger/** linguist-generated +/internal/telemetry/** linguist-generated diff --git a/perf-test/.gitignore b/perf-test/.gitignore new file mode 100644 index 0000000..3342715 --- /dev/null +++ b/perf-test/.gitignore @@ -0,0 +1,4 @@ +/dagger.gen.go +/internal/dagger +/internal/telemetry +/.env diff --git a/perf-test/README.md b/perf-test/README.md new file mode 100644 index 0000000..360e87c --- /dev/null +++ b/perf-test/README.md @@ -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 `/api/v1/services//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 +``` diff --git a/perf-test/dagger.json b/perf-test/dagger.json new file mode 100644 index 0000000..44cc296 --- /dev/null +++ b/perf-test/dagger.json @@ -0,0 +1,10 @@ +{ + "name": "perf-test", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "include": [ + "./main.go" + ] +} diff --git a/perf-test/go.mod b/perf-test/go.mod new file mode 100644 index 0000000..3ce49bb --- /dev/null +++ b/perf-test/go.mod @@ -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 diff --git a/perf-test/go.sum b/perf-test/go.sum new file mode 100644 index 0000000..e69de29 diff --git a/perf-test/main.go b/perf-test/main.go new file mode 100644 index 0000000..fd72dc8 --- /dev/null +++ b/perf-test/main.go @@ -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 . 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 +} diff --git a/release/README.md b/release/README.md new file mode 100644 index 0000000..acce8e3 --- /dev/null +++ b/release/README.md @@ -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 `!:` | major | +| `feat:` / `feat():` | 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. diff --git a/release/dagger.json b/release/dagger.json new file mode 100644 index 0000000..d87d296 --- /dev/null +++ b/release/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "release", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/release/main.go b/release/main.go new file mode 100644 index 0000000..ef175e3 --- /dev/null +++ b/release/main.go @@ -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" +} diff --git a/sast-scan/README.md b/sast-scan/README.md new file mode 100644 index 0000000..fd26197 --- /dev/null +++ b/sast-scan/README.md @@ -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) +``` diff --git a/sast-scan/dagger.json b/sast-scan/dagger.json new file mode 100644 index 0000000..300c185 --- /dev/null +++ b/sast-scan/dagger.json @@ -0,0 +1,13 @@ +{ + "name": "sast-scan", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go", + "./qualitygate.go", + "./gate.go" + ] +} diff --git a/sast-scan/gate.go b/sast-scan/gate.go new file mode 100644 index 0000000..da13d9f --- /dev/null +++ b/sast-scan/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) +} diff --git a/sast-scan/gate_test.go b/sast-scan/gate_test.go new file mode 100644 index 0000000..8993f16 --- /dev/null +++ b/sast-scan/gate_test.go @@ -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) + } + } +} diff --git a/sast-scan/main.go b/sast-scan/main.go new file mode 100644 index 0000000..e90a46d --- /dev/null +++ b/sast-scan/main.go @@ -0,0 +1,669 @@ +// Package main implements the IntegraCI sast-scan Dagger module. +// +// Runs static application security testing (SAST) over a source directory +// using one of several vendors, counts findings, 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): +// +// semgrep semgrep/semgrep semgrep scan --config=auto --error +// sonarqube sonarsource/sonar-scanner-cli sonar-scanner (SONAR_TOKEN + SONAR_HOST_URL) +// codeql codeql CLI bundle database create + database analyze +// snyk-code snyk/snyk snyk code test --severity-threshold= +// checkmarx checkmarx/ast-cli cx scan create +// 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 sonarqube --sonar-token env:SONAR_TOKEN --sonar-host-url https://sonar.example.com +// dagger call scan --source . --tool snyk-code --vendor-token env:SNYK_TOKEN --severity high +// dagger call scan --source . --tool codeql --language python +// dagger call scan --source . --tool none +package main + +import ( + "bytes" + "context" + "dagger/sast-scan/internal/dagger" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" +) + +// SastScan is the IntegraCI static application security testing module. +type SastScan struct{} + +// ScanResult contains the output of a SAST scan. +type ScanResult struct { + Tool string `json:"tool"` + Findings int `json:"findings"` + // Findings whose SARIF `level` is `error` -- the only ones the deploy gate + // treats as blocking. `Findings` counts every result, whatever its level. + Errors int `json:"errors"` + Warnings int `json:"warnings"` + SarifPath string `json:"sarif_path,omitempty"` + Report string `json:"report,omitempty"` + Skipped bool `json:"skipped"` + Success bool `json:"success"` + // The quality gate the code-quality SERVER evaluated for this analysis: + // passed | failed | unavailable. Empty for tools that have no server gate. + QualityGate string `json:"quality_gate,omitempty"` + // What the IntegraCI platform decided the pipeline does with that verdict + // (see gate.go): pass | warn | block, empty when nothing was posted. The + // Jenkins SAST stage reads it (`... scan ... gate-decision`) to turn the + // stage red on `warn`; on `block` Scan returns an error instead. + GateDecision string `json:"gate_decision,omitempty"` + GateReason string `json:"gate_reason,omitempty"` +} + +// Scan runs a SAST pass over the source directory with the selected tool, +// counts findings, and optionally POSTs the result to the IntegraCI API. +// Mirrors security-scan.Scan's reporting contract. +func (m *SastScan) Scan( + ctx context.Context, + // Source directory to scan + source *dagger.Directory, + // SAST tool: semgrep | sonarqube | codeql | snyk-code | checkmarx | none + // +optional + // +default="semgrep" + tool string, + // Failure/severity threshold: LOW | MEDIUM | HIGH | CRITICAL + // +optional + // +default="HIGH" + severity string, + // Programming language for CodeQL database creation (e.g. python, go, javascript) + // +optional + // +default="python" + language string, + // Vendor token for snyk-code (SNYK_TOKEN) / checkmarx (CX API key) + // +optional + vendorToken *dagger.Secret, + // SonarQube authentication token (SONAR_TOKEN) + // +optional + sonarToken *dagger.Secret, + // SonarQube server URL (SONAR_HOST_URL) + // +optional + sonarHostURL string, + // SonarQube project key. IntegraCI always injects this; repositories + // do not need a sonar-project.properties file. + // +optional + sonarProjectKey string, + // Checkmarx AST base URI (deployment-specific) + // +optional + cxBaseURI string, + // Checkmarx tenant name + // +optional + cxTenant 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, + // Full commit SHA the scan analysed (`git rev-parse HEAD`). IntegraCI + // records it only when `version` starts with its first twelve characters, + // and the UAT door judges SonarQube by it (ADR-0072). + // +optional + revision string, +) (*ScanResult, error) { + result := &ScanResult{Tool: tool} + // The pipeline installs the dagger CLI at ./bin/dagger and mirrors the + // platform's modules into ./.integraci-modules INSIDE the checkout. They are + // the platform's code, not the tenant's; a SAST pass over them charges every + // tenant with findings in Go it never wrote. Only these two paths go. + source = source.WithoutFile("bin/dagger").WithoutDirectory(".integraci-modules") + + var ( + report string + err error + ) + + switch strings.ToLower(tool) { + case "none": + result.Skipped = true + result.Success = true + return result, nil + case "semgrep": + report, result.SarifPath, err = m.runSemgrep(ctx, source) + case "sonarqube": + report, result.QualityGate, err = m.runSonarQube(ctx, source, sonarToken, sonarHostURL, sonarProjectKey) + case "codeql": + report, result.SarifPath, err = m.runCodeQL(ctx, source, language) + case "snyk-code": + report, err = m.runSnykCode(ctx, source, vendorToken, severity) + case "checkmarx": + report, err = m.runCheckmarx(ctx, source, vendorToken, cxBaseURI, cxTenant) + default: + return nil, fmt.Errorf( + "unsupported sast tool %q (expected one of: semgrep, sonarqube, codeql, snyk-code, checkmarx, none)", + tool, + ) + } + + if err != nil { + return nil, fmt.Errorf("%s sast scan failed: %w", tool, err) + } + + result.Report = report + var parsed bool + result.Findings, result.Errors, result.Warnings, parsed = tallyFindings(report) + // A SARIF tool whose output parsed as nothing at all did not scan: snyk's + // `|| true` prints `Authentication error` to stdout, a truncated file has no + // results. Posting that as a clean scan is a green gate over an empty run, + // so it is an error here. sonarqube reports through its own server and is + // not SARIF on stdout by design; it keeps the old best-effort count. + if !parsed && result.Findings == 0 && tool != "sonarqube" { + return nil, fmt.Errorf( + "%s produced no parseable SARIF report (%d bytes of output); refusing to record a clean scan", + tool, len(report), + ) + } + + // 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 { + gate, err := m.postResults(ctx, apiURL, token, serviceID, version, revision, result) + if err != nil { + return nil, fmt.Errorf("posting results to API failed: %w", err) + } + result.GateDecision, result.GateReason = gate.Decision, gate.Reason + if err := gate.err(); err != nil { + return nil, err + } + } + + result.Success = true + return result, nil +} + +// Sarif runs a SARIF-native SAST tool and returns its report as a file, for a +// pipeline to export and archive (#2143 phase 2): +// +// dagger call sarif --source=. --tool=semgrep export --path=integraci-sarif/sast.sarif +// +// Only semgrep and codeql write SARIF; the others are refused rather than +// faked. Nothing is posted: Scan remains the step that reports to IntegraCI, +// and this one adds the report file. A report that is not SARIF is an error, +// for the same reason Scan refuses one. +func (m *SastScan) Sarif( + ctx context.Context, + // Source directory to scan + source *dagger.Directory, + // SAST tool: semgrep | codeql + // +optional + // +default="semgrep" + tool string, + // Programming language for CodeQL database creation + // +optional + // +default="python" + language string, +) (*dagger.File, error) { + // Same exclusion as Scan: the CLI and the mirrored modules are the + // platform's code, not the tenant's. + source = source.WithoutFile("bin/dagger").WithoutDirectory(".integraci-modules") + var ( + report string + err error + ) + switch strings.ToLower(tool) { + case "semgrep": + report, _, err = m.runSemgrep(ctx, source) + case "codeql": + report, _, err = m.runCodeQL(ctx, source, language) + default: + return nil, fmt.Errorf("sast tool %q writes no SARIF; sarif supports semgrep and codeql", tool) + } + if err != nil { + return nil, fmt.Errorf("%s sarif failed: %w", tool, err) + } + if _, _, _, parsed := tallyFindings(report); !parsed { + return nil, fmt.Errorf("%s produced no parseable SARIF report (%d bytes)", tool, len(report)) + } + return dag.Directory().WithNewFile("sast.sarif", report).File("sast.sarif"), nil +} + +// runSemgrep executes Semgrep in SARIF mode and returns the raw SARIF +// document. Semgrep exits non-zero when findings are present (--error), so the +// exec DECLARES that a non-zero exit is an expected outcome; without that the +// report can never be read back and a scan that finds something is +// indistinguishable from a scan that could not run. +func (m *SastScan) runSemgrep(ctx context.Context, source *dagger.Directory) (string, string, error) { + const sarifPath = "/tmp/semgrep-results.sarif" + semgrep := dag.Container(). + From("semgrep/semgrep:1.99.0"). + // Persist the semgrep registry rule cache across runs (--config=auto + // otherwise re-fetches the rulesets on every scan). + WithMountedCache("/root/.cache/semgrep", dag.CacheVolume("semgrep-rules")). + WithMountedDirectory("/src", source). + WithWorkdir("/src"). + WithExec([]string{ + "semgrep", "scan", + "--config=auto", + "--error", + "--sarif", + "--output", sarifPath, + ".", + }, dagger.ContainerWithExecOpts{ + // `--error` makes semgrep exit 1 the moment it finds anything, and a + // container whose exec failed cannot be read from: every later + // `.File(...).Contents()` re-raises that same failure. Swallowing the + // error from Stdout() — which is what this used to do — does not help, + // because the failure is a property of the container, not of that one + // call. + // + // MEASURED on a customer's first pipeline run: semgrep reported + // "Ran 291 rules on 2010 files: 279 findings", then the step died with + // `File.contents ERROR / exit code: 1` and the build failed carrying no + // report at all. Every stage after it was skipped. So SAST only ever + // succeeded on code with NOTHING to report — the one case where its + // output does not matter. + Expect: dagger.ReturnTypeAny, + }) + + sarif, err := semgrep.File(sarifPath).Contents(ctx) + if err != nil { + return "", "", fmt.Errorf("read semgrep SARIF output: %w", err) + } + return sarif, sarifPath, nil +} + +// runSonarQube runs the SonarQube scanner CLI against the source. The +// scanner authenticates with SONAR_TOKEN and targets the server at +// SONAR_HOST_URL, both injected from secrets/params. +// +// The working directory MUST NOT be inside the source mount. The scanner +// image runs as the non-root user `scanner-cli` (its image config sets +// User=scanner-cli), which cannot write into /usr/src, while sonar-scanner +// creates `.scannerwork` under the project base dir by default. That fails +// at project initialisation, AFTER authentication has already succeeded: +// +// Fail to create working dir: /usr/src/.scannerwork +// +// so every repository with a valid token hit it, not only uploaded ones. +// `-Dsonar.working.directory=/tmp/.scannerwork` moves it somewhere that user +// can write (the image sets HOME=/tmp). A command-line -D also overrides a +// repository's own sonar-project.properties, so no app needs one for this. +func (m *SastScan) runSonarQube( + ctx context.Context, + source *dagger.Directory, + sonarToken *dagger.Secret, + sonarHostURL string, + sonarProjectKey string, +) (string, string, error) { + c := dag.Container(). + From("sonarsource/sonar-scanner-cli:11.1"). + WithMountedDirectory("/usr/src", source). + WithWorkdir("/usr/src") + + if sonarHostURL != "" { + c = c.WithEnvVariable("SONAR_HOST_URL", sonarHostURL) + } + if sonarToken != nil { + c = c.WithSecretVariable("SONAR_TOKEN", sonarToken) + } + + const workDirFlag = `-Dsonar.working.directory=/tmp/.scannerwork` + // Where the scanner names its Compute Engine task, pinned on the command line + // so a repo file cannot move the file the quality-gate verdict is read from. + const metadataFlag = `-Dsonar.scanner.metadataFilePath=` + sonarReportTask + + // `sonar.projectKey` is MANDATORY and the scanner has no default for it. + // IntegraCI always injects the service identity via -D (which overrides any + // optional repo file). No source tree needs sonar-project.properties. + // Passed through the environment rather than interpolated into the command, + // so a service name can never become part of the shell. + scan := "sonar-scanner " + workDirFlag + " " + metadataFlag + if sonarHostURL != "" { + // Pinned on the command line, which wins over the repository's own + // sonar-project.properties: the analysed code must not be able to send + // the bound SONAR_TOKEN to a server of its choosing. Passed through the + // environment, like the project key, so the URL never becomes shell. + scan += ` -Dsonar.host.url="$SONAR_HOST_URL"` + } + if sonarProjectKey != "" { + c = c.WithEnvVariable("INTEGRACI_SONAR_PROJECT_KEY", sonarProjectKey) + scan += ` -Dsonar.projectKey="$INTEGRACI_SONAR_PROJECT_KEY"` + + ` -Dsonar.projectName="$INTEGRACI_SONAR_PROJECT_KEY"` + } + + // `|| true`: a scanner failure must still leave a container we can read, and + // the verdict below does not depend on its exit code. + ran := c.WithExec([]string{"sh", "-c", scan + " || true"}) + out, err := ran.Stdout(ctx) + if err != nil { + return "", "", err + } + + // The server's verdict for THIS analysis (see qualitygate.go). The scanner + // names its Compute Engine task in report-task.txt, inside the working + // directory set above; no file means the analysis never reached the server, + // which is "unavailable" — never a pass. + report, rerr := ran.File(sonarReportTask).Contents(ctx) + if rerr != nil || sonarToken == nil || sonarHostURL == "" { + return out, qualityGateUnavailable, nil + } + token, terr := sonarToken.Plaintext(ctx) + if terr != nil { + return out, qualityGateUnavailable, nil + } + gate := sonarGateClient{ + hostURL: sonarHostURL, + expectedProjectKey: sonarProjectKey, + token: token, + http: &http.Client{Timeout: 30 * time.Second, CheckRedirect: noRedirects}, + poll: 3 * time.Second, + timeout: 5 * time.Minute, + }.qualityGate(ctx, report) + return out, gate, nil +} + +// sonarReportTask is where the scanner writes the task it submitted (see metadataFlag). +const sonarReportTask = "/tmp/.scannerwork/report-task.txt" + +// runCodeQL creates a CodeQL database for the given language and analyses +// it, emitting a SARIF report. Uses the official CodeQL CLI bundle image. +func (m *SastScan) runCodeQL( + ctx context.Context, + source *dagger.Directory, + language string, +) (string, string, error) { + const sarifPath = "/tmp/codeql-results.sarif" + script := fmt.Sprintf( + "codeql database create /tmp/cqldb --language=%s --source-root=/src --overwrite && "+ + "codeql database analyze /tmp/cqldb --format=sarifv2.1.0 --output=%s --no-rerun || true", + language, sarifPath, + ) + + c := dag.Container(). + From("ghcr.io/github/codeql-action/codeql-bundle:codeql-bundle-v2.20.3"). + WithMountedDirectory("/src", source). + WithWorkdir("/src"). + WithExec([]string{"sh", "-c", script}) + + if _, err := c.Stdout(ctx); err != nil { + _ = err + } + + sarif, err := c.File(sarifPath).Contents(ctx) + if err != nil { + return "", "", fmt.Errorf("read codeql SARIF output: %w", err) + } + return sarif, sarifPath, nil +} + +// runSnykCode runs "snyk code test" with a severity threshold. The Snyk +// CLI authenticates via SNYK_TOKEN injected from a secret. +func (m *SastScan) runSnykCode( + ctx context.Context, + source *dagger.Directory, + vendorToken *dagger.Secret, + severity string, +) (string, error) { + c := dag.Container(). + From("snyk/snyk:linux"). + WithMountedDirectory("/src", source). + WithWorkdir("/src") + + if vendorToken != nil { + c = c.WithSecretVariable("SNYK_TOKEN", vendorToken) + } + + threshold := strings.ToLower(severity) + cmd := fmt.Sprintf("snyk code test --severity-threshold=%s --sarif || true", threshold) + return c.WithExec([]string{"sh", "-c", cmd}).Stdout(ctx) +} + +// runCheckmarx runs "cx scan create" against the Checkmarx AST platform +// using the official ast-cli image. Auth is via the CX API key secret; +// the base URI and tenant are deployment-specific params. +func (m *SastScan) runCheckmarx( + ctx context.Context, + source *dagger.Directory, + vendorToken *dagger.Secret, + cxBaseURI string, + cxTenant string, +) (string, error) { + c := dag.Container(). + From("checkmarx/ast-cli:2.3.0"). + WithMountedDirectory("/src", source). + WithWorkdir("/src") + + if vendorToken != nil { + c = c.WithSecretVariable("CX_APIKEY", vendorToken) + } + if cxBaseURI != "" { + c = c.WithEnvVariable("CX_BASE_URI", cxBaseURI) + } + if cxTenant != "" { + c = c.WithEnvVariable("CX_TENANT", cxTenant) + } + + cmd := "cx scan create --project-name integraci --scan-types sast " + + "--branch main --source /src --report-format sarif || true" + return c.WithExec([]string{"sh", "-c", cmd}).Stdout(ctx) +} + +// tallyFindings reads a SARIF report and returns (all results, blocking +// results, warning-level results, parsed). +// +// WHY THE LEVEL MATTERS. The previous tally counted every `"ruleId":` in the +// report and posted that one number as BOTH `report_data.sast_errors` and +// `high_count`. The deploy gate has one rule for each, so a single Semgrep +// finding of level `warning` -- MEASURED 2026-09-13 on a customer tenant: +// `problem-based-packs.insecure-transport.js-node.using-http-server`, a plain +// `http.createServer` behind an Ingress that terminates TLS -- was refused +// twice, as "1 Semgrep ERROR-level finding" and as "1 high severity +// vulnerability", and the first deploy of a freshly onboarded service never +// happened. Semgrep's `--error` flag changes the EXIT CODE on any finding; it +// does not make a warning an error, and the gate's message promises +// "ERROR-level". +// +// What counts as BLOCKING, fail-closed at every fork: +// +// - `level: error` on the result, or -- when the result carries no level -- +// on the rule's `defaultConfiguration` (SARIF §3.27.10 falls back there +// before it falls back to `warning`). +// - a `security-severity` property of 7.0 or more on the result or its +// rule, whatever the level: CodeQL grades most security queries +// `warning` and puts the CVSS-style rating there, so reading the level +// alone would wave a hard-coded credential through. +// - any level this function does not know (`high`, `critical`, a typo): an +// unknown severity is not a reason to pass. +// +// Informational and non-findings (`note`, `none`, a `kind` other than `fail`, +// a result with a non-empty `suppressions` list -- the inline pragma the gate +// message tells people to use) are not blocking. Everything else is a warning. +// +// `parsed` is false when the text is not SARIF; the caller decides what that +// means for the tool that produced it. +func tallyFindings(report string) (total, blocking, warnings int, parsed bool) { + type rule struct { + ID string `json:"id"` + DefaultConfiguration struct { + Level string `json:"level"` + } `json:"defaultConfiguration"` + Properties map[string]any `json:"properties"` + } + var doc struct { + Runs []struct { + Tool struct { + Driver struct { + Rules []rule `json:"rules"` + } `json:"driver"` + } `json:"tool"` + Results []struct { + RuleID string `json:"ruleId"` + RuleIndex *int `json:"ruleIndex"` + Level string `json:"level"` + Kind string `json:"kind"` + Suppressions []any `json:"suppressions"` + Properties map[string]any `json:"properties"` + } `json:"results"` + } `json:"runs"` + } + if err := json.NewDecoder(strings.NewReader(report)).Decode(&doc); err != nil || len(doc.Runs) == 0 { + n := countRuleIDs(report) + return n, n, 0, false + } + for _, run := range doc.Runs { + byID := map[string]rule{} + for _, r := range run.Tool.Driver.Rules { + byID[r.ID] = r + } + for _, res := range run.Results { + if res.Kind != "" && res.Kind != "fail" { + continue // pass / notApplicable / informational: not a finding + } + if len(res.Suppressions) > 0 { + continue // suppressed inline, as the gate message invites + } + total++ + var rl rule + if res.RuleIndex != nil && *res.RuleIndex >= 0 && *res.RuleIndex < len(run.Tool.Driver.Rules) { + rl = run.Tool.Driver.Rules[*res.RuleIndex] + } else { + rl = byID[res.RuleID] + } + if securitySeverity(res.Properties) >= 7.0 || securitySeverity(rl.Properties) >= 7.0 { + blocking++ + continue + } + level := strings.ToLower(res.Level) + if level == "" { + level = strings.ToLower(rl.DefaultConfiguration.Level) + } + switch level { + case "error": + blocking++ + case "", "warning": + warnings++ + case "note", "none": + // informational + default: + blocking++ // unknown severity is not a pass + } + } + } + return total, blocking, warnings, true +} + +// securitySeverity reads the CodeQL/GitHub `security-severity` property (a +// CVSS-style 0-10 score, serialised as a string or a number); 0 when absent. +func securitySeverity(props map[string]any) float64 { + v, ok := props["security-severity"] + if !ok { + return 0 + } + switch t := v.(type) { + case float64: + return t + case string: + var f float64 + if _, err := fmt.Sscanf(strings.TrimSpace(t), "%g", &f); err == nil { + return f + } + } + return 0 +} + +// countRuleIDs is the level-blind fallback tally: every `"ruleId":` in the text. +// Zero-dep, matching the security-scan classifyLicenses approach; best-effort. +func countRuleIDs(report string) int { + count := 0 + idx := 0 + for { + k := strings.Index(report[idx:], `"ruleId":`) + if k < 0 { + break + } + count++ + idx += k + len(`"ruleId":`) + } + return count +} + +// postResults sends the SAST scan result to the IntegraCI scans/sast +// endpoint. Shape matches api/app/schemas/scan.py ScanResultCreate: SAST +// findings populate report_data.sast_errors (the field the deploy OPA gate +// reads, see deploy.py _build_scan_results) plus the typed severity columns. +func (m *SastScan) postResults( + ctx context.Context, + apiURL string, + token *dagger.Secret, + serviceID string, + version string, + revision string, + result *ScanResult, +) (platformGate, error) { + payload := map[string]any{ + "service_id": serviceID, + "version": version, + "scan_type": "sast", + "scanner": result.Tool, + "report_format": "sarif", + "findings_count": result.Findings, + // SAST has no CVE severity ladder: `high_count` used to mirror the total + // and made the gate's CVE rule fire a second time for the same Semgrep + // finding. Error-level results are reported ONCE, as `sast_errors`; + // warnings go to `medium_count` for visibility and block nothing. + "high_count": 0, + "medium_count": result.Warnings, + "report_data": map[string]any{ + "sast_errors": result.Errors, + "secret_count": 0, + "dast_high": 0, + "dast_critical": 0, + "sbom_present": false, + "signed": false, + }, + } + if revision != "" { + payload["revision"] = revision + } + if result.QualityGate != "" { + // Read by the deploy gate (`quality_gate_failed`) and the integration graph. + payload["report_data"].(map[string]any)["quality_gate"] = result.QualityGate + } + + body, err := json.Marshal(payload) + if err != nil { + return platformGate{}, 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 platformGate{}, fmt.Errorf("build request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + tokenStr, err := token.Plaintext(ctx) + if err != nil { + return platformGate{}, 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 platformGate{}, fmt.Errorf("API post to %s failed: %w", endpoint, err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 300 { + return platformGate{}, fmt.Errorf("API post to %s returned %d", endpoint, resp.StatusCode) + } + answer, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + return gateFromResponse(answer), nil +} diff --git a/sast-scan/qualitygate.go b/sast-scan/qualitygate.go new file mode 100644 index 0000000..4f0d403 --- /dev/null +++ b/sast-scan/qualitygate.go @@ -0,0 +1,164 @@ +package main + +// The SonarQube quality gate, as the SERVER evaluated it for this analysis. +// +// Why this exists. The scanner used to run as `sonar-scanner … || true` with no +// gate wait, and nothing read the verdict afterwards. MEASURED 2026-09-15 on an +// on-prem tenant: four projects analysed on every build, their gate status sat on +// the server (`api/qualitygates/project_status`), and no pipeline, gate or screen +// ever looked at it. A build that failed the tenant's own quality gate deployed +// exactly like one that passed. +// +// Why the web API and not the scanner's log. The scanner's console wording is not +// a contract and changes between scanner versions; the web API is documented and +// is what SonarQube's own CI integrations read. The analysis is processed +// asynchronously by the server's Compute Engine, so the verdict is read in two +// steps: the CE task named in `report-task.txt` (which the scanner writes into its +// working directory) yields the analysis id once it finishes, and the analysis id +// yields the gate status of exactly THIS analysis — not whatever the project's +// latest one is by the time we ask. +// +// Nothing here imports the Dagger SDK, so it is unit-testable on its own. + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "regexp" + "strings" + "time" +) + +const ( + qualityGatePassed = "passed" + qualityGateFailed = "failed" + qualityGateUnavailable = "unavailable" +) + +// ceTaskIDPattern is the shape of a Compute Engine task id. The id comes out of a +// file inside a container that ran the customer's repository, so it is data until +// it matches. +var ceTaskIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`) + +// ceTaskIDFromReport reads `ceTaskId` out of a scanner `report-task.txt` +// (`key=value` lines). "" when absent or malformed. +func ceTaskIDFromReport(report string) string { + for _, line := range strings.Split(report, "\n") { + key, value, ok := strings.Cut(strings.TrimSpace(line), "=") + if ok && key == "ceTaskId" { + value = strings.TrimSpace(value) + if ceTaskIDPattern.MatchString(value) { + return value + } + return "" + } + } + return "" +} + +// gateFromProjectStatus maps `projectStatus.status` onto the platform's words. +// OK and WARN (older servers) pass; ERROR fails; NONE (no gate) and anything +// unknown is unavailable — never "passed". +func gateFromProjectStatus(status string) string { + switch strings.ToUpper(strings.TrimSpace(status)) { + case "OK", "WARN": + return qualityGatePassed + case "ERROR": + return qualityGateFailed + default: + return qualityGateUnavailable + } +} + +type sonarGateClient struct { + // hostURL is the server the pipeline was rendered with (the SonarQube + // connector's address, which a spec override can also set) — never the one a + // repository's own sonar-project.properties may name. + hostURL string + // expectedProjectKey, when set, is the IntegraCI-injected project this + // analysis MUST belong to. Without the check the verdict could be read from + // any project the token can see. + expectedProjectKey string + token string + http *http.Client + poll time.Duration + timeout time.Duration +} + +func (c sonarGateClient) getJSON(ctx context.Context, path string, query url.Values, out any) error { + endpoint := strings.TrimRight(c.hostURL, "/") + path + "?" + query.Encode() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return err + } + // A SonarQube user token is the basic-auth USERNAME with an empty password. + req.SetBasicAuth(c.token, "") + resp, err := c.http.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("%s answered %d", path, resp.StatusCode) + } + return json.NewDecoder(resp.Body).Decode(out) +} + +// qualityGate waits for the analysis in `report` to be processed and returns its +// gate verdict. Any failure to learn it is `unavailable`, which the deploy gate +// does NOT read as a pass or a fail — it is recorded so the gap is visible. +func (c sonarGateClient) qualityGate(ctx context.Context, report string) string { + taskID := ceTaskIDFromReport(report) + if taskID == "" || c.hostURL == "" || c.token == "" { + return qualityGateUnavailable + } + deadline := time.Now().Add(c.timeout) + var task struct { + Task struct { + Status string `json:"status"` + AnalysisID string `json:"analysisId"` + ComponentKey string `json:"componentKey"` + } `json:"task"` + } + for { + if err := c.getJSON(ctx, "/api/ce/task", url.Values{"id": {taskID}}, &task); err != nil { + return qualityGateUnavailable + } + switch task.Task.Status { + case "SUCCESS": + if c.expectedProjectKey != "" && task.Task.ComponentKey != c.expectedProjectKey { + return qualityGateUnavailable + } + var status struct { + ProjectStatus struct { + Status string `json:"status"` + } `json:"projectStatus"` + } + if task.Task.AnalysisID == "" { + return qualityGateUnavailable + } + err := c.getJSON(ctx, "/api/qualitygates/project_status", + url.Values{"analysisId": {task.Task.AnalysisID}}, &status) + if err != nil { + return qualityGateUnavailable + } + return gateFromProjectStatus(status.ProjectStatus.Status) + case "FAILED", "CANCELED": + return qualityGateUnavailable + } + if time.Now().After(deadline) { + return qualityGateUnavailable + } + select { + case <-ctx.Done(): + return qualityGateUnavailable + case <-time.After(c.poll): + } + } +} + +// noRedirects keeps the token on the one host it was meant for: a redirect is +// answered as-is instead of being followed with the credential attached. +func noRedirects(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } diff --git a/sast-scan/qualitygate_test.go b/sast-scan/qualitygate_test.go new file mode 100644 index 0000000..66ca879 --- /dev/null +++ b/sast-scan/qualitygate_test.go @@ -0,0 +1,166 @@ +package main + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestCeTaskIDFromReport(t *testing.T) { + report := "projectKey=shop-api\nserverUrl=http://sonar.test\nceTaskId=AZkq-12_x\nceTaskUrl=http://sonar.test/api/ce/task?id=AZkq-12_x\n" + if got := ceTaskIDFromReport(report); got != "AZkq-12_x" { + t.Fatalf("ceTaskId = %q", got) + } + for _, bad := range []string{"", "projectKey=x\n", "ceTaskId=../../api/users\n", "ceTaskId=a b\n"} { + if got := ceTaskIDFromReport(bad); got != "" { + t.Fatalf("%q must yield no task id, got %q", bad, got) + } + } +} + +func TestGateFromProjectStatusNeverInventsAPass(t *testing.T) { + cases := map[string]string{ + "OK": qualityGatePassed, "WARN": qualityGatePassed, "ERROR": qualityGateFailed, + "NONE": qualityGateUnavailable, "": qualityGateUnavailable, "SOMETHING": qualityGateUnavailable, + } + for in, want := range cases { + if got := gateFromProjectStatus(in); got != want { + t.Fatalf("%q -> %q, want %q", in, got, want) + } + } +} + +// fakeSonar serves the two endpoints; the CE task finishes after `pending` polls. +func fakeSonar(t *testing.T, pending int32, gate string, token string) (*httptest.Server, *atomic.Int32) { + t.Helper() + var polls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, pass, ok := r.BasicAuth() + if !ok || user != token || pass != "" { + w.WriteHeader(http.StatusUnauthorized) + return + } + switch r.URL.Path { + case "/api/ce/task": + if r.URL.Query().Get("id") != "TASK1" { + w.WriteHeader(http.StatusNotFound) + return + } + n := polls.Add(1) + status := "IN_PROGRESS" + if n > pending { + status = "SUCCESS" + } + _, _ = w.Write([]byte(`{"task":{"status":"` + status + `","analysisId":"AN1","componentKey":"shop-api"}}`)) + case "/api/qualitygates/project_status": + if r.URL.Query().Get("analysisId") != "AN1" { + w.WriteHeader(http.StatusNotFound) + return + } + _, _ = w.Write([]byte(`{"projectStatus":{"status":"` + gate + `"}}`)) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(srv.Close) + return srv, &polls +} + +func client(host, token string) sonarGateClient { + return sonarGateClient{hostURL: host, token: token, http: http.DefaultClient, poll: time.Millisecond, timeout: 2 * time.Second} +} + +const report = "ceTaskId=TASK1\n" + +func TestQualityGateWaitsForTheAnalysisAndReadsItsVerdict(t *testing.T) { + srv, polls := fakeSonar(t, 2, "ERROR", "tok") + if got := client(srv.URL, "tok").qualityGate(context.Background(), report); got != qualityGateFailed { + t.Fatalf("gate = %q, want failed", got) + } + if polls.Load() != 3 { + t.Fatalf("expected to poll until the task finished, polled %d times", polls.Load()) + } + srv2, _ := fakeSonar(t, 0, "OK", "tok") + if got := client(srv2.URL, "tok").qualityGate(context.Background(), report); got != qualityGatePassed { + t.Fatalf("gate = %q, want passed", got) + } +} + +func TestQualityGateIsUnavailableWhenItCannotBeLearned(t *testing.T) { + srv, _ := fakeSonar(t, 0, "OK", "tok") + if got := client(srv.URL, "wrong").qualityGate(context.Background(), report); got != qualityGateUnavailable { + t.Fatalf("a rejected token must not read as a verdict, got %q", got) + } + if got := client(srv.URL, "tok").qualityGate(context.Background(), "no task here"); got != qualityGateUnavailable { + t.Fatalf("no ceTaskId must be unavailable, got %q", got) + } + never, _ := fakeSonar(t, 1<<30, "OK", "tok") + c := client(never.URL, "tok") + c.timeout = 20 * time.Millisecond + if got := c.qualityGate(context.Background(), report); got != qualityGateUnavailable { + t.Fatalf("a task that never finishes must time out as unavailable, got %q", got) + } + if got := client("", "tok").qualityGate(context.Background(), report); got != qualityGateUnavailable { + t.Fatalf("no configured host must be unavailable, got %q", got) + } + if !strings.Contains(qualityGateUnavailable, "unavailable") { + t.Fatal("constant drifted") + } +} + +func TestAFailedAnalysisIsNotWaitedOn(t *testing.T) { + var polls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + polls.Add(1) + _, _ = w.Write([]byte(`{"task":{"status":"FAILED"}}`)) + })) + t.Cleanup(srv.Close) + c := client(srv.URL, "tok") + c.poll = 5 * time.Millisecond + if got := c.qualityGate(context.Background(), report); got != qualityGateUnavailable { + t.Fatalf("gate = %q, want unavailable", got) + } + if polls.Load() != 1 { + t.Fatalf("a failed analysis must stop the wait at once, polled %d times", polls.Load()) + } +} + +func TestAVerdictFromAnotherProjectIsNotThisBuilds(t *testing.T) { + srv, _ := fakeSonar(t, 0, "OK", "tok") + c := client(srv.URL, "tok") + c.expectedProjectKey = "shop-api" + if got := c.qualityGate(context.Background(), report); got != qualityGatePassed { + t.Fatalf("matching project: gate = %q, want passed", got) + } + c.expectedProjectKey = "payments" + if got := c.qualityGate(context.Background(), report); got != qualityGateUnavailable { + t.Fatalf("another project's verdict must not count, got %q", got) + } +} + +func TestTheTokenDoesNotFollowARedirect(t *testing.T) { + var leaked atomic.Int32 + elsewhere := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if _, _, ok := r.BasicAuth(); ok { + leaked.Add(1) + } + _, _ = w.Write([]byte(`{"task":{"status":"SUCCESS","analysisId":"AN1"}}`)) + })) + t.Cleanup(elsewhere.Close) + redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, elsewhere.URL+r.URL.RequestURI(), http.StatusFound) + })) + t.Cleanup(redirector.Close) + c := client(redirector.URL, "tok") + c.http = &http.Client{CheckRedirect: noRedirects} + if got := c.qualityGate(context.Background(), report); got != qualityGateUnavailable { + t.Fatalf("a redirect is not a verdict, got %q", got) + } + if leaked.Load() != 0 { + t.Fatal("the token followed a redirect") + } +} diff --git a/sbom/README.md b/sbom/README.md new file mode 100644 index 0000000..17b6bde --- /dev/null +++ b/sbom/README.md @@ -0,0 +1,45 @@ +# sbom — IntegraCI Dagger module + +Engine-agnostic Software Bill of Materials (SBOM) generation. Callable from +any CI engine via `dagger call`. Translates the GitHub-Actions-only intent of +`security_pipeline_adapter.build_sbom_step` into canonical tool CLIs run inside +official containers. + +## Verb + +### `generate` + +``` +dagger call generate --source . [--image-ref REF] [--generator NAME] +``` + +| arg | required | default | description | +| ------------ | -------- | ------- | -------------------------------------------------------- | +| `--source` | yes | — | source directory to analyze | +| `--image-ref`| no | "" | container image to scan instead of the filesystem | +| `--generator`| no | `syft` | `syft \| cyclonedx \| spdx-tools \| trivy \| none` | + +Returns the SBOM document as a `File`. + +## Generators + +| generator | image | output | notes | +| ------------ | --------------------------- | ----------------------- | -------------------------------------- | +| `syft` | `anchore/syft` | CycloneDX JSON | source dir or `--image-ref` | +| `cyclonedx` | `cyclonedx/cyclonedx-cli` | CycloneDX JSON | converts existing `bom.{xml,json}` | +| `spdx-tools` | `anchore/syft` | SPDX JSON | practical SPDX generator; dir or image | +| `trivy` | `aquasec/trivy` | CycloneDX JSON | `trivy fs`/`trivy image` | +| `none` | `alpine` | skip marker JSON | no-op, mirrors adapter skip intent | + +## Examples + +```bash +# Default: Syft CycloneDX over the source tree +dagger call generate --source . -o sbom.cdx.json + +# Trivy scanning a built image +dagger call generate --source . --image-ref ghcr.io/org/app:tag --generator trivy -o sbom.cdx.json + +# SPDX document +dagger call generate --source . --generator spdx-tools -o sbom.spdx.json +``` diff --git a/sbom/dagger.json b/sbom/dagger.json new file mode 100644 index 0000000..40b7934 --- /dev/null +++ b/sbom/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "sbom", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/sbom/main.go b/sbom/main.go new file mode 100644 index 0000000..19485ef --- /dev/null +++ b/sbom/main.go @@ -0,0 +1,179 @@ +// Package main implements the IntegraCI sbom Dagger module. +// +// Engine-agnostic Software Bill of Materials (SBOM) generation. Translates +// the GitHub-Actions-only intent of security_pipeline_adapter.build_sbom_step +// into canonical tool CLIs run inside official containers, so the same +// pipeline logic is callable from ANY CI engine via `dagger call`. +// +// Each generator emits a CycloneDX or SPDX document: +// +// syft -> anchore/syft, CycloneDX JSON +// cyclonedx -> cyclonedx/cyclonedx-cli, CycloneDX JSON +// spdx-tools -> anchore/syft, SPDX JSON (the practical SPDX generator) +// trivy -> aquasec/trivy fs/image --format cyclonedx +// none -> no-op skip (mirrors adapter _comment_skip intent) +// +// Usage: +// +// dagger call generate --source . --generator syft +// dagger call generate --source . --image-ref ghcr.io/org/app:tag --generator trivy +// dagger call generate --source . --generator spdx-tools +package main + +import ( + "context" + "dagger/sbom/internal/dagger" + "fmt" +) + +// Sbom is the IntegraCI SBOM generation module. +type Sbom struct{} + +// Generate produces an SBOM document for the given source (or image) using +// the selected generator and returns the resulting file. +// +// When imageRef is set, generators that support image scanning (syft, +// spdx-tools, trivy) scan the image; otherwise they scan the source +// filesystem. The cyclonedx generator always operates on the source tree. +func (m *Sbom) Generate( + ctx context.Context, + // Source directory to analyze for the SBOM + source *dagger.Directory, + // Optional container image reference to scan instead of the filesystem + // +optional + imageRef string, + // SBOM generator: syft | cyclonedx | spdx-tools | trivy | none + // +optional + // +default="syft" + generator string, + // The registry holding --image-ref is served over plain HTTP, so the pull + // must not assume TLS. Same opt-in as standard-build's --registry-insecure + // and driven by the same resolution (the connected registry's own scheme) — + // never a default, never an address in this file. + // +optional + registryInsecure bool, +) (*dagger.File, error) { + switch generator { + case "none": + // No-op skip: emit a marker file mirroring the adapter's + // _comment_skip("SBOM disabled") intent so downstream steps see a + // deterministic, empty result instead of failing. + return dag.Container(). + From("alpine:3.20"). + WithExec([]string{ + "sh", "-c", + "mkdir -p /out && echo '{\"skipped\":true,\"reason\":\"SBOM disabled (generator=none)\"}' > /out/sbom.skip.json", + }). + File("/out/sbom.skip.json"), nil + + case "syft": + // anchore/syft, CycloneDX JSON. Source dir or image. The anchore/syft + // image is distroless (no shell), so copy the syft binary into alpine + // — which has sh — for the mkdir + output redirect. + syftBin := dag.Container().From("anchore/syft:v1.18.1").File("/syft") + return syftRegistryEnv(dag.Container(). + From("alpine:3.20"). + WithFile("/usr/local/bin/syft", syftBin). + WithMountedDirectory("/src", source). + WithWorkdir("/src"), imageRef, registryInsecure). + WithExec([]string{ + "sh", "-c", + fmt.Sprintf("mkdir -p /out && syft %s -o cyclonedx-json=/out/sbom.cdx.json", syftTarget(imageRef)), + }). + File("/out/sbom.cdx.json"), nil + + case "spdx-tools": + // Practical SPDX generator: syft emitting SPDX JSON. Source or image. + // anchore/syft is distroless; copy the binary into alpine for a shell. + syftBin := dag.Container().From("anchore/syft:v1.18.1").File("/syft") + return syftRegistryEnv(dag.Container(). + From("alpine:3.20"). + WithFile("/usr/local/bin/syft", syftBin). + WithMountedDirectory("/src", source). + WithWorkdir("/src"), imageRef, registryInsecure). + WithExec([]string{ + "sh", "-c", + fmt.Sprintf("mkdir -p /out && syft %s -o spdx-json=/out/sbom.spdx.json", syftTarget(imageRef)), + }). + File("/out/sbom.spdx.json"), nil + + case "cyclonedx": + // cyclonedx/cyclonedx-cli: convert/aggregate over the source tree. + // We scan for existing component manifests and emit a CycloneDX doc. + return dag.Container(). + From("cyclonedx/cyclonedx-cli:0.27.2"). + WithMountedDirectory("/src", source). + WithWorkdir("/src"). + WithExec([]string{ + "sh", "-c", + "mkdir -p /out && cyclonedx-cli --version > /dev/null 2>&1 || true; " + + "if [ -f bom.xml ]; then cyclonedx-cli convert --input-file bom.xml --output-file /out/sbom.cdx.json --output-format json; " + + "elif [ -f bom.json ]; then cyclonedx-cli convert --input-file bom.json --output-file /out/sbom.cdx.json --output-format json; " + + "else echo '{\"bomFormat\":\"CycloneDX\",\"specVersion\":\"1.5\",\"version\":1,\"components\":[]}' > /out/sbom.cdx.json; fi", + }). + File("/out/sbom.cdx.json"), nil + + case "trivy": + // aquasec/trivy fs/image --format cyclonedx. + subcmd := "fs" + target := "." + if imageRef != "" { + subcmd = "image" + target = imageRef + } + return 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")). + WithMountedDirectory("/src", source). + WithWorkdir("/src"). + WithExec([]string{ + "sh", "-c", + fmt.Sprintf("mkdir -p /out && trivy %s --format cyclonedx --output /out/sbom.cdx.json %s", subcmd, target), + }). + File("/out/sbom.cdx.json"), nil + + default: + return nil, fmt.Errorf("unsupported SBOM generator: %q (want syft|cyclonedx|spdx-tools|trivy|none)", generator) + } +} + +// syftTarget names the SOURCE syft should read, explicitly. +// +// A bare image reference leaves syft to guess, and its guess chain starts with +// a local Docker daemon. Inside a Dagger container there is no daemon and no +// docker socket, so the chain runs out and syft gives up on the whole run. +// MEASURED on a live build against a managed registry with no ingress +// certificate: `could not determine source: ... ':/library/'` +// — an SBOM stage that failed the build for every image it was ever pointed at. +// +// `registry:` names the one source that does exist here, so syft pulls the +// manifest itself. It is correct for a TLS registry too; nothing about it is +// specific to the plain-HTTP case below. +func syftTarget(imageRef string) string { + if imageRef == "" { + return "dir:/src" + } + return "registry:" + imageRef +} + +// syftRegistryEnv applies the registry options syft reads from its environment. +// +// OPT-IN and nothing else: with insecure false — the default, and what every +// existing caller gets — the container is returned untouched and syft keeps +// requiring TLS. It is only relevant when there is an image to pull at all. +// +// Why an env var rather than a flag: syft has no per-invocation `--insecure`. +// Its registry behaviour is configuration (`registry.insecure-use-http` / +// `registry.insecure-skip-tls-verify`), and every syft configuration key has an +// `SYFT_`-prefixed environment spelling. This is the same shape as the crane +// `--insecure` path in standard-build: one boolean, resolved from the registry +// the tenant actually connected, never an address written down here. +func syftRegistryEnv(c *dagger.Container, imageRef string, insecure bool) *dagger.Container { + if !insecure || imageRef == "" { + return c + } + return c. + WithEnvVariable("SYFT_REGISTRY_INSECURE_USE_HTTP", "true"). + WithEnvVariable("SYFT_REGISTRY_INSECURE_SKIP_TLS_VERIFY", "true") +} diff --git a/secret-scan/README.md b/secret-scan/README.md new file mode 100644 index 0000000..7a4febb --- /dev/null +++ b/secret-scan/README.md @@ -0,0 +1,49 @@ +# secret-scan + +Engine-agnostic IntegraCI Dagger module for **secret / credential detection**. +Catches committed credentials and keys before they ship — a best-practice +gate every service should run, callable from any CI engine via `dagger call`. + +Translates `security_pipeline_adapter.build_secret_scan_step` (which renders +GitHub-Actions YAML) into portable container-exec recipes. + +## Verb + +### `scan` + +``` +dagger call scan --source . [--tool gitleaks|trufflehog|detect-secrets|none] +``` + +| Arg | Type | Default | Description | +| -------- | ----------- | ---------- | --------------------------------------------- | +| `source` | `Directory` | (required) | Source tree to scan | +| `tool` | `String` | `gitleaks` | Scanner to run | + +## Tools + +| Tool | Image | Command | +| ---------------- | --------------------------------- | --------------------------------------------------------------- | +| `gitleaks` | `zricethezav/gitleaks` | `detect --source=/src --no-git -v` | +| `trufflehog` | `trufflesecurity/trufflehog` | `filesystem /src --results=verified,unknown --fail` | +| `detect-secrets` | `python:3.12-slim` | `pip install detect-secrets && detect-secrets scan --all-files` | +| `none` | — (no-op) | skip (mirrors `governance.secret_scan=none`) | + +## Result (`ScanResult`) + +```json +{ "tool": "gitleaks", "skipped": false, "findings": 0, "report": "...", "pass": true } +``` + +Tools exit non-zero when secrets are found; the module swallows that exit, +captures the report, and surfaces `pass` / `findings` so the calling CI +engine decides how to gate the pipeline. + +## Examples + +```bash +dagger call scan --source . +dagger call scan --source . --tool trufflehog +dagger call scan --source . --tool detect-secrets +dagger call scan --source . --tool none +``` diff --git a/secret-scan/dagger.json b/secret-scan/dagger.json new file mode 100644 index 0000000..ef35d68 --- /dev/null +++ b/secret-scan/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "secret-scan", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/secret-scan/main.go b/secret-scan/main.go new file mode 100644 index 0000000..f87b95d --- /dev/null +++ b/secret-scan/main.go @@ -0,0 +1,278 @@ +// Package main implements the IntegraCI secret-scan Dagger module. +// +// Catches committed credentials/keys before they ship — a best-practice +// gate every service should run regardless of CI engine. Translates the +// build_secret_scan_step intent from the GitHub-Actions security pipeline +// adapter into engine-agnostic container-exec recipes. +// +// Supported tools (mirrors governance.secret_scan): +// +// gitleaks — zricethezav/gitleaks, fast, no token (default) +// trufflehog — trufflesecurity/trufflehog, verified+unknown results +// detect-secrets — Yelp detect-secrets baseline scan (python image) +// none — no-op skip (governance.secret_scan=none) +// +// Usage: +// +// dagger call scan --source . +// dagger call scan --source . --tool trufflehog +// dagger call scan --source . --tool detect-secrets +// dagger call scan --source . --tool none +package main + +import ( + "context" + "dagger/secret-scan/internal/dagger" + "fmt" + "strings" +) + +// SecretScan is the IntegraCI secret-scanning module. +type SecretScan struct{} + +// ScanResult is the normalised output of any secret-scan tool we run. +type ScanResult struct { + Tool string `json:"tool"` // gitleaks | trufflehog | detect-secrets | none + Skipped bool `json:"skipped"` // true for the "none" no-op branch + Findings int `json:"findings"` // best-effort count of detected secrets + Report string `json:"report"` // raw tool stdout/report + Pass bool `json:"pass"` // false when secrets were detected + Error string `json:"error,omitempty"` // failure detail, if any +} + +// Scan runs the selected secret-detection tool over the source tree. +// +// Each tool runs its canonical CLI inside its official image, and each argv +// NAMES THE BINARY. Dagger's WithExec does not use the image ENTRYPOINT, so an +// argv that starts at the subcommand (`detect …`, `filesystem …`) is looked up +// as an executable of that name and there is none. Measured on a live build: +// the Secret Scan stage ran, found nothing, and reported a pass — because the +// scanner had never started. +// +// Findings must not be confused with a scanner that could not run. Every tool +// below is therefore configured to exit 0 WHEN IT COMPLETES (gitleaks +// `--exit-code 0`; trufflehog without `--fail`) and the exec error is returned +// rather than swallowed, so a missing binary, an unpullable image or a crashed +// scan fails the stage while a real finding is still surfaced through +// Pass/Findings for the caller (any CI engine) to gate on. +func (m *SecretScan) Scan( + ctx context.Context, + // Source directory to scan + source *dagger.Directory, + // Tool: gitleaks | trufflehog | detect-secrets | none + // +optional + // +default="gitleaks" + tool string, +) (*ScanResult, error) { + switch tool { + case "none": + // Mirrors _comment_skip — governance.secret_scan=none. + return &ScanResult{Tool: "none", Skipped: true, Pass: true}, nil + + case "gitleaks": + return runGitleaks(ctx, source) + + case "trufflehog": + return runTruffleHog(ctx, source) + + case "detect-secrets": + return runDetectSecrets(ctx, source) + + default: + return nil, fmt.Errorf("unsupported secret-scan tool: %q (want gitleaks|trufflehog|detect-secrets|none)", tool) + } +} + +// Sarif runs gitleaks and returns its SARIF report, for a pipeline to export +// and archive (#2143 phase 2): +// +// dagger call sarif --source=. export --path=integraci-sarif/secrets.sarif +// +// `--redact` is the point of this function, not a detail: without it the +// SARIF carries every matched secret in its snippets, and the archived report +// becomes a second, longer-lived copy of the credential it found. Only +// gitleaks writes SARIF; the other tools are refused rather than faked. +func (m *SecretScan) Sarif( + ctx context.Context, + // Source directory to scan + source *dagger.Directory, + // Tool: gitleaks + // +optional + // +default="gitleaks" + tool string, +) (*dagger.File, error) { + if tool != "gitleaks" { + return nil, fmt.Errorf("secret-scan tool %q writes no SARIF; sarif supports gitleaks", tool) + } + const reportPath = "/tmp/gitleaks-results.sarif" + report := dag.Container(). + From("zricethezav/gitleaks:v8.21.2"). + WithMountedDirectory("/src", source). + WithWorkdir("/src"). + WithExec([]string{ + "gitleaks", "detect", "--source=/src", "--no-git", "--redact", + "--exit-code", "0", "--report-format", "sarif", "--report-path", reportPath, + }). + File(reportPath) + if _, err := report.Contents(ctx); err != nil { + return nil, fmt.Errorf("gitleaks sarif failed: %w", err) + } + return report, nil +} + +// runGitleaks runs `gitleaks detect --source=/src --no-git -v --exit-code 0`. +// --no-git scans the working tree (the Dagger-mounted source has no .git), -v +// prints each leak. +// +// The argv NAMES `gitleaks` — this is the same invocation the security-scan +// module has always used, and it used to read just `detect` here, which is not +// an executable in that image. +// +// `--exit-code 0` turns gitleaks' documented exit-1-on-findings into a plain +// success, which is what makes the remaining error meaningful: with it, a +// non-zero exit can only be the scan failing to run, so it is returned instead +// of discarded. Leaks are still reported — through Findings/Pass below. +func runGitleaks(ctx context.Context, source *dagger.Directory) (*ScanResult, error) { + out, err := dag.Container(). + From("zricethezav/gitleaks:v8.21.2"). + WithMountedDirectory("/src", source). + WithWorkdir("/src"). + WithExec([]string{"gitleaks", "detect", "--source=/src", "--no-git", "-v", "--exit-code", "0"}). + Stdout(ctx) + if err != nil { + return &ScanResult{ + Tool: "gitleaks", + Error: fmt.Sprintf("gitleaks could not run: %v", err), + }, + fmt.Errorf("gitleaks execution failed: %w", err) + } + + result := &ScanResult{Tool: "gitleaks", Report: out} + // gitleaks prints a "leaks found: N" / "Finding:" line per secret. + result.Findings = strings.Count(out, "Finding:") + if result.Findings == 0 { + // Fall back to the summary line when -v output is buffered to stderr. + result.Findings = countGitleaksSummary(out) + } + result.Pass = result.Findings == 0 + if !result.Pass { + result.Error = fmt.Sprintf("gitleaks: %d secret(s) detected", result.Findings) + } + return result, nil +} + +// runTruffleHog runs `trufflehog filesystem /src --results=verified,unknown`. +// +// The argv NAMES `trufflehog`: the trufflesecurity image puts the CLI behind an +// ENTRYPOINT, which Dagger's WithExec does not use, so the previous argv +// starting at `filesystem` asked for an executable of that name. +// +// `--fail` is deliberately absent. Its only purpose is to make the process exit +// non-zero when results are found, which the caller then has to swallow — and +// swallowing it also hides the scan never having started. Findings are counted +// from the report below, so without --fail a non-zero exit means exactly one +// thing: trufflehog could not run. +func runTruffleHog(ctx context.Context, source *dagger.Directory) (*ScanResult, error) { + out, err := dag.Container(). + From("trufflesecurity/trufflehog:3.88.0"). + WithMountedDirectory("/src", source). + WithWorkdir("/src"). + WithExec([]string{"trufflehog", "filesystem", "/src", "--results=verified,unknown"}). + Stdout(ctx) + if err != nil { + return &ScanResult{ + Tool: "trufflehog", + Error: fmt.Sprintf("trufflehog could not run: %v", err), + }, + fmt.Errorf("trufflehog execution failed: %w", err) + } + + result := &ScanResult{Tool: "trufflehog", Report: out} + // trufflehog emits one finding block per detector hit. + result.Findings = strings.Count(out, "Found ") + if result.Findings == 0 { + result.Findings = strings.Count(out, "DetectorType:") + } + result.Pass = result.Findings == 0 + if !result.Pass { + result.Error = fmt.Sprintf("trufflehog: %d secret(s) detected", result.Findings) + } + return result, nil +} + +// runDetectSecrets installs Yelp detect-secrets and runs a full-tree scan, +// producing a baseline JSON on stdout. detect-secrets scan exits 0 even +// when secrets are present (the baseline is the artifact), so we parse the +// baseline for results. +// +// This one was already right on both counts the other two got wrong: the argv +// starts at `sh`, a real executable in the python image, and the exec error is +// returned rather than dropped. Left as the shape the others now match. +func runDetectSecrets(ctx context.Context, source *dagger.Directory) (*ScanResult, error) { + out, err := dag.Container(). + From("python:3.12-slim"). + WithMountedDirectory("/src", source). + WithWorkdir("/src"). + WithExec([]string{ + "sh", "-c", + "pip install --quiet detect-secrets && detect-secrets scan --all-files", + }). + Stdout(ctx) + if err != nil { + return &ScanResult{ + Tool: "detect-secrets", + Error: fmt.Sprintf("detect-secrets scan failed: %v", err), + }, fmt.Errorf("detect-secrets scan failed: %w", err) + } + + result := &ScanResult{Tool: "detect-secrets", Report: out} + result.Findings = countDetectSecrets(out) + result.Pass = result.Findings == 0 + if !result.Pass { + result.Error = fmt.Sprintf("detect-secrets: %d potential secret(s) detected", result.Findings) + } + return result, nil +} + +// ───── helpers (zero-dep, substring-based) ───── + +// countGitleaksSummary extracts N from gitleaks' "leaks found: N" summary. +func countGitleaksSummary(out string) int { + for _, line := range strings.Split(out, "\n") { + l := strings.ToLower(line) + if strings.Contains(l, "leaks found:") { + fields := strings.Fields(l) + for i, f := range fields { + if f == "found:" && i+1 < len(fields) { + return atoiSafe(fields[i+1]) + } + } + } + } + return 0 +} + +// countDetectSecrets counts secret entries in detect-secrets' baseline +// JSON. The "results" object maps filename -> [secrets]; each entry has a +// "type" key. Counting "type":"..." occurrences is a reliable, zero-dep +// proxy for the number of flagged secrets. +func countDetectSecrets(out string) int { + return strings.Count(out, `"type":`) +} + +// atoiSafe parses a leading integer, ignoring trailing punctuation. +func atoiSafe(s string) int { + n := 0 + found := false + for _, r := range s { + if r < '0' || r > '9' { + if found { + break + } + continue + } + found = true + n = n*10 + int(r-'0') + } + return n +} diff --git a/security-scan/README.md b/security-scan/README.md new file mode 100644 index 0000000..4479deb --- /dev/null +++ b/security-scan/README.md @@ -0,0 +1,10 @@ +# IntegraCI — Security Scan Dagger Module + +Run Trivy container scan, Gitleaks secret detection, and license scan. + +## Usage + +```bash +dagger call scan --source . --api-url http://localhost:8000 --token $TOKEN +dagger call license-scan --source . --forbidden GPL-2.0,GPL-3.0,AGPL-3.0 +``` diff --git a/security-scan/dagger.json b/security-scan/dagger.json new file mode 100644 index 0000000..ad05722 --- /dev/null +++ b/security-scan/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "security-scan", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/security-scan/main.go b/security-scan/main.go new file mode 100644 index 0000000..00bb0c0 --- /dev/null +++ b/security-scan/main.go @@ -0,0 +1,597 @@ +// Package main implements the IntegraCI security-scan Dagger module. +// +// Runs Trivy filesystem vuln scan + Gitleaks secret detection + (opt-in) +// Trivy static IaC misconfig scan + (opt-in) Trivy CIS-benchmark/hardening +// compliance scan + Trivy license scan, outputs SARIF / CycloneDX reports, and +// POSTs results to the IntegraCI API. The misconfig and CIS passes are off by +// default (--iac-scan none, --cis none) so they never change a pipeline's +// baseline until a tenant enables them. +// +// Usage: +// +// dagger call scan --source . --api-url http://localhost:8000 --token $TOKEN --service-id $SVC_ID +// dagger call scan --source . --iac-scan trivy --api-url ... --token $TOKEN --service-id $SVC_ID +// dagger call license-scan --source . --forbidden GPL-2.0,GPL-3.0,AGPL-3.0 +// dagger call image-scan --image-ref reg/app:tag --registry-username u --registry-password env://P --api-url ... --token $TOKEN --service-id $SVC_ID +package main + +import ( + "bytes" + "context" + "dagger/security-scan/internal/dagger" + "encoding/json" + "fmt" + "net/http" + "regexp" + "strings" + "time" +) + +// Trivy writes its JSON with json.MarshalIndent — `"Severity": "HIGH"`, a +// space after the colon (measured on aquasec/trivy:0.58.1). The counters below +// once matched `"Severity":"` with no space and so counted ZERO findings in +// every real report: every Trivy scan the pipelines posted read clean, and the +// deploy gate's CVE and licence thresholds never saw a thing. Whitespace- +// tolerant patterns match both the indented and the compact form. +var ( + severityPattern = regexp.MustCompile(`"Severity"\s*:\s*"([A-Za-z]+)"`) + licensePattern = regexp.MustCompile(`"License"\s*:\s*"([^"]*)"`) + ruleIDPattern = regexp.MustCompile(`"RuleID"\s*:\s*"`) +) + +// SecurityScan is the IntegraCI security scanning module. +type SecurityScan struct{} + +// ScanResult contains the output of a security scan. +type ScanResult struct { + TrivyFindings int `json:"trivy_findings"` + GitleaksFindings int `json:"gitleaks_findings"` + LicenseFindings int `json:"license_findings"` + ForbiddenFound int `json:"forbidden_found"` + Critical int `json:"critical"` + High int `json:"high"` + Medium int `json:"medium"` + SecretCount int `json:"secret_count"` + IacCritical int `json:"iac_critical"` + IacHigh int `json:"iac_high"` + SarifPath string `json:"sarif_path,omitempty"` + Success bool `json:"success"` +} + +// LicenseReport summarises Trivy's license scan output. +type LicenseReport struct { + Total int `json:"total"` + Forbidden int `json:"forbidden"` + ForbiddenList []string `json:"forbidden_list"` + UnknownLicenses int `json:"unknown_licenses"` + JSONReport string `json:"json_report"` + Pass bool `json:"pass"` +} + +// Scan runs Trivy vulnerability scan + Gitleaks secret detection. +func (m *SecurityScan) Scan( + ctx context.Context, + // Source directory to scan + 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 scan results + // +optional + serviceID string, + // Version (commit SHA / image tag) the scan applies to + // +optional + version string, + // Static IaC misconfig scan: "trivy" (trivy config) or "none". + // Opt-in (default none) so enabling it never changes a pipeline's baseline. + // +optional + // +default="none" + iacScan string, + // CIS Benchmark / hardening scan: "trivy" (trivy config --compliance + // docker-cis) or "none". Opt-in; failed CIS controls fold into iac_high. + // +optional + // +default="none" + cis string, +) (*ScanResult, error) { + result := &ScanResult{} + source = withoutCITooling(source) + + // Run Trivy filesystem scan + critical, high, medium, err := m.runTrivy(ctx, source) + if err != nil { + return nil, fmt.Errorf("trivy scan failed: %w", err) + } + result.Critical = critical + result.High = high + result.Medium = medium + result.TrivyFindings = critical + high + medium + + // Run Gitleaks secret detection + secretCount, err := m.runGitleaks(ctx, source) + if err != nil { + return nil, fmt.Errorf("gitleaks failed: %w", err) + } + result.SecretCount = secretCount + result.GitleaksFindings = secretCount + + // Optional static IaC misconfig scan (opt-in). trivy config detects + // insecure Dockerfiles / k8s manifests / Terraform (open ports, missing + // encryption, privileged containers, ...). Counts land in report_data as + // iac_critical/iac_high, which the deploy OPA gate reads. When disabled + // they stay 0 — identical to the pre-existing payload, so no flag day. + if iacScan != "" && iacScan != "none" { + iacCritical, iacHigh, err := m.runTrivyConfig(ctx, source) + if err != nil { + return nil, fmt.Errorf("trivy config (iac misconfig) scan failed: %w", err) + } + result.IacCritical = iacCritical + result.IacHigh = iacHigh + } + + // Optional CIS Benchmark / hardening scan (opt-in). Trivy's docker-cis + // compliance scan technically tests config against CIS controls (closing + // the SOP-004 / STD-TI-001 hardening requirement, distinct from the + // compliance *mapping* the platform already ships). Failed controls fold + // into iac_high so hardening failures gate like IaC misconfig. Off by + // default → 0, identical payload, no flag day. + if cis != "" && cis != "none" { + failed := m.runTrivyCisCompliance(ctx, source) + result.IacHigh += failed + } + + // 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 +} + +// ImageScan scans the image the build PUBLISHED — the artifact that is promoted +// — for vulnerabilities and embedded secrets, and posts the counts as scanner +// "trivy-image". `Scan` looks at the source tree; an image carries its base +// layers and whatever the build copied in, which a source scan cannot see. +// +// The image is pulled from the registry by reference, with the build's own +// registry credentials, so what is scanned is what the engine will promote. +// exit-code 0: gating is the deploy policy gate's job, and it reads these +// counts per (scan_type, scanner), so this row cannot hide the source scan's. +func (m *SecurityScan) ImageScan( + ctx context.Context, + // Image reference the build pushed (`/:` or `@sha256:`) + imageRef string, + // +optional + registryUsername string, + // +optional + registryPassword *dagger.Secret, + // Registry without TLS (a tenant Nexus on plain HTTP) + // +optional + registryInsecure bool, + // +optional + apiURL string, + // +optional + token *dagger.Secret, + // +optional + serviceID string, + // Version (commit SHA / image tag) the scan applies to + // +optional + version string, +) (*ScanResult, error) { + if strings.TrimSpace(imageRef) == "" { + return nil, fmt.Errorf("image-scan needs --image-ref") + } + const reportPath = "/tmp/trivy-image.json" + args := []string{ + "trivy", "image", + "--image-src", "remote", + "--scanners", "vuln,secret", + "--format", "json", + "--severity", "CRITICAL,HIGH,MEDIUM", + "--exit-code", "0", + "--output", reportPath, + } + if registryInsecure { + args = append(args, "--insecure") + } + args = append(args, imageRef) + ctr := dag.Container(). + From("aquasec/trivy:0.58.1"). + WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")) + if registryUsername != "" && registryPassword != nil { + ctr = ctr. + WithEnvVariable("TRIVY_USERNAME", registryUsername). + WithSecretVariable("TRIVY_PASSWORD", registryPassword) + } + report, err := ctr.WithExec(args).File(reportPath).Contents(ctx) + if err != nil { + return nil, fmt.Errorf("trivy image scan of %s failed: %w", imageRef, err) + } + critical, high, medium := countTrivySeverities(report) + result := &ScanResult{ + Critical: critical, + High: high, + Medium: medium, + TrivyFindings: critical + high + medium, + SecretCount: len(ruleIDPattern.FindAllStringIndex(report, -1)), + } + if apiURL != "" && token != nil { + if err := m.postScan(ctx, apiURL, token, serviceID, version, "trivy-image", imageRef, result); err != nil { + return nil, fmt.Errorf("posting image scan to API failed: %w", err) + } + } + result.Success = true + return result, nil +} + +// withoutCITooling removes what the PIPELINE put into the checkout before the +// scan: the dagger CLI (`./bin/dagger`, installed by every stage's install +// script) and the platform's module mirror (`./.integraci-modules`). They are +// the platform's tools, not the tenant's code, and scanning them charged every +// tenant with the CVEs of a Go binary and its module graph — measured +// 2026-09-26: a repository with no dependencies at all reported 13 HIGH on two +// different commits, identically. Only these two exact paths go; an +// application's own `bin/` stays in scope. +func withoutCITooling(source *dagger.Directory) *dagger.Directory { + return source.WithoutFile("bin/dagger").WithoutDirectory(".integraci-modules") +} + +// postResults sends the security-scan result back to the IntegraCI scans +// endpoint. Shape matches api/app/schemas/scan.py ScanResultCreate: typed +// severity columns plus the report_data counters the deploy OPA gate reads +// (see deploy.py _build_scan_results). +func (m *SecurityScan) postResults( + ctx context.Context, + apiURL string, + token *dagger.Secret, + serviceID string, + version string, + result *ScanResult, +) error { + return m.postScan(ctx, apiURL, token, serviceID, version, "trivy", "", result) +} + +// postScan posts one scanner's counts. `scanner` keeps the source scan +// ("trivy") and the image scan ("trivy-image") apart for the deploy gate. +func (m *SecurityScan) postScan( + ctx context.Context, + apiURL string, + token *dagger.Secret, + serviceID string, + version string, + scanner string, + imageRef string, + result *ScanResult, +) error { + payload := map[string]any{ + "service_id": serviceID, + "version": version, + "scan_type": "container", + "scanner": scanner, + "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": result.SecretCount, + "dast_high": 0, + "dast_critical": 0, + "sast_errors": 0, + "iac_critical": result.IacCritical, + "iac_high": result.IacHigh, + "sbom_present": false, + "signed": false, + }, + } + if imageRef != "" { + payload["report_data"].(map[string]any)["image_ref"] = imageRef + } + + 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 +} + +// LicenseScan runs Trivy in license-scan mode and fails when forbidden +// licenses are detected. Default forbidden list mirrors the "no GPL in +// production" policy from the Phase 5 PRD (5.6). +func (m *SecurityScan) LicenseScan( + ctx context.Context, + // Source directory to scan + source *dagger.Directory, + // Comma-separated list of forbidden SPDX license identifiers + // +optional + // +default="GPL-2.0,GPL-3.0,AGPL-3.0,LGPL-3.0,SSPL-1.0,Commons-Clause" + forbidden string, + // Exit non-zero when forbidden licenses are found + // +optional + // +default=true + failOnForbidden bool, +) (*LicenseReport, error) { + forbiddenList := strings.Split(forbidden, ",") + for i, s := range forbiddenList { + forbiddenList[i] = strings.TrimSpace(s) + } + + trivy := 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", withoutCITooling(source)). + WithWorkdir("/src"). + WithExec([]string{ + "trivy", "fs", + "--scanners", "license", + "--format", "json", + "--license-full", + "--severity", "UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL", + "--exit-code", "0", + "--output", "/tmp/trivy-licenses.json", + ".", + }) + + if _, err := trivy.Stdout(ctx); err != nil { + return nil, fmt.Errorf("trivy license scan failed: %w", err) + } + + jsonOut, err := trivy.File("/tmp/trivy-licenses.json").Contents(ctx) + if err != nil { + return nil, fmt.Errorf("read trivy license output: %w", err) + } + + report := classifyLicenses(jsonOut, forbiddenList) + report.JSONReport = jsonOut + + if failOnForbidden && report.Forbidden > 0 { + return report, fmt.Errorf( + "license scan: %d forbidden license(s) detected: %s", + report.Forbidden, strings.Join(report.ForbiddenList, ", "), + ) + } + return report, nil +} + +// classifyLicenses parses Trivy's JSON and returns a summary. We avoid +// pulling in a JSON schema dependency; the surface area we care about is +// just License + PkgName. +func classifyLicenses(rawJSON string, forbidden []string) *LicenseReport { + report := &LicenseReport{ForbiddenList: []string{}, Pass: true} + + forbiddenSet := map[string]bool{} + for _, l := range forbidden { + if l != "" { + forbiddenSet[strings.ToUpper(l)] = true + } + } + + // Every "License" value in the report (whitespace-tolerant, see + // licensePattern). + for _, match := range licensePattern.FindAllStringSubmatch(rawJSON, -1) { + license := match[1] + if license == "" { + continue + } + report.Total++ + upper := strings.ToUpper(license) + if upper == "UNKNOWN" { + report.UnknownLicenses++ + continue + } + for f := range forbiddenSet { + if strings.Contains(upper, f) { + report.Forbidden++ + report.ForbiddenList = append(report.ForbiddenList, license) + report.Pass = false + break + } + } + } + return report +} + +// Sarif runs Trivy's filesystem vulnerability scan and returns the report as +// SARIF, for a pipeline to export and archive (#2143 phase 2): +// +// dagger call sarif --source=. export --path=integraci-sarif/trivy.sarif +// +// `--scanners vuln` only: secrets are reported by the secret-scan module's +// redacted SARIF, and a second copy of a matched secret in an archived report +// is a leak. Nothing is posted; Scan remains the step that reports. +func (m *SecurityScan) Sarif( + ctx context.Context, + // Source directory to scan + source *dagger.Directory, +) (*dagger.File, error) { + const reportPath = "/tmp/trivy-results.sarif" + report := dag.Container(). + From("aquasec/trivy:0.58.1"). + WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")). + WithDirectory("/src", source.WithoutFile("bin/dagger").WithoutDirectory(".integraci-modules")). + WithWorkdir("/src"). + WithExec([]string{ + "trivy", "fs", + "--scanners", "vuln", + "--format", "sarif", + "--exit-code", "0", + "--output", reportPath, + ".", + }). + File(reportPath) + if _, err := report.Contents(ctx); err != nil { + return nil, fmt.Errorf("trivy sarif failed: %w", err) + } + return report, nil +} + +// runTrivy runs a Trivy filesystem scan and returns the critical/high/medium +// vulnerability counts parsed from the JSON report. Trivy may exit non-zero +// when vulnerabilities are present, so counts are read from the report file +// rather than the exit code. +func (m *SecurityScan) runTrivy(ctx context.Context, source *dagger.Directory) (int, int, int, error) { + const reportPath = "/tmp/trivy-results.json" + trivy := 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", + "--format", "json", + "--severity", "CRITICAL,HIGH,MEDIUM", + "--exit-code", "0", + "--output", reportPath, + ".", + }) + + report, err := trivy.File(reportPath).Contents(ctx) + if err != nil { + return 0, 0, 0, fmt.Errorf("read trivy output: %w", err) + } + + critical, high, medium := countTrivySeverities(report) + return critical, high, medium, nil +} + +// runTrivyConfig runs a Trivy static misconfiguration scan (`trivy config`) +// over the source tree and returns the critical/high misconfig counts parsed +// from the JSON report. Reuses countTrivySeverities — trivy config emits the +// same "Severity":"" shape as the vuln scan. exit-code 0 so findings +// don't fail the container step; gating is the deploy OPA gate's job. +func (m *SecurityScan) runTrivyConfig(ctx context.Context, source *dagger.Directory) (int, int, error) { + const reportPath = "/tmp/trivy-config.json" + trivy := dag.Container(). + From("aquasec/trivy:0.58.1"). + // Persist Trivy's DB across runs (avoids re-downloading it). + WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")). + WithDirectory("/src", source). + WithWorkdir("/src"). + WithExec([]string{ + "trivy", "config", + "--format", "json", + "--severity", "CRITICAL,HIGH,MEDIUM", + "--exit-code", "0", + "--output", reportPath, + ".", + }) + + report, err := trivy.File(reportPath).Contents(ctx) + if err != nil { + return 0, 0, fmt.Errorf("read trivy config output: %w", err) + } + + critical, high, _ := countTrivySeverities(report) + return critical, high, nil +} + +// runTrivyCisCompliance runs `trivy config --compliance docker-cis-1.6.0` over +// the source and returns the number of FAILED CIS controls. exit-code 0 so +// failures don't fail the container step; gating is the deploy gate's job. +func (m *SecurityScan) runTrivyCisCompliance(ctx context.Context, source *dagger.Directory) int { + out, _ := dag.Container(). + From("aquasec/trivy:0.58.1"). + WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")). + WithDirectory("/src", source). + WithWorkdir("/src"). + WithExec([]string{ + "trivy", "config", + "--compliance", "docker-cis-1.6.0", + "--report", "summary", + "--format", "json", + "--exit-code", "0", + ".", + }). + Stdout(ctx) + // Trivy's compliance report marks each control PASS/FAIL; counting FAIL + // statuses is a zero-dep proxy for failed CIS controls. + return strings.Count(out, `"FAIL"`) + strings.Count(out, `"status":"FAIL"`) +} + +// runGitleaks runs Gitleaks secret detection and returns the number of +// detected secrets, parsed from the SARIF report (one "ruleId" per finding). +func (m *SecurityScan) runGitleaks(ctx context.Context, source *dagger.Directory) (int, error) { + const reportPath = "/tmp/gitleaks-results.sarif" + gitleaks := dag.Container(). + From("zricethezav/gitleaks:v8.21.2"). + WithDirectory("/src", source). + WithWorkdir("/src"). + WithExec([]string{ + "gitleaks", "detect", + "--source", ".", + "--report-format", "sarif", + "--report-path", reportPath, + "--exit-code", "0", + }) + + report, err := gitleaks.File(reportPath).Contents(ctx) + if err != nil { + return 0, fmt.Errorf("read gitleaks output: %w", err) + } + + return countSarifResults(report), nil +} + +// countTrivySeverities tallies CRITICAL/HIGH/MEDIUM occurrences from Trivy's +// JSON report: one "Severity" per finding (see severityPattern for why the +// match is whitespace-tolerant). +func countTrivySeverities(rawJSON string) (critical, high, medium int) { + for _, match := range severityPattern.FindAllStringSubmatch(rawJSON, -1) { + switch strings.ToUpper(match[1]) { + case "CRITICAL": + critical++ + case "HIGH": + high++ + case "MEDIUM": + medium++ + } + } + return critical, high, medium +} + +// countSarifResults counts findings in a SARIF document by tallying +// "ruleId" occurrences (one per result). Zero-dep, matching sast-scan. +func countSarifResults(report string) int { + count := 0 + idx := 0 + for { + k := strings.Index(report[idx:], `"ruleId":`) + if k < 0 { + break + } + count++ + idx += k + len(`"ruleId":`) + } + return count +} diff --git a/serverless-deploy/README.md b/serverless-deploy/README.md new file mode 100644 index 0000000..b3dc3a5 --- /dev/null +++ b/serverless-deploy/README.md @@ -0,0 +1,10 @@ +# IntegraCI — Serverless Deploy Dagger Module + +Deploy functions to AWS Lambda, GCP Cloud Functions, and Azure Functions. + +## Usage + +```bash +dagger call lambda --source ./build.zip --name my-fn --runtime python3.12 +dagger call cloud-function --source ./build.zip --name my-fn --runtime python312 +``` diff --git a/serverless-deploy/dagger.json b/serverless-deploy/dagger.json new file mode 100644 index 0000000..79af427 --- /dev/null +++ b/serverless-deploy/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "serverless-deploy", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/serverless-deploy/main.go b/serverless-deploy/main.go new file mode 100644 index 0000000..bf5666b --- /dev/null +++ b/serverless-deploy/main.go @@ -0,0 +1,183 @@ +// Package main implements the IntegraCI serverless-deploy Dagger module. +// +// One-stop module for deploying functions to: +// - AWS Lambda (zip & container image) +// - GCP Cloud Function (gen2) +// - Azure Function (zip) +// +// All providers share a common ServerlessResult contract so the IntegraCI +// ServerlessDeployWorkflow can render uniform UI/audit data. +// +// Usage: +// +// dagger call lambda --source ./build.zip --name my-fn --runtime python3.12 --role-arn $ROLE +// dagger call cloud-function --source ./build.zip --name my-fn --runtime python312 --region us-central1 +package main + +import ( + "context" + "dagger/serverless-deploy/internal/dagger" + "fmt" + "strings" +) + +// ServerlessDeploy is the multi-provider FaaS deploy module. +type ServerlessDeploy struct{} + +// ServerlessResult summarises a single function deployment. +type ServerlessResult struct { + Provider string `json:"provider"` + FunctionName string `json:"function_name"` + Region string `json:"region"` + Version string `json:"version,omitempty"` + InvokeURL string `json:"invoke_url,omitempty"` + Output string `json:"output,omitempty"` + Success bool `json:"success"` +} + +// Lambda packages and deploys a function to AWS Lambda using the AWS CLI. +func (m *ServerlessDeploy) Lambda( + ctx context.Context, + // Build artifact (.zip with handler). + source *dagger.File, + // Function name in AWS. + name string, + // Runtime e.g. python3.12 / nodejs20.x / provided.al2023. + runtime string, + // IAM role ARN with execution permissions. + roleARN string, + // AWS region. + // +optional + // +default="us-east-1" + region string, + // Handler entry point. + // +optional + // +default="app.handler" + handler string, + // AWS access key ID secret. + awsAccessKey *dagger.Secret, + // AWS secret access key secret. + awsSecretKey *dagger.Secret, + // Function memory in MB. + // +optional + // +default=128 + memory int, + // Timeout seconds. + // +optional + // +default=10 + timeout int, +) (*ServerlessResult, error) { + c := dag.Container(). + From("amazon/aws-cli:2.17.0"). + WithMountedFile("/work/fn.zip", source). + WithSecretVariable("AWS_ACCESS_KEY_ID", awsAccessKey). + WithSecretVariable("AWS_SECRET_ACCESS_KEY", awsSecretKey). + WithEnvVariable("AWS_REGION", region) + + upsert := strings.Join([]string{ + fmt.Sprintf("aws lambda get-function --function-name %s >/dev/null 2>&1", name), + "&&", + fmt.Sprintf("aws lambda update-function-code --function-name %s --zip-file fileb:///work/fn.zip", name), + "||", + strings.Join([]string{ + "aws lambda create-function", + "--function-name " + name, + "--runtime " + runtime, + "--role " + roleARN, + "--handler " + handler, + fmt.Sprintf("--memory-size %d", memory), + fmt.Sprintf("--timeout %d", timeout), + "--zip-file fileb:///work/fn.zip", + }, " "), + }, " ") + c = c.WithExec([]string{"sh", "-c", upsert + " || true"}) + out, _ := c.Stdout(ctx) + + return &ServerlessResult{ + Provider: "aws_lambda", + FunctionName: name, + Region: region, + Output: out, + Success: strings.Contains(out, `"FunctionArn"`) || !strings.Contains(strings.ToLower(out), "error"), + }, nil +} + +// CloudFunction deploys a Gen2 Cloud Function via gcloud. +func (m *ServerlessDeploy) CloudFunction( + ctx context.Context, + source *dagger.Directory, + name string, + // Runtime e.g. python312 / nodejs20. + runtime string, + // HTTP trigger entry point. + entrypoint string, + region string, + // Service-account JSON key. + serviceAccount *dagger.Secret, + // +optional + // +default="256MB" + memory string, + // +optional + // +default=60 + timeout int, +) (*ServerlessResult, error) { + c := dag.Container(). + From("google/cloud-sdk:slim"). + WithMountedDirectory("/src", source). + 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{ + "cd /src && gcloud functions deploy " + name, + "--gen2", + "--runtime=" + runtime, + "--entry-point=" + entrypoint, + "--region=" + region, + "--memory=" + memory, + fmt.Sprintf("--timeout=%ds", timeout), + "--trigger-http", + "--allow-unauthenticated", + "--source=.", + "|| true", + }, " ")}) + out, _ := c.Stdout(ctx) + return &ServerlessResult{ + Provider: "gcp_cloud_function", + FunctionName: name, + Region: region, + Output: out, + Success: strings.Contains(out, "https://"), + }, nil +} + +// AzureFunction deploys via az func. +func (m *ServerlessDeploy) AzureFunction( + ctx context.Context, + source *dagger.Directory, + name string, + resourceGroup string, + region string, + // Azure SP credentials JSON. + credentialsJSON *dagger.Secret, +) (*ServerlessResult, error) { + c := dag.Container(). + From("mcr.microsoft.com/azure-cli:2.67.0"). + WithMountedDirectory("/src", source). + WithMountedSecret("/work/sp.json", credentialsJSON). + WithExec([]string{"sh", "-c", + `AZ=$(cat /work/sp.json) && ` + + `az login --service-principal -u $(echo $AZ | jq -r .clientId) -p $(echo $AZ | jq -r .clientSecret) --tenant $(echo $AZ | jq -r .tenantId) || true`, + }). + WithExec([]string{"sh", "-c", strings.Join([]string{ + "cd /src && func azure functionapp publish " + name, + "--resource-group " + resourceGroup, + "|| true", + }, " ")}) + out, _ := c.Stdout(ctx) + return &ServerlessResult{ + Provider: "azure_function", + FunctionName: name, + Region: region, + Output: out, + Success: !strings.Contains(strings.ToLower(out), "error"), + }, nil +} diff --git a/standard-build/README.md b/standard-build/README.md new file mode 100644 index 0000000..da52e8d --- /dev/null +++ b/standard-build/README.md @@ -0,0 +1,24 @@ +# IntegraCI — Standard Build Dagger Module + +Standard build pipeline: lint → test → build → container image. + +## Functions + +| Function | What it does | +|----------|--------------| +| `build` | lint → test → image (→ publish when `--image-ref` is given). **A root `Dockerfile` wins over `--language`**: the tree is built from it and the language lane is skipped (`--ignore-dockerfile=true` forces the lane). Languages outside go/python/node/php always need a Dockerfile. A `.dockerignore` beside the Dockerfile being built is applied by the module itself. For the `.integraci/Dockerfile` IntegraCI generates: after the context's root `.dockerignore` and without the sidecar's `!` re-includes, so no rule can bring back what it excludes, and a symlinked or non-regular ignore file refuses the build. For your own Dockerfile: BuildKit's rule -- the sidecar replaces the root file and keeps its `!` lines. | +| `test` | lint + tests of the language lane only — no image, no publish. `image_ref` is always empty. Runs the lane even when a Dockerfile is present (a Dockerfile says how to package, not how to test); an unknown language is an error. Python accepts `pyproject.toml` (`uv pip install -e ".[dev]"`) or brownfield `requirements.txt` (+ ruff/pytest). Use this for the pipeline's "Lint and Test" stage instead of running `npm ci` / `pip` / `golangci-lint` / `docker run` natively on an agent that has no toolchains. | + +## Usage + +```bash +dagger call build --source . --language go +dagger call build --source . --language python +dagger call build --source . --language node +dagger call build --source . --language php # no Dockerfile: php:8.3-apache + your tree +dagger call build --source . --language node --ignore-dockerfile=true # lane, even with a Dockerfile + +dagger call test --source . --language node # lint + tests, no image +dagger call test --source . --language php --runtime-version 7.4 +dagger call test --source . --language java --java-version 17 # JDK 11, 17 or 21 (default 21) +``` diff --git a/standard-build/dagger.json b/standard-build/dagger.json new file mode 100644 index 0000000..75c9234 --- /dev/null +++ b/standard-build/dagger.json @@ -0,0 +1,14 @@ +{ + "name": "standard-build", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go", + "./evidence/evidence.go", + "./layout/layout.go", + "./layout/ignore.go" + ] +} diff --git a/standard-build/evidence/evidence.go b/standard-build/evidence/evidence.go new file mode 100644 index 0000000..4766256 --- /dev/null +++ b/standard-build/evidence/evidence.go @@ -0,0 +1,281 @@ +// Package evidence builds the supply-chain evidence files a build leaves behind +// (ADR-0068 Layer 2, #2143 phase 1): an in-toto Statement carrying an SLSA v1 +// provenance predicate for ONE image digest, and a SHA256SUMS manifest over the +// evidence set. +// +// It is a separate package, standard library only, for the reason db-migration +// keeps its logic in verdict/: the generated `dagger` package panics at init +// without a Dagger session, so nothing in package main can run under a plain +// `go test`. Everything here is pure and deterministic — the same inputs give +// the same bytes — which is what a later golden test comparing the Dagger and +// render-only paths (#2143 acceptance criterion 1) needs. +// +// What this package does NOT do: sign. A statement written here is evidence of +// what the build claims; it becomes an attestation only when cosign signs it +// (`cosign attest-provenance --predicate`), and the deploy-time gate that +// verifies the signature is a later phase. +package evidence + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "net/url" + "regexp" + "sort" + "strings" + "time" +) + +const ( + // StatementType is the in-toto Statement v1 `_type`. + StatementType = "https://in-toto.io/Statement/v1" + // SLSAProvenanceV1 is the SLSA v1.0 provenance predicate type. + SLSAProvenanceV1 = "https://slsa.dev/provenance/v1" + // DefaultBuildType names the recipe this module runs. A verifier keys its + // interpretation of externalParameters off this URI, so it is stable. + DefaultBuildType = "https://integraci.co/buildtypes/dagger-standard-build/v1" +) + +// digestRef matches a reference pinned to a sha256 manifest digest, with or +// without a tag before it: host/repo@sha256:<64>, host/repo:tag@sha256:<64>. +var digestRef = regexp.MustCompile(`^([^@\s]+)@sha256:([0-9a-f]{64})$`) + +// gitRevision is a full commit id: 40 hex (SHA-1 repositories) or 64 hex +// (SHA-256 repositories). An abbreviated id is refused — it does not pin a +// commit, and provenance that does not pin its source is not provenance. +var gitRevision = regexp.MustCompile(`^([0-9a-f]{40}|[0-9a-f]{64})$`) + +// Subject is the artifact a statement is about. +type Subject struct { + Name string `json:"name"` + Digest map[string]string `json:"digest"` +} + +// ParseDigestRef splits a digest-pinned image reference into the subject name +// (repository, no tag) and the hex sha256. +// +// A TAG-ONLY reference is an error, not a lookup. A tag moves; a statement +// about a tag says nothing about the bytes that will be deployed, and resolving +// the tag here would record whatever it points at by the time this step runs — +// possibly another build's image. +func ParseDigestRef(ref string) (Subject, error) { + m := digestRef.FindStringSubmatch(strings.TrimSpace(ref)) + if m == nil { + return Subject{}, fmt.Errorf( + "image reference %q is not pinned to a sha256 digest (want [:tag]@sha256:<64 hex>)", ref) + } + name := m[1] + // Strip a tag, but not a registry port: the tag is after the LAST slash. + if slash := strings.LastIndexByte(name, '/'); strings.LastIndexByte(name, ':') > slash { + name = name[:strings.LastIndexByte(name, ':')] + } + if name == "" { + return Subject{}, fmt.Errorf("image reference %q has no repository", ref) + } + return Subject{Name: name, Digest: map[string]string{"sha256": m[2]}}, nil +} + +// ProvenanceInput is everything the provenance statement records. Every field +// is supplied by the caller (the CI step) — nothing is read from the +// environment here, so nothing in the output is a placeholder. +type ProvenanceInput struct { + ImageRef string // digest-pinned + BuilderID string // absolute URI identifying the build platform/pipeline + BuildType string // empty -> DefaultBuildType + SourceURI string // e.g. git+https://git.example/org/repo@refs/heads/main + SourceRevision string // full commit id + InvocationID string // CI run id; optional + StartedOn string // RFC 3339; optional, omitted when empty + FinishedOn string // RFC 3339; optional, omitted when empty + EngineVersion string // Dagger engine version the module is pinned to + Language string // build lane; optional +} + +type resourceDescriptor struct { + URI string `json:"uri"` + Digest map[string]string `json:"digest"` +} + +type buildDefinition struct { + BuildType string `json:"buildType"` + ExternalParameters map[string]string `json:"externalParameters"` + InternalParameters map[string]string `json:"internalParameters,omitempty"` + ResolvedDependencies []resourceDescriptor `json:"resolvedDependencies"` +} + +type builder struct { + ID string `json:"id"` + Version map[string]string `json:"version,omitempty"` +} + +type buildMetadata struct { + InvocationID string `json:"invocationId,omitempty"` + StartedOn string `json:"startedOn,omitempty"` + FinishedOn string `json:"finishedOn,omitempty"` +} + +type runDetails struct { + Builder builder `json:"builder"` + Metadata *buildMetadata `json:"metadata,omitempty"` +} + +type provenancePredicate struct { + BuildDefinition buildDefinition `json:"buildDefinition"` + RunDetails runDetails `json:"runDetails"` +} + +type statement struct { + Type string `json:"_type"` + Subject []Subject `json:"subject"` + PredicateType string `json:"predicateType"` + Predicate provenancePredicate `json:"predicate"` +} + +// ProvenanceStatement renders the in-toto Statement (SLSA v1 provenance) for +// one image digest, indented and newline-terminated. It refuses — rather than +// writes something a verifier would later have to distrust — when the subject +// is not digest-pinned, the builder is not an absolute URI, the source does +// not pin a full commit, or a timestamp is not RFC 3339. +func ProvenanceStatement(in ProvenanceInput) ([]byte, error) { + subject, err := ParseDigestRef(in.ImageRef) + if err != nil { + return nil, err + } + if err := absoluteURI("builder id", in.BuilderID); err != nil { + return nil, err + } + buildType := in.BuildType + if buildType == "" { + buildType = DefaultBuildType + } + if err := absoluteURI("build type", buildType); err != nil { + return nil, err + } + 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.SourceRevision)) + if !gitRevision.MatchString(rev) { + return nil, fmt.Errorf("source revision %q is not a full commit id (40 or 64 hex)", in.SourceRevision) + } + for name, ts := range map[string]string{"started-on": in.StartedOn, "finished-on": in.FinishedOn} { + if ts == "" { + continue + } + if _, err := time.Parse(time.RFC3339, ts); err != nil { + return nil, fmt.Errorf("%s %q is not RFC 3339: %w", name, ts, err) + } + } + if strings.ContainsAny(in.InvocationID, "\r\n") { + return nil, fmt.Errorf("invocation id must be a single line") + } + + external := map[string]string{"source": in.SourceURI, "revision": rev} + var internal map[string]string + if in.Language != "" { + internal = map[string]string{"language": in.Language} + } + var version map[string]string + if in.EngineVersion != "" { + version = map[string]string{"dagger-engine": in.EngineVersion} + } + var meta *buildMetadata + if in.InvocationID != "" || in.StartedOn != "" || in.FinishedOn != "" { + meta = &buildMetadata{InvocationID: in.InvocationID, StartedOn: in.StartedOn, FinishedOn: in.FinishedOn} + } + + st := statement{ + Type: StatementType, + Subject: []Subject{subject}, + PredicateType: SLSAProvenanceV1, + Predicate: provenancePredicate{ + BuildDefinition: buildDefinition{ + BuildType: buildType, + ExternalParameters: external, + InternalParameters: internal, + // `gitCommit` is the in-toto DigestSet key for a commit id. The + // old cosign predicate labelled it `sha1` after stripping a + // `sha256:` prefix — a digest under the wrong algorithm name. + ResolvedDependencies: []resourceDescriptor{{ + URI: in.SourceURI, + Digest: map[string]string{"gitCommit": rev}, + }}, + }, + RunDetails: runDetails{ + Builder: builder{ID: in.BuilderID, Version: version}, + Metadata: meta, + }, + }, + } + out, err := json.MarshalIndent(st, "", " ") + if err != nil { + return nil, err + } + return append(out, '\n'), nil +} + +func absoluteURI(what, raw string) error { + u, err := url.Parse(raw) + if err != nil || u.Scheme == "" || (u.Host == "" && u.Opaque == "") || strings.ContainsAny(raw, " \t\r\n") { + return fmt.Errorf("%s %q must be an absolute URI", what, raw) + } + return nil +} + +// fileName is what may appear in a SHA256SUMS line: a plain name, so a +// manifest can never point a verifier outside the evidence directory. +var fileName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) + +// SHA256Sums renders a `sha256sum -c`-compatible manifest over the given +// files, sorted by name so the output is deterministic. +func SHA256Sums(files map[string][]byte) ([]byte, error) { + names := make([]string, 0, len(files)) + for name := range files { + if !fileName.MatchString(name) { + return nil, fmt.Errorf("evidence file name %q is not a plain file name", name) + } + names = append(names, name) + } + sort.Strings(names) + var b strings.Builder + for _, name := range names { + sum := sha256.Sum256(files[name]) + fmt.Fprintf(&b, "%s %s\n", hex.EncodeToString(sum[:]), name) + } + return []byte(b.String()), nil +} + +// SBOMFileName maps an SBOM format to the file name the evidence set uses. +func SBOMFileName(format string) (name string, syftOutput string, err error) { + switch format { + case "", "cyclonedx": + return "sbom.cdx.json", "cyclonedx-json", nil + case "spdx": + return "sbom.spdx.json", "spdx-json", nil + default: + return "", "", fmt.Errorf("unsupported sbom format %q (want cyclonedx|spdx)", format) + } +} + +// DigestFromPushOutput finds the digest reference a push printed. crane push +// prints `@sha256:<64>` on success; Dagger's Publish returns +// `:@sha256:<64>`. Empty when no such reference is present. +func DigestFromPushOutput(out string) string { + for _, field := range strings.Fields(out) { + field = strings.Trim(field, `'"`) + if digestRef.MatchString(field) { + return field + } + } + return "" +} + +// DigestOf returns `sha256:` for a digest-pinned reference, else "". +func DigestOf(ref string) string { + if m := digestRef.FindStringSubmatch(ref); m != nil { + return "sha256:" + m[2] + } + return "" +} diff --git a/standard-build/evidence/evidence_test.go b/standard-build/evidence/evidence_test.go new file mode 100644 index 0000000..8454d1b --- /dev/null +++ b/standard-build/evidence/evidence_test.go @@ -0,0 +1,211 @@ +package evidence + +import ( + "encoding/json" + "strings" + "testing" +) + +const ( + hexDigest = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + commit = "89abcdef0123456789abcdef0123456789abcdef" +) + +func validInput() ProvenanceInput { + return ProvenanceInput{ + ImageRef: "registry.example:5000/team/orders:abc123@sha256:" + hexDigest, + BuilderID: "https://jenkins.example/job/orders/", + SourceURI: "git+https://git.example/team/orders@refs/heads/main", + SourceRevision: commit, + InvocationID: "42", + StartedOn: "2026-10-11T08:00:00Z", + FinishedOn: "2026-10-11T08:05:00Z", + EngineVersion: "v0.21.7", + Language: "go", + } +} + +func TestParseDigestRefKeepsPortStripsTag(t *testing.T) { + cases := map[string]string{ + "registry.example:5000/team/orders:abc@sha256:" + hexDigest: "registry.example:5000/team/orders", + "registry.example:5000/team/orders@sha256:" + hexDigest: "registry.example:5000/team/orders", + "ghcr.io/acme/app@sha256:" + hexDigest: "ghcr.io/acme/app", + } + for ref, want := range cases { + s, err := ParseDigestRef(ref) + if err != nil { + t.Fatalf("%q: %v", ref, err) + } + if s.Name != want || s.Digest["sha256"] != hexDigest { + t.Fatalf("%q -> %+v, want name %q", ref, s, want) + } + } +} + +// A tag is never accepted as a subject: it moves, and a statement about a tag +// says nothing about the bytes that get deployed. +func TestParseDigestRefRefusesUnpinned(t *testing.T) { + for _, ref := range []string{ + "", + "ghcr.io/acme/app:1.0.0", + "ghcr.io/acme/app@sha256:" + hexDigest[:63], // short + "ghcr.io/acme/app@sha256:" + strings.ToUpper(hexDigest), // not lowercase hex + "ghcr.io/acme/app@sha512:" + hexDigest, + "@sha256:" + hexDigest, + "ghcr.io/acme/app@sha256:" + hexDigest + "\nextra", + } { + if _, err := ParseDigestRef(ref); err == nil { + t.Fatalf("%q must be refused", ref) + } + } +} + +func TestProvenanceStatementShape(t *testing.T) { + out, err := ProvenanceStatement(validInput()) + if err != nil { + t.Fatal(err) + } + var st map[string]any + if err := json.Unmarshal(out, &st); err != nil { + t.Fatalf("not JSON: %v", err) + } + if st["_type"] != StatementType || st["predicateType"] != SLSAProvenanceV1 { + t.Fatalf("wrong types: %v / %v", st["_type"], st["predicateType"]) + } + subj := st["subject"].([]any)[0].(map[string]any) + if subj["name"] != "registry.example:5000/team/orders" { + t.Fatalf("subject name %v", subj["name"]) + } + if subj["digest"].(map[string]any)["sha256"] != hexDigest { + t.Fatalf("subject digest %v", subj["digest"]) + } + bd := st["predicate"].(map[string]any)["buildDefinition"].(map[string]any) + if bd["buildType"] != DefaultBuildType { + t.Fatalf("buildType %v", bd["buildType"]) + } + dep := bd["resolvedDependencies"].([]any)[0].(map[string]any) + if dep["digest"].(map[string]any)["gitCommit"] != commit { + t.Fatalf("source dependency digest %v", dep["digest"]) + } + // The old cosign predicate shipped literal shell placeholders that nothing + // ever expanded. None may appear here. + if strings.Contains(string(out), "${") { + t.Fatalf("statement carries an unexpanded placeholder:\n%s", out) + } + if !strings.HasSuffix(string(out), "}\n") { + t.Fatal("statement must end with a newline") + } +} + +func TestProvenanceStatementIsDeterministic(t *testing.T) { + a, err := ProvenanceStatement(validInput()) + if err != nil { + t.Fatal(err) + } + b, _ := ProvenanceStatement(validInput()) + if string(a) != string(b) { + t.Fatal("same input must give the same bytes") + } +} + +func TestProvenanceStatementOmitsUnsetMetadata(t *testing.T) { + in := validInput() + in.InvocationID, in.StartedOn, in.FinishedOn = "", "", "" + out, err := ProvenanceStatement(in) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(out), "metadata") { + t.Fatalf("unset metadata must be omitted, not invented:\n%s", out) + } +} + +func TestProvenanceStatementRefusesBadInput(t *testing.T) { + mutate := map[string]func(*ProvenanceInput){ + "tag-only image": func(in *ProvenanceInput) { in.ImageRef = "ghcr.io/acme/app:1.0.0" }, + "relative builder": func(in *ProvenanceInput) { in.BuilderID = "jenkins/job/orders" }, + "empty builder": func(in *ProvenanceInput) { in.BuilderID = "" }, + "builder whitespace": func(in *ProvenanceInput) { in.BuilderID = "https://ci.example/a b" }, + "relative build type": func(in *ProvenanceInput) { in.BuildType = "standard-build" }, + "empty source": func(in *ProvenanceInput) { in.SourceURI = "" }, + "source newline": func(in *ProvenanceInput) { in.SourceURI = "git+https://x\n\"evil\"" }, + "short revision": func(in *ProvenanceInput) { in.SourceRevision = commit[:12] }, + "branch as revision": func(in *ProvenanceInput) { in.SourceRevision = "main" }, + "bad started-on": func(in *ProvenanceInput) { in.StartedOn = "yesterday" }, + "placeholder ts": func(in *ProvenanceInput) { in.FinishedOn = "${BUILD_FINISHED_ON}" }, + "multiline run id": func(in *ProvenanceInput) { in.InvocationID = "1\n2" }, + } + for name, m := range mutate { + in := validInput() + m(&in) + if _, err := ProvenanceStatement(in); err == nil { + t.Fatalf("%s: must be refused", name) + } + } +} + +// Legitimate values a strict-looking validator must not reject. +func TestProvenanceStatementAcceptsLegitimateValues(t *testing.T) { + ok := map[string]func(*ProvenanceInput){ + "sha256 repository commit": func(in *ProvenanceInput) { in.SourceRevision = hexDigest }, + "uppercase commit": func(in *ProvenanceInput) { in.SourceRevision = strings.ToUpper(commit) }, + "urn builder": func(in *ProvenanceInput) { in.BuilderID = "urn:integraci:builder:jenkins" }, + "ssh source": func(in *ProvenanceInput) { in.SourceURI = "git+ssh://git@git.example:2222/team/orders.git" }, + "offset timestamp": func(in *ProvenanceInput) { in.StartedOn = "2026-10-11T15:00:00+07:00" }, + "no tag before digest": func(in *ProvenanceInput) { in.ImageRef = "ghcr.io/acme/app@sha256:" + hexDigest }, + "no language": func(in *ProvenanceInput) { in.Language = "" }, + } + for name, m := range ok { + in := validInput() + m(&in) + if _, err := ProvenanceStatement(in); err != nil { + t.Fatalf("%s: legitimate value refused: %v", name, err) + } + } +} + +func TestSHA256SumsFormat(t *testing.T) { + out, err := SHA256Sums(map[string][]byte{"b.json": []byte("b"), "a.json": []byte("")}) + if err != nil { + t.Fatal(err) + } + want := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 a.json\n" + + "3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d b.json\n" + if string(out) != want { + t.Fatalf("got\n%s\nwant\n%s", out, want) + } +} + +func TestSHA256SumsRefusesPathNames(t *testing.T) { + for _, name := range []string{"../x", "dir/x", "", ".hidden", "a b", "x\ny"} { + if _, err := SHA256Sums(map[string][]byte{name: nil}); err == nil { + t.Fatalf("%q must be refused", name) + } + } +} + +func TestSBOMFileName(t *testing.T) { + if n, o, err := SBOMFileName(""); err != nil || n != "sbom.cdx.json" || o != "cyclonedx-json" { + t.Fatalf("default: %q %q %v", n, o, err) + } + if n, o, err := SBOMFileName("spdx"); err != nil || n != "sbom.spdx.json" || o != "spdx-json" { + t.Fatalf("spdx: %q %q %v", n, o, err) + } + if _, _, err := SBOMFileName("cyclonedx-json; rm -rf /"); err == nil { + t.Fatal("unknown format must be refused") + } +} + +func TestDigestFromPushOutput(t *testing.T) { + ref := "registry.example:5000/team/orders@sha256:" + hexDigest + out := "logged in\n2026/10/11 pushed blob: sha256:aaaa\n" + ref + "\nPUSHED 'registry.example:5000/team/orders:abc'\ncrane exit=0\n" + if got := DigestFromPushOutput(out); got != ref { + t.Fatalf("got %q", got) + } + if got := DigestFromPushOutput("pushed blob: sha256:" + hexDigest + "\n"); got != "" { + t.Fatalf("a bare blob digest is not an image reference, got %q", got) + } + if DigestOf(ref) != "sha256:"+hexDigest || DigestOf("ghcr.io/a:1") != "" { + t.Fatal("DigestOf") + } +} diff --git a/standard-build/layout/ignore.go b/standard-build/layout/ignore.go new file mode 100644 index 0000000..6ae691b --- /dev/null +++ b/standard-build/layout/ignore.go @@ -0,0 +1,159 @@ +package layout + +// Per-Dockerfile ignore files (`.dockerignore`). +// +// IntegraCI commits a generated Dockerfile at `.integraci/Dockerfile` with an +// `.integraci/Dockerfile.dockerignore` beside it. That sidecar is the only thing +// between the generated `COPY . .` and a `.env` or a private key committed to +// the repository: whatever the build context holds is readable by every layer, +// and a secret copied in is a secret published with the image. +// +// Two modes (ContextFilters), chosen by WHOSE Dockerfile is built: +// +// The generated `.integraci/Dockerfile` (IsGeneratedDockerfile) -- STRICT. The +// module applies the sidecar ITSELF, before DockerBuild, instead of trusting +// the engine's Dockerfile frontend to find it, and applies the context's root +// `.dockerignore` as well (BuildKit ignores the root file whenever a +// per-Dockerfile one exists, so the sidecar IntegraCI wrote would otherwise +// silently re-include everything the customer had excluded). Two filters, not +// one merged list: +// +// 1. the root `.dockerignore`, re-includes (`!`) kept, so an allowlist such +// as `*` then `!src` keeps working; +// 2. the sidecar's exclusions, its `!` lines DROPPED, applied to what is left. +// +// A root `!.env` therefore cannot bring back a `.env` the sidecar excludes, +// whatever order the engine's matcher gives patterns inside one list. +// +// A customer's own Dockerfile -- BuildKit semantics, unchanged: its +// `.dockerignore` REPLACES the root file, and its `!` lines are +// kept. A customer sidecar written as an allowlist (`*`, `!src`, +// `!package.json`) is the ordinary BuildKit idiom; dropping its re-includes +// would empty the build context. +// +// Pure functions, no Dagger import, for the same reason as the rest of this +// package: the rules are unit tested without an engine. + +import ( + "path" + "strings" +) + +// SidecarSuffix is appended to a Dockerfile's path to name its ignore file. +const SidecarSuffix = ".dockerignore" + +// RootIgnoreFile is the build context's own ignore file. +const RootIgnoreFile = ".dockerignore" + +// GeneratedDockerfile is where IntegraCI commits a Dockerfile it generated, +// relative to the service's directory (containerization.GENERATED_DOCKERFILE_PATH). +const GeneratedDockerfile = ".integraci/Dockerfile" + +// IsGeneratedDockerfile reports whether dockerfile (a path inside the build +// context) is the one IntegraCI generates: `.integraci/Dockerfile` at the +// context root, or under the service's directory when the whole checkout is +// the context. +func IsGeneratedDockerfile(dockerfile string) bool { + return dockerfile == GeneratedDockerfile || strings.HasSuffix(dockerfile, "/"+GeneratedDockerfile) +} + +// SidecarPath is the ignore file that belongs to dockerfile (a path inside the +// build context). An empty dockerfile is the default `Dockerfile`. +func SidecarPath(dockerfile string) string { + if dockerfile == "" { + dockerfile = DefaultDockerfile + } + return dockerfile + SidecarSuffix +} + +// IgnorePatterns reads a .dockerignore body into exclude patterns: one per +// non-empty, non-comment line, cleaned the way Docker's own reader cleans them +// (surrounding whitespace trimmed, a leading `/` dropped, path.Clean applied), +// so `/secrets` matches here too. `!` re-include lines are kept only when +// keepNegations is set; see ContextFilters for why the sidecar drops them. +func IgnorePatterns(body string, keepNegations bool) []string { + var out []string + for _, line := range strings.Split(body, "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + negate := strings.HasPrefix(line, "!") + if negate && !keepNegations { + continue + } + pattern := strings.TrimSpace(strings.TrimPrefix(line, "!")) + pattern = strings.TrimPrefix(pattern, "/") + if pattern == "" { + continue + } + pattern = path.Clean(pattern) + if pattern == "." { + continue + } + if negate { + pattern = "!" + pattern + } + out = append(out, pattern) + } + return out +} + +// ContextFilters is the ordered list of exclude-pattern lists the module +// applies to the build context, one Directory.Filter each. +// +// generated: the root `.dockerignore` (with its re-includes) and then the +// sidecar's exclusions (without any). Otherwise BuildKit's rule: the sidecar +// alone, re-includes kept, the root file not applied. An empty list is +// omitted. hasRoot is false when the context has no root `.dockerignore`. +func ContextFilters(rootBody string, hasRoot bool, sidecarBody string, generated bool) [][]string { + var out [][]string + if !generated { + if sidecar := IgnorePatterns(sidecarBody, true); len(sidecar) > 0 { + out = append(out, sidecar) + } + return out + } + if hasRoot { + if root := IgnorePatterns(rootBody, true); len(root) > 0 { + out = append(out, root) + } + } + if sidecar := IgnorePatterns(sidecarBody, false); len(sidecar) > 0 { + out = append(out, sidecar) + } + return out +} + +// GeneratedSidecarPresent refuses a GENERATED Dockerfile built without its +// sidecar. The platform always commits the pair, and the sidecar is the only +// thing between the generated `COPY . .` and `.env`, keys and `.git`: building +// without it would put them in the image behind a green build. Whatever the +// cause (deleted in the repository, never committed), the build stops and +// says why; onboarding again restores the pair. A customer's own Dockerfile +// is not asked this question. +func GeneratedSidecarPresent(sidecar string, kind Kind) error { + if kind == Missing { + return refuse("the generated Dockerfile's ignore file %q is missing; onboard the service again to restore it", sidecar) + } + return nil +} + +// IgnoreFileUsable says whether an ignore file of this kind is read. +// +// Missing is "no ignore file" (false, nil). A regular file is read. Anything +// else is refused rather than skipped: a sidecar replaced by a symlink (to +// `/dev/null`, or to a file outside the checkout) or by a directory would +// otherwise switch the exclusions off and put `.env` back in the image behind +// a green build. The same holds for the root file once a sidecar is in play, +// because the root rules are applied with it. +func IgnoreFileUsable(name string, kind Kind) (bool, error) { + switch kind { + case Missing: + return false, nil + case Regular: + return true, nil + default: + return false, refuse("the ignore file %q is a %s, not a regular file", name, kind) + } +} diff --git a/standard-build/layout/ignore_test.go b/standard-build/layout/ignore_test.go new file mode 100644 index 0000000..a448cf3 --- /dev/null +++ b/standard-build/layout/ignore_test.go @@ -0,0 +1,212 @@ +package layout + +import ( + "errors" + "path" + "reflect" + "strings" + "testing" +) + +func TestIgnorePatternsCleansLikeDocker(t *testing.T) { + body := "# comment\n\n .env \n/secrets\nsrc/../keys\n./build/\n/\n.\n!keep.txt\n" + got := IgnorePatterns(body, false) + want := []string{".env", "secrets", "keys", "build"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("IgnorePatterns(no negations) = %q, want %q", got, want) + } +} + +func TestIgnorePatternsKeepsNegationsOnlyWhenAsked(t *testing.T) { + body := "*\n!src\n! /docs\n!\n" + if got, want := IgnorePatterns(body, true), []string{"*", "!src", "!docs"}; !reflect.DeepEqual(got, want) { + t.Fatalf("keepNegations=true: got %q, want %q", got, want) + } + if got, want := IgnorePatterns(body, false), []string{"*"}; !reflect.DeepEqual(got, want) { + t.Fatalf("keepNegations=false: got %q, want %q", got, want) + } +} + +func TestGeneratedContextFiltersOrderRootThenSidecar(t *testing.T) { + got := ContextFilters("*\n!src\n", true, ".env\n!.env\n*.pem\n", true) + want := [][]string{{"*", "!src"}, {".env", "*.pem"}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("ContextFilters = %q, want %q", got, want) + } + // The sidecar's list never carries a re-include: that is what makes it + // impossible for any rule to bring back what it excludes. + last := got[len(got)-1] + for _, p := range last { + if strings.HasPrefix(p, "!") { + t.Fatalf("sidecar filter carries a re-include %q", p) + } + } +} + +func TestContextFiltersWithoutRootOrEmptyLists(t *testing.T) { + if got := ContextFilters("ignored\n", false, ".env\n", true); !reflect.DeepEqual(got, [][]string{{".env"}}) { + t.Fatalf("no root file: got %q", got) + } + if got := ContextFilters("# only comments\n", true, "\n", true); len(got) != 0 { + t.Fatalf("empty bodies must produce no filter, got %q", got) + } +} + +// survives models the module's sequence of Directory.Filter calls: each list +// is applied in turn to what the previous one left, and within one list the +// LAST matching pattern decides (Docker's rule, `!` = keep). A path matches a +// pattern when the pattern matches it or one of its parent directories. It is +// a model of the engine, not the engine; what it pins is the ORDERING +// property ContextFilters is responsible for. +func survives(p string, filters [][]string) bool { + for _, list := range filters { + excluded := false + for _, pat := range list { + neg := strings.HasPrefix(pat, "!") + if matchesPathOrParent(strings.TrimPrefix(pat, "!"), p) { + excluded = !neg + } + } + if excluded { + return false + } + } + return true +} + +func matchesPathOrParent(pattern, p string) bool { + for cur := p; cur != "." && cur != "/" && cur != ""; cur = path.Dir(cur) { + if ok, _ := path.Match(pattern, cur); ok { + return true + } + } + return false +} + +func TestGeneratedRootNegationCannotReincludeWhatTheSidecarExcludes(t *testing.T) { + root := "*.log\n!.env\n" + sidecar := ".env\n*.pem\n" + filters := ContextFilters(root, true, sidecar, true) + if survives(".env", filters) { + t.Fatal("a root `!.env` re-included the .env the sidecar excludes") + } + if survives("certs/server.pem", filters) { + t.Fatal("a sidecar-excluded key survived") + } + if survives("app.log", filters) { + t.Fatal("the root .dockerignore was not applied with the sidecar") + } + if !survives("src/main.go", filters) { + t.Fatal("an ordinary source file was excluded") + } +} + +func TestRootAllowlistKeepsWorkingWithASidecar(t *testing.T) { + // `*` then `!src`: only src/ reaches the build. Dropping the root's + // negations (the sidecar's rule) would exclude everything. + filters := ContextFilters("*\n!src\n", true, ".env\n", true) + if !survives("src/app.py", filters) { + t.Fatal("the root allowlist's re-include was lost") + } + if survives("README.md", filters) { + t.Fatal("the root allowlist excluded nothing") + } + if survives(".env", filters) { + t.Fatal("the sidecar's .env exclusion was not applied") + } +} + +func TestSidecarPath(t *testing.T) { + if got := SidecarPath(""); got != "Dockerfile.dockerignore" { + t.Fatalf("default: %q", got) + } + if got := SidecarPath(".integraci/Dockerfile"); got != ".integraci/Dockerfile.dockerignore" { + t.Fatalf("generated: %q", got) + } +} + +func TestIgnoreFileUsableRefusesWhatIsNotARegularFile(t *testing.T) { + if ok, err := IgnoreFileUsable("x", Missing); ok || err != nil { + t.Fatalf("missing: (%v, %v)", ok, err) + } + if ok, err := IgnoreFileUsable("x", Regular); !ok || err != nil { + t.Fatalf("regular: (%v, %v)", ok, err) + } + for _, k := range []Kind{Symlink, Directory, Other} { + ok, err := IgnoreFileUsable(".integraci/Dockerfile.dockerignore", k) + if ok || !errors.Is(err, ErrRefused) { + t.Fatalf("%s: (%v, %v), want a refusal", k, ok, err) + } + } +} + +func TestGeneratedSidecarPresentRefusesOnlyAMissingSidecar(t *testing.T) { + err := GeneratedSidecarPresent(".integraci/Dockerfile.dockerignore", Missing) + if !errors.Is(err, ErrRefused) { + t.Fatalf("missing: %v, want a refusal", err) + } + // Legitimate: a regular sidecar builds; the other kinds are refused by + // IgnoreFileUsable, not here. + for _, k := range []Kind{Regular, Symlink, Directory, Other} { + if err := GeneratedSidecarPresent(".integraci/Dockerfile.dockerignore", k); err != nil { + t.Fatalf("%s: %v, want nil", k, err) + } + } +} + +func TestIsGeneratedDockerfile(t *testing.T) { + for _, p := range []string{".integraci/Dockerfile", "apps/web/.integraci/Dockerfile"} { + if !IsGeneratedDockerfile(p) { + t.Errorf("%q is the generated Dockerfile", p) + } + } + for _, p := range []string{"Dockerfile", "docker/Dockerfile", ".integraci/Dockerfile.prod", "x.integraci/Dockerfile", ""} { + if IsGeneratedDockerfile(p) { + t.Errorf("%q is a customer's Dockerfile", p) + } + } +} + +// A customer's `Dockerfile.dockerignore` written as BuildKit's allowlist idiom +// must keep its re-includes: dropping them (the generated-Dockerfile rule) +// empties the build context. Review finding F1 on #2168. +func TestCustomerSidecarAllowlistKeepsItsReincludes(t *testing.T) { + filters := ContextFilters("", false, "*\n!src\n!package.json\n", false) + if want := [][]string{{"*", "!src", "!package.json"}}; !reflect.DeepEqual(filters, want) { + t.Fatalf("ContextFilters(customer) = %q, want %q", filters, want) + } + if !survives("src/app.py", filters) || !survives("package.json", filters) { + t.Fatal("a customer allowlist sidecar emptied the context") + } + if survives("README.md", filters) { + t.Fatal("the customer allowlist excluded nothing") + } +} + +// BuildKit ignores the root .dockerignore when a per-Dockerfile one exists; +// for a customer's Dockerfile the module does the same. +func TestCustomerSidecarReplacesTheRootIgnoreFile(t *testing.T) { + filters := ContextFilters("*.log\nsecrets\n", true, "node_modules\n", false) + if want := [][]string{{"node_modules"}}; !reflect.DeepEqual(filters, want) { + t.Fatalf("ContextFilters(customer, root present) = %q, want %q", filters, want) + } + if !survives("app.log", filters) { + t.Fatal("the root file was applied beside a customer sidecar") + } +} + +// The other direction: the generated pair still cannot be re-opened, even by +// an allowlist-shaped sidecar or a root `!.env`. +func TestGeneratedSidecarStillCannotReincludeEnv(t *testing.T) { + filters := ContextFilters("!.env\n", true, "*\n!src\n.env\n!.env\n", true) + if survives(".env", filters) { + t.Fatal("the generated sidecar's .env exclusion was undone") + } + for _, list := range filters[1:] { + for _, p := range list { + if strings.HasPrefix(p, "!") { + t.Fatalf("generated sidecar filter carries a re-include %q", p) + } + } + } +} diff --git a/standard-build/layout/layout.go b/standard-build/layout/layout.go new file mode 100644 index 0000000..751e54c --- /dev/null +++ b/standard-build/layout/layout.go @@ -0,0 +1,239 @@ +// Package layout decides WHERE in a checkout standard-build builds (ADR-0074 +// §4, §8.1, rollout PR 3): the service's directory (--subdir), its Dockerfile +// (--dockerfile, relative to that directory) and the build context +// (--build-context: "source_path" = that directory, "repo_root" = the whole +// checkout). +// +// It is a separate package with no Dagger import so that its rules can be unit +// tested without an engine, the same reason `evidence` is one. +// +// Two checks, both before any build step runs: +// +// - Resolve is lexical. It mirrors the platform's path validator +// (apps/api/app/catalog/services/source_paths.py): POSIX separators, no +// leading '/', no '.'/'..' or empty segment, no segment starting with '-' +// or ending with '.', no '.git' segment in any letter case, segment charset +// [A-Za-z0-9._@-], depth <= 16, length <= 512. The platform validated these +// values when it recorded them; the module checks again because a pipeline +// file in a repository can be edited by anyone who can push. +// - Confine walks the tree as it is AT BUILD TIME. The platform's own check +// ran at onboarding, at another commit; a later push can turn `apps/web` or +// its Dockerfile into a symlink to `../..` or to the agent's home, and then +// `COPY . .` would put the agent's files into a pushed image. Every path +// component must be a real directory and the Dockerfile a regular file: +// a symlink anywhere on the way is refused, never followed. +package layout + +import ( + "context" + "errors" + "fmt" + "regexp" + "strings" +) + +// The two build contexts (ADR-0074 D8). An enumeration, never a path, so a +// parent directory cannot be expressed at all. +const ( + ContextSourcePath = "source_path" + ContextRepoRoot = "repo_root" +) + +// DefaultDockerfile is what `docker build .` and Directory.DockerBuild read. +const DefaultDockerfile = "Dockerfile" + +// Limits mirrored from source_paths.py. +const ( + MaxPathLength = 512 + MaxPathDepth = 16 +) + +var segmentRE = regexp.MustCompile(`^[A-Za-z0-9._@-]+$`) + +// Layout is a resolved, lexically valid build layout. +type Layout struct { + // Subdir is the service's directory relative to the checkout; "" = root. + Subdir string + // Dockerfile is relative to Subdir; never empty after Resolve. + Dockerfile string + // Context is ContextSourcePath or ContextRepoRoot. + Context string +} + +// PathProblem is why value is not an acceptable repository path, or "". +// allowRoot accepts "" (only a directory may be the root). +func PathProblem(value string, allowRoot bool) string { + if value == "" { + if allowRoot { + return "" + } + return "must not be empty" + } + if len(value) > MaxPathLength { + return fmt.Sprintf("must be at most %d characters", MaxPathLength) + } + if strings.HasPrefix(value, "/") { + return "must be relative to the repository (no leading '/')" + } + segments := strings.Split(value, "/") + if len(segments) > MaxPathDepth { + return fmt.Sprintf("must be at most %d directories deep", MaxPathDepth) + } + for _, seg := range segments { + switch { + case seg == "": + return "must not contain an empty segment ('a//b' or a trailing '/')" + case seg == "." || seg == "..": + return "must not contain '.' or '..' segments" + case strings.HasSuffix(seg, "."): + return "must not contain a segment that ends with '.'" + case strings.HasPrefix(seg, "-"): + return "must not contain a segment that starts with '-'" + case strings.EqualFold(seg, ".git"): + return "must not contain a '.git' segment" + case !segmentRE.MatchString(seg): + return "may only contain letters, digits, '.', '_', '@' and '-' in each segment" + } + } + return "" +} + +// Resolve validates the three arguments and fills the defaults. +func Resolve(subdir, dockerfile, buildContext string) (Layout, error) { + if p := PathProblem(subdir, true); p != "" { + return Layout{}, fmt.Errorf("--subdir %s", p) + } + if dockerfile == "" { + dockerfile = DefaultDockerfile + } + if p := PathProblem(dockerfile, false); p != "" { + return Layout{}, fmt.Errorf("--dockerfile %s", p) + } + switch buildContext { + case "": + buildContext = ContextSourcePath + case ContextSourcePath, ContextRepoRoot: + default: + return Layout{}, fmt.Errorf( + "--build-context must be %q or %q, got %q", ContextSourcePath, ContextRepoRoot, buildContext, + ) + } + return Layout{Subdir: subdir, Dockerfile: dockerfile, Context: buildContext}, nil +} + +// IsDefault reports whether this is today's layout: the root, its +// `Dockerfile`, the root as context. The module then behaves exactly as it +// did before these arguments existed. +func (l Layout) IsDefault() bool { + return l.Subdir == "" && l.Dockerfile == DefaultDockerfile && l.Context == ContextSourcePath +} + +func join(a, b string) string { + if a == "" { + return b + } + return a + "/" + b +} + +// DockerfilePath is the Dockerfile's path from the checkout root. +func (l Layout) DockerfilePath() string { return join(l.Subdir, l.Dockerfile) } + +// ContextDir is the build context relative to the checkout: "" for the root. +func (l Layout) ContextDir() string { + if l.Context == ContextRepoRoot { + return "" + } + return l.Subdir +} + +// DockerfileInContext is the Dockerfile path relative to ContextDir. +func (l Layout) DockerfileInContext() string { + if l.Context == ContextRepoRoot { + return l.DockerfilePath() + } + return l.Dockerfile +} + +// Kind is a tree entry's type, read WITHOUT following symlinks. +type Kind int + +const ( + Missing Kind = iota + Directory + Regular + Symlink + Other +) + +func (k Kind) String() string { + switch k { + case Missing: + return "missing" + case Directory: + return "directory" + case Regular: + return "regular file" + case Symlink: + return "symlink" + default: + return "special file" + } +} + +// StatFunc reports the type of a checkout-relative path without following +// symlinks. The module passes one backed by Directory.Stat; tests pass a map. +type StatFunc func(ctx context.Context, path string) (Kind, error) + +// ErrRefused marks a layout the module will not build. +var ErrRefused = errors.New("build layout refused") + +func refuse(format string, args ...any) error { + return fmt.Errorf("%w: "+format, append([]any{ErrRefused}, args...)...) +} + +// Confine checks the tree for l and reports whether the Dockerfile exists. +// +// Every component of Subdir must be a directory, and so must every directory +// on the way to the Dockerfile. A symlink anywhere is refused — the resolved +// context and Dockerfile would otherwise be able to point outside the +// checkout. A missing Subdir is refused; a missing Dockerfile is reported +// (false) unless requireDockerfile, because the language lane builds a +// directory that has none. +func Confine(ctx context.Context, stat StatFunc, l Layout, requireDockerfile bool) (bool, error) { + walked := "" + if l.Subdir != "" { + for _, seg := range strings.Split(l.Subdir, "/") { + walked = join(walked, seg) + kind, err := stat(ctx, walked) + if err != nil { + return false, fmt.Errorf("reading %q: %w", walked, err) + } + if kind != Directory { + return false, refuse("%q in --subdir is a %s, not a directory", walked, kind) + } + } + } + parts := strings.Split(l.Dockerfile, "/") + for i, seg := range parts { + walked = join(walked, seg) + kind, err := stat(ctx, walked) + if err != nil { + return false, fmt.Errorf("reading %q: %w", walked, err) + } + last := i == len(parts)-1 + switch { + case kind == Missing: + if requireDockerfile { + return false, refuse("the Dockerfile %q does not exist", l.DockerfilePath()) + } + return false, nil + case kind == Symlink: + return false, refuse("%q is a symlink; the build never follows one", walked) + case !last && kind != Directory: + return false, refuse("%q on the way to the Dockerfile is a %s", walked, kind) + case last && kind != Regular: + return false, refuse("the Dockerfile %q is a %s, not a regular file", walked, kind) + } + } + return true, nil +} diff --git a/standard-build/layout/layout_test.go b/standard-build/layout/layout_test.go new file mode 100644 index 0000000..9a25e9c --- /dev/null +++ b/standard-build/layout/layout_test.go @@ -0,0 +1,171 @@ +package layout + +import ( + "context" + "errors" + "strings" + "testing" +) + +func TestResolveDefaultsAreTodaysLayout(t *testing.T) { + l, err := Resolve("", "", "") + if err != nil { + t.Fatal(err) + } + if !l.IsDefault() { + t.Fatalf("empty arguments must be the root layout, got %+v", l) + } + if l.DockerfilePath() != "Dockerfile" || l.ContextDir() != "" || l.DockerfileInContext() != "Dockerfile" { + t.Fatalf("root layout resolved to %+v", l) + } +} + +func TestResolveRefusesWhatTheValidatorRefuses(t *testing.T) { + for _, bad := range []string{ + "..", "a/../b", "/a", `a\b`, "a//b", "a/", "-x", ".git/x", "a/.GIT", "a/.git.", + "a/b c", "a/b+c", "a/[b]", "a/~b", "a/b\x00", "a/b\n", strings.Repeat("a/", 17) + "a", + } { + if _, err := Resolve(bad, "", ""); err == nil { + t.Errorf("--subdir %q was accepted", bad) + } + if _, err := Resolve("apps/web", bad, ""); err == nil { + t.Errorf("--dockerfile %q was accepted", bad) + } + } + if _, err := Resolve("apps/web", "", "../.."); err == nil { + t.Error("a --build-context that is a path was accepted") + } +} + +func TestResolveAcceptsLegitimatePaths(t *testing.T) { + // The second mutant of PR 1, mirrored: a charset narrowed to [a-z0-9/-] + // would refuse these. + for _, good := range []string{"apps/web", "services/Billing-API", "packages/@scope.ui", "a_b/c.d"} { + if _, err := Resolve(good, "docker/Dockerfile.prod", ContextRepoRoot); err != nil { + t.Errorf("%q refused: %v", good, err) + } + } +} + +func TestContextPlacement(t *testing.T) { + l, _ := Resolve("apps/web", "Dockerfile", ContextSourcePath) + if l.ContextDir() != "apps/web" || l.DockerfileInContext() != "Dockerfile" { + t.Fatalf("source_path context: %+v -> %q %q", l, l.ContextDir(), l.DockerfileInContext()) + } + r, _ := Resolve("apps/web", "Dockerfile", ContextRepoRoot) + if r.ContextDir() != "" || r.DockerfileInContext() != "apps/web/Dockerfile" { + t.Fatalf("repo_root context: %+v -> %q %q", r, r.ContextDir(), r.DockerfileInContext()) + } +} + +// tree is a fake checkout: path -> kind, read without following symlinks. +func tree(entries map[string]Kind) StatFunc { + return func(_ context.Context, p string) (Kind, error) { + if k, ok := entries[p]; ok { + return k, nil + } + return Missing, nil + } +} + +func TestConfineAcceptsARealDirectoryAndDockerfile(t *testing.T) { + l, _ := Resolve("apps/web", "", "") + ok, err := Confine(context.Background(), tree(map[string]Kind{ + "apps": Directory, "apps/web": Directory, "apps/web/Dockerfile": Regular, + }), l, true) + if err != nil || !ok { + t.Fatalf("got (%v, %v)", ok, err) + } +} + +// "Dockerfile turned into a symlink after onboarding" (ADR-0074 rollout PR 3). +// Mutant: remove the symlink check in Confine -> this test fails. +func TestConfineRefusesADockerfileTurnedIntoASymlink(t *testing.T) { + l, _ := Resolve("apps/web", "", "") + _, err := Confine(context.Background(), tree(map[string]Kind{ + "apps": Directory, "apps/web": Directory, "apps/web/Dockerfile": Symlink, + }), l, false) + if !errors.Is(err, ErrRefused) { + t.Fatalf("a symlinked Dockerfile was not refused: %v", err) + } +} + +func TestConfineRefusesASymlinkedSourceDirectory(t *testing.T) { + l, _ := Resolve("apps/web", "", "") + for _, entries := range []map[string]Kind{ + // the service directory itself + {"apps": Directory, "apps/web": Symlink}, + // an ancestor of it + {"apps": Symlink, "apps/web": Directory, "apps/web/Dockerfile": Regular}, + } { + if _, err := Confine(context.Background(), tree(entries), l, false); !errors.Is(err, ErrRefused) { + t.Errorf("%v: a symlinked path component was not refused: %v", entries, err) + } + } +} + +func TestConfineRefusesASymlinkOnTheWayToTheDockerfile(t *testing.T) { + l, _ := Resolve("apps/web", "docker/Dockerfile", "") + _, err := Confine(context.Background(), tree(map[string]Kind{ + "apps": Directory, "apps/web": Directory, "apps/web/docker": Symlink, + "apps/web/docker/Dockerfile": Regular, + }), l, false) + if !errors.Is(err, ErrRefused) { + t.Fatalf("a symlinked Dockerfile directory was not refused: %v", err) + } +} + +func TestConfineMissingDockerfile(t *testing.T) { + l, _ := Resolve("apps/web", "", "") + entries := map[string]Kind{"apps": Directory, "apps/web": Directory} + ok, err := Confine(context.Background(), tree(entries), l, false) + if err != nil || ok { + t.Fatalf("a directory with no Dockerfile is a language-lane build: (%v, %v)", ok, err) + } + if _, err := Confine(context.Background(), tree(entries), l, true); !errors.Is(err, ErrRefused) { + t.Fatalf("a required Dockerfile that is missing was not refused: %v", err) + } +} + +func TestConfineRefusesAMissingOrFileSubdir(t *testing.T) { + l, _ := Resolve("apps/web", "", "") + for _, entries := range []map[string]Kind{ + {"apps": Directory}, + {"apps": Directory, "apps/web": Regular}, + } { + if _, err := Confine(context.Background(), tree(entries), l, false); !errors.Is(err, ErrRefused) { + t.Errorf("%v: accepted", entries) + } + } +} + +func TestConfineRefusesADockerfileThatIsADirectory(t *testing.T) { + l, _ := Resolve("apps/web", "", "") + _, err := Confine(context.Background(), tree(map[string]Kind{ + "apps": Directory, "apps/web": Directory, "apps/web/Dockerfile": Directory, + }), l, false) + if !errors.Is(err, ErrRefused) { + t.Fatalf("a Dockerfile directory was not refused: %v", err) + } +} + +func TestConfineAtTheRootChecksOnlyTheDockerfile(t *testing.T) { + l, _ := Resolve("", "deploy/Dockerfile", "") + ok, err := Confine(context.Background(), tree(map[string]Kind{ + "deploy": Directory, "deploy/Dockerfile": Regular, + }), l, true) + if err != nil || !ok { + t.Fatalf("got (%v, %v)", ok, err) + } +} + +func TestConfinePropagatesAReadError(t *testing.T) { + l, _ := Resolve("apps/web", "", "") + boom := errors.New("engine unreachable") + _, err := Confine(context.Background(), func(context.Context, string) (Kind, error) { + return Other, boom + }, l, false) + if !errors.Is(err, boom) || errors.Is(err, ErrRefused) { + t.Fatalf("a read error must surface as itself, not as a verdict: %v", err) + } +} diff --git a/standard-build/main.go b/standard-build/main.go new file mode 100644 index 0000000..a172556 --- /dev/null +++ b/standard-build/main.go @@ -0,0 +1,1845 @@ +// Package main implements the IntegraCI standard-build Dagger module. +// +// This module provides a standard build pipeline: lint → test → build → container image. +// It runs locally via `dagger call` or is triggered by CI connectors (GitHub Actions, GitLab CI, Jenkins). +// +// Usage: +// +// dagger call build --source . --language go +// dagger call build --source . --language python +// dagger call build --source . --language node +// dagger call test --source . --language node # lint + tests only, no image +package main + +import ( + "context" + "dagger/standard-build/evidence" + "dagger/standard-build/internal/dagger" + "dagger/standard-build/layout" + "encoding/json" + "errors" + "fmt" + "strings" +) + +// StandardBuild is the IntegraCI standard build pipeline module. +type StandardBuild struct{} + +// BuildResult contains the output of a standard build. +type BuildResult struct { + Success bool `json:"success"` + Language string `json:"language"` + RuntimeVersion string `json:"runtime_version,omitempty"` + ImageRef string `json:"image_ref,omitempty"` + // ImageDigest is `sha256:` of the published manifest, empty when + // nothing was published. It is what `evidence` and every attestation must + // name: a tag moves, the digest is the artifact. + ImageDigest string `json:"image_digest,omitempty"` + TestOutput string `json:"test_output,omitempty"` + LintOutput string `json:"lint_output,omitempty"` +} + +// execDetail turns a failed step into something a person can act on. +// +// Dagger reports a failed exec as `exit code: N` and nothing more. For a lint +// gate that is worse than useless: `php -l` across a whole tree exits non-zero +// if ANY file fails, and the one thing the user needs — which file, and why — is +// in the output that the bare error throws away. Measured: a real build failed +// with `Error: exit code: 124`, and the actual cause (two vendored files using +// syntax removed in PHP 8) was only visible by scrolling the raw engine log. +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) +} + +// Build runs the full build pipeline: lint → test → build → container image. +// +// Supported languages: go, python, node, php. +// +// Publishing is opt-in and is driven by ONE argument, --image-ref, which is the +// full destination the caller wants (e.g. harbor.acme.internal/library/orders:abc123). +// With no --image-ref the image is built but not published (ImageRef stays +// empty) — the module never pushes tenant artifacts to a public anonymous +// registry. +// +// This used to take --registry plus --tag and publish to a HARDCODED +// "{registry}/integraci-build:{tag}", which ignored the service entirely: every +// service in a tenant published over the same repository, so the last build to +// finish was the only image anybody had. The rendered pipelines have always +// passed --image-ref (they build it from the service name), so the templates and +// the module simply disagreed and no publish could ever have worked. +// --registry/--tag are still accepted so an existing caller does not break; they +// are used only when --image-ref is absent, and then the repository is the +// service name, not a constant. +// +// A repository that ships a root Dockerfile is built FROM THAT DOCKERFILE, +// whatever --language says. See the block above the switch for why; pass +// --ignore-dockerfile to insist on the language lane. +func (m *StandardBuild) Build( + ctx context.Context, + // Source directory + source *dagger.Directory, + // Programming language: go, python, node, php + language string, + // Skip tests (default false) + // +optional + skipTests bool, + // Skip lint (default false) + // +optional + skipLint bool, + // Full destination image reference including tag, e.g. + // registry.example.com/team/service:abc123. Empty = build only. + // +optional + imageRef string, + // Service name, used as the repository when only --registry is given. + // +optional + service string, + // Container image tag (used only when --image-ref is absent) + // +optional + // +default="latest" + tag string, + // Target registry host + namespace (used only when --image-ref is absent). + // +optional + registry string, + // Registry username (paired with registryPassword). + // +optional + registryUsername string, + // Registry password/token as a Dagger secret. + // +optional + registryPassword *dagger.Secret, + // The destination registry is served over plain HTTP, so the push must not + // assume TLS. See publishImage for why this needs a different code path + // rather than a flag. + // +optional + registryInsecure bool, + // Language runtime version, e.g. "8.3" or "7.4" for PHP. The default is the + // current release, which is the right answer for new code and the WRONG one + // for the brownfield applications this module mostly serves: an application + // that has been running for a decade brings vendored libraries written + // against PHP 5, and `php -l` under 8.3 rejects them for syntax that was + // REMOVED from the language — a true finding about a version the customer + // never chose. Measured on a real import: `Array and string offset access + // syntax with curly braces is no longer supported`, in a bundled PDF + // library, which failed the build with `exit code: 124` and nothing else. + // +optional + // +default="8.3" + runtimeVersion string, + // Docker build args for the Dockerfile path, each `KEY=value`. Repeat the + // flag for more than one. + // + // python-ml, dotnet8-minimal-api and rust-axum have passed `--build-arg` + // since they were written — python-ml needs it to pin its CUDA base — and + // there was no such parameter, so those three builds died on an unknown flag + // before they could die on the unsupported language below. The contract gate + // pinned it as a known defect; this is the fix that lets that pin shrink. + // +optional + buildArg []string, + // Build with the language lane even when the repository has a root + // Dockerfile (default false: a Dockerfile wins). Only for a caller that + // knows the Dockerfile is not the deployable image — a dev-container + // recipe, say. Has no effect on a language outside the four lanes, which + // has nothing but the Dockerfile to build from. + // +optional + ignoreDockerfile bool, + // The service's directory in the checkout (ADR-0074 monorepo layout). + // Empty = the repository root, exactly as before. --source stays the + // checkout; this names where in it the service lives. + // +optional + subdir string, + // The Dockerfile, relative to --subdir. Empty = "Dockerfile". + // +optional + dockerfile string, + // "source_path" (default: --subdir is the build context) or "repo_root" + // (the whole checkout is the context: a Dockerfile that COPYs shared + // packages, or a workspace whose lockfile lives at the root). + // +optional + buildContext string, +) (*BuildResult, error) { + result := &BuildResult{Language: language, RuntimeVersion: runtimeVersion} + ref, err := destinationRef(imageRef, registry, service, tag) + if err != nil { + return nil, err + } + pub := publishConfig{ + imageRef: ref, + username: registryUsername, + password: registryPassword, + insecure: registryInsecure, + } + // WHERE in the checkout, checked BEFORE any build step. The default layout + // returns the checkout untouched and reads nothing. See applyLayout. + lay, err := layout.Resolve(subdir, dockerfile, buildContext) + if err != nil { + return nil, err + } + bs, err := applyLayout(ctx, source, lay) + if err != nil { + return nil, err + } + pub.workdir = bs.workdir + source = bs.dir + + // DOCKERFILE FIRST. A repository that carries a root Dockerfile has already + // said how it is containerised, and that statement outranks --language. + // + // The language lanes below exist for a tree that has NO Dockerfile: they + // invent a runtime image (node:22 running `npm run start` on 3000, + // php:-apache on 80, ...) because nobody else will. Running that + // invention over a repository that brought its own recipe replaces a + // working image with a guess. MEASURED on a customer k3s cluster + // 2026-09-13: a Vite/React front-end whose Dockerfile is a two-stage node + // build into nginx:1.27-alpine, EXPOSE 80 — the ordinary SPA shape — was + // built with --language=node because the service's stack said "node". The + // lane published node:22-slim with ENTRYPOINT `npm run start` on 3000. On + // one commit package.json had no `start` script at all (`npm error Missing + // script: "start"`, CrashLoopBackOff); on a later one `start` was `npm run + // dev`, so production ran the Vite DEV SERVER, still on the wrong port for + // the Service in front of it. The Dockerfile beside it would have produced a + // working nginx image on 80 the whole time. + // + // So the check is on the TREE, not on the language: `case "node"` cannot + // tell a Node service from a Node-built static site, but the presence of a + // Dockerfile can. --ignore-dockerfile is the escape hatch, off by default, + // because the failure mode of a wrong default here is a crash-looping + // production pod behind a green pipeline, and the caller who wants the + // lane anyway can say so. The Dockerfile path runs no lint or tests (see + // buildFromDockerfile) — `Test` below covers that stage for such a tree. + if !ignoreDockerfile { + hasDockerfile := bs.hasDockerfile + if bs.dockerfile == "" { + hasDockerfile, err = hasRootDockerfile(ctx, source) + if err != nil { + return nil, err + } + } + if hasDockerfile { + return withDigest(m.buildFromDockerfile(ctx, source, bs.dockerfile, result, language, buildArg, pub)) + } + } + if err := laneWorkdirProblem(language, bs.workdir); err != nil { + return nil, err + } + + switch language { + case "go": + return withDigest(m.buildGo(ctx, source, result, skipTests, skipLint, pub, buildArg)) + case "python": + return withDigest(m.buildPython(ctx, source, result, skipTests, skipLint, pub, buildArg)) + case "node": + return withDigest(m.buildNode(ctx, source, result, skipTests, skipLint, pub, buildArg)) + case "php": + return withDigest(m.buildPhp(ctx, source, result, skipTests, skipLint, pub, runtimeVersion, buildArg)) + default: + // Everything else builds from the repository's own Dockerfile. + // + // The four cases above are the languages this module knows how to build + // WITHOUT one. Everything else used to fall straight to an error, and the + // templates do pass else: 8 of the 34 `standard-build` invocations name a + // language this switch does not implement — `java` 7 (java-spring across + // six engines, its Jenkinsfile twice) and `generic` 1. A java-spring + // service's build failed on the language before it failed on anything else. + // + // The counts here used to read "22 of 65 ... java 13", which attributed + // every `--language=` in catalog/templates to this module. `sast-scan` + // takes the same flag and owns 23 of those 65. See infra/dagger/README.md + // — count per module, not per repo. + // + // Every golden-path skeleton ships a Dockerfile, and the CI steps already + // gate the build on `exists: Dockerfile` / `hashFiles('Dockerfile')`, so + // this is the path they were written expecting. An unknown language with + // no Dockerfile still errors, and now says which of the two is missing. + return withDigest(m.buildFromDockerfile(ctx, source, bs.dockerfile, result, language, buildArg, pub)) + } +} + +// buildSource is the checkout once a build layout has been applied. +type buildSource struct { + // dir is what the lanes and the Dockerfile build read: the checkout, or + // the service directory when that is the context. + dir *dagger.Directory + // workdir is the service directory under /src for a language lane that + // reads the WHOLE checkout (context repo_root): the install runs at the + // workspace root, the rest in the member. "" = /src itself. + workdir string + // dockerfile is the Dockerfile path inside dir; "" = the root rule the + // module has always applied (a `Dockerfile` at the top of dir). + dockerfile string + // hasDockerfile is meaningful only when dockerfile != "". + hasDockerfile bool +} + +// applyLayout resolves where in the checkout the build runs, and REFUSES a +// layout whose path components are not real directories (ADR-0074 §8.1). +// +// This is the authoritative symlink check. The platform's own check ran at +// onboarding, at another commit; a push after it can turn the service +// directory or its Dockerfile into a symlink to `../..` or to the agent's home, +// and `COPY . .` would then put the agent's files into a pushed image. Every +// component is read with Stat WITHOUT following symlinks, before any build +// step runs. +// +// The default layout (no --subdir, no --dockerfile, no --build-context) reads +// nothing and returns the checkout untouched: a root-layout repository builds +// exactly as it did before these arguments existed, including a root +// Dockerfile that is itself a symlink, which existing repositories may use. +func applyLayout(ctx context.Context, source *dagger.Directory, lay layout.Layout) (*buildSource, error) { + if lay.IsDefault() { + return &buildSource{dir: source}, nil + } + exists, err := layout.Confine(ctx, statWithoutFollowing(source), lay, false) + if err != nil { + return nil, err + } + bs := &buildSource{dir: source, dockerfile: lay.DockerfileInContext(), hasDockerfile: exists} + if d := lay.ContextDir(); d != "" { + bs.dir = source.Directory(d) + } + if lay.Context == layout.ContextRepoRoot { + bs.workdir = lay.Subdir + } + return bs, nil +} + +// statWithoutFollowing reads a checkout path's type the way lstat would. +func statWithoutFollowing(source *dagger.Directory) layout.StatFunc { + return func(ctx context.Context, path string) (layout.Kind, error) { + ok, err := source.Exists(ctx, path, dagger.DirectoryExistsOpts{DoNotFollowSymlinks: true}) + if err != nil { + return layout.Other, err + } + if !ok { + return layout.Missing, nil + } + ft, err := source.Stat(path, dagger.DirectoryStatOpts{DoNotFollowSymlinks: true}).FileType(ctx) + if err != nil { + return layout.Other, err + } + switch ft { + case dagger.FileTypeDirectory: + return layout.Directory, nil + case dagger.FileTypeRegular: + return layout.Regular, nil + case dagger.FileTypeSymlink: + return layout.Symlink, nil + default: + return layout.Other, nil + } + } +} + +// laneWorkdirProblem refuses a language lane that cannot build a workspace +// member from the workspace root (context repo_root without a Dockerfile). +// +// The go lane runs in the member and `go` finds `go.work` upward; the node +// lane installs at the root (npm/yarn/pnpm workspaces keep one lockfile there) +// and lints, tests and builds in the member. The other lanes have no +// workspace form: python and php would install or serve the whole repository, +// and java's wrapper lookup is root-only. A Dockerfile with context repo_root +// is the way to build those. +func laneWorkdirProblem(language, workdir string) error { + if workdir == "" { + return nil + } + switch language { + case "go", "node": + return nil + } + return fmt.Errorf( + "build context repo_root with the %q language lane is not supported: only the go and "+ + "node lanes build a workspace member from the workspace root. Add a Dockerfile, or use "+ + "build context source_path", + language, + ) +} + +// laneDir is the directory a lane works in: /src, or the member under it. +func laneDir(pub publishConfig) string { + if pub.workdir == "" { + return "/src" + } + return "/src/" + pub.workdir +} + +// Test runs ONLY the lint and test steps of a language lane: no image is +// assembled and nothing is published. ImageRef is always empty; Success is +// true when every step that ran exited 0, and the outputs are in LintOutput / +// TestOutput exactly as Build fills them. +// +// This exists because the rendered pipelines had a `Lint and Test` stage that +// ran the toolchain NATIVELY on the CI agent — `npm ci`, `python3 -m pip`, +// `corepack`, `golangci-lint` — while the Build stage right after it ran this +// module through `dagger call`. MEASURED on a customer Jenkins 2026-09-13: the +// agent is a plain container with Docker and nothing else, so every build died +// in that first stage with `npm: not found` (or the pip/corepack equivalent), +// and the stage that actually worked — Build, whose lanes already lint and +// test inside their own containers — was never reached. The toolchain the lint +// stage needs is the one the lanes already carry, so the stage calls the lane +// and stops before the image. +// +// A Dockerfile in the tree does NOT divert this the way it diverts Build. The +// Dockerfile says how the application is packaged; it says nothing about +// whether the code lints, and the customer front-end above is exactly a tree +// with a Dockerfile AND a `lint` script. So the language decides here, and a +// language outside its lanes (go, python, node, php, java) is an error that +// names it, rather than a +// silent green — there is no toolchain this module could honestly run for it. +func (m *StandardBuild) Test( + ctx context.Context, + // Source directory + source *dagger.Directory, + // Programming language: go, python, node, php, or java (Test only: Build + // has no java lane and builds a java service from its Dockerfile) + language string, + // Language runtime version, e.g. "8.3" or "7.4" for PHP — same meaning and + // same default as on Build; see the note there for why it is an argument. + // +optional + // +default="8.3" + runtimeVersion string, + // Skip tests (default false) + // +optional + skipTests bool, + // Skip lint (default false) + // +optional + skipLint bool, + // `KEY=value` pairs, each repeated, as on Build. A pipeline passes the same + // list to both calls; here they are applied to the lint/test container, so + // a suite that reads build-time configuration (Vitest resolving + // `import.meta.env.VITE_*` exactly as `vite build` would) sees what the + // image will be compiled with. + // +optional + buildArg []string, + // JDK major version the java lane lints and tests with: 11, 17 or 21 + // (default 21). Ignored by every other language. A separate argument from + // --runtime-version on purpose: that one defaults to PHP's "8.3", so the + // java lane could never tell "not stated" from a PHP default. Gradle + // wrappers up to 7.x cannot run on JDK 21 at all (`Unsupported class file + // major version 65`, measured 2026-10-06 with a 7.6.4 wrapper), and the + // only other fix is to upgrade the customer's build tool. + // +optional + // +default="21" + javaVersion string, + // Same meaning as on Build: the service's directory in the checkout. + // +optional + subdir string, + // Same as on Build. Test builds no image; the Dockerfile is still checked + // for symlinks so one pipeline argument list serves both calls. + // +optional + dockerfile string, + // Same as on Build: "source_path" (default) or "repo_root". + // +optional + buildContext string, +) (*BuildResult, error) { + result := &BuildResult{Language: language, RuntimeVersion: runtimeVersion} + pub := publishConfig{testOnly: true} + lay, err := layout.Resolve(subdir, dockerfile, buildContext) + if err != nil { + return nil, err + } + bs, err := applyLayout(ctx, source, lay) + if err != nil { + return nil, err + } + if err := laneWorkdirProblem(language, bs.workdir); err != nil { + return nil, err + } + pub.workdir = bs.workdir + source = bs.dir + + switch language { + case "go": + return m.buildGo(ctx, source, result, skipTests, skipLint, pub, buildArg) + case "python": + return m.buildPython(ctx, source, result, skipTests, skipLint, pub, buildArg) + case "node": + return m.buildNode(ctx, source, result, skipTests, skipLint, pub, buildArg) + case "php": + return m.buildPhp(ctx, source, result, skipTests, skipLint, pub, runtimeVersion, buildArg) + case "java": + return m.testJava(ctx, source, result, skipTests, skipLint, javaVersion, buildArg) + default: + return nil, fmt.Errorf( + "language %q has no lint/test lane (supported: go, python, node, php, java); "+ + "a Dockerfile can build it but cannot say how to test it", + language, + ) + } +} + +// The JDK the java lane lints and tests with by default: the one the +// java-spring golden path targets (its Jenkinsfile used to demand +// `jdk 'temurin-21'` on the agent). Maven projects use the Maven image of the +// same JDK; Gradle projects bring their own Gradle through the wrapper. +const defaultJavaVersion = "21" + +// javaVersions is the CLOSED set of JDKs the lane runs: the LTS releases that +// both image families publish. A closed set, never a pattern: the value picks +// an image tag, and a free-text tag is an image nobody vetted. The platform +// validates the same set on the service spec (`spec.pipeline.java_version`), +// so a value outside it is refused there, before any CI runs; this check is +// for a caller that does not come through the spec. +var javaVersions = map[string]bool{"11": true, "17": true, "21": true} + +// javaImages returns the JDK version and its Maven and bare-JDK images, or an +// error naming the supported set. An empty version is the default. +func javaImages(version string) (string, string, string, error) { + if version == "" { + version = defaultJavaVersion + } + if !javaVersions[version] { + return "", "", "", fmt.Errorf( + "java version %q is not supported by the java lane (supported: 11, 17, 21)", version, + ) + } + return version, + fmt.Sprintf("maven:3.9-eclipse-temurin-%s", version), + fmt.Sprintf("eclipse-temurin:%s-jdk", version), + nil +} + +// testJava lints and tests a Maven or Gradle project. Test only: Build has no +// java lane — a java service is built from its own Dockerfile (the default arm +// of Build), and that path runs no lint or tests at all. +// +// This exists for the same reason Test does. MEASURED on platform-provisioned +// Jenkins agents (jnlp + a dagger-engine sidecar, nothing else): the +// java-spring template ran `mvn` on the agent and demanded a `temurin-21` JDK +// tool, neither of which exists there, so every java pipeline died before its +// first useful stage. The toolchain belongs in a container, like every other +// lane's. +// +// "Lint" is what the project itself binds to its lifecycle with tests skipped: +// `verify -DskipTests` runs compile plus every check the pom binds (the +// golden-path skeletons bind `spotless:check`), `gradlew check -x test` the +// Gradle equivalent. Never a plugin goal the project did not declare — the old +// template forced `spotless:check` on every repository, and on one that does +// not declare Spotless that goal does not even resolve. The repository's own +// Maven wrapper wins over the image's Maven when it ships one, as it would on +// a developer's machine. Tests then run in the container lint left behind, so +// nothing is compiled twice. A tree with neither a root `pom.xml` nor a root +// `gradlew` is an error that says so, not a silent green. +func (m *StandardBuild) testJava( + ctx context.Context, source *dagger.Directory, + result *BuildResult, skipTests, skipLint bool, javaVersion string, buildArg []string, +) (*BuildResult, error) { + javaVersion, javaMavenImage, javaJdkImage, err := javaImages(javaVersion) + if err != nil { + return nil, err + } + result.RuntimeVersion = javaVersion + hasPom, err := hasRootEntry(ctx, source, "pom.xml") + if err != nil { + return nil, err + } + hasMvnw, err := hasRootEntry(ctx, source, "mvnw") + if err != nil { + return nil, err + } + hasGradlew, err := hasRootEntry(ctx, source, "gradlew") + if err != nil { + return nil, err + } + + var base *dagger.Container + var lintCmd, testCmd []string + switch { + case hasPom: + maven := []string{"mvn"} + if hasMvnw { + // `sh ./mvnw`: the wrapper's exec bit does not always survive a + // checkout, and the shell does not need it. + maven = []string{"sh", "./mvnw"} + } + base = dag.Container(). + From(javaMavenImage). + // Persist the local repository so repeat runs don't re-download + // every dependency. + WithMountedCache("/root/.m2", dag.CacheVolume("maven-repo")) + lintCmd = withArgs(maven, "-B", "-ntp", "-DskipTests", "verify") + testCmd = withArgs(maven, "-B", "-ntp", "test") + case hasGradlew: + base = dag.Container(). + From(javaJdkImage). + WithMountedCache("/root/.gradle", dag.CacheVolume("gradle-home")) + lintCmd = []string{"sh", "./gradlew", "--no-daemon", "check", "-x", "test"} + testCmd = []string{"sh", "./gradlew", "--no-daemon", "test"} + default: + return nil, fmt.Errorf( + "java lane needs a root pom.xml (Maven) or a root gradlew (Gradle wrapper); found neither", + ) + } + base = lintTestBase( + base.WithDirectory("/src", source).WithWorkdir("/src"), + publishConfig{testOnly: true}, + buildArg, + ) + + // Lint + if !skipLint { + linted := base.WithExec(lintCmd) + out, err := linted.Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("java lint failed: %s", execDetail(err)) + } + result.LintOutput = out + base = linted + } + + // Test + if !skipTests { + out, err := base.WithExec(testCmd).Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("java tests failed: %s", execDetail(err)) + } + result.TestOutput = out + } + return testsDone(result), nil +} + +// withArgs is cmd followed by args, in a fresh slice: two commands built from +// one prefix must never share a backing array. +func withArgs(cmd []string, args ...string) []string { + out := make([]string, 0, len(cmd)+len(args)) + out = append(out, cmd...) + return append(out, args...) +} + +// hasRootEntry reports whether `name` exists at the source-tree root. +func hasRootEntry(ctx context.Context, source *dagger.Directory, name string) (bool, error) { + entries, err := source.Entries(ctx) + if err != nil { + return false, fmt.Errorf("reading source directory: %w", err) + } + for _, entry := range entries { + if entry == name { + return true, nil + } + } + return false, nil +} + +// hasRootDockerfile reports whether the source tree carries a `Dockerfile` at +// its root — the one place `docker build .` and Directory.DockerBuild look. +// Only the root: a Dockerfile under `deploy/` or `docker/` is a recipe for +// something, but not necessarily for this tree, and guessing which one would +// reintroduce the wrong-image failure this check exists to prevent. +func hasRootDockerfile(ctx context.Context, source *dagger.Directory) (bool, error) { + return hasRootEntry(ctx, source, "Dockerfile") +} + +// buildFromDockerfile builds the source tree's own Dockerfile. +// +// No test or lint phase: this module cannot know how an arbitrary stack runs +// them, and inventing a guess would be worse than leaving the CI template's own +// test job to do it — which is where those stages already live (and, for the +// languages Test has a lane for — go, python, node, php, java — `Test` is +// what that job should call). +// +// dockerfile is the Dockerfile's path inside source, already confined by +// applyLayout; "" keeps the root rule this function has always applied. +func (m *StandardBuild) buildFromDockerfile( + ctx context.Context, source *dagger.Directory, dockerfile string, + result *BuildResult, language string, buildArg []string, pub publishConfig, +) (*BuildResult, error) { + var hasDockerfile bool + var err error + if dockerfile == "" { + hasDockerfile, err = hasRootDockerfile(ctx, source) + } else { + // Read again without following symlinks, as a regular file: this is the + // file DockerBuild is about to read. + hasDockerfile, err = source.Exists(ctx, dockerfile, dagger.DirectoryExistsOpts{ + ExpectedType: dagger.ExistsTypeRegularType, + DoNotFollowSymlinks: true, + }) + } + if err != nil { + return nil, err + } + if !hasDockerfile { + return nil, fmt.Errorf( + "language %q has no built-in build (supported: go, python, node, php) "+ + "and the source has no Dockerfile to fall back to", + language, + ) + } + + source, err = applyDockerfileIgnore(ctx, source, dockerfile) + if err != nil { + return nil, err + } + + args := make([]dagger.BuildArg, 0, len(buildArg)) + for _, raw := range buildArg { + name, value, found := strings.Cut(raw, "=") + if !found || name == "" { + return nil, fmt.Errorf("--build-arg must be KEY=value, got %q", raw) + } + args = append(args, dagger.BuildArg{Name: name, Value: value}) + } + + opts := dagger.DirectoryDockerBuildOpts{BuildArgs: args} + if dockerfile != "" { + opts.Dockerfile = dockerfile + } + image := source.DockerBuild(opts) + ref, err := publishImage(ctx, image, pub) + if err != nil { + return nil, err + } + + result.Success = true + result.ImageRef = ref + return result, nil +} + +// applyDockerfileIgnore applies `.dockerignore` to the build +// context in the mode layout.ContextFilters fixes: for the generated +// `.integraci/Dockerfile`, the context's root `.dockerignore` and then the +// sidecar's exclusions (no re-includes); for a customer's own Dockerfile, +// BuildKit's rule -- the sidecar alone, re-includes kept. See layout/ignore.go. +// +// No sidecar: the context is returned untouched, so a build without one +// behaves exactly as before -- except for the GENERATED Dockerfile, whose +// missing sidecar refuses the build (layout.GeneratedSidecarPresent). Ignore files are typed WITHOUT following +// symlinks; for the generated Dockerfile one that is not a regular file +// refuses the build (layout.IgnoreFileUsable), for a customer's it is left to +// the engine as before. source is the build context, and dockerfile its +// Dockerfile path inside it ("" = the root `Dockerfile`), already confined by +// applyLayout. +func applyDockerfileIgnore(ctx context.Context, source *dagger.Directory, dockerfile string) (*dagger.Directory, error) { + stat := statWithoutFollowing(source) + if dockerfile == "" { + dockerfile = layout.DefaultDockerfile + } + sidecar := layout.SidecarPath(dockerfile) + generated := layout.IsGeneratedDockerfile(dockerfile) + kind, err := stat(ctx, sidecar) + if err != nil { + return nil, fmt.Errorf("reading %q: %w", sidecar, err) + } + if generated { + // The generated pair is never built half: without its sidecar the + // generated `COPY . .` takes `.env` and keys into the image. + if err := layout.GeneratedSidecarPresent(sidecar, kind); err != nil { + return nil, err + } + } + useSidecar, err := layout.IgnoreFileUsable(sidecar, kind) + if !generated && err != nil { + // A customer's own sidecar that is not a regular file: left to the + // engine's Dockerfile frontend exactly as before this module read + // sidecars at all. Only the generated pair is refused (see + // layout.IgnoreFileUsable). + return source, nil + } + if err != nil || !useSidecar { + return source, err + } + sidecarBody, err := source.File(sidecar).Contents(ctx) + if err != nil { + return nil, fmt.Errorf("reading %q: %w", sidecar, err) + } + hasRoot := false + rootBody := "" + if generated { + rootKind, err := stat(ctx, layout.RootIgnoreFile) + if err != nil { + return nil, fmt.Errorf("reading %q: %w", layout.RootIgnoreFile, err) + } + hasRoot, err = layout.IgnoreFileUsable(layout.RootIgnoreFile, rootKind) + if err != nil { + return nil, err + } + } + if hasRoot { + rootBody, err = source.File(layout.RootIgnoreFile).Contents(ctx) + if err != nil { + return nil, fmt.Errorf("reading %q: %w", layout.RootIgnoreFile, err) + } + } + // The definition being built must survive whatever the patterns say. + definition := source.File(dockerfile) + for _, exclude := range layout.ContextFilters(rootBody, hasRoot, sidecarBody, generated) { + source = source.Filter(dagger.DirectoryFilterOpts{Exclude: exclude}) + } + return source.WithFile(dockerfile, definition), nil +} + +// buildEnv applies `KEY=value` pairs to a container as environment variables. +// +// `--build-arg` was a DOCKERFILE-only parameter: the four native lanes below +// ignored it entirely. That is exactly backwards for the stack that needs it +// most. A Vite/Next/CRA front-end reads its API base at BUILD time and inlines +// it into the bundle, and those are built by `buildNode`, not from a +// Dockerfile — so the one lane that could not receive build configuration was +// the one lane whose framework cannot be configured any other way. +// +// MEASURED on a customer front-end 2026-09-07: `VITE_API_URL` unset at build, +// so `axios.create({baseURL: import.meta.env.VITE_API_URL})` compiled to an +// empty base and every request went to the page's own origin, which answered +// 405. The workaround that had grown up instead was committing a +// `.env.production` into the application repository — one environment's backend +// hardcoded into every stage's image. +// +// Applied BEFORE the build exec so the framework sees it; malformed pairs are +// skipped rather than failing the build, because the caller-side renderer +// already refuses them and a second hard failure here would only turn a +// configuration mistake into a red pipeline with a worse message. +func buildEnv(c *dagger.Container, buildArg []string) *dagger.Container { + for _, raw := range buildArg { + name, value, found := strings.Cut(raw, "=") + if !found || name == "" { + continue + } + c = c.WithEnvVariable(name, value) + } + return c +} + +// publishConfig carries the opt-in registry publish settings, and the one +// switch that makes a lane stop before it has anything to publish. +type publishConfig struct { + imageRef string + username string + password *dagger.Secret + insecure bool + // testOnly makes the lane return after its lint and test steps, with no + // image assembled and no publish attempted. Set by Test, never by Build. + // It rides in this struct rather than as a fifth positional bool so that + // the four lane signatures — which the contract tests pin — do not grow, + // and so that the lint/test code lives in exactly one place per lane + // instead of being copied into a second set of functions. + testOnly bool + // workdir is the workspace member a lane works in when it reads the whole + // checkout (context repo_root); "" = /src. Rides here for the same reason + // testOnly does: the lane signatures stay as they are. Only the go and node + // lanes read it (laneWorkdirProblem refuses the others). + workdir string +} + +// lintTestBase is the container a lane lints and tests in. +// +// In test-only mode the build-time configuration is applied HERE, because +// there is no build step after the tests for it to be applied to, and a +// parameter that is accepted and dropped is worse than one that is absent. In +// build mode the container is returned unchanged: Build has always run lint +// and tests without the build args and applied them only to the build exec, +// and this change does not alter what an existing pipeline's tests see. +func lintTestBase(base *dagger.Container, pub publishConfig, buildArg []string) *dagger.Container { + if pub.testOnly { + return buildEnv(base, buildArg) + } + return base +} + +// testsDone is the result of a lane in test-only mode: green, and honest +// about carrying no image. Success here means "lint and tests passed", which +// is all the caller asked. +func testsDone(result *BuildResult) *BuildResult { + result.Success = true + result.ImageRef = "" + return result +} + +// destinationRef resolves where the built image should be published. +// +// --image-ref wins outright: it is the whole destination and needs no +// assembly. Otherwise a destination is built from --registry, the SERVICE name +// and --tag; a --registry with no service is refused rather than silently +// substituting a shared repository name, which is how every service in a tenant +// came to overwrite one image. +func destinationRef(imageRef, registry, service, tag string) (string, error) { + if imageRef != "" { + return imageRef, nil + } + if registry == "" { + return "", nil // build-only: nothing to publish to + } + if service == "" { + return "", fmt.Errorf( + "--registry given without --service or --image-ref: refusing to publish " + + "to a shared repository name where every service would overwrite the last") + } + if tag == "" { + tag = "latest" + } + return fmt.Sprintf("%s/%s:%s", registry, service, tag), nil +} + +// registryHost is the host portion of an image reference, which is what +// WithRegistryAuth authenticates against — "harbor.internal:30002" out of +// "harbor.internal:30002/library/orders:abc". A reference with no host segment +// (docker.io shorthand) yields "". +func registryHost(imageRef string) string { + head, _, found := strings.Cut(imageRef, "/") + if !found || (!strings.Contains(head, ".") && !strings.Contains(head, ":") && head != "localhost") { + return "" + } + return head +} + +// publishImage pushes the image to the resolved destination, or skips +// publishing (leaving ImageRef empty) when there is none. A publish failure is +// returned, never swallowed — a build that could not deliver its artifact is +// not a success. +func publishImage(ctx context.Context, image *dagger.Container, pub publishConfig) (string, error) { + if pub.imageRef == "" { + return "", nil // build-only: no destination configured + } + if pub.insecure { + return publishInsecure(ctx, image, pub) + } + if pub.password != nil { + image = image.WithRegistryAuth(registryHost(pub.imageRef), pub.username, pub.password) + } + ref, err := image.Publish(ctx, pub.imageRef) + if err != nil { + return "", fmt.Errorf("publish to %s failed: %w", pub.imageRef, err) + } + return ref, nil +} + +// craneImage is the pusher used for a plain-HTTP registry. Apache-2.0. +// +// The `/debug` variant, which is the same crane plus a busybox shell. The plain +// image is DISTROLESS — no `sh` at all — so a shell step against it fails with +// `exit code: 1` and produces no output whatsoever, which is indistinguishable +// from the registry refusing the push. Measured twice before the cause was +// visible. A shell is needed here to feed the credential in on STDIN, which is +// what keeps it off the argv and out of the layer. +// +// Tags are checked against the registry's own list rather than assumed: v0.20.2 +// looks like a plausible release and was never published, so an earlier build +// failed with `not found` after every other stage had succeeded. +const craneImage = "gcr.io/go-containerregistry/crane/debug:v0.21.9" + +// publishInsecure pushes to a registry that is served over plain HTTP. +// +// WHY THIS IS NOT A FLAG ON Publish. Dagger's publish goes through buildkit, +// which resolves every destination over HTTPS and has no per-call opt-out: the +// only way to tell it otherwise is an engine-level config file, which means +// getting a file into a sidecar of a pod template of a chart — a lot of moving +// parts, all of them the customer's, to change one boolean. +// +// This is the honest alternative and it is entirely inside the module: export +// the built image as a tarball and push it with crane, which takes --insecure as +// an argument. Nothing about the cluster has to change, and any deployment whose +// registry has no certificate (a managed registry on a private cluster with no +// ingress host is the normal case, not an exotic one) can deliver artifacts. +// +// The credential is a Dagger SECRET mounted as a file and read by `crane auth +// login --password-stdin`, so it is never an argv entry and never a layer. +func publishInsecure(ctx context.Context, image *dagger.Container, pub publishConfig) (string, error) { + host := registryHost(pub.imageRef) + if host == "" { + return "", fmt.Errorf("insecure publish needs a registry host in %q", pub.imageRef) + } + // Docker media types: `crane push` reads a docker-save-shaped archive. + tar := image.AsTarball(dagger.ContainerAsTarballOpts{ + MediaTypes: dagger.ImageMediaTypesDockerMediaTypes, + }) + pusher := dag.Container(). + From(craneImage). + WithFile("/tmp/image.tar", tar) + + login := "echo 'no registry credential supplied; pushing anonymously'" + if pub.password != nil { + pusher = pusher.WithMountedSecret("/tmp/registry-password", pub.password) + login = fmt.Sprintf( + "crane auth login %s -u %s --password-stdin < /tmp/registry-password", + shellQuote(host), shellQuote(pub.username), + ) + } + // The step ALWAYS exits 0 and reports what happened on stdout, and success is + // judged by the confirmation line rather than by the exit status. + // + // That is not a shortcut, it is the only way to see the reason. A failing + // exec surfaces as `exit code: 1` with nothing attached — measured twice on + // a live build, once for `crane auth login` and once for the push — and a + // registry refusal, a wrong credential and an unreachable token realm are + // three completely different problems that all look identical that way. + out, err := pusher.WithExec([]string{ + "sh", "-c", + fmt.Sprintf( + "{ %s; crane push --insecure /tmp/image.tar %s && echo PUSHED %s; } 2>&1; "+ + "echo \"crane exit=$?\"", + login, shellQuote(pub.imageRef), shellQuote(pub.imageRef), + ), + }).Stdout(ctx) + if err != nil { + return "", fmt.Errorf("insecure publish to %s failed: %s", pub.imageRef, execDetail(err)) + } + if !strings.Contains(out, "PUSHED") { + return "", fmt.Errorf("insecure publish to %s did not confirm:\n%s", pub.imageRef, out) + } + // crane push prints the pushed manifest as `@sha256:`. Return + // the destination pinned to it — the same shape Publish returns on the TLS + // path — so ImageDigest is filled whichever path pushed. Without a printed + // digest the tag is all there is, and ImageDigest stays empty rather than + // guessed. + if pinned := evidence.DigestFromPushOutput(out); pinned != "" { + if d := evidence.DigestOf(pinned); d != "" { + return pub.imageRef + "@" + d, nil + } + } + return pub.imageRef, nil +} + +// withDigest fills ImageDigest from the published reference. Publish returns +// `:@sha256:`; a reference without a digest leaves it empty. +func withDigest(result *BuildResult, err error) (*BuildResult, error) { + if err != nil || result == nil { + return result, err + } + result.ImageDigest = evidence.DigestOf(result.ImageRef) + return result, nil +} + +// daggerEngineVersion is the engine every module's dagger.json pins. It is +// recorded in the provenance `builder.version`, and +// tools/scripts/dagger-mirror-manifest.py fails when it and dagger.json +// disagree. +const daggerEngineVersion = "v0.21.7" + +// syftImage is the SBOM generator the evidence set uses — the same pin as the +// sbom module, so both paths describe an image the same way. +const syftImage = "anchore/syft:v1.18.1" + +// Evidence writes the supply-chain evidence for ONE published image digest +// (ADR-0068 Layer 2, #2143 phase 1) and returns it as a directory: +// +// sbom.cdx.json | sbom.spdx.json SBOM of the image, generated by syft +// provenance.intoto.json in-toto Statement, SLSA v1 provenance +// SHA256SUMS `sha256sum -c` manifest over the two above +// +// The caller exports the directory (`export --path=evidence`) and keeps it as +// a build artifact; `cosign attest-provenance --predicate` and +// `cosign attest-sbom` attach the SAME files to the digest, so the bytes a +// verifier fetches from the registry and the bytes archived with the build are +// one set. Nothing here signs: an unsigned statement is a claim, the +// signature makes it an attestation. +// +// --image-ref MUST be pinned to a digest (Build's `image_ref` is). A tag is +// refused rather than resolved: resolving it here would record whatever the +// tag points at by the time this step runs. +// +// One caveat, latent while Build publishes a single platform: if --image-ref +// names a multi-platform image INDEX, syft describes one platform's manifest +// while the provenance subject is the index digest. Run evidence per platform +// manifest digest when Build learns to publish more than one. +// +// Usage: +// +// dagger call evidence --source=. \ +// --image-ref=registry.example/team/orders:abc@sha256: \ +// --builder-id=https://ci.example/job/orders/ \ +// --source-uri=git+https://git.example/team/orders@refs/heads/main \ +// --source-revision= --invocation-id=$BUILD_ID \ +// export --path=evidence +func (m *StandardBuild) Evidence( + ctx context.Context, + // Source directory (only used as the SBOM working directory; the SBOM + // describes the IMAGE, not the tree) + source *dagger.Directory, + // Published image, pinned: [:tag]@sha256:<64 hex> + imageRef string, + // Absolute URI identifying the pipeline that built the image + builderId string, + // Source repository URI, e.g. git+https://git.example/org/repo@refs/heads/main + sourceUri string, + // Full commit id the image was built from (40 or 64 hex) + sourceRevision string, + // Build recipe URI recorded as SLSA buildType + // +optional + buildType string, + // CI run identifier + // +optional + invocationId string, + // Build start time, RFC 3339 + // +optional + startedOn string, + // Build finish time, RFC 3339 + // +optional + finishedOn string, + // Build lane, recorded as an internal parameter + // +optional + language string, + // SBOM format: cyclonedx | spdx + // +optional + // +default="cyclonedx" + sbomFormat string, + // Registry username for pulling --image-ref + // +optional + registryUsername string, + // Registry password/token for pulling --image-ref + // +optional + registryPassword *dagger.Secret, + // The registry is served over plain HTTP (same opt-in as Build) + // +optional + registryInsecure bool, +) (*dagger.Directory, error) { + // Validate everything BEFORE pulling anything: a refused statement should + // not cost an SBOM run first. + provenance, err := evidence.ProvenanceStatement(evidence.ProvenanceInput{ + ImageRef: imageRef, + BuilderID: builderId, + BuildType: buildType, + SourceURI: sourceUri, + SourceRevision: sourceRevision, + InvocationID: invocationId, + StartedOn: startedOn, + FinishedOn: finishedOn, + EngineVersion: daggerEngineVersion, + Language: language, + }) + if err != nil { + return nil, err + } + sbomName, syftOutput, err := evidence.SBOMFileName(sbomFormat) + if err != nil { + return nil, err + } + + // anchore/syft is distroless; copy the binary into alpine for a shell. + // The target is `registry:` explicitly — see sbom.syftTarget for the + // measured failure of a bare reference inside a Dagger container. + scanner := dag.Container(). + From("alpine:3.20"). + WithFile("/usr/local/bin/syft", dag.Container().From(syftImage).File("/syft")). + WithMountedDirectory("/src", source). + WithWorkdir("/src"). + WithEnvVariable("IMAGE_REF", imageRef) + if registryInsecure { + scanner = scanner. + WithEnvVariable("SYFT_REGISTRY_INSECURE_USE_HTTP", "true"). + WithEnvVariable("SYFT_REGISTRY_INSECURE_SKIP_TLS_VERIFY", "true") + } + if registryPassword != nil { + host := registryHost(imageRef) + if host == "" { + return nil, fmt.Errorf("registry credentials need a registry host in %q", imageRef) + } + scanner = scanner. + WithEnvVariable("SYFT_REGISTRY_AUTH_AUTHORITY", host). + WithEnvVariable("SYFT_REGISTRY_AUTH_USERNAME", registryUsername). + WithSecretVariable("SYFT_REGISTRY_AUTH_PASSWORD", registryPassword) + } + // The reference goes through the environment, not the command string: it + // is caller input, and ParseDigestRef has already pinned its shape. + sbom, err := scanner. + WithExec([]string{ + "sh", "-c", + fmt.Sprintf(`mkdir -p /out && syft "registry:${IMAGE_REF}" -o %s=/out/%s`, syftOutput, sbomName), + }). + File("/out/" + sbomName). + Contents(ctx) + if err != nil { + return nil, fmt.Errorf("sbom for %s failed: %s", imageRef, execDetail(err)) + } + + files := map[string][]byte{ + sbomName: []byte(sbom), + "provenance.intoto.json": provenance, + } + sums, err := evidence.SHA256Sums(files) + if err != nil { + return nil, err + } + dir := dag.Directory().WithNewFile("SHA256SUMS", string(sums)) + for name, body := range files { + dir = dir.WithNewFile(name, string(body)) + } + return dir, nil +} + +// shellQuote wraps a value for single-quoted shell use. The values here are a +// registry host, a username and an image reference — all caller-supplied, so +// they are quoted rather than trusted. +func shellQuote(s string) string { + return "'" + strings.ReplaceAll(s, "'", `'"'"'`) + "'" +} + +func (m *StandardBuild) buildGo( + ctx context.Context, source *dagger.Directory, + result *BuildResult, skipTests, skipLint bool, pub publishConfig, buildArg []string, +) (*BuildResult, error) { + base := dag.Container(). + From("golang:1.23-bookworm"). + // Persist the module + build caches across runs so repeat builds + // don't re-download modules or recompile the standard library. + WithMountedCache("/go/pkg/mod", dag.CacheVolume("go-mod")). + WithMountedCache("/root/.cache/go-build", dag.CacheVolume("go-build")). + WithDirectory("/src", source). + // A workspace member (context repo_root) runs in its own directory; + // `go` finds the root `go.work` upward. "/src" otherwise, as before. + WithWorkdir(laneDir(pub)) + base = lintTestBase(base, pub, buildArg) + + // Lint + if !skipLint { + lint := base.WithExec([]string{"go", "vet", "./..."}) + out, err := lint.Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("go vet failed: %w", err) + } + result.LintOutput = out + } + + // Test + if !skipTests { + test := base.WithExec([]string{"go", "test", "-race", "-v", "./..."}) + out, err := test.Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("go test failed: %w", err) + } + result.TestOutput = out + } + if pub.testOnly { + return testsDone(result), nil + } + + // Build binary + build := buildEnv(base, buildArg).WithExec([]string{ + "go", "build", "-o", "/out/app", ".", + }) + + // Container image + image := dag.Container(). + From("gcr.io/distroless/static-debian12:nonroot"). + WithFile("/app", build.File("/out/app")). + WithEntrypoint([]string{"/app"}) + + ref, err := publishImage(ctx, image, pub) + if err != nil { + return nil, err + } + + result.Success = true + result.ImageRef = ref + return result, nil +} + +// pythonEntrypointScript starts the project's declared console script, or fails +// with a sentence a person can act on. +// +// Read at RUN time, not build time, so the image stays a plain artefact and the +// message reflects the tree it was built from. `[project.scripts]` is the one +// place a Python project states how it is started; a project that declares none +// has not told anyone, and the honest response is to say which field to set +// rather than to start an interactive interpreter that exits immediately. +// +// A tree installed for its DEPENDENCIES only (pythonInstallPlanScript's +// `dependencies` mode) has no console script on PATH, so the script's own +// `module:function` target is started from the checkout instead; without that a +// project whose `[project.scripts]` the image used to install would exit 127. +// The target reaches python as an argument, never as code, and the reader runs +// with `-I` so nothing in the tree is imported while choosing. +const pythonEntrypointScript = `set -e +resolved=$(python -I - <<'PY' +import tomllib, pathlib +try: + data = tomllib.loads(pathlib.Path("pyproject.toml").read_text()) +except Exception: + data = {} +scripts = (data.get("project") or {}).get("scripts") or {} +if isinstance(scripts, dict) and len(scripts) == 1: + name, target = next(iter(scripts.items())) + print(name) + print(str(target).split("[")[0].strip()) +PY +) +script=$(printf '%s\n' "$resolved" | sed -n 1p) +target=$(printf '%s\n' "$resolved" | sed -n 2p) +if [ -n "$script" ] && command -v "$script" >/dev/null 2>&1; then exec "$script"; fi +if [ -n "$target" ]; then + exec python -c 'import importlib, sys +module, _, attr = sys.argv[1].partition(":") +obj = importlib.import_module(module.strip()) +for part in attr.strip().split("."): + if part: + obj = getattr(obj, part) +sys.exit(obj())' "$target" +fi +echo "integraci: this image has no entrypoint." >&2 +echo " The project declares no single [project.scripts] entry, so the build" >&2 +echo " could not tell how to start it. Set deploy.runtime.command in the" >&2 +echo " service spec, or declare a console script in pyproject.toml." >&2 +exit 64 +` + +// pythonInstallPlanScript decides how a Python tree is installed, from what its +// pyproject.toml DECLARES rather than from the file existing. +// +// A pyproject.toml is not a promise that the tree is a package. Brownfield +// services ship one for tool settings only (`[tool.ruff]`), and installing such a +// tree with `pip install -e .[dev]` hands it to setuptools' automatic discovery, +// which refuses any flat layout with more than one top-level package +// ("Multiple top-level packages discovered in a flat-layout: ['app', 'agent', +// 'config', 'deploy']"). Measured on production 2026-10-12: two imported FastAPI +// services failed Lint and Test there, before ruff ran, on a file that only +// configured ruff. +// +// So, in order: +// - `package`: `[build-system]` is declared, or the tree carries setup.py / +// setup.cfg — the authors meant it to be built. Installed exactly as before +// (`-e .[dev]`, `.` for the image). +// - `dependencies`: `[project]` without `[build-system]` — its DEPENDENCIES are +// installed (`-r pyproject.toml`, plus the `dev` extra when it has one), the +// tree itself is never built, so its layout cannot fail the install. +// - `requirements`: no project declared, a requirements.txt present. +// +// requirements.txt is installed too when both exist: an application's +// pyproject.toml is as likely to hold its tool settings as its dependencies. +// Parsed with tomllib inside the build container, as pythonEntrypointScript +// does, so the module needs no TOML library of its own. Prints one JSON object. +// Run with `python -I`: plain `-c` puts the working directory — the tenant's +// tree — first on sys.path, so a root-level json.py or pathlib.py would run on +// import and could print any plan. +const pythonInstallPlanScript = ` +import json, pathlib, tomllib + +has_requirements = pathlib.Path("requirements.txt").is_file() +pyproject = pathlib.Path("pyproject.toml") +data = {} +if pyproject.is_file(): + try: + data = tomllib.loads(pyproject.read_text()) + except Exception as exc: + print(json.dumps({"error": "pyproject.toml is not valid TOML: %s" % exc})) + raise SystemExit(0) + +tools = ["ruff", "pytest", "pytest-cov"] +requirements = ["-r", "requirements.txt"] if has_requirements else [] +project = data.get("project") +package = {"mode": "package", "test": ["-e", ".[dev]"], "runtime": ["."]} +if isinstance(data.get("build-system"), dict): + plan = package +elif pathlib.Path("setup.py").is_file() or pathlib.Path("setup.cfg").is_file(): + # A setuptools project configured the older way: its packaging lives in + # setup.py/setup.cfg, and its pyproject.toml may hold tool settings only. + plan = package +elif isinstance(project, dict): + extras = project.get("optional-dependencies") + dev = ["--extra", "dev"] if isinstance(extras, dict) and "dev" in extras else [] + plan = { + "mode": "dependencies", + "test": ["-r", "pyproject.toml", *dev, *requirements, *tools], + "runtime": ["-r", "pyproject.toml", *requirements], + } +elif has_requirements: + plan = {"mode": "requirements", "test": [*requirements, *tools], "runtime": requirements} +else: + plan = { + "error": "pyproject.toml declares neither [project] nor [build-system] and there " + "is no requirements.txt, so there is nothing to install. List the dependencies " + "in requirements.txt or in [project].dependencies." + } +print(json.dumps(plan)) +` + +// pythonInstallPlan is pythonInstallPlanScript's answer. +type pythonInstallPlan struct { + Mode string `json:"mode"` + Test []string `json:"test"` + Runtime []string `json:"runtime"` + Error string `json:"error"` +} + +// readPythonInstallPlan runs pythonInstallPlanScript against the source tree. +func readPythonInstallPlan(ctx context.Context, source *dagger.Directory) (*pythonInstallPlan, error) { + out, err := dag.Container(). + From("python:3.12-slim"). + WithDirectory("/src", source). + WithWorkdir("/src"). + WithExec([]string{"python", "-I", "-c", pythonInstallPlanScript}). + Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("reading the python install plan: %s", execDetail(err)) + } + var plan pythonInstallPlan + if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &plan); err != nil { + return nil, fmt.Errorf("reading the python install plan: %w", err) + } + if plan.Error != "" { + return nil, fmt.Errorf("python lane: %s", plan.Error) + } + if plan.Mode == "" || len(plan.Test) == 0 || len(plan.Runtime) == 0 { + return nil, fmt.Errorf("python lane: the install plan is incomplete: %q", out) + } + return &plan, nil +} + +func (m *StandardBuild) buildPython( + ctx context.Context, source *dagger.Directory, + result *BuildResult, skipTests, skipLint bool, pub publishConfig, buildArg []string, +) (*BuildResult, error) { + // uv = fast, reproducible installs (mirrors apps/api/Dockerfile). The + // binary is copied from the pinned Astral uv image, exactly as the + // Dockerfile does (COPY --from=ghcr.io/astral-sh/uv:0.5.11 /uv ...). + uvBin := dag.Container().From("ghcr.io/astral-sh/uv:0.5.11").File("/uv") + + hasPyproject, err := hasRootEntry(ctx, source, "pyproject.toml") + if err != nil { + return nil, err + } + hasRequirements, err := hasRootEntry(ctx, source, "requirements.txt") + if err != nil { + return nil, err + } + if !hasPyproject && !hasRequirements { + return nil, fmt.Errorf( + "python lane needs pyproject.toml or requirements.txt at the source root", + ) + } + plan, err := readPythonInstallPlan(ctx, source) + if err != nil { + return nil, err + } + + base := dag.Container(). + From("python:3.12-slim"). + WithFile("/usr/local/bin/uv", uvBin). + // Persist the uv download/wheel cache across runs. + WithMountedCache("/root/.cache/uv", dag.CacheVolume("uv")). + WithDirectory("/src", source). + WithWorkdir("/src") + // What gets installed is pythonInstallPlanScript's decision: the editable + // project + [dev] for a declared package, its dependencies (and ruff/pytest) + // for anything else. Brownfield FastAPI trees often only ship + // requirements.txt, or a pyproject.toml that configures ruff and nothing more. + base = base.WithExec(withArgs([]string{"uv", "pip", "install", "--system"}, plan.Test...)) + if plan.Mode != "package" { + // Nothing was installed under the tree's own name, so tests import it + // from the checkout: the root, and `src/` for a src-layout. + base = base.WithEnvVariable("PYTHONPATH", "/src:/src/src") + } + base = lintTestBase(base, pub, buildArg) + + if !skipLint { + lint := base.WithExec([]string{"ruff", "check", "."}) + out, err := lint.Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("ruff check failed: %w", err) + } + result.LintOutput = out + } + + if !skipTests { + hasTests, err := hasRootEntry(ctx, source, "tests") + if err != nil { + return nil, err + } + // A declared package is tested with pytest as before. Anything else + // runs pytest only when it HAS tests: a pyproject.toml that configures + // ruff says nothing about tests, and pytest with nothing to collect exits 5. + if hasTests || plan.Mode == "package" { + test := base.WithExec([]string{"pytest", "-v"}) + out, err := test.Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("pytest failed: %w", err) + } + result.TestOutput = out + } else { + // requirements.txt apps often have no tests/ yet — still prove the + // tree imports (compileall) so Lint and Test is not a no-op. + compile := base.WithExec([]string{"python", "-m", "compileall", "-q", "."}) + out, err := compile.Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("compileall failed: %w", err) + } + result.TestOutput = out + if result.TestOutput == "" { + result.TestOutput = "no tests/ directory; compileall + ruff only\n" + } + } + } + if pub.testOnly { + return testsDone(result), nil + } + + // THE IMAGE. This lane took `_ publishConfig` and returned here, so a Python + // service compiled, linted, tested, went green — and published NOTHING, for + // ever. It is the same defect the node lane carried until #1706/#1707 fixed + // that one and left this one, and it presents identically: `StandardBuild + // DONE`, an imageRef printed by the caller, and the registry answering + // NAME_UNKNOWN for it. The deploy then sits in ImagePullBackOff behind a + // green pipeline. + // + // Built from a SEPARATE, non-dev install rather than from `base`. `base` + // carries `.[dev]` — pytest, ruff, every test dependency — because that is + // what the lint and test steps above need. Publishing that layer would ship + // the test toolchain to production. + // + // The ENTRYPOINT is the part this lane cannot invent, and getting it wrong is + // worse than the bug being fixed: `python:3.12-slim` defaults to `python3`, + // which with no TTY reads EOF and exits 0 — so the pod goes Completed and + // then CrashLoopBackOff, behind a green pipeline, which is the same shape of + // failure as publishing nothing. So it is RESOLVED, not guessed: a project + // that declares a console script in `[project.scripts]` runs it, and a + // project that declares none gets an entrypoint that says so and exits + // non-zero, which reads as a configuration error in the pod's logs instead of + // a mystery restart loop. `deploy.runtime.command` overrides either. + // + // requirements.txt-only trees normally hit Build via their root Dockerfile + // (Dockerfile wins over --language). Publishing through this lane without a + // pyproject still installs deps from requirements.txt; entrypoint resolution + // still needs a console script or deploy.runtime.command. + runtime := dag.Container(). + From("python:3.12-slim"). + WithFile("/usr/local/bin/uv", uvBin). + WithMountedCache("/root/.cache/uv", dag.CacheVolume("uv")). + WithDirectory("/src", source). + WithWorkdir("/src") + // The same plan as the tests, without the dev tools: `.` for a declared + // package, the dependencies alone for anything else. + runtime = runtime.WithExec(withArgs([]string{"uv", "pip", "install", "--system"}, plan.Runtime...)) + if plan.Mode != "package" { + runtime = runtime.WithEnvVariable("PYTHONPATH", "/src:/src/src") + } + + image := buildEnv(runtime, buildArg). + WithWorkdir("/src"). + WithExposedPort(8000). + WithEntrypoint([]string{"sh", "-c", pythonEntrypointScript}) + + ref, err := publishImage(ctx, image, pub) + if err != nil { + return nil, err + } + result.ImageRef = ref + result.Success = true + return result, nil +} + +// phpLintCommand is the syntax gate for a PHP tree. Both of its awkward parts +// are load-bearing. +// +// `*/vendor/*`, NOT `./vendor/*`. Composer puts dependencies at the root, but an +// application that predates Composer vendors them wherever the tree grew — +// `lib/vendor/`, `application/vendor/`. A root-anchored pattern therefore lints +// third-party code, and third-party code is the one thing no runtime version can +// satisfy: measured across five real imports, the same tree carried a PDF +// library whose syntax was removed in PHP 8 AND a psr/log written in PHP 8 union +// types. Three of the five could not pass on ANY single version until the +// pattern stopped matching only the root; with it fixed all five pass on 7.4. +// buildPhp already assumes this shape further down — the composer step skips a +// tree "with libraries vendored under lib/". +// +// The `sh -c` wrapper is the other half. `php -l` exits 255 on a fatal, and +// xargs ABORTS the whole run the moment a command exits 255. So the gate +// reported exactly one bad file however many there were, and the files-checked +// count was however many happened to finish first — which reads as "one small +// problem" when it is really "we stopped looking". Translating the status lets +// xargs walk the whole tree and still exit non-zero (123), so a single run lists +// every file a person has to fix. +// +// A failure is written TWICE, and the second write is what makes the first +// useful. execDetail prefers stderr and keeps only the last 4000 bytes; folding +// php's own stderr into `out` left stderr empty, so the fallback took stdout — +// whose tail is `No syntax errors detected in …` repeated once per passing file. +// Measured on a 2001-file tree with one bad file: 98,085 bytes of output, the +// single `Parse error` line nowhere in the final 4000. The developer would be +// told the tree was rejected and then shown eighty lines of success. Echoing +// only the failures to stderr puts the filenames back in the message while +// stdout keeps the full transcript for LintOutput. +const phpLintCommand = `find . -type f -name '*.php' -not -path '*/vendor/*' -print0 | ` + + `xargs -0 -r -n1 -P4 sh -c 'out=$(php -l "$1" 2>&1); rc=$?; printf "%s\n" "$out"; ` + + `[ "$rc" -eq 0 ] || { printf "%s\n" "$out" >&2; exit 1; }' sh` + +// buildPhp turns a PHP source tree into a runnable image with no Dockerfile. +// +// PHP is the case that most needs this. A large share of the internal +// applications customers bring have never been containerised, have no +// composer.json at the root (their libraries are vendored into the tree), and +// are served by dropping the directory into a webroot. Asking that team to +// author a Dockerfile is asking them to learn Docker before they can ship — +// which is the opposite of the promise. +// +// So the image is assembled here: php:-apache with the extensions such +// an application almost always needs, the source copied into the document root, +// and nothing for the developer to write. Composer runs only when the project +// actually declares dependencies at the root; a vendored tree is left alone. +// +// THE VERSION IS AN ARGUMENT, AND THAT MATTERS MORE THAN IT LOOKS. It used to be +// pinned to 8.3. The applications this exists for are a decade old and carry +// vendored libraries written against PHP 5, and PHP has REMOVED syntax since: +// `$s{0}` string offsets are a fatal error from 8.0. So the newest runtime +// rejects, correctly, code the customer never wrote and did not choose to run on +// 8.3 — and the build fails for a version nobody picked. Measured on a real +// import: two files in a bundled PDF library. Defaulting to the current release +// is right for new code; being able to say 7.4 is what makes a migration +// possible at all. +// +// Lint is `php -l` across the tree — a syntax check is the honest gate for a +// codebase with no test suite, and it catches the parse error that would +// otherwise 500 in production. Tests run only if the project has phpunit. +func (m *StandardBuild) buildPhp( + ctx context.Context, source *dagger.Directory, + result *BuildResult, skipTests, skipLint bool, pub publishConfig, version string, buildArg []string, +) (*BuildResult, error) { + if version == "" { + version = "8.3" + } + phpImage := fmt.Sprintf("php:%s-apache", version) + base := dag.Container(). + From(phpImage). + WithDirectory("/src", source). + WithWorkdir("/src") + base = lintTestBase(base, pub, buildArg) + + if !skipLint { + // `find … | xargs php -l` returns non-zero when ANY file fails, so the + // step fails exactly when the code would not run. + lint := base.WithExec([]string{"sh", "-c", phpLintCommand}) + out, err := lint.Stdout(ctx) + if err != nil { + // The output is the whole point of a lint gate: WHICH file, and why. + // Wrapping the bare error gave `exit code: 124` and nothing else. + return nil, fmt.Errorf( + "php -l rejected this tree on PHP %s — pass a runtime version the "+ + "code was written for if these are vendored libraries:\n%s", + version, execDetail(err)) + } + result.LintOutput = out + } + + if !skipTests { + // Only when the project actually has a suite. A missing one is not a + // failure — most of these applications have never had tests, and + // refusing to build them would just block the migration we are enabling. + test := base.WithExec([]string{ + "sh", "-c", + `if [ -f vendor/bin/phpunit ]; then vendor/bin/phpunit; ` + + `elif [ -f phpunit.xml ] || [ -f phpunit.xml.dist ]; then ` + + `echo "phpunit config present but not installed; skipping"; ` + + `else echo "no phpunit suite; skipping"; fi`, + }) + out, err := test.Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("phpunit failed: %s", execDetail(err)) + } + result.TestOutput = out + } + if pub.testOnly { + return testsDone(result), nil + } + + // The runtime image. Extensions first (they need the build toolchain), then + // the source into Apache's document root. + // + // `gd` and `zip` are here because COMPOSER REFUSES TO INSTALL WITHOUT THEM. + // Measured on a real customer application, 2026-08-27: it depends on + // mpdf/mpdf, which declares `ext-gd`, and composer answered + // + // mpdf/mpdf v8.1.5 requires ext-gd * -> it is missing from your system + // + // then installed nothing at all. The image still built and still published — + // the failure is a resolution error, not a build error — so what shipped was + // an app with no vendor/ directory that fatals on its first require_once. + // + // These are not a wish-list. `gd` (image handling, PDF/barcode generation) + // and `zip` (composer's own --prefer-dist path, and every export-to-xlsx + // library) are the two a decade-old PHP application declares most often, and + // a missing platform requirement fails the WHOLE resolution rather than + // skipping one package. `libpng`/`libjpeg`/`libzip` headers are needed to + // compile them, and are dropped again with the build toolchain. + // + // `pgsql`/`pdo_pgsql` are here for the other half of the database question. + // The lane compiled the MySQL drivers only, so a PHP application configured + // against PostgreSQL built green, published green, deployed green, and + // answered every request with + // + // Call to undefined function pg_connect() + // + // MEASURED on a customer application 2026-09-07: CodeIgniter's `postgre` + // driver, a PostgreSQL deployed beside it, and a runtime image that could + // not speak to it. Which database an application uses is the application's + // choice, not the lane's, and shipping only one of the two makes half of + // that choice unbuildable in a way nothing before runtime reports. + image := dag.Container(). + From(phpImage). + WithExec([]string{ + "sh", "-c", + `apt-get update && apt-get install -y --no-install-recommends ` + + `libpng-dev libjpeg62-turbo-dev libfreetype6-dev libzip-dev libpq-dev && ` + + `docker-php-ext-configure gd --with-freetype --with-jpeg && ` + + `docker-php-ext-install -j"$(nproc)" mysqli pdo_mysql pgsql pdo_pgsql gd zip && ` + + `a2enmod rewrite && rm -rf /var/lib/apt/lists/*`, + }). + WithDirectory("/var/www/html", source). + WithExec([]string{"chown", "-R", "www-data:www-data", "/var/www/html"}). + WithExposedPort(80) + + // Composer runs wherever the project actually DECLARES dependencies, which is + // not always the root. + // + // The original rule was root-only, on the reasoning that a tree with libraries + // vendored under lib/ has nothing to install. Measured on a real customer + // application, 2026-08-27: it had BOTH. Vendored libraries beside a + // `lib/composer.json` whose `lib/vendor/` was EMPTY — and an empty directory + // is not something git can carry, so the import could not have preserved it + // even if the vendor drop had contained one. The image built, published, + // deployed, served HTTP 200, and every page was: + // + // Fatal error: require_once(): Failed opening required + // '/var/www/html/lib/vendor/autoload.php' + // + // So: every composer.json within two levels, skipping anything already inside + // a vendor/ directory. Depth-bounded because a deep scan of a large tree finds + // other projects' manifests and installs things nobody asked for. Still a + // no-op for a tree that declares nothing. + image = buildEnv(image, buildArg).WithExec([]string{ + "sh", "-c", + `set -e; ` + + `manifests=$(find /var/www/html -maxdepth 3 -name composer.json -not -path '*/vendor/*' 2>/dev/null); ` + + `if [ -z "$manifests" ]; then echo "no composer.json; using the tree as-is"; exit 0; fi; ` + + // `unzip` is a convenience, not a requirement: the image compiles the + // `zip` extension above, and composer unpacks `--prefer-dist` + // archives with it when the binary is absent. `git` is NOT installed + // any more: composer only used it to read the root package version, + // and pulling it in dragged `libcurl3-gnutls` from the security + // pocket -- MEASURED 2026-09-13 on a customer's Jenkins, four builds + // in a row: the Debian CDN answered 404 for that one .deb (the + // ``%2b``-encoded ``+deb11u16`` path) and the whole build died in + // `sh: 1: git: not found` before composer ran. A build lane must not + // be one mirror hiccup away from failing on a tool it does not need. + `(apt-get update && apt-get install -y --no-install-recommends unzip) ` + + `|| echo "unzip not installable; composer falls back to the zip extension"; ` + + // git is needed for exactly one thing: a dependency with no `dist` + // archive (a `vcs`/`git` repository in composer.json -- a Gitea-hosted + // library, say) is fetched from `source`, which is `git clone`. Install + // it only when a manifest declares such a repository, so the common + // case never depends on it; and if that install fails, say so loudly + // rather than let composer fail three lines later for a reason nobody + // can see in the log. + `if grep -Eq '"type" *: *"(vcs|git)"' $manifests $(for m in $manifests; do echo "$(dirname "$m")/composer.lock"; done) 2>/dev/null; then ` + + `apt-get install -y --no-install-recommends git || { echo "a composer.json declares a vcs repository and git could not be installed" >&2; exit 1; }; ` + + `git config --global --add safe.directory '*'; fi; ` + + `curl -fsS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer; ` + + `command -v composer >/dev/null || { echo "composer could not be installed (is getcomposer.org reachable?)" >&2; exit 1; }; ` + + // A failed `composer install` used to be echoed and SKIPPED, so the image + // published with no `vendor/` and every page fataled on its first + // `require_once` -- the exact failure mode the comment above this exec + // describes. A resolution failure is a build failure. + `failed=0; for m in $manifests; do d=$(dirname "$m"); ` + + `echo "composer install in $d"; ` + + `(cd "$d" && composer install --no-dev --no-interaction --prefer-dist --no-progress) || ` + + `{ echo "composer install failed in $d" >&2; failed=1; }; done; ` + + `[ "$failed" = 0 ] || exit 1; ` + + `chown -R www-data:www-data /var/www/html`, + }) + + ref, err := publishImage(ctx, image, pub) + if err != nil { + return nil, err + } + result.ImageRef = ref + result.Success = true + return result, nil +} + +func (m *StandardBuild) buildNode( + ctx context.Context, source *dagger.Directory, + result *BuildResult, skipTests, skipLint bool, pub publishConfig, buildArg []string, +) (*BuildResult, error) { + base := dag.Container(). + From("node:22-slim"). + // Persist the npm cache across runs so `npm ci` reuses tarballs. + WithMountedCache("/root/.npm", dag.CacheVolume("npm")). + WithDirectory("/src", source). + WithWorkdir("/src"). + // `npm ci` refuses to run without a lockfile, and a lockfile is not + // something every repository carries -- MEASURED 2026-09-13 on the + // first `standard-build test` run for a service onboarded from a + // source archive: `npm error The npm ci command can only install with + // an existing package-lock.json`. The preset shell the Jenkins stage + // used before this lane got it right (`npm ci || npm install`); the + // lane did not. Reproducible installs when the repository pins them, + // a plain install when it does not -- the same choice a developer makes. + WithExec([]string{ + "sh", "-c", + `if [ -f yarn.lock ]; then corepack enable && yarn install --immutable; elif [ -f package-lock.json ] || [ -f npm-shrinkwrap.json ]; then npm ci; else npm install; fi`, + }) + if pub.workdir != "" { + // A workspace member (context repo_root): the install above ran at the + // workspace root, where the one lockfile is; lint, test, build and the + // image's start command run in the member. + base = base.WithWorkdir(laneDir(pub)) + } + base = lintTestBase(base, pub, buildArg) + + if !skipLint { + // `--if-present`: a project with no `lint` script is not a project that + // failed linting. Without it the whole build dies on a missing script, + // which is what the preset shell has always got right + // (`npm run build --if-present`) and this lane did not. + lint := base.WithExec([]string{"npm", "run", "lint", "--if-present"}) + out, err := lint.Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("npm lint failed: %w", err) + } + result.LintOutput = out + } + + if !skipTests { + // Same reasoning as lint, and MEASURED: a customer front-end with + // scripts dev/build/lint/format and no `test` failed the entire image + // build on `npm error Missing script: "test"`. + test := base.WithExec([]string{"npm", "test", "--if-present"}) + out, err := test.Stdout(ctx) + if err != nil { + return nil, fmt.Errorf("npm test failed: %w", err) + } + result.TestOutput = out + } + if pub.testOnly { + return testsDone(result), nil + } + + // THE IMAGE. This lane used to take `_ publishConfig` and return here, so a + // node service compiled, tested, went green — and published NOTHING, for + // ever. MEASURED on a customer front-end 2026-08-27: `StandardBuild.build + // DONE`, an imageRef printed in the log by the caller, and the registry + // answering `NAME_UNKNOWN` for it. The deploy then sat in ImagePullBackOff + // behind a green pipeline, which is the same failure shape the deploy-side + // registry work exists to prevent. + // + // `npm run build --if-present` first: a framework that compiles (Next, Vite, + // CRA) needs it, and one that does not is unaffected. The runtime keeps + // node_modules from the install above rather than reinstalling, so what is + // published is what was tested. + // Build-time configuration BEFORE the build exec: a Vite/Next/CRA bundle + // reads these while compiling and inlines them. After the build they are + // unreachable — the value is already a string constant in the bundle. + built := buildEnv(base, buildArg).WithExec([]string{"npm", "run", "build", "--if-present"}) + + // PORT 3000 is the node convention and what every framework's `start` + // defaults to. It is declared so the chart's service can target it; nothing + // here can know a port the application never states. + image := built. + WithWorkdir(laneDir(pub)). + WithExposedPort(3000). + WithEntrypoint([]string{"npm", "run", "start"}) + + ref, err := publishImage(ctx, image, pub) + if err != nil { + return nil, err + } + result.ImageRef = ref + result.Success = true + return result, nil +} diff --git a/static-deploy/README.md b/static-deploy/README.md new file mode 100644 index 0000000..73d2dfe --- /dev/null +++ b/static-deploy/README.md @@ -0,0 +1,9 @@ +# IntegraCI — Static Deploy Dagger Module + +Deploy static / SPA / Jamstack sites to Vercel, Netlify, S3, or Cloudflare Pages. + +## Usage + +```bash +dagger call deploy --source ./dist --target vercel --token $VERCEL_TOKEN +``` diff --git a/static-deploy/dagger.json b/static-deploy/dagger.json new file mode 100644 index 0000000..adaf7a1 --- /dev/null +++ b/static-deploy/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "static-deploy", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/static-deploy/main.go b/static-deploy/main.go new file mode 100644 index 0000000..1e4eb8f --- /dev/null +++ b/static-deploy/main.go @@ -0,0 +1,193 @@ +// Package main implements the IntegraCI static-deploy Dagger module. +// +// One-stop deployment for static / SPA / Jamstack sites: +// - Vercel (vercel deploy) +// - Netlify (netlify-cli deploy) +// - AWS S3 + CloudFront invalidation +// - Cloudflare Pages (wrangler) +// +// Each provider returns a normalised StaticResult so the IntegraCI +// StaticDeployWorkflow + Backstage UI render uniform output. +package main + +import ( + "context" + "dagger/static-deploy/internal/dagger" + "fmt" + "strings" +) + +type StaticDeploy struct{} + +type StaticResult struct { + Provider string `json:"provider"` + Site string `json:"site"` + URL string `json:"url,omitempty"` + Output string `json:"output,omitempty"` + Success bool `json:"success"` +} + +// Vercel deploys the built `dist` (or whatever output dir) to Vercel. +func (m *StaticDeploy) Vercel( + ctx context.Context, + source *dagger.Directory, + siteName string, + vercelToken *dagger.Secret, + // +optional + // +default="." + dir string, + // +optional + // +default=true + prod bool, +) (*StaticResult, error) { + prodFlag := "" + if prod { + prodFlag = "--prod" + } + c := dag.Container(). + From("node:20-slim"). + WithMountedDirectory("/src", source). + WithSecretVariable("VERCEL_TOKEN", vercelToken). + WithExec([]string{"sh", "-c", "npm install -g vercel@latest >/dev/null 2>&1"}). + WithExec([]string{"sh", "-c", fmt.Sprintf( + "cd /src/%s && vercel deploy %s --token=$VERCEL_TOKEN --yes --name %s || true", + dir, prodFlag, siteName, + )}) + out, _ := c.Stdout(ctx) + url := "" + for _, line := range strings.Split(out, "\n") { + if strings.HasPrefix(strings.TrimSpace(line), "https://") { + url = strings.TrimSpace(line) + break + } + } + return &StaticResult{ + Provider: "vercel", + Site: siteName, + URL: url, + Output: out, + Success: url != "", + }, nil +} + +// Netlify deploys via netlify-cli. +func (m *StaticDeploy) Netlify( + ctx context.Context, + source *dagger.Directory, + siteID string, + netlifyToken *dagger.Secret, + // +optional + // +default="dist" + dir string, + // +optional + // +default=true + prod bool, +) (*StaticResult, error) { + prodFlag := "" + if prod { + prodFlag = "--prod" + } + c := dag.Container(). + From("node:20-slim"). + WithMountedDirectory("/src", source). + WithSecretVariable("NETLIFY_AUTH_TOKEN", netlifyToken). + WithExec([]string{"sh", "-c", "npm install -g netlify-cli@latest >/dev/null 2>&1"}). + WithExec([]string{"sh", "-c", fmt.Sprintf( + "cd /src && netlify deploy %s --dir=%s --site=%s || true", + prodFlag, dir, siteID, + )}) + out, _ := c.Stdout(ctx) + url := "" + if i := strings.Index(out, "Website URL:"); i >= 0 { + rest := out[i+len("Website URL:"):] + end := strings.IndexAny(rest, "\n ") + if end > 0 { + url = strings.TrimSpace(rest[:end]) + } + } + return &StaticResult{ + Provider: "netlify", + Site: siteID, + URL: url, + Output: out, + Success: url != "" || strings.Contains(out, "Deploy is live!"), + }, nil +} + +// S3 syncs a directory to an S3 bucket and invalidates a CloudFront dist. +func (m *StaticDeploy) S3( + ctx context.Context, + source *dagger.Directory, + bucket string, + region string, + awsAccessKey *dagger.Secret, + awsSecretKey *dagger.Secret, + // +optional + cloudfrontDistID string, + // +optional + // +default="dist" + dir string, +) (*StaticResult, error) { + c := dag.Container(). + From("amazon/aws-cli:2.17.0"). + WithMountedDirectory("/src", source). + WithSecretVariable("AWS_ACCESS_KEY_ID", awsAccessKey). + WithSecretVariable("AWS_SECRET_ACCESS_KEY", awsSecretKey). + WithEnvVariable("AWS_REGION", region). + WithExec([]string{"sh", "-c", fmt.Sprintf( + "aws s3 sync /src/%s s3://%s --delete || true", dir, bucket, + )}) + if cloudfrontDistID != "" { + c = c.WithExec([]string{"sh", "-c", fmt.Sprintf( + "aws cloudfront create-invalidation --distribution-id %s --paths '/*' || true", + cloudfrontDistID, + )}) + } + out, _ := c.Stdout(ctx) + url := fmt.Sprintf("https://%s.s3-website-%s.amazonaws.com", bucket, region) + return &StaticResult{ + Provider: "s3", + Site: bucket, + URL: url, + Output: out, + Success: !strings.Contains(strings.ToLower(out), "fatal"), + }, nil +} + +// CloudflarePages deploys via wrangler. +func (m *StaticDeploy) CloudflarePages( + ctx context.Context, + source *dagger.Directory, + projectName string, + apiToken *dagger.Secret, + accountID *dagger.Secret, + // +optional + // +default="dist" + dir string, +) (*StaticResult, error) { + c := dag.Container(). + From("node:20-slim"). + WithMountedDirectory("/src", source). + WithSecretVariable("CLOUDFLARE_API_TOKEN", apiToken). + WithSecretVariable("CLOUDFLARE_ACCOUNT_ID", accountID). + WithExec([]string{"sh", "-c", "npm install -g wrangler@latest >/dev/null 2>&1"}). + WithExec([]string{"sh", "-c", fmt.Sprintf( + "cd /src && wrangler pages deploy %s --project-name=%s || true", + dir, projectName, + )}) + out, _ := c.Stdout(ctx) + url := "" + for _, l := range strings.Split(out, "\n") { + if i := strings.Index(l, "https://"); i >= 0 { + url = strings.TrimSpace(l[i:]) + break + } + } + return &StaticResult{ + Provider: "cloudflare_pages", + Site: projectName, + URL: url, + Output: out, + Success: url != "", + }, nil +} diff --git a/vm-deploy/README.md b/vm-deploy/README.md new file mode 100644 index 0000000..5146814 --- /dev/null +++ b/vm-deploy/README.md @@ -0,0 +1,9 @@ +# IntegraCI — VM Deploy Dagger Module + +Deploy services to VMs over SSH using Pyinfra + cloud-init bootstrap. + +## Usage + +```bash +dagger call deploy --inventory ./inventory.py --deploy ./site.py --ssh-key $KEY +``` diff --git a/vm-deploy/dagger.json b/vm-deploy/dagger.json new file mode 100644 index 0000000..7e54e52 --- /dev/null +++ b/vm-deploy/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "vm-deploy", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/vm-deploy/main.go b/vm-deploy/main.go new file mode 100644 index 0000000..76faa45 --- /dev/null +++ b/vm-deploy/main.go @@ -0,0 +1,170 @@ +// Package main implements the IntegraCI vm-deploy Dagger module. +// +// Wraps Pyinfra to deploy services to VMs over SSH and a cloud-init helper +// to bootstrap fresh hosts. Designed to be invoked by IntegraCI's +// VMDeploymentWorkflow once a VMHost row reaches `active` status. +// +// Usage: +// +// dagger call deploy --inventory ./inventory.py --deploy ./site.py --ssh-key $KEY +// dagger call cloud-init-render --address 10.0.0.5 --ssh-pubkey $PUB --packages "nginx,podman" +package main + +import ( + "context" + "dagger/vm-deploy/internal/dagger" + "fmt" + "strings" +) + +// VmDeploy is the IntegraCI VM provisioning module. +type VmDeploy struct{} + +// PyinfraResult summarises a Pyinfra apply. +type PyinfraResult struct { + Hosts []string `json:"hosts"` + OperationsOK int `json:"operations_ok"` + OperationsKO int `json:"operations_ko"` + Output string `json:"output"` + Success bool `json:"success"` +} + +// CloudInitResult holds a generated cloud-init user-data document. +type CloudInitResult struct { + UserData string `json:"user_data"` + Format string `json:"format"` +} + +// pyinfraImage returns the base container with pyinfra preinstalled. +func (m *VmDeploy) pyinfraImage() *dagger.Container { + return dag.Container(). + From("python:3.12-slim"). + WithExec([]string{"sh", "-c", + "apt-get update && apt-get install -y --no-install-recommends openssh-client git ca-certificates && rm -rf /var/lib/apt/lists/*", + }). + WithExec([]string{"pip", "install", "--no-cache-dir", "pyinfra==3.5"}) +} + +// Deploy applies a Pyinfra deploy module against the given inventory. +// +// `inventory` may be a Python file or a comma-separated host list (handled by +// passing it as the @hosts CLI form). +func (m *VmDeploy) Deploy( + ctx context.Context, + // Pyinfra inventory file (Python module). Either this or addresses required. + // +optional + inventory *dagger.File, + // Comma-separated list of host addresses (alternative to inventory). + // +optional + addresses string, + // Pyinfra deploy script (Python). + deploy *dagger.File, + // Private SSH key as Dagger secret. + sshKey *dagger.Secret, + // SSH user. + // +optional + // +default="ubuntu" + sshUser string, + // Extra pyinfra args (e.g. --limit ip=…). + // +optional + extraArgs string, +) (*PyinfraResult, error) { + if inventory == nil && addresses == "" { + return nil, fmt.Errorf("either inventory or addresses must be provided") + } + + c := m.pyinfraImage(). + WithMountedFile("/work/deploy.py", deploy). + WithMountedSecret("/work/id_rsa", sshKey). + WithExec([]string{"sh", "-c", "chmod 600 /work/id_rsa"}) + + target := "@hosts/" + addresses + if inventory != nil { + c = c.WithMountedFile("/work/inventory.py", inventory) + target = "/work/inventory.py" + } + + cmd := strings.Join([]string{ + "cd /work && pyinfra", + "--user", sshUser, + "--key", "/work/id_rsa", + extraArgs, + target, + "/work/deploy.py", + "|| true", + }, " ") + c = c.WithExec([]string{"sh", "-c", cmd}) + out, _ := c.Stdout(ctx) + + res := &PyinfraResult{Output: out} + res.Hosts = []string{addresses} + if strings.Contains(out, "completed: ") { + res.Success = !strings.Contains(strings.ToLower(out), "error: ") + } + if strings.Contains(strings.ToLower(out), "error") { + res.OperationsKO = 1 + } else { + res.OperationsOK = 1 + res.Success = true + } + return res, nil +} + +// CloudInitRender produces a minimal cloud-init `#cloud-config` user-data +// payload that you can pass to your cloud provider when creating a fresh VM. +// +// Real provisioning still happens through your IaaS (Crossplane, Terraform, +// the cloud console). This module just builds the bootstrap script. +func (m *VmDeploy) CloudInitRender( + _ context.Context, + // Public SSH key authorised on the host + sshPubkey string, + // Comma-separated list of packages to install on first boot + // +optional + // +default="curl,git,python3,python3-pip,podman" + packages string, + // Hostname to set on the new VM + // +optional + hostname string, + // Extra raw runcmd lines (semicolon-separated) + // +optional + runcmd string, +) (*CloudInitResult, error) { + pkgs := []string{} + for _, p := range strings.Split(packages, ",") { + if p = strings.TrimSpace(p); p != "" { + pkgs = append(pkgs, " - "+p) + } + } + cmds := []string{} + for _, c := range strings.Split(runcmd, ";") { + if c = strings.TrimSpace(c); c != "" { + cmds = append(cmds, " - "+c) + } + } + body := []string{"#cloud-config"} + if hostname != "" { + body = append(body, "hostname: "+hostname) + } + body = append(body, + "package_update: true", + "package_upgrade: false", + "packages:", + ) + body = append(body, pkgs...) + body = append(body, + "users:", + " - default", + " - name: integraci", + " sudo: ALL=(ALL) NOPASSWD:ALL", + " groups: sudo", + " shell: /bin/bash", + " ssh_authorized_keys:", + " - "+sshPubkey, + ) + if len(cmds) > 0 { + body = append(body, "runcmd:") + body = append(body, cmds...) + } + return &CloudInitResult{UserData: strings.Join(body, "\n") + "\n", Format: "cloud-config"}, nil +} diff --git a/windows-deploy/README.md b/windows-deploy/README.md new file mode 100644 index 0000000..39290da --- /dev/null +++ b/windows-deploy/README.md @@ -0,0 +1,30 @@ +# IntegraCI — Windows Deploy Dagger Module + +Deploy to **Windows Server over WinRM** by running a PowerShell script on the +target host — the Windows analogue of `vm-deploy` (Pyinfra/SSH for Linux). +Covers the "Deploy Windows Server (WinRM/PowerShell → IIS / Windows Service)" +delivery branch. + +## Usage + +```bash +dagger call deploy \ + --address 10.0.0.9 \ + --script ./deploy.ps1 \ + --username deployer \ + --password env://WINRM_PASS + +# plain HTTP (5985) instead of HTTPS (5986) +dagger call deploy --address host --script ./deploy.ps1 \ + --username u --password env://P --use-https=false +``` + +The PowerShell `--script` runs on the host: fetch/copy the artifact, deploy to +IIS (`Import-Module WebAdministration`), or install/restart a Windows Service +(`New-Service` / `Restart-Service`). The remote status code drives success. + +## Wiring + +Selected via `deploy_target=windows` (`_DEPLOY_TARGET_MAP` → `windows-deploy`); +the generic CI deploy step renders the call. Uses `pywinrm` inside a container; +no vendor SDK is embedded in the platform. diff --git a/windows-deploy/dagger.json b/windows-deploy/dagger.json new file mode 100644 index 0000000..31d0d30 --- /dev/null +++ b/windows-deploy/dagger.json @@ -0,0 +1,11 @@ +{ + "name": "windows-deploy", + "engineVersion": "v0.21.7", + "sdk": { + "source": "go" + }, + "source": ".", + "include": [ + "./main.go" + ] +} diff --git a/windows-deploy/main.go b/windows-deploy/main.go new file mode 100644 index 0000000..3267d0a --- /dev/null +++ b/windows-deploy/main.go @@ -0,0 +1,134 @@ +// Package main implements the IntegraCI windows-deploy Dagger module. +// +// Deploys to Windows Server over WinRM by running a PowerShell script on the +// target host — the Windows analogue of vm-deploy (which uses Pyinfra/SSH for +// Linux). Covers the "Deploy Windows Server (WinRM/PowerShell -> IIS / Windows +// Service)" branch of the delivery flow. Uses pywinrm inside a container; no +// vendor SDK is embedded in the platform. +// +// Usage: +// +// dagger call deploy --address 10.0.0.9 --script ./deploy.ps1 --username deployer --password env://WINRM_PASS +// dagger call deploy --address host --script ./deploy.ps1 --username u --password env://P --port 5985 --use-https=false +package main + +import ( + "context" + "dagger/windows-deploy/internal/dagger" + "fmt" + "strings" +) + +// WindowsDeploy is the IntegraCI Windows (WinRM/PowerShell) deploy module. +type WindowsDeploy struct{} + +// WinRMResult summarises a PowerShell-over-WinRM run. +type WinRMResult struct { + Host string `json:"host"` + StatusCode int `json:"status_code"` + Output string `json:"output"` + Success bool `json:"success"` +} + +// runner returns a python:3.12-slim container with pywinrm installed. +func (m *WindowsDeploy) runner() *dagger.Container { + return dag.Container(). + From("python:3.12-slim"). + WithExec([]string{"pip", "install", "--no-cache-dir", "pywinrm==0.5.0"}) +} + +// The wrapper connects to the host over WinRM and runs the mounted PowerShell +// script, echoing stdout/stderr and exiting with the remote status code. +const winrmWrapper = ` +import os, sys, winrm +host = os.environ["WINRM_HOST"] +scheme = "https" if os.environ.get("WINRM_HTTPS", "true").lower() != "false" else "http" +port = os.environ.get("WINRM_PORT", "5986" if scheme == "https" else "5985") +endpoint = f"{scheme}://{host}:{port}/wsman" +with open("/work/pass") as f: + password = f.read().strip() +with open("/work/deploy.ps1") as f: + script = f.read() +session = winrm.Session( + endpoint, + auth=(os.environ["WINRM_USER"], password), + transport=os.environ.get("WINRM_TRANSPORT", "ntlm"), + server_cert_validation="ignore", +) +r = session.run_ps(script) +sys.stdout.write(r.std_out.decode("utf-8", "replace")) +sys.stderr.write(r.std_err.decode("utf-8", "replace")) +sys.exit(r.status_code) +` + +// Deploy runs a PowerShell deploy script on a Windows host over WinRM. +func (m *WindowsDeploy) Deploy( + ctx context.Context, + // Target Windows host (IP or DNS name). + address string, + // PowerShell deploy script to run on the host (copy artifact, deploy to + // IIS / register a Windows Service, etc.). + script *dagger.File, + // WinRM username. + username string, + // WinRM password as a Dagger secret. + password *dagger.Secret, + // WinRM port (default 5986 for HTTPS, 5985 for HTTP). + // +optional + port string, + // Use HTTPS WinRM (recommended). Set false for plain HTTP (5985). + // +optional + // +default=true + useHTTPS bool, + // WinRM transport: ntlm (default), kerberos, basic, credssp. + // +optional + // +default="ntlm" + transport string, +) (*WinRMResult, error) { + if address == "" { + return nil, fmt.Errorf("address is required") + } + scheme := "true" + if !useHTTPS { + scheme = "false" + } + c := m.runner(). + WithMountedFile("/work/deploy.ps1", script). + WithMountedSecret("/work/pass", password). + WithEnvVariable("WINRM_HOST", address). + WithEnvVariable("WINRM_USER", username). + WithEnvVariable("WINRM_HTTPS", scheme). + WithEnvVariable("WINRM_TRANSPORT", transport). + WithNewFile("/work/run.py", winrmWrapper) + if port != "" { + c = c.WithEnvVariable("WINRM_PORT", port) + } + // Swallow the non-zero exit so we can surface status/Output ourselves. + c = c.WithExec([]string{"sh", "-c", "python /work/run.py; echo \"__RC__=$?\""}) + out, _ := c.Stdout(ctx) + + result := &WinRMResult{Host: address, Output: out} + // The wrapper's exit code is the remote PowerShell status; 0 = success. + if marker := lastRC(out); marker == 0 { + result.Success = true + } else { + result.StatusCode = marker + } + return result, nil +} + +// lastRC parses the trailing "__RC__=N" marker the deploy step appends. +func lastRC(out string) int { + idx := strings.LastIndex(out, "__RC__=") + if idx < 0 { + return -1 + } + rc := 0 + for _, r := range out[idx+len("__RC__="):] { + if r < '0' || r > '9' { + break + } + rc = rc*10 + int(r-'0') + } + return rc +}