721 lines
31 KiB
Go
721 lines
31 KiB
Go
// Package main implements the IntegraCI mobile-flutter Dagger module.
|
|
//
|
|
// Flutter is not "Android with extra steps": the toolchain owns the Gradle
|
|
// invocation, the artefact paths differ from a native project
|
|
// (`build/app/outputs/flutter-apk/…` rather than `app/build/outputs/apk/…`),
|
|
// and `flutter test` is a Dart runner, not a Gradle task. A Flutter repo handed
|
|
// the native Android module is given a Gradle project it does not have at its
|
|
// root — which is why this is a module of its own rather than a flag on that
|
|
// one.
|
|
//
|
|
// Usage:
|
|
//
|
|
// dagger call build --source . export --path ./mobile-out
|
|
// dagger call test --source .
|
|
// dagger call sign --artifact ./mobile-out/app.aab --keystore file:ks.jks … export --path signed.aab
|
|
// dagger call publish-raw --artifact ./mobile-out/app.aab --url http://nexus:8081 --repository raw-hosted …
|
|
//
|
|
// Every exec here is allowed to FAIL. See the sibling mobile-android module for
|
|
// why that sentence needs writing down: both modules used to end every command
|
|
// in `|| true` and infer success by grepping stdout, which cannot fail.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"dagger/mobile-flutter/internal/dagger"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
// MobileFlutter is the IntegraCI Flutter pipeline module.
|
|
type MobileFlutter struct{}
|
|
|
|
// FlutterBuildMetadata is what the build could learn about its own artefact.
|
|
type FlutterBuildMetadata struct {
|
|
ApplicationID string `json:"application_id,omitempty"`
|
|
VersionName string `json:"version_name,omitempty"`
|
|
VersionCode int `json:"version_code,omitempty"`
|
|
APKName string `json:"apk_name,omitempty"`
|
|
AABName string `json:"aab_name,omitempty"`
|
|
}
|
|
|
|
// FlutterTestResult summarises a `flutter test` run.
|
|
type FlutterTestResult struct {
|
|
Logs string `json:"logs,omitempty"`
|
|
Success bool `json:"success"`
|
|
}
|
|
|
|
func execDetail(err error) string {
|
|
var exec *dagger.ExecError
|
|
if !errors.As(err, &exec) {
|
|
return err.Error()
|
|
}
|
|
out := strings.TrimSpace(exec.Stderr)
|
|
if out == "" {
|
|
out = strings.TrimSpace(exec.Stdout)
|
|
}
|
|
const maxDetail = 4000
|
|
if len(out) > maxDetail {
|
|
out = "…" + out[len(out)-maxDetail:]
|
|
}
|
|
if out == "" {
|
|
return err.Error()
|
|
}
|
|
return fmt.Sprintf("exit code %d\n%s", exec.ExitCode, out)
|
|
}
|
|
|
|
// flutterImage returns a container with the Flutter SDK + Android SDK.
|
|
//
|
|
// `flutterVersion` is a REQUIRED-ish parameter with a conservative default
|
|
// rather than "latest": a Flutter major upgrade changes the Dart language
|
|
// version, and one of the applications this platform onboards is pinned to
|
|
// `sdk: ">=2.15.1 <3.0.0"` — it cannot build on a modern channel at all. The
|
|
// version a repo needs is a property of that repo.
|
|
// signerImage is the SMALLEST image that can sign an artefact: a JDK (for
|
|
// jarsigner) plus Android build-tools (for apksigner).
|
|
//
|
|
// WHY NOT flutterImage. Sign used to reuse the build image, which downloads the
|
|
// entire Flutter SDK — **661 MB compressed** (measured 2026-09-06) — plus the
|
|
// Android compile platform. Signing invokes neither `flutter` nor anything from
|
|
// a platform: it reads a finished .apk/.aab. And the managed Jenkins agent runs
|
|
// the engine on an EmptyDir with `podRetention: Never`, so no cache volume
|
|
// survives the build and that download is paid EVERY time.
|
|
func (m *MobileFlutter) signerImage(jdkVersion, buildTools string) *dagger.Container {
|
|
if jdkVersion == "" {
|
|
jdkVersion = "17"
|
|
}
|
|
if buildTools == "" {
|
|
buildTools = defaultBuildTools
|
|
}
|
|
tools, toolsSlug := buildToolsList(buildTools)
|
|
pkgs := ""
|
|
for _, v := range tools {
|
|
pkgs += " 'build-tools;" + v + "'"
|
|
}
|
|
return dag.Container().
|
|
From(jdkImage(jdkVersion)).
|
|
WithExec([]string{"sh", "-c", "apt-get update && apt-get install -y --no-install-recommends zip unzip wget && rm -rf /var/lib/apt/lists/*"}).
|
|
WithEnvVariable("ANDROID_HOME", "/opt/android-sdk").
|
|
WithEnvVariable("ANDROID_SDK_ROOT", "/opt/android-sdk").
|
|
WithMountedCache("/opt/android-sdk", dag.CacheVolume("android-buildtools-"+toolsSlug)).
|
|
WithExec([]string{"sh", "-c", strings.Join([]string{
|
|
"set -eu",
|
|
"if [ ! -x \"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager\" ]; then",
|
|
" mkdir -p \"$ANDROID_HOME/cmdline-tools\"",
|
|
" cd \"$ANDROID_HOME/cmdline-tools\"",
|
|
" wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip -O cli.zip",
|
|
" unzip -q cli.zip",
|
|
" rm -rf latest && mv cmdline-tools latest",
|
|
" rm cli.zip",
|
|
"fi",
|
|
}, "\n")}).
|
|
WithEnvVariable("PATH", "/opt/android-sdk/cmdline-tools/latest/bin:/opt/android-sdk/build-tools/"+tools[0]+":${PATH}", dagger.ContainerWithEnvVariableOpts{Expand: true}).
|
|
WithExec([]string{"sh", "-c", strings.Join([]string{
|
|
"set -eu",
|
|
"yes | sdkmanager --licenses > /dev/null 2>&1 || true",
|
|
"sdkmanager" + pkgs,
|
|
}, "\n")})
|
|
}
|
|
|
|
// defaultJDKImage is pinned BY DIGEST, not by tag, and that is an air-gap
|
|
// requirement rather than a style preference.
|
|
//
|
|
// Measured 2026-09-07: with the engine's network cut but its content store warm
|
|
// from a previous build, `From("eclipse-temurin:17-jdk")` still failed::
|
|
//
|
|
// failed to resolve image "docker.io/library/eclipse-temurin:17-jdk":
|
|
// Head "https://registry-1.docker.io/v2/library/eclipse-temurin/manifests/17-jdk":
|
|
// dial tcp: lookup registry-1.docker.io: i/o timeout
|
|
//
|
|
// A TAG is mutable, so BuildKit must ask the registry which digest it points at
|
|
// today -- every build, even when the bytes are already local. A DIGEST is the
|
|
// content address: it resolves from the local store and needs no registry.
|
|
//
|
|
// The build therefore could not even START on an air-gapped agent, before any
|
|
// SDK or dependency question arose. Pinning also removes a reproducibility hole
|
|
// that has nothing to do with air-gap: a tag can move between two builds of the
|
|
// same commit.
|
|
//
|
|
// To move to a newer JDK image: `docker pull eclipse-temurin:<tag>` then
|
|
// `docker inspect --format '{{index .RepoDigests 0}}'`. This is the multi-arch
|
|
// manifest-list digest, so it stays correct on any platform.
|
|
const defaultJDKImage = "eclipse-temurin@sha256:a27c79d44326d5f689668df5fedfee487652066d2a91e172747056cc7fbee6fc"
|
|
|
|
// defaultJDKVersion is the JDK the digest above actually contains. Kept beside
|
|
// it so the two cannot drift silently: a caller asking for a different JDK gets
|
|
// the mutable tag and, with it, the registry round-trip described above.
|
|
const defaultJDKVersion = "17"
|
|
|
|
// jdkImage returns the digest-pinned base for the default JDK and a plain tag
|
|
// for anything else. A caller pinning a different JDK accepts the registry
|
|
// round-trip that comes with a mutable reference -- see defaultJDKImage.
|
|
func jdkImage(jdkVersion string) string {
|
|
if jdkVersion == "" || jdkVersion == defaultJDKVersion {
|
|
return defaultJDKImage
|
|
}
|
|
return fmt.Sprintf("eclipse-temurin:%s-jdk", jdkVersion)
|
|
}
|
|
|
|
// defaultBuildTools is a LIST, and the second entry is the point of it.
|
|
//
|
|
// 34.0.0 is what this module's own tooling uses (`aapt2` in the collect step,
|
|
// `apksigner` in Sign). 33.0.1 is what the Android Gradle plugin pinned by
|
|
// Flutter 3.24.5's project template (AGP 8.1.0) asks for while the build runs.
|
|
// Installing only the first is what made a real build reach out to
|
|
// dl.google.com twenty minutes in -- fine on this box, fatal on an air-gapped
|
|
// agent. Both are small (~60MB each) next to the SDKs already being installed.
|
|
//
|
|
// A project on a different AGP will want a different one; that is why this is a
|
|
// parameter rather than a constant, and why `android.builder.sdkDownload=false`
|
|
// is set as well: the build then FAILS naming the package instead of fetching
|
|
// it, so the answer arrives in one line rather than after an air-gapped
|
|
// deployment fails in production.
|
|
const defaultBuildTools = "34.0.0,33.0.1"
|
|
|
|
// buildToolsList splits the comma-separated --build-tools into the versions to
|
|
// install, plus a slug safe to use in a cache-volume key.
|
|
//
|
|
// A LIST, not one version, because the project decides which one Gradle asks
|
|
// for and the module cannot see that decision. AGP picks a default from its own
|
|
// version -- AGP 8.1.0, which Flutter 3.24.5's template pins, wants 33.0.1 --
|
|
// and when the requested package is missing the Android Gradle plugin
|
|
// DOWNLOADS it mid-build. Measured 2026-09-07 on a real Flutter release build::
|
|
//
|
|
// Checking the license for package Android SDK Build-Tools 33.0.1 ...
|
|
// Installing Android SDK Build-Tools 33.0.1 in /opt/android-sdk/build-tools/33.0.1
|
|
//
|
|
// That is a silent network dependency in the middle of the longest stage, and
|
|
// on an air-gapped agent it is a build that fails after twenty minutes with a
|
|
// message about a licence. Listing the versions makes the toolchain explicit;
|
|
// `android.builder.sdkDownload=false` (written into GRADLE_USER_HOME by Build)
|
|
// makes a missing one fail
|
|
// immediately and by name instead of being fetched.
|
|
func buildToolsList(raw string) (versions []string, slug string) {
|
|
for _, v := range strings.Split(raw, ",") {
|
|
v = strings.TrimSpace(v)
|
|
if v == "" {
|
|
continue
|
|
}
|
|
versions = append(versions, v)
|
|
}
|
|
if len(versions) == 0 {
|
|
versions = []string{defaultBuildTools}
|
|
}
|
|
return versions, strings.Join(versions, "_")
|
|
}
|
|
|
|
func (m *MobileFlutter) flutterImage(flutterVersion, compileSdk, buildTools string) *dagger.Container {
|
|
if flutterVersion == "" {
|
|
flutterVersion = "3.24.5"
|
|
}
|
|
if compileSdk == "" {
|
|
compileSdk = "34"
|
|
}
|
|
if buildTools == "" {
|
|
buildTools = defaultBuildTools
|
|
}
|
|
tools, toolsSlug := buildToolsList(buildTools)
|
|
pkgs := ""
|
|
for _, v := range tools {
|
|
pkgs += " 'build-tools;" + v + "'"
|
|
}
|
|
return dag.Container().
|
|
From(defaultJDKImage).
|
|
WithExec([]string{"sh", "-c", "apt-get update && apt-get install -y --no-install-recommends git unzip wget curl xz-utils && rm -rf /var/lib/apt/lists/*"}).
|
|
WithEnvVariable("ANDROID_HOME", "/opt/android-sdk").
|
|
WithEnvVariable("ANDROID_SDK_ROOT", "/opt/android-sdk").
|
|
WithEnvVariable("FLUTTER_HOME", "/opt/flutter").
|
|
// Both SDKs are public and pinned, so these volumes are shared.
|
|
//
|
|
// Same two caveats as the sibling mobile-android module. (1) On the managed
|
|
// Jenkins agent this saves NOTHING: that pod runs the engine as a sidecar
|
|
// with /var/lib/dagger on an EmptyDir and podRetention Never, so every
|
|
// cache volume dies with the build. (2) On an engine where it DOES persist,
|
|
// the mount is writable while the tenant's own build runs and is keyed with
|
|
// no tenant component — "immutable" is an assumption about the contents,
|
|
// not an enforcement. The Pub/Gradle DEPENDENCY caches are opt-in per
|
|
// tenant (see cacheKey) because those can hold private packages.
|
|
WithMountedCache("/opt/android-sdk", dag.CacheVolume("android-sdk-"+compileSdk+"-"+toolsSlug)).
|
|
WithMountedCache("/opt/flutter", dag.CacheVolume("flutter-sdk-"+flutterVersion)).
|
|
WithExec([]string{"sh", "-c", strings.Join([]string{
|
|
"set -eu",
|
|
"if [ ! -x \"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager\" ]; then",
|
|
" mkdir -p \"$ANDROID_HOME/cmdline-tools\"",
|
|
" cd \"$ANDROID_HOME/cmdline-tools\"",
|
|
" wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip -O cli.zip",
|
|
" unzip -q cli.zip && rm -rf latest && mv cmdline-tools latest && rm cli.zip",
|
|
"fi",
|
|
"if [ ! -x \"$FLUTTER_HOME/bin/flutter\" ]; then",
|
|
" rm -rf \"$FLUTTER_HOME\"/*",
|
|
fmt.Sprintf(" wget -q https://storage.googleapis.com/flutter_infra_release/releases/stable/linux/flutter_linux_%s-stable.tar.xz -O /tmp/f.tar.xz", flutterVersion),
|
|
" tar -xJf /tmp/f.tar.xz -C /opt && rm /tmp/f.tar.xz",
|
|
"fi",
|
|
}, "\n")}).
|
|
// The FIRST listed version is the one on PATH: `aapt2` in the collect
|
|
// step has to resolve to something, and the extra versions exist for
|
|
// Gradle to find by path, not for us to call.
|
|
WithEnvVariable("PATH", "/opt/flutter/bin:/opt/android-sdk/cmdline-tools/latest/bin:/opt/android-sdk/platform-tools:/opt/android-sdk/build-tools/"+tools[0]+":${PATH}", dagger.ContainerWithEnvVariableOpts{Expand: true}).
|
|
WithExec([]string{"sh", "-c", strings.Join([]string{
|
|
"set -eu",
|
|
// SIGPIPE (141) on success — see the sibling module. This is the only
|
|
// tolerated non-zero status in this file.
|
|
"yes | sdkmanager --licenses > /dev/null 2>&1 || true",
|
|
fmt.Sprintf("sdkmanager 'platform-tools' 'platforms;android-%s'%s", compileSdk, pkgs),
|
|
// Flutter refuses to run from a directory owned by another user.
|
|
"git config --global --add safe.directory /opt/flutter",
|
|
"flutter --version",
|
|
}, "\n")})
|
|
}
|
|
|
|
// Build runs `flutter build apk` and `flutter build appbundle`, returning a
|
|
// directory with the artefacts under stable names plus `metadata.json`.
|
|
func (m *MobileFlutter) Build(
|
|
ctx context.Context,
|
|
// +defaultPath="."
|
|
source *dagger.Directory,
|
|
// +optional
|
|
// +default="release"
|
|
buildMode string,
|
|
// Also build the .aab
|
|
// +optional
|
|
// +default=true
|
|
bundle bool,
|
|
// Flutter SDK version — a property of the REPO, not of this module.
|
|
// +optional
|
|
// +default="3.24.5"
|
|
flutterVersion string,
|
|
// +optional
|
|
// +default="34"
|
|
compileSdk string,
|
|
// +optional
|
|
// Android Build-Tools to install: a COMMA-SEPARATED LIST.
|
|
//
|
|
// The default carries two because the Android Gradle plugin picks its
|
|
// own version at build time and downloads it if absent -- measured
|
|
// 2026-09-07: AGP 8.1.0 (what Flutter 3.24.5 pins) pulled 33.0.1 from
|
|
// dl.google.com even though 34.0.0 was installed. Pre-installing both
|
|
// removes that network call; `android.builder.sdkDownload=false` turns
|
|
// any remaining one into an immediate, named failure.
|
|
// +default="34.0.0,33.0.1"
|
|
buildTools string,
|
|
// Per-tenant Pub/Gradle dependency cache. Empty ⇒ no dependency cache.
|
|
// +optional
|
|
cacheKey string,
|
|
// Extra flags for the flutter build invocation.
|
|
// +optional
|
|
buildArgs string,
|
|
) (*dagger.Directory, error) {
|
|
mode := strings.ToLower(strings.TrimSpace(buildMode))
|
|
if mode == "" {
|
|
mode = "release"
|
|
}
|
|
|
|
// EVALUATE THE TOOLCHAIN BEFORE THE BUILD, so a toolchain failure says so.
|
|
//
|
|
// Dagger is lazy: without this, every failure in the whole chain surfaces
|
|
// from the build exec below and is wrapped as "flutter build (release)
|
|
// failed". Measured 2026-09-07 with --build-tools=99.0.0, which cannot
|
|
// install: the operator was told the Flutter BUILD failed and handed
|
|
// sdkmanager's "Warning: Failed to find package 'build-tools;99.0.0'" --
|
|
// the right clue attached to the wrong stage.
|
|
//
|
|
// (sdkmanager exits 1 for a package that does not exist, and installs
|
|
// NOTHING when a bad version is listed alongside a good one -- both
|
|
// measured -- so the failure itself is already reliable. What was missing
|
|
// was saying which stage produced it.)
|
|
toolchain := m.flutterImage(flutterVersion, compileSdk, buildTools)
|
|
if _, err := toolchain.Sync(ctx); err != nil {
|
|
return nil, fmt.Errorf("preparing the Flutter/Android toolchain failed: %s", execDetail(err))
|
|
}
|
|
c := toolchain.WithMountedDirectory("/src", source)
|
|
|
|
// GRADLE_USER_HOME is set whether or not a dependency cache is shared,
|
|
// because it is also where the air-gap switch below has to live -- Gradle
|
|
// reads `$GRADLE_USER_HOME/gradle.properties` for every build, and the
|
|
// module must not write into the tenant's checked-out repository to set a
|
|
// property.
|
|
c = c.WithEnvVariable("GRADLE_USER_HOME", "/gradle-home").
|
|
WithEnvVariable("PUB_CACHE", "/pub-cache")
|
|
if strings.TrimSpace(cacheKey) != "" {
|
|
// SHARED and persistent: reuse across this tenant's builds. Keyed with
|
|
// the tenant component precisely because these hold resolved
|
|
// dependencies, which can be private packages.
|
|
c = c.WithMountedCache("/pub-cache", dag.CacheVolume("pub-cache-"+cacheKey)).
|
|
WithMountedCache("/gradle-home", dag.CacheVolume("gradle-deps-"+cacheKey))
|
|
}
|
|
|
|
// STOP GRADLE FETCHING ANDROID PACKAGES MID-BUILD.
|
|
//
|
|
// Without this the Android Gradle plugin installs whatever SDK package it
|
|
// finds missing, from dl.google.com, in the middle of the build. Measured
|
|
// 2026-09-07: a release build downloaded Build-Tools 33.0.1 even though
|
|
// 34.0.0 had been installed explicitly. Three things are wrong with that,
|
|
// in ascending order: the toolchain is no longer the one the module
|
|
// declared; the build silently depends on the public internet; and on an
|
|
// air-gapped agent it fails after twenty minutes with a message about a
|
|
// licence rather than about a missing package.
|
|
//
|
|
// `false` makes it fail immediately and say which package it wanted, which
|
|
// is then added to --build-tools. Written into GRADLE_USER_HOME rather than
|
|
// the project so nothing in the tenant's repository is modified.
|
|
c = c.WithExec([]string{"sh", "-c", strings.Join([]string{
|
|
"set -eu",
|
|
"mkdir -p \"$GRADLE_USER_HOME\"",
|
|
"grep -q '^android.builder.sdkDownload=' \"$GRADLE_USER_HOME/gradle.properties\" 2>/dev/null ||",
|
|
" echo 'android.builder.sdkDownload=false' >> \"$GRADLE_USER_HOME/gradle.properties\"",
|
|
}, "\n")})
|
|
|
|
steps := []string{
|
|
"set -eu",
|
|
// DELETE THE PREVIOUS BUILD'S OUTPUT FIRST.
|
|
//
|
|
// The source arrives from the agent's WORKSPACE, and Jenkins reuses
|
|
// workspaces between builds -- so `build/` from the previous commit is
|
|
// uploaded and mounted along with the code. The collect step then globs
|
|
// for an .apk/.aab and takes the FIRST match (`-print -quit`), which can
|
|
// be last week's artefact. A stale artefact that gets signed, reported
|
|
// and published is worse than a failed build: everything downstream
|
|
// looks correct.
|
|
//
|
|
// Scoped to exactly what collect globs over, so nothing else in the
|
|
// tenant's checkout is touched. The mount is the container's view; the
|
|
// agent's workspace on disk is not modified.
|
|
"rm -rf /src/build",
|
|
"cd /src",
|
|
"flutter pub get",
|
|
fmt.Sprintf("flutter build apk --%s %s", mode, buildArgs),
|
|
}
|
|
if bundle {
|
|
steps = append(steps, fmt.Sprintf("flutter build appbundle --%s %s", mode, buildArgs))
|
|
}
|
|
build := c.WithExec([]string{"sh", "-c", strings.Join(steps, "\n")})
|
|
if _, err := build.Stdout(ctx); err != nil {
|
|
return nil, fmt.Errorf("flutter build (%s) failed: %s", mode, execDetail(err))
|
|
}
|
|
|
|
collect := `set -eu
|
|
# /out is EMPTIED first, not just created.
|
|
#
|
|
# The build exec above ran the project's own Gradle/Flutter scripts as root in
|
|
# this same container, so anything it chose to write to /out is still here and
|
|
# would be exported as if this module had produced it. That matters because the
|
|
# pipeline decides what to publish by FILENAME: a repo that plants
|
|
# /out/signed-app.aab during its build would get an artefact no Sign stage ever
|
|
# touched uploaded to the tenant's registry, and reported as signed.
|
|
#
|
|
# Emptying the directory makes the export contain exactly what the lines below
|
|
# put there. It costs nothing: /out is this module's own output staging area,
|
|
# never a mount and never the caller's directory.
|
|
rm -rf /out
|
|
mkdir -p /out
|
|
apk="$(find /src/build -path '*/flutter-apk/*.apk' -print -quit 2>/dev/null || true)"
|
|
[ -n "$apk" ] || apk="$(find /src/build -path '*/outputs/apk/*/*.apk' -print -quit 2>/dev/null || true)"
|
|
aab="$(find /src/build -path '*/outputs/bundle/*/*.aab' -print -quit 2>/dev/null || true)"
|
|
if [ -z "$apk" ] && [ -z "$aab" ]; then
|
|
echo "no .apk or .aab under /src/build after a successful flutter build" >&2
|
|
exit 1
|
|
fi
|
|
apk_name=""; aab_name=""
|
|
if [ -n "$apk" ]; then cp "$apk" /out/app.apk; apk_name="$(basename "$apk" | tr -cd 'A-Za-z0-9._ -')"; fi
|
|
if [ -n "$aab" ]; then cp "$aab" /out/app.aab; aab_name="$(basename "$aab" | tr -cd 'A-Za-z0-9._ -')"; fi
|
|
app_id=""; ver_name=""; ver_code=""
|
|
if [ -f /out/app.apk ]; then
|
|
badging="$(aapt2 dump badging /out/app.apk 2>/dev/null || true)"
|
|
app_id="$(printf '%s' "$badging" | sed -n "s/^package: name='\([^']*\)'.*/\1/p" | head -1 | tr -cd 'A-Za-z0-9._-')"
|
|
ver_code="$(printf '%s' "$badging" | sed -n "s/^package:.*versionCode='\([^']*\)'.*/\1/p" | head -1 | tr -cd '0-9')"
|
|
# SANITISED: version_name becomes a PATH SEGMENT in the upload and a VALUE in
|
|
# the report JSON. ../../otherteam/prod/9.9 would land the artefact on another
|
|
# team's path (curl normalises dot segments, it does not reject them), and a
|
|
# quote would rewrite the report body. The charset excludes slash,
|
|
# double-quote and backslash.
|
|
ver_name="$(printf '%s' "$badging" | sed -n "s/^package:.*versionName='\([^']*\)'.*/\1/p" | head -1 | tr -cd 'A-Za-z0-9._-')"
|
|
fi
|
|
: "${ver_code:=0}"
|
|
cat > /out/metadata.json <<JSON
|
|
{"application_id":"$app_id","version_name":"$ver_name","version_code":$ver_code,"apk_name":"$apk_name","aab_name":"$aab_name"}
|
|
JSON
|
|
cat /out/metadata.json
|
|
`
|
|
out := build.WithExec([]string{"sh", "-c", collect})
|
|
if _, err := out.Stdout(ctx); err != nil {
|
|
return nil, fmt.Errorf("collecting flutter artifacts: %s", execDetail(err))
|
|
}
|
|
return out.Directory("/out"), nil
|
|
}
|
|
|
|
// Metadata re-reads the metadata a Build produced.
|
|
func (m *MobileFlutter) Metadata(
|
|
ctx context.Context,
|
|
artifacts *dagger.Directory,
|
|
) (*FlutterBuildMetadata, error) {
|
|
raw, err := artifacts.File("metadata.json").Contents(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("reading metadata.json: %w", err)
|
|
}
|
|
meta := &FlutterBuildMetadata{}
|
|
if err := json.Unmarshal([]byte(raw), meta); err != nil {
|
|
return nil, fmt.Errorf("parsing metadata.json (%q): %w", raw, err)
|
|
}
|
|
return meta, nil
|
|
}
|
|
|
|
// Test runs `flutter test` and fails when the suite fails.
|
|
func (m *MobileFlutter) Test(
|
|
ctx context.Context,
|
|
// +defaultPath="."
|
|
source *dagger.Directory,
|
|
// +optional
|
|
// +default="3.24.5"
|
|
flutterVersion string,
|
|
// +optional
|
|
// +default="34"
|
|
compileSdk string,
|
|
// +optional
|
|
// +default="34.0.0"
|
|
buildTools string,
|
|
// +optional
|
|
cacheKey string,
|
|
) (*FlutterTestResult, error) {
|
|
c := m.flutterImage(flutterVersion, compileSdk, buildTools).WithMountedDirectory("/src", source)
|
|
if strings.TrimSpace(cacheKey) != "" {
|
|
c = c.WithEnvVariable("PUB_CACHE", "/pub-cache").
|
|
WithMountedCache("/pub-cache", dag.CacheVolume("pub-cache-"+cacheKey))
|
|
}
|
|
logs, err := c.WithExec([]string{"sh", "-c", strings.Join([]string{
|
|
"set -eu",
|
|
"cd /src",
|
|
"flutter pub get",
|
|
"flutter analyze",
|
|
"flutter test",
|
|
}, "\n")}).Stdout(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("flutter analyze/test failed: %s", execDetail(err))
|
|
}
|
|
return &FlutterTestResult{Logs: logs, Success: true}, nil
|
|
}
|
|
|
|
// Sign signs the built artefact and returns the SIGNED FILE.
|
|
//
|
|
// An .aab goes through jarsigner and an .apk through apksigner: apksigner only
|
|
// understands the APK container and rejects a bundle outright.
|
|
func (m *MobileFlutter) Sign(
|
|
ctx context.Context,
|
|
artifact *dagger.File,
|
|
keystore *dagger.Secret,
|
|
keystorePassword *dagger.Secret,
|
|
keyAlias string,
|
|
keyPassword *dagger.Secret,
|
|
// JDK that runs jarsigner. Signing does not care which JDK built the app —
|
|
// this exists so the parameter list matches the sibling mobile-android
|
|
// module, whose Sign has carried it since it was written.
|
|
// +optional
|
|
// +default="17"
|
|
jdk string,
|
|
// +optional
|
|
// +default="34.0.0"
|
|
buildTools string,
|
|
) (*dagger.File, error) {
|
|
name, err := artifact.Name(ctx)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("reading artifact name: %w", err)
|
|
}
|
|
// IN and OUT are DIFFERENT PATHS — see the same note in mobile-android's
|
|
// Sign. Both signers default to signing IN PLACE, and the artifact arrives
|
|
// on its own `WithMountedFile` mount, so an in-place sign dies renaming
|
|
// across that mount point (MEASURED: `attempt to rename /work/app.aab to
|
|
// /work/app.aab.orig failed`) — a failure that has nothing to do with the
|
|
// key and only appears in a real run.
|
|
base := "app.apk"
|
|
isBundle := strings.HasSuffix(strings.ToLower(name), ".aab")
|
|
if isBundle {
|
|
base = "app.aab"
|
|
}
|
|
in := "/work/in/" + base
|
|
out := "/work/out/" + base
|
|
|
|
signCmd := strings.Join([]string{
|
|
"apksigner sign --ks /work/keystore.jks",
|
|
"--ks-pass env:KEYSTORE_PASSWORD",
|
|
"--key-pass env:KEY_PASSWORD",
|
|
"--ks-key-alias \"$KEY_ALIAS\"",
|
|
"--out", out,
|
|
in,
|
|
}, " ")
|
|
verifyCmd := fmt.Sprintf("apksigner verify --print-certs %s", out)
|
|
// STRIP FIRST, then sign. Empty for an APK; the whole point for a bundle.
|
|
prepare := "true"
|
|
if isBundle {
|
|
// A .aab is signed as a JAR, and `jarsigner -signedjar` ADDS a signer;
|
|
// it does not replace one. Gradle already signed this bundle -- with the
|
|
// ANDROID DEBUG KEY when the project declares no signingConfig -- so
|
|
// signing on top left BOTH signers in place. Measured 2026-09-07 on a
|
|
// bundle this module built and then signed::
|
|
//
|
|
// META-INF/RELEASE-.SF <- ours
|
|
// META-INF/RELEASE-.RSA
|
|
// META-INF/ANDROIDD.SF <- Gradle's debug key, still there
|
|
// META-INF/ANDROIDD.RSA
|
|
//
|
|
// and `jarsigner -verify -certs` duly reported both
|
|
// "CN=IntegraCI Release Proof" and "C=US, O=Android, CN=Android Debug".
|
|
// A release bundle that still carries a debug signature is not a release
|
|
// bundle: the debug key is public, so a second valid signer means the
|
|
// artefact's provenance is not what the pipeline claims.
|
|
//
|
|
// The APK path does not need this -- apksigner rebuilds the v1 block and
|
|
// the debug entry is gone -- which is exactly why the defect survived:
|
|
// the two formats behave differently under the same-looking call.
|
|
//
|
|
// Stripping happens on a COPY. `zip -d` rewrites the archive in place,
|
|
// and `in` is a Dagger mount, where in-place rewrites fail the same way
|
|
// in-place signing does.
|
|
prepare = strings.Join([]string{
|
|
"mkdir -p /work/strip",
|
|
"cp " + in + " /work/strip/" + base,
|
|
"zip -q -d /work/strip/" + base + " 'META-INF/*.SF' 'META-INF/*.RSA' 'META-INF/*.DSA' 'META-INF/*.EC' >/dev/null 2>&1 || true",
|
|
}, "\n")
|
|
signCmd = strings.Join([]string{
|
|
"jarsigner -keystore /work/keystore.jks",
|
|
"-storepass:env KEYSTORE_PASSWORD",
|
|
"-keypass:env KEY_PASSWORD",
|
|
"-sigalg SHA256withRSA -digestalg SHA-256",
|
|
"-signedjar", out,
|
|
"/work/strip/" + base, "\"$KEY_ALIAS\"",
|
|
}, " ")
|
|
verifyCmd = fmt.Sprintf("jarsigner -verify -certs %s", out)
|
|
}
|
|
|
|
// TWO GATES ON THE RESULT, both inside the container that produced it.
|
|
//
|
|
// Signing that "succeeded" is not the property anyone actually wants; the
|
|
// property is that the artefact carries ONE signer and that it is not the
|
|
// debug identity. Checked here rather than left to whoever looks at the
|
|
// artefact later, because by then it has been published.
|
|
//
|
|
// The signer count is asked in the way each FORMAT answers it, which is not
|
|
// pedantry. A bundle is a JAR, so one signer means exactly one
|
|
// META-INF/*.SF. An APK is not: v2/v3 signatures live in the APK Signing
|
|
// Block, and apksigner omits the v1 (META-INF) block entirely when the
|
|
// project's minSdk is 24 or higher. Counting .SF files on an APK would
|
|
// therefore REFUSE a perfectly good modern release -- the gate would fire on
|
|
// the projects most likely to be shipping.
|
|
//
|
|
// For the APK it counts the "Signer #N certificate DN:" lines rather than
|
|
// apksigner's "Number of signers:" summary: that summary is printed only
|
|
// under --verbose, and the first version of this gate grepped for it,
|
|
// counted 0, and refused a correctly signed APK. Also measured, also only
|
|
// visible by running it.
|
|
countCmd := "apksigner verify --print-certs " + out + " 2>/dev/null | grep -c '^Signer #[0-9]* certificate DN:' || true"
|
|
expectation := "exactly one signer certificate"
|
|
if isBundle {
|
|
countCmd = "unzip -l " + out + " | awk '{print $NF}' | grep -ciE '^META-INF/.*[.]SF$' || true"
|
|
expectation = "exactly one META-INF/*.SF block"
|
|
}
|
|
assertCmd := strings.Join([]string{
|
|
"signers=\"$(" + countCmd + ")\"",
|
|
"if [ \"$signers\" != \"1\" ]; then",
|
|
" echo \"REFUSING: the signed artefact does not show " + expectation + " (got $signers).\" >&2",
|
|
" echo \"More than one means an earlier signature survived; zero means nothing signed it.\" >&2",
|
|
" exit 1",
|
|
"fi",
|
|
"if " + verifyCmd + " 2>&1 | grep -q 'CN=Android Debug'; then",
|
|
" echo \"REFUSING: the signed artefact still carries the ANDROID DEBUG identity.\" >&2",
|
|
" echo \"The debug key is public and anyone can re-sign with it, so an artefact\" >&2",
|
|
" echo \"bearing it is not release-signed no matter what else verifies.\" >&2",
|
|
" exit 1",
|
|
"fi",
|
|
}, "\n")
|
|
|
|
c := m.signerImage(jdk, buildTools).
|
|
WithMountedFile(in, artifact).
|
|
WithMountedSecret("/work/keystore.jks", keystore).
|
|
WithSecretVariable("KEYSTORE_PASSWORD", keystorePassword).
|
|
WithSecretVariable("KEY_PASSWORD", keyPassword).
|
|
WithEnvVariable("KEY_ALIAS", keyAlias).
|
|
WithExec([]string{"sh", "-c", strings.Join([]string{"set -eu", "mkdir -p /work/out", prepare, signCmd, verifyCmd, assertCmd}, "\n")})
|
|
|
|
if _, err := c.Stdout(ctx); err != nil {
|
|
return nil, fmt.Errorf("signing %s failed: %s", name, execDetail(err))
|
|
}
|
|
return c.File(out), nil
|
|
}
|
|
|
|
// PublishRaw uploads the artefact to a raw (non-OCI) repository such as Nexus.
|
|
//
|
|
// Identical in shape to the mobile-android module's: a Dagger module is its own
|
|
// deployable unit and cannot import a sibling, so the two carry the same twenty
|
|
// lines rather than a shared package that neither could resolve.
|
|
func (m *MobileFlutter) PublishRaw(
|
|
ctx context.Context,
|
|
artifact *dagger.File,
|
|
url string,
|
|
repository string,
|
|
path string,
|
|
username string,
|
|
password *dagger.Secret,
|
|
// +optional
|
|
insecure bool,
|
|
) (string, error) {
|
|
base := strings.TrimRight(strings.TrimSpace(url), "/")
|
|
repo := strings.Trim(strings.TrimSpace(repository), "/")
|
|
rel := strings.TrimLeft(strings.TrimSpace(path), "/")
|
|
if base == "" || repo == "" || rel == "" {
|
|
return "", fmt.Errorf("publish-raw needs --url, --repository and --path (got url=%q repository=%q path=%q)", url, repo, rel)
|
|
}
|
|
// A dot segment walks out of the tenant prefix. curl NORMALISES `..`, it does
|
|
// not reject it, so `<tenant>/<svc>/1.0/../../<other>/x` resolves to another
|
|
// tenant's path in a shared raw repository — and that prefix is the only
|
|
// isolation the upload has. The caller sanitises the version it builds this
|
|
// from; this refuses independently, because a module is used by more than
|
|
// the one template that ships with it.
|
|
for _, seg := range strings.Split(rel, "/") {
|
|
if seg == ".." {
|
|
return "", fmt.Errorf("publish-raw refuses a '..' segment in --path (got %q)", rel)
|
|
}
|
|
}
|
|
// The REPOSITORY name too, and for the same reason. It sits one segment
|
|
// above the tenant prefix in the URL, so `--repository=..` yields
|
|
// `<base>/repository/../<tenant>/…` which curl normalises to
|
|
// `<base>/<tenant>/…` — out of the repository namespace entirely. Unlike
|
|
// the tenant and service segments, this value is not platform-resolved: it
|
|
// comes from the caller's spec, so the module cannot assume the template
|
|
// vetted it.
|
|
if repo == "." || repo == ".." || strings.Trim(repo, ".") == "" {
|
|
return "", fmt.Errorf("publish-raw refuses a dot segment as --repository (got %q)", repository)
|
|
}
|
|
target := fmt.Sprintf("%s/repository/%s/%s", base, repo, rel)
|
|
|
|
// The URL travels as an ENVIRONMENT VARIABLE, never interpolated into the
|
|
// command string — see the sibling mobile-android module for the whole
|
|
// reasoning. Short version: `%q` leaves `$` and backticks intact, the result
|
|
// sat in a shell double-quoted position, and `path` is built from the
|
|
// artefact's own `versionName`. `"$UPLOAD_URL"` is quoted and an expansion's
|
|
// result is not re-scanned, so the value cannot become code.
|
|
script := `set -eu
|
|
if [ -n "${REG_INSECURE:-}" ]; then
|
|
curl --fail-with-body -sS --insecure -u "$REG_USER:$REG_PASS" --upload-file /work/artifact "$UPLOAD_URL"
|
|
else
|
|
curl --fail-with-body -sS -u "$REG_USER:$REG_PASS" --upload-file /work/artifact "$UPLOAD_URL"
|
|
fi
|
|
echo
|
|
echo "published: $UPLOAD_URL"`
|
|
|
|
c := dag.Container().
|
|
From("curlimages/curl:8.11.1").
|
|
WithMountedFile("/work/artifact", artifact).
|
|
WithEnvVariable("REG_USER", username).
|
|
WithEnvVariable("UPLOAD_URL", target).
|
|
WithSecretVariable("REG_PASS", password)
|
|
if insecure {
|
|
c = c.WithEnvVariable("REG_INSECURE", "1")
|
|
}
|
|
c = c.WithExec([]string{"sh", "-c", script})
|
|
|
|
if _, err := c.Stdout(ctx); err != nil {
|
|
return "", fmt.Errorf("publishing to %s failed: %s", target, execDetail(err))
|
|
}
|
|
return target, nil
|
|
}
|