carlos / platform Public

cli: carlos releases pull copies a release out of a console

#1389 item 1, task 3. carlos releases pull <version> --app <a> --out <dir>
reads a shipped release through the console's read doors: it streams each
artifact to a .partial file, checks its size and sha256 against the
manifest, and renames it into place; a mismatch removes the partial and
fails. manifest.json is written last with the exact bytes the console
stores, so a directory holding it holds the whole release, and a pull
refuses a directory that already has one. A directory without it (an
interrupted pull) is finished by pulling again.

Adds the two-console test fixture (release_copy_e2e_test.go) that
ship --from-release will reuse, the parity row, the CLI page entry and
the golden corpus lines for the new leaf.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f47d0d8db07f81dc4e25cf5e6abf0faadbaa6dec parent ff974ce
9 files changed, +546 −4
  • commands.go +3 −2
  • docs/parity.md +3 −2
  • docs/site/cli.md +13 −0
  • parity/cli.tsv +1 −0
  • parity/parity.tsv +1 −0
  • release_copy_e2e_test.go +105 −0
  • release_pull.go +235 −0
  • release_pull_test.go +183 −0
  • testdata/clireg-golden.jsonl +2 −0

CI cancelled — superseded by a newer push — run details

CI log
=== gate ===
go: downloading go1.26.10 (linux/arm64)
go version go1.26.10 linux/arm64
opentofu: arm64, tofu 1.13.9, aws 6.73.0, archive 2.8.1
  tofu: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/tofu_1.13.9_linux_arm64.tar.gz
  tofu: downloaded, digest verified
  aws: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-aws_6.73.0_linux_arm64.zip
  aws: downloaded, digest verified
  archive: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-archive_2.8.1_linux_arm64.zip
  archive: downloaded, digest verified
  installed in /tmp/carlos-opentofu-DGaqJp
.amadan/test-gate.sh
go: downloading github.com/aws/aws-sdk-go-v2 v1.44.0
go: downloading github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0
go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5
go: downloading github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0
go: downloading github.com/aws/smithy-go v1.28.1
go: downloading github.com/benbjohnson/litestream v0.5.14
go: downloading golang.org/x/net v0.62.0
go: downloading github.com/superfly/ltx v0.5.1
go: downloading modernc.org/sqlite v1.55.0
go: downloading golang.org/x/crypto v0.58.0
go: downloading github.com/aws/aws-sdk-go-v2/service/iam v1.58.2
go: downloading github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0
go: downloading golang.org/x/sys v0.49.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4
go: downloading github.com/aws/aws-sdk-go-v2/service/signin v1.0.4
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.18
go: downloading golang.org/x/sync v0.24.0
go: downloading github.com/prometheus/client_golang v1.17.0
go: downloading github.com/wlynxg/anet v0.0.5
go: downloading github.com/lmittmann/tint v1.1.3
go: downloading github.com/prometheus/client_model v0.5.0
go: downloading github.com/beorn7/perks v1.0.1
go: downloading github.com/cespare/xxhash/v2 v2.3.0
go: downloading github.com/prometheus/common v0.45.0
go: downloading github.com/prometheus/procfs v0.12.0
go: downloading google.golang.org/protobuf v1.36.10
go: downloading golang.org/x/text v0.43.0
go: downloading github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0
go: downloading github.com/klauspost/compress v1.20.2
go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/memory v1.11.0
go: downloading github.com/google/uuid v1.6.0
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading modernc.org/mathutil v1.7.1
go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec

amadan: job cancelled — a newer push superseded it
diff --git a/commands.go b/commands.go
index 7a3365eb2..6e893d059 100644
--- a/commands.go
+++ b/commands.go
@@ -322,8 +322,8 @@ func channelsCommand() *clireg.Node {
}
}
-// releasesCommand is `carlos releases`, moved from main's switch. Two
-// sub-verbs, `retention` and `authorize`: the `carlos version target`
+// releasesCommand is `carlos releases`, moved from main's switch. Three
+// sub-verbs, `retention`, `authorize` and `pull`: the `carlos version target`
// judgment call: flags-only verbs stay flat until a word genuinely names a
// different action, and a policy write or a signature is not a listing.
// Anything else lists. The sub-verbs skip the update hint, as channels'.
@@ -335,6 +335,7 @@ func releasesCommand() *clireg.Node {
Children: []*clireg.Node{
noHint(raw("retention", cust, runReleasesRetention)),
noHint(raw("authorize", clireg.Operator, runReleasesAuthorize)),
+ noHint(rawErr("pull", cust, runReleasesPull)),
},
DefaultLeaf: &clireg.Node{Audience: cust, Run: clireg.RawArgs(runReleases)},
DefaultOn: clireg.OnAbsent | clireg.OnFlag | clireg.OnWord,
diff --git a/docs/parity.md b/docs/parity.md
index 636c4ae54..624562a18 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -13,9 +13,9 @@ CLI rows are checked against the command registry (`parity/cli.tsv`).
| both | 48 |
| partial | 9 |
| gap | 68 |
-| cli-only | 19 |
+| cli-only | 20 |
| console-only | 18 |
-| Total | 162 |
+| Total | 163 |
## account
@@ -214,6 +214,7 @@ CLI rows are checked against the command registry (`parity/cli.tsv`).
| canary-rm | gap | `canary rm` | | [wp-instances](#wp-instances) | Deletes the canary's instance and leaves its channel. The console has no instance delete (instances-delete); its Retire is a different operation (canary-retire). |
| canary-retire | console-only | | `POST /a/{sqid}/apps/{app}/canary/retire` | | Retires the canary's channel and refuses while any host follows it. No CLI verb retires a channel: canary rm deletes the instance and leaves the channel. |
| channels | both | `channels` | `GET /a/{sqid}/apps/{app}/releases` | | |
+| releases-pull | cli-only | `releases pull` | | | Copies a shipped release out of a console and checks every file against its digests. |
| channels-resign | gap | `channels resign` | | [wp-settings](#wp-settings) | |
| pipeline | both | `pipeline show`<br>`pipeline init`<br>`pipeline set`<br>`pipeline add`<br>`pipeline remove` | `GET /a/{sqid}/apps/{app}/pipeline`<br>`POST /a/{sqid}/apps/{app}/pipeline`<br>`GET /a/{sqid}/apps/{app}/settings/{section}` | | |
| releases | both | `releases` | `GET /a/{sqid}/apps/{app}/releases`<br>`GET /a/{sqid}/apps/{app}/deployments` | | |
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 3e5a1140c..95825b5dc 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -1010,6 +1010,19 @@ disappears by policy. `--off` goes back to keeping everything.
`carlos releases authorize <app> <version>` is for operators. It shows a build's manifest and file digests and, when you type yes, signs a promotion record for exactly those bytes. Every promotion writes one; this is for a build promoted before records existed, so an instance can be pinned to it or recovered onto it on a box that does not already have it.
+#### carlos releases pull
+
+Copies a shipped release out of a console into a directory: its
+`manifest.json`, exactly as the console stores it, and every file the
+manifest names. Each file is checked against the manifest's size and sha256
+as it arrives, and a file that does not match is removed and the pull fails.
+The manifest is written last, so a directory that holds one holds the whole
+release. In CI the directory can be a build artifact handed to a later job.
+
+```sh
+carlos releases pull v12 --app shop --out ./release
+```
+
### carlos version
`carlos version` prints the build id of the binary in front of you. It is the
diff --git a/parity/cli.tsv b/parity/cli.tsv
index 20a0d650f..e9b52298b 100644
--- a/parity/cli.tsv
+++ b/parity/cli.tsv
@@ -220,6 +220,7 @@ relay status customer - - - - -
release-keygen box-local - - - - -
releases customer - - - - -
releases authorize operator - - - - -
+releases pull customer - - - - -
releases retention customer - - - - -
remove box-local - - - - -
restart customer - - - - -
diff --git a/parity/parity.tsv b/parity/parity.tsv
index 01e281fbc..9ebadbdbd 100644
--- a/parity/parity.tsv
+++ b/parity/parity.tsv
@@ -38,6 +38,7 @@ canary-list releases both canary ls GET /a/{sqid}/apps/{app}/releases
canary-rm releases gap canary rm wp-instances Deletes the canary's instance and leaves its channel. The console has no instance delete (instances-delete); its Retire is a different operation (canary-retire).
canary-retire releases console-only POST /a/{sqid}/apps/{app}/canary/retire Retires the canary's channel and refuses while any host follows it. No CLI verb retires a channel: canary rm deletes the instance and leaves the channel.
channels releases both channels GET /a/{sqid}/apps/{app}/releases
+releases-pull releases cli-only releases pull Copies a shipped release out of a console and checks every file against its digests.
channels-resign releases gap channels resign wp-settings
pipeline releases both pipeline show ; pipeline init ; pipeline set ; pipeline add ; pipeline remove GET /a/{sqid}/apps/{app}/pipeline ; POST /a/{sqid}/apps/{app}/pipeline ; GET /a/{sqid}/apps/{app}/settings/{section}
releases releases both releases GET /a/{sqid}/apps/{app}/releases ; GET /a/{sqid}/apps/{app}/deployments
diff --git a/release_copy_e2e_test.go b/release_copy_e2e_test.go
new file mode 100644
index 000000000..2f09c5f50
--- /dev/null
+++ b/release_copy_e2e_test.go
@@ -0,0 +1,105 @@
+// The shared fixture for copying a release between consoles (#1389 item 1):
+// each copyConsole is a REAL console.Server over its own dir store, built as
+// TestE2ECLIThroughConsole builds its one, so a pull and a ship run through
+// the same doors and gates a pipeline meets.
+package main
+
+import (
+ "crypto/ed25519"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// copyOwner owns the fixture's account and mints its credentials.
+const copyOwner = "paul@keymail.dev"
+
+// copyConsole is one in-process console and what a test reads behind it.
+type copyConsole struct {
+ url string
+ storeDir string // the dir store's root: a release key is a path under it
+ st *console.Store
+ rel release.Store
+ pub ed25519.PublicKey
+}
+
+// newCopyConsole starts a console with app created in the ops account.
+func newCopyConsole(t *testing.T, app string) copyConsole {
+ t.Helper()
+ tmp := t.TempDir()
+ storeDir := filepath.Join(tmp, "store")
+ relStore := release.NewDirStore(storeDir)
+ seed, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ priv, err := release.ParseSigningKey(seed, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := release.ParsePublicKey(pubB64, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ cst, err := console.Open(filepath.Join(tmp, "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cst.Close() })
+
+ // The origin must equal the listener's own URL, which only exists after
+ // the listener starts.
+ var srv *console.Server
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ srv.ServeHTTP(w, r)
+ }))
+ t.Cleanup(ts.Close)
+ srv, err = console.NewServer(console.Config{
+ Origin: ts.URL,
+ Keymail: "http://keymail.invalid",
+ Registry: filepath.Join(tmp, "registry.db"),
+ Releases: relStore,
+ ReleasePub: pub,
+ Key: priv,
+ AppScheme: "http",
+ SeedScratchDir: filepath.Join(tmp, "seeds"),
+ }, cst)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := cst.AddMember(console.OpsAccountID, copyOwner, console.RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := cst.CreateAppIn(console.OpsAccountID, app, copyOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ return copyConsole{url: ts.URL, storeDir: storeDir, st: cst, rel: relStore, pub: pub}
+}
+
+// token mints a service credential for app with role. A deploy credential
+// may promote to canary and edge.
+func (c copyConsole) token(t *testing.T, app string, role svcrole.Role) string {
+ t.Helper()
+ var rungs []string
+ if role == svcrole.Deploy {
+ rungs = []string{"canary", "edge"}
+ }
+ tok, err := c.st.NewServicePrincipalScoped(console.OpsAccountID, "ci-"+string(role), app, role, rungs, nil, copyOwner, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return tok
+}
+
+// useConsole points the CLI at c as token, the way CI is configured.
+func useConsole(t *testing.T, c copyConsole, token string) {
+ t.Helper()
+ t.Setenv("CARLOS_CONSOLE", c.url)
+ t.Setenv("CARLOS_SERVICE_TOKEN", token)
+}
diff --git a/release_pull.go b/release_pull.go
new file mode 100644
index 000000000..c5f662889
--- /dev/null
+++ b/release_pull.go
@@ -0,0 +1,235 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// `carlos releases pull` (#1389 item 1): the source half of copying a
+// shipped release from one console to another, so production runs the
+// exact bytes staging tested. It writes the manifest the source stores and
+// every artifact it names into a directory, checking each file against the
+// manifest's size and sha256. `carlos ship --from-release` is the target
+// half.
+
+const (
+ // releaseManifestMaxBytes caps the manifest read: a manifest is a few
+ // KiB, and a body past this is not one.
+ releaseManifestMaxBytes = 1 << 20
+
+ releasesPullUsage = "usage: carlos releases pull <version> --app <a> --out <dir> [--account <sqid-or-name>] [--account-id <sqid>] [--console <origin>]"
+ releasesPullNeedsConsole = "carlos releases pull reads from a console. set CARLOS_CONSOLE or run carlos login"
+ releasesPullDone = "pulled %s %s into %s: %d files, every digest matches"
+)
+
+// runReleasesPull is `carlos releases pull <version> --app <a> --out <dir>`.
+func runReleasesPull(args []string) error {
+ fs := flag.NewFlagSet("releases pull", flag.ExitOnError)
+ app := appFlag(fs, "")
+ acctRaw, acctIDRaw, _ := accountFlags(fs)
+ consoleFlag := consoleOption(fs, "console origin to read the release from (default: the only logged-in one)")
+ out := fs.String("out", "", "directory to write the manifest and artifacts into (created if missing)")
+ fs.Usage = flagUsage(fs, releasesPullUsage)
+ pos, _ := parseInterspersed(fs, args)
+ if len(pos) != 1 || strings.TrimSpace(*out) == "" {
+ fs.Usage()
+ return exitCode(2)
+ }
+ version := pos[0]
+
+ sess, err := resolveMode(*consoleFlag)
+ if err != nil {
+ return err
+ }
+ if sess == nil {
+ return errors.New(releasesPullNeedsConsole)
+ }
+ printUsing(stdout, sess)
+ ctx := context.Background()
+ acct := apiAccount(acctRaw, acctIDRaw)
+ if acct.Seg == "" {
+ if acct, err = sess.defaultAccount(ctx); err != nil {
+ return err
+ }
+ }
+ name := strings.TrimSpace(*app)
+ if name == "" {
+ if name, err = sess.defaultApp(ctx, acct, true); err != nil {
+ return err
+ }
+ if name == "" {
+ return errors.New(releasesPullUsage)
+ }
+ }
+ m, err := pullRelease(ctx, sess, acct, name, version, *out)
+ if err != nil {
+ return err
+ }
+ fmt.Fprintf(stdout, releasesPullDone+"\n", name, version, *out, len(m.Artifacts))
+ return nil
+}
+
+// pullRelease writes app's release version into out: every artifact first,
+// each checked against the manifest, then manifest.json with the exact
+// bytes the console stores. manifest.json is written last and only once,
+// so a directory holding it always holds the whole release; a directory
+// without it is an interrupted pull, which a second pull finishes.
+func pullRelease(ctx context.Context, sess *apiSession, a apiAcct, app, version, out string) (*release.Manifest, error) {
+ manifestPath := filepath.Join(out, "manifest.json")
+ if _, err := os.Lstat(manifestPath); err == nil {
+ return nil, fmt.Errorf("%s already holds a release. pull into a new or empty directory", out)
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return nil, err
+ }
+ if err := os.MkdirAll(out, 0o755); err != nil {
+ return nil, err
+ }
+ raw, err := sess.releaseManifestRaw(ctx, a, app, version)
+ if err != nil {
+ return nil, err
+ }
+ var m release.Manifest
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return nil, fmt.Errorf("the console's manifest for %s %s does not parse: %w", app, version, err)
+ }
+ if m.Version != version {
+ return nil, fmt.Errorf("the console answered with release %q, not %q", m.Version, version)
+ }
+ if len(m.Artifacts) == 0 {
+ return nil, fmt.Errorf("release %s %s names no files", app, version)
+ }
+ keys := make([]string, 0, len(m.Artifacts))
+ files := map[string]bool{}
+ for k, art := range m.Artifacts {
+ if !validPulledFile(art.File) {
+ return nil, fmt.Errorf("the release names a file %q that cannot be written safely", art.File)
+ }
+ // Folded, because macOS and Windows file systems are: two names
+ // differing only in case would land on one file there.
+ fold := strings.ToLower(art.File)
+ if files[fold] {
+ return nil, fmt.Errorf("the release names the file %q twice", art.File)
+ }
+ files[fold] = true
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ art := m.Artifacts[k]
+ if err := pullArtifactBounded(ctx, sess, a, app, version, m.IsRootfs(), art, filepath.Join(out, art.File)); err != nil {
+ return nil, err
+ }
+ }
+ f, err := os.OpenFile(manifestPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
+ if err != nil {
+ return nil, err
+ }
+ _, err = f.Write(raw)
+ if cerr := f.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil {
+ // A torn manifest.json would make the directory look complete.
+ _ = os.Remove(manifestPath)
+ return nil, err
+ }
+ return &m, nil
+}
+
+// pullArtifactBounded is pullArtifact under the deadline its kind ships
+// under: a rootfs image may take as long to leave as it took to arrive.
+func pullArtifactBounded(ctx context.Context, sess *apiSession, a apiAcct, app, version string, rootfs bool, art release.Artifact, dst string) error {
+ limit := shipTimeout
+ if rootfs {
+ limit = shipRootfsTimeout
+ }
+ ctx, cancel := context.WithTimeout(ctx, limit)
+ defer cancel()
+ return sess.pullArtifact(ctx, a, app, version, art, dst)
+}
+
+// validPulledFile reports whether a manifest's File name can be written
+// into the pull directory as itself: one plain name, not the manifest, not
+// a partial download's name. The last two compare without case, as macOS
+// and Windows file systems do.
+func validPulledFile(name string) bool {
+ lower := strings.ToLower(name)
+ return name != "" && name == filepath.Base(name) &&
+ !strings.ContainsAny(name, `/\`) &&
+ name != "." && name != ".." &&
+ lower != "manifest.json" &&
+ !strings.HasSuffix(lower, ".partial")
+}
+
+// releasePath is the read doors' path for one release of app.
+func releasePath(a apiAcct, app, version, tail string) string {
+ return apiPath(a, app, "/releases/"+url.PathEscape(version)+tail)
+}
+
+// releaseManifestRaw reads GET .../releases/{version}/manifest: the exact
+// bytes the console stores.
+func (s *apiSession) releaseManifestRaw(ctx context.Context, a apiAcct, app, version string) ([]byte, error) {
+ res, err := s.c.doStream(ctx, http.MethodGet, releasePath(a, app, version, "/manifest"), nil, -1, nil)
+ if err != nil {
+ return nil, err
+ }
+ defer res.Body.Close()
+ body, err := io.ReadAll(io.LimitReader(res.Body, releaseManifestMaxBytes+1))
+ if err != nil {
+ return nil, err
+ }
+ if res.StatusCode/100 != 2 {
+ return nil, apiErrorFromBody(res.StatusCode, body)
+ }
+ if len(body) > releaseManifestMaxBytes {
+ return nil, fmt.Errorf("the console's manifest for %s %s is larger than %d bytes", app, version, releaseManifestMaxBytes)
+ }
+ return body, nil
+}
+
+// pullArtifact streams one artifact to dst+".partial", hashing as it goes,
+// and renames it over dst only when its size and sha256 match art. A
+// mismatch or a failed read removes the partial file.
+func (s *apiSession) pullArtifact(ctx context.Context, a apiAcct, app, version string, art release.Artifact, dst string) error {
+ res, err := s.c.doStream(ctx, http.MethodGet, releasePath(a, app, version, "/artifacts/"+url.PathEscape(art.File)), nil, -1, nil)
+ if err != nil {
+ return err
+ }
+ defer res.Body.Close()
+ if res.StatusCode/100 != 2 {
+ body, _ := io.ReadAll(io.LimitReader(res.Body, releaseManifestMaxBytes))
+ return apiErrorFromBody(res.StatusCode, body)
+ }
+ partial := dst + ".partial"
+ f, err := os.OpenFile(partial, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
+ if err != nil {
+ return err
+ }
+ h := sha256.New()
+ n, copyErr := io.Copy(io.MultiWriter(f, h), io.LimitReader(res.Body, art.Size+1))
+ closeErr := f.Close()
+ sum := hex.EncodeToString(h.Sum(nil))
+ if copyErr != nil || closeErr != nil || n != art.Size || sum != art.SHA256 {
+ _ = os.Remove(partial)
+ mismatch := fmt.Errorf("%s: got %d bytes with sha256 %s but the release says %d bytes with sha256 %s. the partial file was removed", art.File, n, sum, art.Size, art.SHA256)
+ if cause := errors.Join(copyErr, closeErr); cause != nil {
+ return fmt.Errorf("%w: %w", mismatch, cause)
+ }
+ return mismatch
+ }
+ return os.Rename(partial, dst)
+}
diff --git a/release_pull_test.go b/release_pull_test.go
new file mode 100644
index 000000000..149f7659d
--- /dev/null
+++ b/release_pull_test.go
@@ -0,0 +1,183 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// pullPayload is the binary every pull test ships as shop v12.
+var pullPayload = bytes.Repeat([]byte{0x42}, 1024)
+
+// shipPullSource starts the source console and ships shop v12 to it under
+// a publish credential.
+func shipPullSource(t *testing.T) copyConsole {
+ t.Helper()
+ a := newCopyConsole(t, "shop")
+ useConsole(t, a, a.token(t, "shop", svcrole.Publish))
+ bin := filepath.Join(t.TempDir(), "shop")
+ if err := os.WriteFile(bin, pullPayload, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ buf := captureStdout(t)
+ runShip([]string{"--app", "shop", "--account", release.OpsAccount, "--version", "v12", "--label", "fixing modals", "--target", "linux-arm64", bin})
+ if !strings.Contains(buf.String(), "shipped shop v12") {
+ t.Fatalf("ship stdout = %q, want the shipped line", buf.String())
+ }
+ return a
+}
+
+// pullV12 pulls shop v12 from a into dir under a deploy credential.
+func pullV12(t *testing.T, a copyConsole, dir string) error {
+ t.Helper()
+ useConsole(t, a, a.token(t, "shop", svcrole.Deploy))
+ return runReleasesPull([]string{"v12", "--app", "shop", "--out", dir})
+}
+
+// noPartials fails when dir holds a .partial file.
+func noPartials(t *testing.T, dir string) {
+ t.Helper()
+ ents, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, e := range ents {
+ if strings.HasSuffix(e.Name(), ".partial") {
+ t.Fatalf("%s left behind in %s", e.Name(), dir)
+ }
+ }
+}
+
+func TestReleasesPullWritesManifestAndArtifacts(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a := shipPullSource(t)
+ dir := filepath.Join(t.TempDir(), "release")
+ buf := captureStdout(t)
+ if err := pullV12(t, a, dir); err != nil {
+ t.Fatalf("pull: %v", err)
+ }
+ if want := "pulled shop v12 into " + dir + ": 1 files, every digest matches"; !strings.Contains(buf.String(), want) {
+ t.Fatalf("pull stdout = %q, want %q", buf.String(), want)
+ }
+ _, raw, err := release.GetManifestRaw(context.Background(), a.rel, release.OpsAccount, "shop", "v12")
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := os.ReadFile(filepath.Join(dir, "manifest.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(got, raw) {
+ t.Fatalf("manifest.json = %s, want the stored bytes %s", got, raw)
+ }
+ bin, err := os.ReadFile(filepath.Join(dir, "linux-arm64"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(bin, pullPayload) {
+ t.Fatalf("linux-arm64 is %d bytes, not the shipped payload", len(bin))
+ }
+ noPartials(t, dir)
+}
+
+func TestReleasesPullRefusesADirThatHoldsARelease(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a := shipPullSource(t)
+ dir := filepath.Join(t.TempDir(), "release")
+ if err := pullV12(t, a, dir); err != nil {
+ t.Fatalf("first pull: %v", err)
+ }
+ err := runReleasesPull([]string{"v12", "--app", "shop", "--out", dir})
+ if err == nil || !strings.Contains(err.Error(), "already holds a release") {
+ t.Fatalf("second pull = %v, want it refused as already holding a release", err)
+ }
+}
+
+func TestReleasesPullFinishesAnIncompleteDir(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a := shipPullSource(t)
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "linux-arm64"), []byte("junk from an interrupted pull"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := pullV12(t, a, dir); err != nil {
+ t.Fatalf("pull into an incomplete dir: %v", err)
+ }
+ bin, err := os.ReadFile(filepath.Join(dir, "linux-arm64"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(bin, pullPayload) {
+ t.Fatalf("linux-arm64 = %q, want the shipped payload", bin)
+ }
+ if _, err := os.Stat(filepath.Join(dir, "manifest.json")); err != nil {
+ t.Fatalf("manifest.json: %v", err)
+ }
+ noPartials(t, dir)
+}
+
+func TestReleasesPullRemovesACorruptDownload(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ a := shipPullSource(t)
+ obj := filepath.Join(a.storeDir, release.ArtifactKey(release.OpsAccount, "shop", "v12", "linux-arm64"))
+ corrupt := bytes.Clone(pullPayload)
+ corrupt[100] ^= 0xff
+ if err := os.WriteFile(obj, corrupt, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ err := pullV12(t, a, dir)
+ if err == nil || !strings.Contains(err.Error(), "the partial file was removed") {
+ t.Fatalf("pull of a corrupt artifact = %v, want the partial-removed refusal", err)
+ }
+ for _, name := range []string{"linux-arm64", "linux-arm64.partial", "manifest.json"} {
+ if _, err := os.Stat(filepath.Join(dir, name)); !os.IsNotExist(err) {
+ t.Fatalf("%s is in %s after a refused pull (stat: %v)", name, dir, err)
+ }
+ }
+}
+
+func TestReleasesPullNeedsAConsole(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ t.Setenv("CARLOS_DEPLOYMENT_DIR", t.TempDir())
+ err := runReleasesPull([]string{"v12", "--app", "shop", "--out", t.TempDir()})
+ if err == nil || err.Error() != releasesPullNeedsConsole {
+ t.Fatalf("pull in bucket mode = %v, want %q", err, releasesPullNeedsConsole)
+ }
+}
+
+func TestValidPulledFile(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ want bool
+ }{
+ {"linux-arm64", true},
+ {"site.tar.gz", true},
+ {"rootfs.squashfs", true},
+ {"", false},
+ {".", false},
+ {"..", false},
+ {"../x", false},
+ {"a/b", false},
+ {`a\b`, false},
+ {"manifest.json", false},
+ {"linux-arm64.partial", false},
+ {"Manifest.JSON", false},
+ {"linux-arm64.PARTIAL", false},
+ } {
+ if got := validPulledFile(tc.name); got != tc.want {
+ t.Errorf("validPulledFile(%q) = %v, want %v", tc.name, got, tc.want)
+ }
+ }
+}
diff --git a/testdata/clireg-golden.jsonl b/testdata/clireg-golden.jsonl
index af1d6e7a4..e9e6052f9 100644
--- a/testdata/clireg-golden.jsonl
+++ b/testdata/clireg-golden.jsonl
@@ -729,6 +729,8 @@
{"case":"release-keygen | -h","argv":["release-keygen","-h"],"exit":0,"stdout":"","stderr":"usage: carlos release-keygen [flags]\nflags:\n --expires <duration> how long the scoped key may sign for (max 8760h) (default: 2160h0m0s)\n --name <string> label for the scoped key; it appears in every refusal it causes\n --scope <string> mint a SCOPED key for these rungs, comma separated (canary,edge,beta) — stable is never delegable\n"}
{"case":"releases authorize | --zz-unknown-flag","argv":["releases","authorize","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\nusage: carlos releases authorize [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --console <string> console origin to authorize through (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n --yes sign without asking\n"}
{"case":"releases authorize | -h","argv":["releases","authorize","-h"],"exit":0,"stdout":"","stderr":"usage: carlos releases authorize [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --console <string> console origin to authorize through (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n --yes sign without asking\n"}
+{"case":"releases pull | --zz-unknown-flag","argv":["releases","pull","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\nusage: carlos releases pull <version> --app <a> --out <dir> [--account <sqid-or-name>] [--account-id <sqid>] [--console <origin>]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --console <string> console origin to read the release from (default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --out <string> directory to write the manifest and artifacts into (created if missing)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n"}
+{"case":"releases pull | -h","argv":["releases","pull","-h"],"exit":0,"stdout":"","stderr":"usage: carlos releases pull <version> --app <a> --out <dir> [--account <sqid-or-name>] [--account-id <sqid>] [--console <origin>]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --console <string> console origin to read the release from (default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --out <string> directory to write the manifest and artifacts into (created if missing)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n"}
{"case":"releases retention | --zz-unknown-flag","argv":["releases","retention","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"flag provided but not defined: -zz-unknown-flag\nusage: carlos releases retention [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app whose retention policy to read or write\n --console <string> console origin (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --dry-run with --keep: list what would be pruned, write nothing\n --keep <int> retain the newest N releases (minimum 20)\n --off clear the retention policy — keep releases forever again\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n"}
{"case":"releases retention | -h","argv":["releases","retention","-h"],"exit":0,"stdout":"","stderr":"usage: carlos releases retention [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app whose retention policy to read or write\n --console <string> console origin (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --dry-run with --keep: list what would be pruned, write nothing\n --keep <int> retain the newest N releases (minimum 20)\n --off clear the retention policy — keep releases forever again\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n"}
{"case":"releases | --help","argv":["releases","--help"],"exit":0,"stdout":"","stderr":"usage: carlos releases [flags]\nflags:\n --account <string> account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one; ops in direct mode)\n --account-id <string> account sqid, matched as a sqid ONLY — supersedes --account; this is the flag an ambiguity error tells you to use\n --app, -a <string> app name\n --console <string> console origin to read through (API mode only; default: the only logged-in one)\n --destination, -d <name> use the named block from .carlos/config's destinations (default: CARLOS_DESTINATION, else the file's default or only one)\n --registry <string> registry database (resolves --account) (default: $DIR/data/registry.db)\n"}