// 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 }