carlos / platform Public

Preserve claimed app source and add member downloads

Pin the published serving job and verify its original archive before a
new claim can commit. Retain the app-owned snapshot until permanent purge,
and provide bounded, audited member downloads through the console and CLI.

Add the approved continuation copy, exact three-step CLI path, archive and
authorization tests, Chromium captures, and census proposal inventories.
Targeted tests, Linux/macOS/Windows builds and vet pass. Independent
security and census approval remain pending; this commit is not pushed.
codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev ac851b77eb618d4d3fadb0ec179dffc0b23d20d7 parent 188c45d
40 files changed, +2,307 −63
  • apps.go +5 −1
  • apps_source.go +133 −0
  • apps_source_e2e_test.go +259 −0
  • apps_source_test.go +143 −0
  • docs/site/cli.md +9 −0
  • docs/superpowers/notes/census-proposal-claim-source.md +17 −0
  • docs/superpowers/specs/LUNA-COPY-BRIEF-CLAIM-SOURCE.md +7 −0
  • docs/superpowers/specs/LUNA-COPY-RESULT-CLAIM-SOURCE.md +33 −0
  • internal/console/app_source.go +275 −0
  • internal/console/app_source_browser_test.go +131 −0
  • internal/console/app_source_test.go +838 −0
  • internal/console/appsettings.go +5 −0
  • internal/console/authcli.go +6 −1
  • internal/console/claim_invariant_fixtures_test.go +2 −0
  • internal/console/claim_invariant_source_test.go +64 −0
  • internal/console/demo_claim_browser_test.go +1 −1
  • internal/console/demo_claim_csp_test.go +3 −4
  • internal/console/demo_claim_page.go +30 −1
  • internal/console/demo_claim_resume_browser_test.go +3 −0
  • internal/console/demo_claim_store.go +8 −3
  • internal/console/demo_claim_target.go +2 −0
  • internal/console/demo_claim_transfer.go +60 −10
  • internal/console/demo_claim_transfer_test.go +13 −0
  • internal/console/demo_claim_ux_test.go +1 −1
  • internal/console/demo_jobs_test.go +10 −2
  • internal/console/server.go +7 −1
  • internal/console/static/demo_claim.js +27 −16
  • internal/console/store.go +13 −2
  • internal/console/templates/app_overview.html +2 −0
  • internal/console/templates/demo_claim.html +9 −6
  • internal/console/testdata/app_source_browser.mjs +83 −0
  • internal/console/testdata/claim-routes.txt +2 −0
  • internal/console/testdata/demo_claim_browser.mjs +1 −1
  • internal/console/testdata/demo_claim_resume_browser.mjs +11 −11
  • internal/demobuild/source.go +17 −1
  • internal/demobuild/source_test.go +36 −0
  • internal/provision/claim_source_census_test.go +28 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-claim-source.tsv +11 −0
diff --git a/apps.go b/apps.go
index f2412ddf0..a986c0853 100644
--- a/apps.go
+++ b/apps.go
@@ -34,7 +34,9 @@ import (
"github.com/carlosframework/platform/internal/release"
)
-const appsUsage = `usage: carlos apps <create|place|build-probe|set|show|delete|restore|ttl|keep|list> [flags] <app>
+const appsUsage = `usage: carlos apps <create|place|build-probe|set|show|delete|restore|ttl|keep|list|source> [flags] <app>
+
+ source pull --app <app> [--account <name-or-sqid> | --account-id <sqid>] --console <origin> [--output <path>]
create --app <name> [flags] claim a new app name in an account, through
the console API — the same claim the console's New app
@@ -152,6 +154,8 @@ func RunApps(args []string) {
os.Exit(1)
}
switch args[0] {
+ case "source":
+ runAppsSource(args[1:])
case "create":
runAppsCreate(args[1:])
case "place":
diff --git a/apps_source.go b/apps_source.go
new file mode 100644
index 000000000..d0e3c1bdf
--- /dev/null
+++ b/apps_source.go
@@ -0,0 +1,133 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+)
+
+const sourceIntegrity = "Source failed integrity or size checks. Nothing was saved."
+const sourceTemporary = "Source download is temporarily unavailable. Try again."
+const sourceExists = "Output already exists. Choose another `--output` path."
+const sourcePullUsage = "carlos apps source pull --app <app> [--account <name-or-sqid> | --account-id <sqid>] --console <origin> [--output <path>]"
+
+func runAppsSource(args []string) {
+ if len(args) == 0 || args[0] != "pull" {
+ log.Fatal(sourcePullUsage)
+ }
+ fs := flag.NewFlagSet("apps source pull", flag.ExitOnError)
+ app := appFlag(fs, "app name")
+ account := fs.String("account", "", "account (sqid or name)")
+ accountID := fs.String("account-id", "", "account sqid")
+ console := consoleOption(fs, "console origin")
+ output := fs.String("output", "", "<path>")
+ fs.Usage = flagUsage(fs, sourcePullUsage)
+ fs.Parse(args[1:])
+ if fs.NArg() != 0 || strings.TrimSpace(*app) == "" {
+ log.Fatal(sourcePullUsage)
+ }
+ if err := validAppName(*app); err != nil {
+ log.Fatal(err)
+ }
+ sess, err := resolveMode(*console)
+ var missing *notLoggedInError
+ if sess == nil && (err == nil || errors.As(err, &missing) || errors.Is(err, errNoDeploymentTarget)) {
+ origin, originErr := loginConsole(*console)
+ if originErr != nil {
+ log.Fatal(originErr)
+ }
+ log.Fatalf("Sign in with `carlos auth login --console %s`.", origin)
+ }
+ if err != nil {
+ log.Fatal(err)
+ }
+ acct := resolvedAccount(sess, account, accountID)
+ if *output == "" {
+ *output = *app + "-source.tar.gz"
+ }
+ at, err := pullAppSource(context.Background(), sess.c, apiPath(acct, *app, "/source"), *output)
+ if err != nil {
+ log.Fatal(err)
+ }
+ fmt.Fprintf(stdout, "Saved claimed-at source to %s (%s)\n", *output, at)
+}
+
+func pullAppSource(ctx context.Context, c *consoleClient, path, output string) (string, error) {
+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+ f, err := os.OpenFile(output, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
+ if err != nil {
+ if errors.Is(err, os.ErrExist) {
+ return "", errors.New(sourceExists)
+ }
+ return "", errors.New(sourceTemporary)
+ }
+ saved := false
+ defer func() {
+ _ = f.Close()
+ if !saved {
+ _ = os.Remove(output)
+ }
+ }()
+ req, err := http.NewRequestWithContext(ctx, "GET", c.base+path, nil)
+ if err != nil {
+ return "", errors.New(sourceTemporary)
+ }
+ req.Header.Set("Authorization", "Bearer "+c.token)
+ req.Header.Set("Accept-Encoding", "identity")
+ client := &http.Client{Timeout: 30 * time.Second, CheckRedirect: neverFollow, Transport: c.transport()}
+ res, err := client.Do(req)
+ if err != nil {
+ return "", errors.New(sourceTemporary)
+ }
+ defer res.Body.Close()
+ switch res.StatusCode {
+ case 200:
+ case 401:
+ return "", fmt.Errorf("Sign in with `carlos auth login --console %s`.", c.base)
+ case 404: // The authenticated missing-snapshot refusal is distinct from the opaque gate.
+ b, _ := io.ReadAll(io.LimitReader(res.Body, 1024))
+ if strings.TrimSpace(string(b)) == "No saved source for this app." {
+ return "", errors.New("No saved source for this app.")
+ }
+ return "", errMembershipNotFound
+ case 429:
+ return "", errors.New("Too many source downloads. Try again in a minute.")
+ default:
+ return "", errors.New(sourceTemporary)
+ }
+ if res.ContentLength <= 0 || res.ContentLength > demo.SourceMaxBytes || res.Header.Get("Content-Encoding") != "" || res.Header.Get("Content-Type") != "application/gzip" {
+ return "", errors.New(sourceIntegrity)
+ }
+ b, err := io.ReadAll(io.LimitReader(res.Body, demo.SourceMaxBytes+1))
+ if err != nil || int64(len(b)) != res.ContentLength {
+ return "", errors.New(sourceIntegrity)
+ }
+ src, err := demobuild.ValidateArchive(bytes.NewReader(b))
+ if err != nil || src.SHA256 != res.Header.Get("X-Carlos-Source-SHA256") {
+ return "", errors.New(sourceIntegrity)
+ }
+ at, err := time.Parse(time.RFC3339, res.Header.Get("X-Carlos-Source-Claimed-At"))
+ if err != nil {
+ return "", errors.New(sourceIntegrity)
+ }
+ if _, err = f.Write(b); err != nil {
+ return "", errors.New(sourceTemporary)
+ }
+ if err = f.Close(); err != nil {
+ return "", errors.New(sourceTemporary)
+ }
+ saved = true
+ return at.UTC().Format(time.RFC3339), nil
+}
diff --git a/apps_source_e2e_test.go b/apps_source_e2e_test.go
new file mode 100644
index 000000000..95f51d4d8
--- /dev/null
+++ b/apps_source_e2e_test.go
@@ -0,0 +1,259 @@
+package main
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "database/sql"
+ "encoding/hex"
+ "encoding/json"
+ "encoding/pem"
+ "fmt"
+ "io"
+ "math/big"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestAppsSourceThreeSteps(t *testing.T) {
+ bin := buildCarlos(t)
+ dir := t.TempDir()
+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute)
+ defer cancel()
+ const app = "kept"
+ const account = "bab"
+ const person = "source@example.com"
+ const host = "kept.bab.oncarlos.test"
+ store := release.NewDirStore(filepath.Join(dir, "store"))
+ public, key, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dbpath := filepath.Join(dir, "console.db")
+ st, err := console.Open(dbpath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer st.Close()
+ if err = st.AddMember(console.OpsAccountID, person, console.RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = st.CreateAppIn(console.OpsAccountID, app, person, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ var archive bytes.Buffer
+ gz := gzip.NewWriter(&archive)
+ tw := tar.NewWriter(gz)
+ for _, file := range [][2]string{{"go.mod", "module demo.local/app\n\ngo 1.22\n"}, {"main.go", "package main\nfunc main() {}\n"}} {
+ if err = tw.WriteHeader(&tar.Header{Name: file[0], Size: int64(len(file[1])), Mode: 0600}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = io.WriteString(tw, file[1]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err = tw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if err = gz.Close(); err != nil {
+ t.Fatal(err)
+ }
+ op, _ := demobuild.NewJobID()
+ job, _ := demobuild.NewJobID()
+ sum := sha256.Sum256(archive.Bytes())
+ sourceKey := "apps/" + account + "/" + app + "/source/claims/" + op + "/source.tar.gz"
+ if _, err = store.Put(ctx, sourceKey, archive.Bytes(), ""); err != nil {
+ t.Fatal(err)
+ }
+ db, err := sql.Open("sqlite", dbpath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var lifetime string
+ if err = db.QueryRow(`SELECT lifetime FROM apps WHERE account_id=? AND app=?`, console.OpsAccountID, app).Scan(&lifetime); err != nil {
+ t.Fatal(err)
+ }
+ descriptor, _ := json.Marshal(map[string]any{"schema": 1, "operation": op, "lifetime": lifetime, "job": job, "sha256": hex.EncodeToString(sum[:]), "bytes": archive.Len(), "version": "v0.0.0-demo.1", "claimed_at": time.Now().UTC().Truncate(time.Second)})
+ if _, err = db.Exec(`UPDATE apps SET claimed_source=? WHERE account_id=? AND app=?`, string(descriptor), console.OpsAccountID, app); err != nil {
+ t.Fatal(err)
+ }
+ db.Close()
+ if _, err = release.SetPipeline(ctx, store, key, account, app, release.DefaultPipelineChannels(), person); err != nil {
+ t.Fatal(err)
+ }
+ manifest := provision.Manifest{Schema: 1, App: app, Domain: account + ".oncarlos.test", Channel: "edge"}
+ if err = provision.PutManifestIfMatch(ctx, store, account, app, manifest, ""); err != nil {
+ t.Fatal(err)
+ }
+ if err = provision.CreateRecord(ctx, store, provision.Record{Host: host, App: app, Account: account, Channel: "edge", CreatedAt: time.Now().UTC(), Region: "eu-west-1"}); err != nil {
+ t.Fatal(err)
+ }
+ var srv *console.Server
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/auth/cli/start" {
+ rec := httptest.NewRecorder()
+ srv.ServeHTTP(rec, r)
+ var start struct {
+ UserCode string `json:"user_code"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &start); err != nil {
+ t.Error(err)
+ }
+ if err := st.ApproveCLIAuth(start.UserCode, person, time.Now()); err != nil {
+ t.Error(err)
+ }
+ for k, vs := range rec.Header() {
+ w.Header()[k] = vs
+ }
+ w.WriteHeader(rec.Code)
+ _, _ = w.Write(rec.Body.Bytes())
+ return
+ }
+ srv.ServeHTTP(w, r)
+ }))
+ defer api.Close()
+ srv, err = console.NewServer(console.Config{Origin: api.URL, Keymail: "http://keymail.invalid", Registry: filepath.Join(dir, "registry.db"), Releases: store, ReleasePub: public, Key: key, AppScheme: "http", AppsDomain: "oncarlos.test"}, st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Route only the fixture hostname through loopback TLS; the subprocess
+ // still exercises its ordinary HTTPS deploy watch without DNS changes.
+ proxy, ca := sourceLoopbackEdge(t, host, func(w http.ResponseWriter, r *http.Request) {
+ ptr, err := release.Channel(r.Context(), store, public, account, app, "edge")
+ if err != nil || ptr == nil {
+ http.Error(w, "not ready", 503)
+ return
+ }
+ w.Header().Set("X-Carlos-Version", ptr.Version)
+ w.WriteHeader(200)
+ })
+ creds := filepath.Join(dir, "credentials")
+ env := carlosTestEnv(t, "CARLOS_CREDENTIALS="+creds, "CARLOS_DEPLOYMENT_BUCKET=", "CARLOS_DEPLOYMENT_DIR=", "HTTPS_PROXY="+proxy, "HTTP_PROXY="+proxy, "NO_PROXY=127.0.0.1,localhost", "SSL_CERT_FILE="+ca)
+ run := func(cwd string, args ...string) string {
+ t.Helper()
+ cmd := exec.CommandContext(ctx, bin, args...)
+ cmd.Env = env
+ cmd.Dir = cwd
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("%v: %v\n%s", args, err, out)
+ }
+ return string(out)
+ }
+ run(dir, "auth", "login", "--console", api.URL)
+ out := run(dir, "apps", "source", "pull", "--console", api.URL, "--account-id", account, "--app", app)
+ if !strings.Contains(out, "Saved claimed-at source to kept-source.tar.gz") {
+ t.Fatal(out)
+ }
+ project := filepath.Join(dir, app)
+ if err = os.Mkdir(project, 0700); err != nil {
+ t.Fatal(err)
+ }
+ unpack := exec.CommandContext(ctx, "tar", "--no-same-owner", "--no-same-permissions", "-xzf", app+"-source.tar.gz", "-C", app)
+ unpack.Dir = dir
+ if out, err := unpack.CombinedOutput(); err != nil {
+ t.Fatalf("tar %v %s", err, out)
+ }
+ build := exec.CommandContext(ctx, "go", "build", "-trimpath", "-buildvcs=false", "-o", "app", ".")
+ build.Dir = project
+ build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOOS=linux", "GOARCH=arm64", "GOWORK=off")
+ if out, err := build.CombinedOutput(); err != nil {
+ t.Fatalf("build %v %s", err, out)
+ }
+ out = run(project, "deploy", "--console", api.URL, "--account-id", account, "--app", app, "--channel", "edge", "--kind", "binary", "--target", "linux-arm64", "--version", "v1", "--swap", "hold", "--no-assets", "./app")
+ if !strings.Contains(out, "live https://"+host) {
+ t.Fatal(out)
+ }
+ m, err := release.GetManifest(ctx, store, account, app, "v1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ built, err := os.ReadFile(filepath.Join(project, "app"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ builtSum := sha256.Sum256(built)
+ if m.Artifacts["linux-arm64"].SHA256 != hex.EncodeToString(builtSum[:]) {
+ t.Fatal("deployed wrong binary")
+ }
+ saved, _, err := store.Get(ctx, sourceKey)
+ if err != nil || !bytes.Equal(saved, archive.Bytes()) {
+ t.Fatal("deploy changed snapshot", err)
+ }
+}
+
+func sourceLoopbackEdge(t *testing.T, host string, h http.HandlerFunc) (string, string) {
+ t.Helper()
+ pub, key, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cert := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: host}, DNSNames: []string{host}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, IsCA: true, BasicConstraintsValid: true}
+ der, err := x509.CreateCertificate(rand.Reader, cert, cert, pub, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ private, err := x509.MarshalPKCS8PrivateKey(key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pemCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
+ pair, err := tls.X509KeyPair(pemCert, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: private}))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ca := filepath.Join(t.TempDir(), "ca.pem")
+ if err = os.WriteFile(ca, pemCert, 0600); err != nil {
+ t.Fatal(err)
+ }
+ edge := httptest.NewUnstartedServer(h)
+ edge.TLS = &tls.Config{Certificates: []tls.Certificate{pair}}
+ edge.StartTLS()
+ t.Cleanup(edge.Close)
+ proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "CONNECT" || r.Host != host+":443" {
+ http.Error(w, "refused", 403)
+ return
+ }
+ upstream, err := net.Dial("tcp", edge.Listener.Addr().String())
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ defer upstream.Close()
+ client, rw, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ defer client.Close()
+ _, _ = fmt.Fprint(rw, "HTTP/1.1 200 Connection Established\r\n\r\n")
+ _ = rw.Flush()
+ done := make(chan struct{})
+ go func() { _, _ = io.Copy(upstream, rw); close(done) }()
+ _, _ = io.Copy(client, upstream)
+ client.Close()
+ <-done
+ }))
+ t.Cleanup(proxy.Close)
+ return proxy.URL, ca
+}
diff --git a/apps_source_test.go b/apps_source_test.go
new file mode 100644
index 000000000..64278e5d1
--- /dev/null
+++ b/apps_source_test.go
@@ -0,0 +1,143 @@
+package main
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func sourceCLIArchive(t *testing.T) []byte {
+ t.Helper()
+ var b bytes.Buffer
+ gz := gzip.NewWriter(&b)
+ tw := tar.NewWriter(gz)
+ body := []byte("package main\nfunc main() {}\n")
+ if err := tw.WriteHeader(&tar.Header{Name: "main.go", Mode: 0600, Size: int64(len(body))}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tw.Write(body); err != nil {
+ t.Fatal(err)
+ }
+ if err := tw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if err := gz.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return b.Bytes()
+}
+func TestAppsSourcePull(t *testing.T) {
+ b := sourceCLIArchive(t)
+ sum := sha256.Sum256(b)
+ for _, mode := range []string{"ok", "digest", "length", "oversize", "archive", "timestamp", "encoding", "redirect", "truncated", "exists", "symlink"} {
+ t.Run(mode, func(t *testing.T) {
+ targetCalls := 0
+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { targetCalls++; t.Error("cross-origin redirect followed") }))
+ defer target.Close()
+ requests := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ if r.URL.Path != "/api/cli/apps/account/demo/source" || r.Header.Get("Authorization") != "Bearer local-token" {
+ t.Error("wrong request")
+ }
+ if mode == "redirect" {
+ http.Redirect(w, r, target.URL, 302)
+ return
+ }
+ w.Header().Set("Content-Type", "application/gzip")
+ w.Header().Set("Content-Length", fmt.Sprint(len(b)))
+ w.Header().Set("X-Carlos-Source-SHA256", hex.EncodeToString(sum[:]))
+ w.Header().Set("X-Carlos-Source-Claimed-At", "2026-11-07T12:00:00Z")
+ switch mode {
+ case "digest":
+ w.Header().Set("X-Carlos-Source-SHA256", strings.Repeat("0", 64))
+ case "length":
+ w.Header().Set("Content-Length", fmt.Sprint(len(b)+1))
+ case "oversize":
+ w.Header().Set("Content-Length", "5000001")
+ case "timestamp":
+ w.Header().Set("X-Carlos-Source-Claimed-At", "bad")
+ case "encoding":
+ w.Header().Set("Content-Encoding", "gzip")
+ case "archive":
+ bad := bytes.Repeat([]byte("x"), len(b))
+ h := sha256.Sum256(bad)
+ w.Header().Set("X-Carlos-Source-SHA256", hex.EncodeToString(h[:]))
+ _, _ = w.Write(bad)
+ return
+ case "truncated":
+ _, _ = w.Write(b[:len(b)/2])
+ return
+ }
+ _, _ = w.Write(b)
+ }))
+ defer server.Close()
+ dir := t.TempDir()
+ out := filepath.Join(dir, "source.tar.gz")
+ if mode == "exists" {
+ if err := os.WriteFile(out, []byte("keep"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if mode == "symlink" {
+ if err := os.Symlink(filepath.Join(dir, "missing"), out); err != nil {
+ t.Fatal(err)
+ }
+ }
+ at, err := pullAppSource(context.Background(), newConsoleClient(server.URL, "local-token"), "/api/cli/apps/account/demo/source", out)
+ if mode == "ok" {
+ if err != nil || at != "2026-11-07T12:00:00Z" {
+ t.Fatal(at, err)
+ }
+ got, e := os.ReadFile(out)
+ if e != nil || !bytes.Equal(got, b) {
+ t.Fatal("bytes changed", e)
+ }
+ st, e := os.Stat(out)
+ if e != nil || st.Mode().Perm() != 0600 {
+ t.Fatal("mode", e)
+ }
+ } else {
+ if err == nil {
+ t.Fatal("accepted bad download")
+ }
+ if mode == "exists" || mode == "symlink" {
+ if requests != 0 {
+ t.Fatal("clobber attempted")
+ }
+ } else if _, err := os.Lstat(out); !os.IsNotExist(err) {
+ t.Fatal("partial file survived", err)
+ }
+ }
+ if targetCalls != 0 {
+ t.Fatal(targetCalls)
+ }
+ })
+ }
+}
+
+func TestAppsSourceSignInCopy(t *testing.T) {
+ bin := buildCarlos(t)
+ dir := t.TempDir()
+ cmd := exec.Command(bin, "apps", "source", "pull", "--console", "http://127.0.0.1:1", "--account-id", "bab", "--app", "kept")
+ cmd.Dir = dir
+ cmd.Env = carlosTestEnv(t, "CARLOS_DEPLOYMENT_BUCKET=", "CARLOS_DEPLOYMENT_DIR=")
+ out, err := cmd.CombinedOutput()
+ if err == nil || !strings.Contains(string(out), "Sign in with `carlos auth login --console http://127.0.0.1:1`.") {
+ t.Fatalf("%v %s", err, out)
+ }
+ if _, err = os.Stat(filepath.Join(dir, "kept-source.tar.gz")); !os.IsNotExist(err) {
+ t.Fatal("output before sign-in", err)
+ }
+}
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 9804272bd..fd2b2132a 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -3284,3 +3284,12 @@ carlos ops restore-verify
Prints the command list, grouped the way this page is. It goes to stdout and
exits 0, so `carlos help | less` works. A bare `carlos` with no arguments
prints the same text on stderr and exits 2, because that one is a mistake.
+
+## carlos apps source pull
+
+Download the source saved when you kept this app. Later deployments do not update it.
+
+```sh
+carlos apps source pull --console '<console-origin>' --account-id '<sqid>' --app '<app>'
+carlos apps source pull --console '<console-origin>' --account '<name-or-sqid>' --app '<app>' --output '<path>'
+```
diff --git a/docs/superpowers/notes/census-proposal-claim-source.md b/docs/superpowers/notes/census-proposal-claim-source.md
new file mode 100644
index 000000000..c6d73eedc
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-claim-source.md
@@ -0,0 +1,17 @@
+# Census approval: claim-source
+
+Ruling `census-ruling-claim-source`. The independent reviewer approves or rejects every change below, 3 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `.`, `internal/demobuild`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `apps_source.go:pullAppSource`: reads +file:OpenFile, +file:ReadAll ×2; written legacy, accepted-legacy, frozen
+- new `internal/demobuild/source.go:validateSource`: reads +file:ReadAll ×3; written legacy, accepted-legacy, frozen
+- quiet `internal/demobuild/source.go:ValidateSource`: reads nothing now; retired while it reads nothing (or its row keeps no sites)
+
+Seal: `cd001bf3a9a8871f12d1ca9cfa0a925760c1fc345dc911246ffaabc235dfabf6` → `5558a3fa153fc1ef971756b4bf20bca57c2a1c80348556b9ffdff86b0d5b149f`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-claim-source.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/specs/LUNA-COPY-BRIEF-CLAIM-SOURCE.md b/docs/superpowers/specs/LUNA-COPY-BRIEF-CLAIM-SOURCE.md
new file mode 100644
index 000000000..ae6903231
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-BRIEF-CLAIM-SOURCE.md
@@ -0,0 +1,7 @@
+You are the copy-review gate itself. Do NOT run the copy-review skill or start any server. Read only.
+
+Read the design /home/paulca/amadan.net/carlos/platform/.claude/worktrees/claim-source/docs/superpowers/specs/2026-11-07-claimed-app-source-design.md (its "Copy inventory" and "CLI and the fresh-agent handoff" sections), the current done page in /home/paulca/amadan.net/carlos/platform/internal/console/templates/demo_claim.html and demo_claim_copy.go (the "Keep going" block: CLAIM-UX-47..56 in docs/superpowers/specs/LUNA-COPY-RESULT-CLAIM-UX.md), and Paul's request below.
+
+Paul (2026-11-07): "'Keep going' after a claim is wrong without context. A fresh agent has no source code, no idea the demo was kept, and /start leads it to build a new demo. Done page 'Keep going', two clear paths: (i) 'Still in the chat where you built it?' tell your agent you kept it; /start's after-claim section takes over (sign in, deploy to the permanent app). (ii) 'Starting fresh, in a new chat or another agent?' a copyable prompt carrying the context: app name, account, console, and a pointer to a NEW /start section (#after-you-keep-it) that explains sign-in, fetching the source, and deploying changes to the claimed app. (iii) The CLI disclosure gets the same three steps for a person (sign in, fetch source, deploy)." Plus a "Download source" action for the claimed app in the console app page.
+
+Produce a copy deck table ID | surface/state | approved text | note, IDs KEEP-01.. for every human-read string: the Keep going heading (keep or change), path (i) heading + one-line instruction (what to tell the agent; give the exact short line the person pastes or says, e.g. "I kept {app}. It now lives at {address} in my account {account}."), path (ii) heading + explanation + the copyable prompt (start from the design's proposed prompt; it is read by an AI agent but also seen by the person, keep it plain; placeholders {app}, {account}, {sqid}, {console}, and the link https://carlosframework.com/start#after-you-keep-it), the Copy button (reuse shipped "Copy"), the CLI disclosure summary (reuse "Prefer the command line?" or improve) and its three step labels with one short line each (Sign in / Fetch the source / Deploy changes), the note that the source was saved when the app was kept and later deploys don't update it, the console "Download source" button and its one-line description, and the CLI's person-facing messages from the design (saved-file confirmation and refusals). Leave command lines themselves verbatim (they are code). Rules: plain, calm, direct, no em dashes, no exclamation marks, never name a tenant, keep placeholders. Then a short list of choices. No other prose.
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-CLAIM-SOURCE.md b/docs/superpowers/specs/LUNA-COPY-RESULT-CLAIM-SOURCE.md
new file mode 100644
index 000000000..356c76f0f
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-RESULT-CLAIM-SOURCE.md
@@ -0,0 +1,33 @@
+| ID | surface/state | approved text | note |
+|---|---|---|---|
+| KEEP-01 | Done page, heading | Keep going | Keep the heading. |
+| KEEP-02 | Done page, path (i) heading | Still in the chat where you built it? | |
+| KEEP-03 | Done page, path (i) instruction | Tell your agent: “I kept {app}. It now lives at {address} in my account {account}.” | Paste or say the sentence to the agent. |
+| KEEP-04 | Done page, path (ii) heading | Starting fresh, in a new chat or with another agent? | |
+| KEEP-05 | Done page, path (ii) explanation | Give your agent this prompt so it can help you sign in, fetch the source, and deploy changes to this app. | |
+| KEEP-06 | Done page, copyable agent prompt | Continue app {app} in account {account} (ID {sqid}) on console {console}. Follow https://carlosframework.com/start#after-you-keep-it to help me sign in, fetch its claimed source, then build and deploy my changes to that existing app. | The prompt is also visible to the person. |
+| KEEP-07 | Done page, prompt button | Copy | Reuse shipped “Copy.” |
+| KEEP-08 | CLI disclosure summary | Prefer the command line? | Reuse current wording. |
+| KEEP-09 | CLI step 1 label | Sign in | |
+| KEEP-10 | CLI step 1 instruction | Sign in to the console with the CLI. | |
+| KEEP-11 | CLI step 2 label | Fetch the source | |
+| KEEP-12 | CLI step 2 instruction | Download the saved source and unpack it into a new folder. | |
+| KEEP-13 | CLI step 3 label | Deploy changes | |
+| KEEP-14 | CLI step 3 instruction | Inspect and edit the source, then build and deploy changes to this app. | |
+| KEEP-15 | Done page, source note | Source was saved when you kept this app. Later deployments do not update it. | The snapshot is the source from when the app was kept. |
+| KEEP-16 | Console app page, button | Download source | |
+| KEEP-17 | Console app page, description | Download the source saved when you kept this app. Later deployments do not update it. | |
+| KEEP-18 | CLI, saved-file confirmation | Saved claimed-at source to {path} ({timestamp}) | |
+| KEEP-19 | CLI, sign-in refusal | Sign in with `carlos auth login --console {origin}`. | |
+| KEEP-20 | CLI, missing source refusal | No saved source for this app. | Show only after account and app authorization. |
+| KEEP-21 | CLI, temporary refusal | Source download is temporarily unavailable. Try again. | |
+| KEEP-22 | CLI, integrity or size refusal | Source failed integrity or size checks. Nothing was saved. | |
+| KEEP-23 | CLI, existing output refusal | Output already exists. Choose another `--output` path. | |
+| KEEP-24 | CLI, rate-limit refusal | Too many source downloads. Try again in a minute. | |
+| KEEP-25 | CLI, account move refusal | This app has saved source. Moving it between accounts is not supported yet. | |
+
+Choices:
+
+- Keep “Keep going” as the heading.
+- Use the exact short sentence in KEEP-03 for the in-chat handoff.
+- Use a plain URL in the prompt so it is easy to copy and follow.
\ No newline at end of file
diff --git a/internal/console/app_source.go b/internal/console/app_source.go
new file mode 100644
index 000000000..62868a853
--- /dev/null
+++ b/internal/console/app_source.go
@@ -0,0 +1,275 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/controlname"
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const sourceUnavailable = "Source download is temporarily unavailable. Try again."
+const sourceMissing = "No saved source for this app."
+const sourceRateLimited = "Too many source downloads. Try again in a minute."
+const sourceMoveRefused = "This app has saved source. Moving it between accounts is not supported yet."
+
+var errClaimSourceInvalid = errors.New("claim source: invalid archive or identity")
+
+type claimedSource struct {
+ Schema int `json:"schema"`
+ Operation string `json:"operation"`
+ Lifetime string `json:"lifetime"`
+ Job string `json:"job"`
+ SHA256 string `json:"sha256"`
+ Bytes int64 `json:"bytes"`
+ Version string `json:"version"`
+ ClaimedAt time.Time `json:"claimed_at"`
+}
+
+func (c claimedSource) valid() bool {
+ return c.Schema == 1 && demobuild.ValidJobID(c.Operation) && demobuild.ValidJobID(c.Job) && c.Lifetime != "" && demobuild.ValidDigest(c.SHA256) && c.Bytes > 0 && c.Bytes <= demo.SourceMaxBytes && c.Version != "" && !c.ClaimedAt.IsZero()
+}
+func claimedSourceKey(sqid, app, op string) string {
+ return "apps/" + sqid + "/" + app + "/source/claims/" + op + "/source.tar.gz"
+}
+func readClaimedSource(ctx context.Context, store release.Store, key, digest string, size int64) ([]byte, error) {
+ r, _, err := release.OpenObjectStreaming(ctx, store, key)
+ if err != nil {
+ return nil, err
+ }
+ b, err := io.ReadAll(io.LimitReader(r, demo.SourceMaxBytes+1))
+ err = errors.Join(err, r.Close())
+ if err != nil {
+ return nil, err
+ }
+ if len(b) == 0 || len(b) > demo.SourceMaxBytes || size > 0 && int64(len(b)) != size {
+ return nil, errClaimSourceInvalid
+ }
+ src, err := demobuild.ValidateArchive(bytes.NewReader(b))
+ if err != nil || src.SHA256 != digest {
+ return nil, errClaimSourceInvalid
+ }
+ return b, nil
+}
+func (s *Server) copyDemoClaimSource(ctx context.Context, op *claimOp) error {
+ if !controlname.ValidAccount(op.Target.Sqid) || !release.ValidApp(op.Target.App) || !demobuild.ValidJobID(op.ID) || !demobuild.ValidJobID(op.SourceJobID) || !demobuild.ValidDigest(op.SourceSHA256) {
+ return errClaimSourceInvalid
+ }
+ d, err := s.store.demoByID(ctx, op.DemoID)
+ if err != nil {
+ return err
+ }
+ if !controlname.ValidAccount(d.AccountSqid) || !release.ValidApp(d.App) {
+ return errClaimSourceInvalid
+ }
+ sourceKey := "apps/" + d.AccountSqid + "/" + d.App + "/demo-build-data/" + op.SourceJobID + "/source.tar.gz"
+ b, err := readClaimedSource(ctx, s.cfg.Releases, sourceKey, op.SourceSHA256, op.SourceBytes)
+ if err != nil {
+ return err
+ }
+ if err = s.claimBoundary("source-read"); err != nil {
+ return err
+ }
+ key := claimedSourceKey(op.Target.Sqid, op.Target.App, op.ID)
+ if _, err = s.cfg.Releases.Put(ctx, key, b, ""); err != nil {
+ existing, readErr := readClaimedSource(ctx, s.cfg.Releases, key, op.SourceSHA256, int64(len(b)))
+ if readErr != nil {
+ if errors.Is(readErr, errClaimSourceInvalid) {
+ return readErr
+ }
+ return err
+ }
+ if !bytes.Equal(b, existing) {
+ return errClaimSourceInvalid
+ }
+ }
+ if err = s.claimBoundary("source-object"); err != nil {
+ return err
+ }
+ op.SourceBytes = int64(len(b))
+ tx, err := s.store.demoTx(ctx)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ res, err := tx.ExecContext(ctx, `UPDATE demo_claim_ops SET source_bytes=? WHERE id=? AND source_job_id=? AND source_sha256=? AND phase='reserved'`, op.SourceBytes, op.ID, op.SourceJobID, op.SourceSHA256)
+ if err != nil {
+ return err
+ }
+ if n, err := res.RowsAffected(); err != nil {
+ return err
+ } else if n != 1 {
+ return errClaimSourceInvalid
+ }
+ if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_progress SET source_copied=1 WHERE operation_id=?`, op.ID); err != nil {
+ return err
+ }
+ if err = tx.Commit(); err != nil {
+ return err
+ }
+ return s.claimBoundary("source-progress")
+}
+
+type sourceDownloads struct {
+ mu sync.Mutex
+ active int
+ windows map[string]sourceWindow
+}
+type sourceWindow struct {
+ at time.Time
+ count int
+}
+
+func (l *sourceDownloads) take(key string, now time.Time) (func(), bool) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ if l.windows == nil {
+ l.windows = map[string]sourceWindow{}
+ }
+ for k, v := range l.windows {
+ if now.Sub(v.at) >= time.Minute {
+ delete(l.windows, k)
+ }
+ }
+ v := l.windows[key]
+ if v.count >= 10 || l.active >= 4 {
+ return nil, false
+ }
+ if v.count == 0 {
+ v.at = now
+ }
+ v.count++
+ l.windows[key] = v
+ l.active++
+ return func() { l.mu.Lock(); l.active--; l.mu.Unlock() }, true
+}
+
+// Authorization helpers may render or redirect on refusal. This door always
+// emits the same 404; no rendered account detail crosses the gate.
+type sourceGateWriter struct{ h http.Header }
+
+func (w sourceGateWriter) Header() http.Header { return w.h }
+func (w sourceGateWriter) WriteHeader(int) {}
+func (w sourceGateWriter) Write(p []byte) (int, error) { return len(p), nil }
+func (s *Server) sourceAdmission(next http.HandlerFunc, cli bool) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "private, no-store")
+ ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
+ defer cancel()
+ r = r.WithContext(ctx)
+ if r.Method != http.MethodGet {
+ http.NotFound(w, r)
+ return
+ }
+ if cli {
+ p, ok := s.store.CLIPrincipal(bearer(r), time.Now())
+ if !ok || p.Kind != PrincipalUser {
+ http.NotFound(w, r)
+ return
+ }
+ }
+ next(w, r)
+ }
+}
+func (s *Server) handleAppSource(w http.ResponseWriter, r *http.Request) {
+ gate := sourceGateWriter{make(http.Header)}
+ actor, _, acct, _, app, ok := s.accountApp(gate, r)
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ s.serveAppSource(w, r, actor, acct, app)
+}
+func (s *Server) handleAPIAppSource(w http.ResponseWriter, r *http.Request) {
+ gate := sourceGateWriter{make(http.Header)}
+ if !s.apiPerson(gate, r) {
+ http.NotFound(w, r)
+ return
+ }
+ actor, acct, app, ok := s.apiAccountApp(gate, r)
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ s.serveAppSource(w, r, actor, acct, app)
+}
+func (s *Server) sourceForMember(ctx context.Context, actor string, acct *Account, app string) (claimedSource, string, error) {
+ if !controlname.ValidAccount(acct.Sqid) || !release.ValidApp(app) {
+ return claimedSource{}, "", errClaimSourceInvalid
+ }
+ var raw string
+ err := s.store.db.QueryRowContext(ctx, `SELECT a.claimed_source FROM apps a JOIN accounts c ON c.id=a.account_id JOIN memberships m ON m.account_id=c.id
+ WHERE a.account_id=? AND c.sqid=? AND a.app=? AND m.address=? AND m.role IN ('owner','member') AND c.deleted_at=0 AND a.deleted_at=0 AND a.restoring=0 AND a.demo_id='' AND a.demo_claim_op=''`, acct.ID, acct.Sqid, app, actor).Scan(&raw)
+ if err != nil {
+ return claimedSource{}, raw, err
+ }
+ var c claimedSource
+ if raw != "" && (json.Unmarshal([]byte(raw), &c) != nil || !c.valid()) {
+ return c, raw, errClaimSourceInvalid
+ }
+ return c, raw, nil
+}
+func (s *Server) serveAppSource(w http.ResponseWriter, r *http.Request, actor string, acct *Account, app string) {
+ ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
+ defer cancel()
+ defer s.lockMembers(acct.Sqid)()
+ defer s.lockAccount(acct.Sqid)()
+ defer s.lockApp(acct.Sqid, app)()
+ c, raw, err := s.sourceForMember(ctx, actor, acct, app)
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ if raw == "" {
+ http.Error(w, sourceMissing, 404)
+ return
+ }
+ done, ok := s.sourceDownloads.take(actor+"\x00"+acct.Sqid+"\x00"+app, time.Now())
+ if !ok {
+ http.Error(w, sourceRateLimited, 429)
+ return
+ }
+ defer done()
+ b, err := readClaimedSource(ctx, s.cfg.Releases, claimedSourceKey(acct.Sqid, app, c.Operation), c.SHA256, c.Bytes)
+ if err != nil {
+ http.Error(w, sourceUnavailable, 503)
+ return
+ }
+ // Membership can be revoked while storage is slow. Recheck before audit
+ // and handoff; the lifecycle locks keep Trash/purge from crossing this read.
+ _, current, err := s.sourceForMember(ctx, actor, acct, app)
+ if err != nil || current != raw {
+ http.NotFound(w, r)
+ return
+ }
+ if ctx.Err() != nil {
+ http.Error(w, sourceUnavailable, 503)
+ return
+ }
+ if err = s.store.RecordActivity(acct.ID, app, actor, Activity{Action: "app-source-download", TargetType: "claimed-source", Target: c.Operation, Detail: `{"state":"started","sha256":"` + c.SHA256 + `"}`}, time.Now().UTC()); err != nil {
+ http.Error(w, sourceUnavailable, 503)
+ return
+ }
+ w.Header().Set("Content-Type", "application/gzip")
+ w.Header().Set("Content-Length", strconv.Itoa(len(b)))
+ w.Header().Set("Content-Disposition", `attachment; filename="`+app+`-source.tar.gz"`)
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.Header().Set("X-Carlos-Source-SHA256", c.SHA256)
+ w.Header().Set("X-Carlos-Source-Claimed-At", c.ClaimedAt.UTC().Format(time.RFC3339))
+ _, _ = w.Write(b)
+}
+
+func (s *Store) hasClaimedSource(accountID int64, app string) (bool, error) {
+ var exists bool
+ err := s.db.QueryRow(`SELECT claimed_source!='' FROM apps WHERE account_id=? AND app=?`, accountID, app).Scan(&exists)
+ return exists, err
+}
diff --git a/internal/console/app_source_browser_test.go b/internal/console/app_source_browser_test.go
new file mode 100644
index 000000000..06636bc67
--- /dev/null
+++ b/internal/console/app_source_browser_test.go
@@ -0,0 +1,131 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+)
+
+func sourceDoneFixture(t *testing.T) (*Server, claimOp, string, string) {
+ t.Helper()
+ s, op, data := claimTransferFixture(t)
+ claimToVerify(t, s, op, data)
+ claimAdvance(t, s, op)
+ s = sourceRouter(t, s)
+ cookie, _ := randomToken()
+ if err := s.store.attachDemoClaimBrowser(t.Context(), cookie, claimFlow{Hash: op.FlowHash}); err != nil {
+ t.Fatal(err)
+ }
+ session, err := s.store.CreateSession(op.Person, "", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s, op, cookie, session
+}
+func TestAppSourceDonePage(t *testing.T) {
+ s, op, cookie, _ := sourceDoneFixture(t)
+ r := httptest.NewRequest("GET", "/demo/claim", nil)
+ r.AddCookie(&http.Cookie{Name: demoClaimBrowserCookie, Value: cookie})
+ w := httptest.NewRecorder()
+ s.ServeHTTP(w, r)
+ if w.Code != 200 {
+ t.Fatalf("%d %s", w.Code, w.Body)
+ }
+ acct, err := s.store.AccountByID(op.Target.AccountID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{"Still in the chat where you built it?", "Starting fresh, in a new chat or with another agent?", acct.Name, op.Target.Sqid, "https://" + op.Target.Host, "https://carlosframework.com/start#after-you-keep-it", "carlos apps source pull", "--version v1 --swap hold --no-assets ./app", "Source was saved when you kept this app. Later deployments do not update it."} {
+ if !strings.Contains(w.Body.String(), want) {
+ t.Errorf("missing %q", want)
+ }
+ }
+ // Status cookie alone has no download authority.
+ r = httptest.NewRequest("GET", "/a/"+op.Target.Sqid+"/apps/"+op.Target.App+"/source", nil)
+ r.AddCookie(&http.Cookie{Name: demoClaimBrowserCookie, Value: cookie})
+ w = httptest.NewRecorder()
+ s.ServeHTTP(w, r)
+ if w.Code != 404 {
+ t.Fatal(w.Code)
+ }
+ r = httptest.NewRequest("GET", "/demo/claim", nil)
+ w = httptest.NewRecorder()
+ s.ServeHTTP(w, r)
+ if strings.Contains(w.Body.String(), op.Target.Sqid) {
+ t.Fatal("account identity without browser capability")
+ }
+}
+func TestAppSourceHeadless(t *testing.T) {
+ chromium, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Fatal("Chromium required", err)
+ }
+ node, err := exec.LookPath("node")
+ if err != nil {
+ t.Fatal(err)
+ }
+ s, op, cookie, session := sourceDoneFixture(t)
+ ts := httptest.NewServer(s)
+ defer ts.Close()
+ s.cfg.Origin = ts.URL
+ shots := os.Getenv("CARLOS_CLAIM_SOURCE_SCREENSHOTS")
+ if shots != "" {
+ if err = os.MkdirAll(shots, 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 90*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, node, "testdata/app_source_browser.mjs", chromium, t.TempDir(), ts.URL, cookie, session, "/a/"+op.Target.Sqid+"/apps/"+op.Target.App, shots)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("browser: %v\n%s", err, out)
+ }
+ t.Log(string(out))
+}
+
+// Progress browser tests simulate worker phases; give their completed-page
+// fixture the same descriptor shape a real source-bearing claim attaches.
+func stampSourcePageFixture(t *testing.T, s *Server) {
+ t.Helper()
+ op, err := scanDemoClaimOp(s.store.db.QueryRow(`SELECT ` + demoClaimOpColumns + ` FROM demo_claim_ops LIMIT 1`))
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ src := demoJobSource()
+ descriptor, err := json.Marshal(claimedSource{Schema: 1, Operation: op.ID, Lifetime: op.Target.Lifetime, Job: op.ID, SHA256: src.SHA256, Bytes: int64(len(src.Archive)), Version: op.Version, ClaimedAt: time.Now().UTC()})
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ if _, err = s.store.db.Exec(`UPDATE apps SET claimed_source=? WHERE account_id=? AND app=?`, string(descriptor), op.Target.AccountID, op.Target.App); err != nil {
+ t.Error(err)
+ }
+}
+
+func TestAppSourceDoneDeletedAccount(t *testing.T) {
+ s, op, cookie, _ := sourceDoneFixture(t)
+ if err := s.store.TrashAppRow(op.Target.AccountID, op.Target.App, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.store.PurgeAppRow(op.Target.AccountID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.store.DeleteAccount(op.Target.AccountID, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ r := httptest.NewRequest("GET", "/demo/claim", nil)
+ r.AddCookie(&http.Cookie{Name: demoClaimBrowserCookie, Value: cookie})
+ w := httptest.NewRecorder()
+ s.ServeHTTP(w, r)
+ if w.Code != 200 || strings.Contains(w.Body.String(), "carlos apps source pull") {
+ t.Fatalf("deleted account continuation: %d", w.Code)
+ }
+}
diff --git a/internal/console/app_source_test.go b/internal/console/app_source_test.go
new file mode 100644
index 000000000..1a431779a
--- /dev/null
+++ b/internal/console/app_source_test.go
@@ -0,0 +1,838 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/s3fake"
+ "github.com/carlosframework/platform/internal/svcrole"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestAppSourceClaimDownload(t *testing.T) {
+ s, op, data := claimTransferFixture(t)
+ claimToVerify(t, s, op, data)
+ claimAdvance(t, s, op)
+ s = sourceRouter(t, s)
+ session, err := s.store.CreateSession(op.Person, "", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := httptest.NewRequest("GET", "/a/"+op.Target.Sqid+"/apps/"+op.Target.App+"/source", nil)
+ r.AddCookie(&http.Cookie{Name: sessionCookie, Value: session})
+ w := httptest.NewRecorder()
+ s.ServeHTTP(w, r)
+ if w.Code != 200 {
+ t.Fatalf("download: %d %s", w.Code, w.Body.String())
+ }
+ if !bytes.Equal(w.Body.Bytes(), demoJobSource().Archive) {
+ t.Fatal("source differs")
+ }
+ if w.Header().Get("Content-Type") != "application/gzip" || w.Header().Get("Cache-Control") != "private, no-store" {
+ t.Fatal(w.Header())
+ }
+}
+
+func sourceRouter(t *testing.T, seed *Server) *Server {
+ t.Helper()
+ cfg := seed.cfg
+ fk := newFakeKeymail(t, "shop@example.com")
+ cfg.Keymail = fk.srv.URL
+ s, err := NewServer(cfg, seed.store)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s
+}
+
+func sourceToken(t *testing.T, s *Server, person string) string {
+ t.Helper()
+ _, _, err := s.store.ResolveSignIn(MethodEmail, person, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ user, device, err := s.store.NewCLIAuth("source-test", "127.0.0.1", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = s.store.ApproveCLIAuth(user, person, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ _, token, _, err := s.store.PollCLIAuth(device, time.Now())
+ if err != nil || token == "" {
+ t.Fatal(err)
+ }
+ return token
+}
+func sourceRequest(t *testing.T, s *Server, op claimOp, door, person, token string) *httptest.ResponseRecorder {
+ t.Helper()
+ path := "/a/" + op.Target.Sqid + "/apps/" + op.Target.App + "/source"
+ if door == "cli" {
+ path = "/api/cli/apps/" + op.Target.Sqid + "/" + op.Target.App + "/source?exact=sqid"
+ }
+ r := httptest.NewRequest("GET", path, nil)
+ if person != "" && door == "browser" {
+ session, err := s.store.CreateSession(person, "", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.AddCookie(&http.Cookie{Name: sessionCookie, Value: session})
+ }
+ if token != "" {
+ r.Header.Set("Authorization", "Bearer "+token)
+ }
+ r.Header.Set("Range", "bytes=0-1")
+ r.Header.Set("If-None-Match", "*")
+ w := httptest.NewRecorder()
+ s.ServeHTTP(w, r)
+ return w
+}
+
+func TestAppSourceDoors(t *testing.T) {
+ seed, op, data := claimTransferFixture(t)
+ claimToVerify(t, seed, op, data)
+ claimAdvance(t, seed, op)
+ s := sourceRouter(t, seed)
+ if err := s.store.AddMember(op.Target.AccountID, "member@example.com", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ count := &sourceCountStore{Store: s.cfg.Releases}
+ s.cfg.Releases = count
+ for _, door := range []string{"browser", "cli"} {
+ for _, person := range []string{op.Person, "member@example.com"} {
+ token := sourceToken(t, s, person)
+ count.reads = 0
+ w := sourceRequest(t, s, op, door, person, token)
+ if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), demoJobSource().Archive) {
+ t.Fatalf("%s %s: %d %s", door, person, w.Code, w.Body)
+ }
+ if count.reads != 1 {
+ t.Fatalf("reads %d", count.reads)
+ }
+ if w.Header().Get("Content-Encoding") != "" || w.Header().Get("Content-Type") != "application/gzip" || w.Header().Get("X-Content-Type-Options") != "nosniff" || w.Header().Get("Content-Length") == "" || w.Header().Get("X-Carlos-Source-SHA256") != demoJobSource().SHA256 {
+ t.Fatal(w.Header())
+ }
+ events, err := s.store.Events(op.Target.AccountID, op.Target.App, 1)
+ if err != nil || len(events) != 1 || events[0].Address != person || events[0].Action != "app-source-download" {
+ t.Fatalf("audit: %+v %v", events, err)
+ }
+ }
+ }
+ if err := s.store.RemoveMember(op.Target.AccountID, "member@example.com"); err != nil {
+ t.Fatal(err)
+ }
+ serviceToken, err := s.store.NewServicePrincipal(op.Target.AccountID, "source-service", op.Target.App, svcrole.Publish, op.Person, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ other := claimAccount(t, s, 888, "other@example.com", RoleOwner)
+ if _, err = s.store.CreateAppIn(other.ID, op.Target.App, "other@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.store.AddMember(OpsAccountID, "operator@example.com", RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ appToken, err := s.store.NewAppToken(op.Target.AccountID, op.Target.App, op.Person, "source test", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, door := range []string{"browser", "cli"} {
+ for _, person := range []string{"member@example.com", "stranger@example.com", "operator@example.com", "other@example.com", ""} {
+ token := "invalid-demo-capability"
+ if person != "" {
+ token = sourceToken(t, s, person)
+ }
+ count.reads = 0
+ w := sourceRequest(t, s, op, door, person, token)
+ if w.Code != 404 || w.Body.String() != "404 page not found\n" || count.reads != 0 || w.Header().Get("Cache-Control") != "private, no-store" {
+ t.Fatalf("%s %s: %d %q reads=%d", door, person, w.Code, w.Body, count.reads)
+ }
+ }
+ count.reads = 0
+ denied := sourceRequest(t, s, op, door, "", serviceToken)
+ if denied.Code != 404 || denied.Body.String() != "404 page not found\n" || count.reads != 0 {
+ t.Fatalf("service: %d %s", denied.Code, denied.Body)
+ }
+ count.reads = 0
+ w := sourceRequest(t, s, op, door, "", appToken)
+ if w.Code != 404 || w.Body.String() != "404 page not found\n" || count.reads != 0 {
+ t.Fatalf("app token: %d %s", w.Code, w.Body)
+ }
+ }
+}
+
+type sourceCountStore struct {
+ release.Store
+ reads, puts, lists int
+ failRead, failPut, loseAck bool
+ beforeRead func()
+}
+
+func (s *sourceCountStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) {
+ s.reads++
+ if s.beforeRead != nil {
+ s.beforeRead()
+ }
+ if s.failRead {
+ return nil, "", errors.New("injected source GET")
+ }
+ return release.OpenObjectStreaming(ctx, s.Store, key)
+}
+func (s *sourceCountStore) Put(ctx context.Context, key string, b []byte, etag string) (string, error) {
+ s.puts++
+ if s.failPut {
+ return "", errors.New("injected source PUT")
+ }
+ tag, err := s.Store.Put(ctx, key, b, etag)
+ if err == nil && s.loseAck {
+ return "", errors.New("injected lost acknowledgement")
+ }
+ return tag, err
+}
+func (s *sourceCountStore) List(ctx context.Context, prefix string) ([]string, error) {
+ s.lists++
+ return s.Store.List(ctx, prefix)
+}
+
+func TestAppSourceAuditFailureAndRate(t *testing.T) {
+ for _, mode := range []string{"audit", "rate", "removed-during-read", "trash"} {
+ t.Run(mode, func(t *testing.T) {
+ seed, op, data := claimTransferFixture(t)
+ claimToVerify(t, seed, op, data)
+ claimAdvance(t, seed, op)
+ s := sourceRouter(t, seed)
+ token := sourceToken(t, s, op.Person)
+ if mode == "audit" {
+ if _, err := s.store.db.Exec(`CREATE TRIGGER fail_source_audit BEFORE INSERT ON audit WHEN NEW.action='app-source-download' BEGIN SELECT RAISE(ABORT,'audit failure'); END`); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if mode == "removed-during-read" {
+ s.cfg.Releases = &sourceCountStore{Store: s.cfg.Releases, beforeRead: func() {
+ if _, err := s.store.db.Exec(`DELETE FROM memberships WHERE account_id=? AND address=?`, op.Target.AccountID, op.Person); err != nil {
+ t.Fatal(err)
+ }
+ }}
+ }
+ if mode == "trash" {
+ if _, err := s.store.db.Exec(`UPDATE apps SET deleted_at=? WHERE account_id=? AND app=?`, time.Now().Unix(), op.Target.AccountID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ }
+ want := 503
+ if mode == "removed-during-read" || mode == "trash" {
+ want = 404
+ }
+ if mode == "rate" {
+ for i := 0; i < 10; i++ {
+ if w := sourceRequest(t, s, op, "cli", "", token); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ }
+ want = 429
+ }
+ w := sourceRequest(t, s, op, "cli", "", token)
+ if w.Code != want || bytes.Equal(w.Body.Bytes(), demoJobSource().Archive) {
+ t.Fatalf("%d %s", w.Code, w.Body)
+ }
+ })
+ }
+}
+
+func TestAppSourceCopyBoundaries(t *testing.T) {
+ for _, boundary := range []string{"source-pin", "source-read", "source-object", "source-progress", "before-commit", "commit"} {
+ t.Run(boundary, func(t *testing.T) {
+ s, op, data := claimTransferFixture(t)
+ hit := false
+ s.demoClaimBoundary = func(at string) error {
+ if at == boundary && !hit {
+ hit = true
+ return errors.New("crash")
+ }
+ return nil
+ }
+ if boundary == "before-commit" || boundary == "commit" {
+ claimToVerify(t, s, op, data)
+ }
+ if err := s.advanceDemoClaim(t.Context(), op.ID); err == nil || !hit {
+ t.Fatalf("boundary %s not hit: %v", boundary, err)
+ }
+ s.demoClaimBoundary = nil
+ if boundary == "source-progress" {
+ claimAdvance(t, s, op)
+ } else if boundary == "source-pin" || boundary == "source-read" || boundary == "source-object" {
+ claimAdvance(t, s, op)
+ }
+ current, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if current.Phase == "freezing" {
+ if err = s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)); err != nil {
+ t.Fatal(err)
+ }
+ claimAdvance(t, s, op)
+ if err = claimSnapshot(t, s, op, data); err != nil {
+ t.Fatal(err)
+ }
+ }
+ claimAdvance(t, s, op)
+ current, _ = s.store.demoClaimOp(t.Context(), op.ID)
+ if current.Phase != "done" {
+ t.Fatal(current.Phase)
+ }
+ s = sourceRouter(t, s)
+ w := sourceRequest(t, s, op, "browser", op.Person, "")
+ if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), demoJobSource().Archive) {
+ t.Fatalf("%d %s", w.Code, w.Body)
+ }
+ })
+ }
+}
+
+func TestAppSourceCopyOperations(t *testing.T) {
+ for _, mode := range []string{"normal", "lost-ack", "get-failure", "put-failure", "mismatch"} {
+ t.Run(mode, func(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ if err := s.pinDemoClaim(t.Context(), &op); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`INSERT OR IGNORE INTO demo_claim_progress(operation_id) VALUES(?)`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ count := &sourceCountStore{Store: s.cfg.Releases, loseAck: mode == "lost-ack", failRead: mode == "get-failure", failPut: mode == "put-failure"}
+ if mode == "mismatch" {
+ if _, err := count.Store.Put(t.Context(), claimedSourceKey(op.Target.Sqid, op.Target.App, op.ID), []byte("foreign bytes"), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ s.cfg.Releases = count
+ err := s.copyDemoClaimSource(t.Context(), &op)
+ if mode == "normal" || mode == "lost-ack" {
+ if err != nil {
+ t.Fatal(err)
+ }
+ } else if err == nil {
+ t.Fatal("failure accepted")
+ }
+ if count.lists != 0 {
+ t.Fatal("copy listed storage")
+ }
+ if mode == "normal" && (count.reads != 1 || count.puts != 1) {
+ t.Fatalf("GET=%d PUT=%d", count.reads, count.puts)
+ }
+ if mode == "lost-ack" && (count.reads != 2 || count.puts != 1) {
+ t.Fatalf("GET=%d PUT=%d", count.reads, count.puts)
+ }
+ })
+ }
+}
+
+func TestAppSourceMissingCorruptAbort(t *testing.T) {
+ for _, mode := range []string{"missing", "corrupt", "oversized", "expired"} {
+ t.Run(mode, func(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ if err := s.pinDemoClaim(t.Context(), &op); err != nil {
+ t.Fatal(err)
+ }
+ d, err := s.store.demoByID(t.Context(), op.DemoID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := "apps/" + d.AccountSqid + "/" + d.App + "/demo-build-data/" + op.SourceJobID + "/source.tar.gz"
+ if mode == "expired" {
+ if _, err = s.store.db.Exec(`UPDATE demo_claim_ops SET deadline=1 WHERE id=?`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ if err = s.cfg.Releases.Delete(t.Context(), key); err != nil {
+ t.Fatal(err)
+ }
+ if mode != "missing" {
+ bad := []byte("corrupt")
+ if mode == "oversized" {
+ bad = bytes.Repeat([]byte("x"), 5_000_001)
+ }
+ if _, err = s.cfg.Releases.Put(t.Context(), key, bad, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ if err = s.advanceDemoClaim(t.Context(), op.ID); err != nil {
+ t.Fatal(err)
+ }
+ fresh, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fresh.Phase != "aborted" && fresh.Phase != "aborting" {
+ t.Fatal(fresh.Phase)
+ }
+ var n int
+ if err = s.store.db.QueryRow(`SELECT count(*) FROM demo_claim_commits WHERE operation_id=?`, op.ID).Scan(&n); err != nil || n != 0 {
+ t.Fatal(n, err)
+ }
+ if _, _, err = s.cfg.Releases.Get(t.Context(), claimedSourceKey(op.Target.Sqid, op.Target.App, op.ID)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("source survived abort", err)
+ }
+ })
+ }
+}
+
+func TestAppSourceProvenanceAndRetention(t *testing.T) {
+ s, op, data := claimTransferFixture(t)
+ d, err := s.store.demoByID(t.Context(), op.DemoID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // A failed later publication has identical binary bytes but different source.
+ var raw []byte
+ if err = s.store.db.QueryRow(`SELECT job FROM demo_jobs WHERE demo_id=? AND state='published'`, d.ID).Scan(&raw); err != nil {
+ t.Fatal(err)
+ }
+ var a demobuild.Job
+ if err = json.Unmarshal(raw, &a); err != nil {
+ t.Fatal(err)
+ }
+ b := a
+ b.ID, _ = demobuild.NewJobID()
+ b.Generation++
+ b.SourceSHA256 = strings.Repeat("f", 64)
+ wire, _ := json.Marshal(b)
+ if _, err = s.store.db.Exec(`INSERT INTO demo_jobs(id,demo_id,generation,attempt,box,deadline,state,wire,job,binary_sha256,publish_stage) SELECT ?,demo_id,?,attempt,box,deadline,'failed',wire,?,binary_sha256,'' FROM demo_jobs WHERE id=?`, b.ID, b.Generation, wire, a.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.store.db.Exec(`UPDATE demo_apps SET source_sha256=?,generation=? WHERE demo_id=?`, []byte(b.SourceSHA256), b.Generation, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ op.Generation = int64(b.Generation)
+ if _, err = s.store.db.Exec(`UPDATE demo_claim_ops SET generation=? WHERE id=?`, op.Generation, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ claimToVerify(t, s, op, data)
+ claimAdvance(t, s, op)
+ op, err = s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if op.SourceJobID != a.ID || op.SourceSHA256 != a.SourceSHA256 {
+ t.Fatal("wrong provenance", op.SourceJobID)
+ }
+ // The source demo and all of its metadata may disappear independently.
+ keys, err := s.cfg.Releases.List(t.Context(), "apps/"+d.AccountSqid+"/"+d.App+"/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, key := range keys {
+ if err = s.cfg.Releases.Delete(t.Context(), key); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, table := range []string{"demo_claim_progress", "demo_claim_commits", "demo_claim_outbox"} {
+ if _, err = s.store.db.Exec("DELETE FROM "+table+" WHERE operation_id=?", op.ID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err = s.store.db.Exec(`DELETE FROM demo_claim_ops WHERE id=?`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.store.db.Exec(`DELETE FROM demo_jobs WHERE demo_id=?`, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.store.db.Exec(`DELETE FROM demo_apps WHERE demo_id=?`, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ s = sourceRouter(t, s)
+ for _, stage := range []string{"purged-demo", "deploy", "trash", "restore", "region"} {
+ switch stage {
+ case "deploy":
+ m := release.Manifest{App: op.Target.App, Version: "v1", Kind: "binary", Artifacts: map[string]release.Artifact{"linux-arm64": {File: "app", SHA256: strings.Repeat("a", 64), Size: 1}}}
+ // The serving pointer can advance without changing app-owned source metadata.
+ raw, _ := json.Marshal(m)
+ if _, err = s.cfg.Releases.Put(t.Context(), release.ManifestKey(op.Target.Sqid, op.Target.App, "v1"), raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ case "trash":
+ if err = s.store.TrashAppRow(op.Target.AccountID, op.Target.App, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ case "restore":
+ if err = s.store.RestoreAppRow(op.Target.AccountID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ case "region":
+ if _, err = s.store.db.Exec(`UPDATE apps SET region='us-east-1' WHERE account_id=? AND app=?`, op.Target.AccountID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ }
+ w := sourceRequest(t, s, op, "browser", op.Person, "")
+ if stage == "trash" {
+ if w.Code != 404 {
+ t.Fatal(w.Code)
+ }
+ } else if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), demoJobSource().Archive) {
+ t.Fatalf("%s: %d %s", stage, w.Code, w.Body)
+ }
+ }
+ if err = s.store.RenameAppIn(op.Target.AccountID, op.Target.App, "renamed"); err == nil {
+ t.Fatal("renamed snapshot")
+ }
+ dest := claimAccount(t, s, 777, op.Person, RoleOwner)
+ if err = s.store.MoveApp(op.Target.App, op.Target.AccountID, dest.ID); err == nil {
+ t.Fatal("moved snapshot")
+ }
+ at := time.Now().Add(-31 * 24 * time.Hour)
+ if err = release.TrashApp(t.Context(), s.cfg.Releases, op.Target.Sqid, op.Target.App, op.Person, at); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.store.TrashAppRow(op.Target.AccountID, op.Target.App, at); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.store.DeleteAccount(op.Target.AccountID, time.Now()); err == nil {
+ t.Fatal("deleted account before Trash purge")
+ }
+ if err = release.PurgeApp(t.Context(), s.cfg.Releases, s.cfg.ReleasePub, op.Target.Sqid, op.Target.App, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.store.PurgeAppRow(op.Target.AccountID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err = s.cfg.Releases.Get(t.Context(), claimedSourceKey(op.Target.Sqid, op.Target.App, op.ID)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("source survived permanent purge", err)
+ }
+ if err = s.store.DeleteAccount(op.Target.AccountID, time.Now()); err != nil {
+ t.Fatal("account deletion after purge", err)
+ }
+}
+
+func TestAppSourceS3Adapter(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ if err := s.pinDemoClaim(t.Context(), &op); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`INSERT OR IGNORE INTO demo_claim_progress(operation_id) VALUES(?)`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ fake := s3fake.New(s.cfg.Releases.(*release.DirStore))
+ var methods []string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ methods = append(methods, r.Method)
+ fake.ServeHTTP(w, r)
+ }))
+ defer server.Close()
+ client := awss3.New(awss3.Options{Region: "us-east-1", Credentials: credentials.NewStaticCredentialsProvider("x", "y", ""), BaseEndpoint: aws.String(server.URL), UsePathStyle: true, RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired})
+ s.cfg.Releases = &release.S3Store{Client: client, Bucket: "local-source"}
+ if err := s.copyDemoClaimSource(t.Context(), &op); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(methods, []string{"GET", "PUT"}) {
+ t.Fatal(methods)
+ }
+ got, err := readClaimedSource(t.Context(), s.cfg.Releases, claimedSourceKey(op.Target.Sqid, op.Target.App, op.ID), op.SourceSHA256, op.SourceBytes)
+ if err != nil || !bytes.Equal(got, demoJobSource().Archive) {
+ t.Fatal(err)
+ }
+}
+
+func TestAppSourceAbortAfterCopyAndLegacy(t *testing.T) {
+ for _, mode := range []string{"abort-after-copy", "legacy-inflight", "legacy-done"} {
+ t.Run(mode, func(t *testing.T) {
+ s, op, data := claimTransferFixture(t)
+ if mode == "legacy-done" {
+ claimToVerify(t, s, op, data)
+ claimAdvance(t, s, op)
+ if _, err := s.store.db.Exec(`UPDATE apps SET claimed_source='' WHERE account_id=? AND app=?`, op.Target.AccountID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ claimAdvance(t, s, op)
+ s = sourceRouter(t, s)
+ w := sourceRequest(t, s, op, "browser", op.Person, "")
+ if w.Code != 404 || strings.TrimSpace(w.Body.String()) != sourceMissing {
+ t.Fatalf("legacy source invented: %d %s", w.Code, w.Body)
+ }
+ return
+ }
+ s.demoClaimBoundary = func(at string) error {
+ if at == "source-progress" {
+ return errors.New("crash")
+ }
+ return nil
+ }
+ if err := s.advanceDemoClaim(t.Context(), op.ID); err == nil {
+ t.Fatal("no copy boundary")
+ }
+ s.demoClaimBoundary = nil
+ if mode == "legacy-inflight" {
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase='freezing',source_job_id='',source_sha256='',source_bytes=0 WHERE id=?`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_progress SET source_copied=0 WHERE operation_id=?`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET deadline=1 WHERE id=?`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ claimAdvance(t, s, op)
+ fresh, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil || fresh.Phase != "aborted" {
+ t.Fatalf("%s %v", fresh.Phase, err)
+ }
+ keys, err := s.cfg.Releases.List(t.Context(), "apps/"+op.Target.Sqid+"/"+op.Target.App+"/")
+ if err != nil || len(keys) != 0 {
+ t.Fatalf("abort leftovers: %v %v", keys, err)
+ }
+ var n int
+ if err = s.store.db.QueryRow(`SELECT count(*) FROM apps WHERE account_id=? AND app=?`, op.Target.AccountID, op.Target.App).Scan(&n); err != nil || n != 0 {
+ t.Fatal(n, err)
+ }
+ })
+ }
+}
+
+func TestAppSourceSQLInventory(t *testing.T) {
+ s := openGatedStore(t)
+ tables, err := claimSQLCensus(s.bootDB(), claimSQLTables)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for table, columns := range map[string][]string{"apps": {"claimed_source"}, "demo_claim_ops": {"source_job_id", "source_sha256", "source_bytes"}, "demo_claim_progress": {"source_copied"}} {
+ for _, column := range columns {
+ found := false
+ for _, got := range tables[table].cols {
+ found = found || got == column
+ }
+ if !found {
+ t.Fatalf("%s.%s missing", table, column)
+ }
+ }
+ }
+ for _, columns := range claimAppsTerminal {
+ for _, column := range columns {
+ if column == "claimed_source" {
+ t.Fatal("terminal update can replace snapshot")
+ }
+ }
+ }
+}
+
+func TestAppSourcePinnedJobCannotChange(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ if err := s.pinDemoClaim(t.Context(), &op); err != nil {
+ t.Fatal(err)
+ }
+ var raw []byte
+ if err := s.store.db.QueryRow(`SELECT job FROM demo_jobs WHERE id=?`, op.SourceJobID).Scan(&raw); err != nil {
+ t.Fatal(err)
+ }
+ var job demobuild.Job
+ if err := json.Unmarshal(raw, &job); err != nil {
+ t.Fatal(err)
+ }
+ job.SourceSHA256 = strings.Repeat("e", 64)
+ raw, _ = json.Marshal(job)
+ if _, err := s.store.db.Exec(`UPDATE demo_jobs SET job=? WHERE id=?`, raw, op.SourceJobID); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.pinDemoClaim(t.Context(), &op); err == nil {
+ t.Fatal("retry switched source identity")
+ }
+}
+
+func TestAppSourceProgressTransactionFailure(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ if _, err := s.store.db.Exec(`CREATE TRIGGER fail_source_progress BEFORE UPDATE OF source_copied ON demo_claim_progress BEGIN SELECT RAISE(ABORT,'progress failure'); END`); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.advanceDemoClaim(t.Context(), op.ID); err == nil {
+ t.Fatal("progress failure ignored")
+ }
+ fresh, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fresh.Phase != "reserved" || fresh.SourceJobID == "" || fresh.SourceBytes != 0 {
+ t.Fatalf("partial progress committed: %+v", fresh)
+ }
+ if _, err = s.store.db.Exec(`DROP TRIGGER fail_source_progress`); err != nil {
+ t.Fatal(err)
+ }
+ claimAdvance(t, s, op)
+ fresh, err = s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil || fresh.Phase != "freezing" || fresh.SourceBytes == 0 {
+ t.Fatal(fresh.Phase, err)
+ }
+}
+
+func TestAppSourceBufferAdmission(t *testing.T) {
+ var limits sourceDownloads
+ var done []func()
+ now := time.Now()
+ for _, key := range []string{"a", "b", "c", "d"} {
+ release, ok := limits.take(key, now)
+ if !ok {
+ t.Fatal("early refusal")
+ }
+ done = append(done, release)
+ }
+ if _, ok := limits.take("e", now); ok {
+ t.Fatal("unbounded buffering")
+ }
+ for _, release := range done {
+ release()
+ }
+ for i := 0; i < 9; i++ {
+ release, ok := limits.take("a", now)
+ if !ok {
+ t.Fatal("early rate refusal")
+ }
+ release()
+ }
+ if _, ok := limits.take("a", now); ok {
+ t.Fatal("rate limit exceeded")
+ }
+ release, ok := limits.take("a", now.Add(time.Minute))
+ if !ok {
+ t.Fatal("window did not reset")
+ }
+ release()
+}
+
+func TestAppSourceDeletionRace(t *testing.T) {
+ seed, op, data := claimTransferFixture(t)
+ claimToVerify(t, seed, op, data)
+ claimAdvance(t, seed, op)
+ s := sourceRouter(t, seed)
+ entered, finish := make(chan struct{}), make(chan struct{})
+ count := &sourceCountStore{Store: s.cfg.Releases, beforeRead: func() { close(entered); <-finish }}
+ s.cfg.Releases = count
+ result := make(chan *httptest.ResponseRecorder, 1)
+ go func() { result <- sourceRequest(t, s, op, "browser", op.Person, "") }()
+ <-entered
+ deleted := make(chan error, 1)
+ go func() {
+ unlock := s.lockApp(op.Target.Sqid, op.Target.App)
+ defer unlock()
+ deleted <- s.store.TrashAppRow(op.Target.AccountID, op.Target.App, time.Now())
+ }()
+ select {
+ case err := <-deleted:
+ t.Fatalf("deletion crossed download: %v", err)
+ case <-time.After(30 * time.Millisecond):
+ }
+ close(finish)
+ if w := <-result; w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ if err := <-deleted; err != nil {
+ t.Fatal(err)
+ }
+ count.reads = 0
+ count.beforeRead = nil
+ w := sourceRequest(t, s, op, "browser", op.Person, "")
+ if w.Code != 404 || count.reads != 0 {
+ t.Fatalf("deleted: %d reads=%d", w.Code, count.reads)
+ }
+}
+
+func TestAppSourceRealPublicationRollback(t *testing.T) {
+ var accepted demobuild.Job
+ s, op, data := claimTransferFixtureBefore(t, func(s *Server, d DemoRow, a demobuild.Job, out demobuild.Result) {
+ accepted = a
+ d, err := s.store.demoByID(t.Context(), d.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sourceB := demoJobSource("// changed upload B, same binary result\n")
+ b, err := s.enqueueDemo(t.Context(), d, sourceB)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.pickupDemo(t.Context(), b.ID, b.Attempt, b.Fleet, b.Box); err != nil {
+ t.Fatal(err)
+ }
+ row, err := s.readDemoJob(t.Context(), b.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b = row.Job
+ out.JobID, out.Attempt, out.SourceSHA256, out.BinaryPath = b.ID, b.Attempt, b.SourceSHA256, ""
+ if err = s.storeDemoResult(t.Context(), b, out, []byte("demo executable bytes")); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.store.db.QueryRow(`SELECT spool_path FROM demo_jobs WHERE id=?`, b.ID).Scan(&out.BinaryPath); err != nil {
+ t.Fatal(err)
+ }
+ d, err = s.store.demoByID(t.Context(), d.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = s.publishDemo(t.Context(), d, b, out); err != nil {
+ t.Fatal(err)
+ }
+ demoAcceptReadiness(s, demoVersion(a))
+ if err = s.finishDemoPublish(t.Context(), b, false); err != nil {
+ t.Fatal(err)
+ }
+ ptr, err := release.Channel(t.Context(), s.cfg.Releases, s.cfg.ReleasePub, d.AccountSqid, d.App, "edge")
+ if err != nil || ptr.Version != demoVersion(a) {
+ t.Fatal("rollback did not restore A", err)
+ }
+ row, err = s.readDemoJob(t.Context(), b.ID)
+ if err != nil || row.State != "failed" {
+ t.Fatal(row.State, err)
+ }
+ })
+ claimToVerify(t, s, op, data)
+ claimAdvance(t, s, op)
+ fresh, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil || fresh.SourceJobID != accepted.ID {
+ t.Fatal("wrong source job", err)
+ }
+ d, err := s.store.demoByID(t.Context(), op.DemoID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ keys, err := s.cfg.Releases.List(t.Context(), "apps/"+d.AccountSqid+"/"+d.App+"/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, key := range keys {
+ if err = s.cfg.Releases.Delete(t.Context(), key); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err = s.store.db.Exec(`DELETE FROM demo_jobs WHERE demo_id=?`, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ s = sourceRouter(t, s)
+ w := sourceRequest(t, s, op, "browser", op.Person, "")
+ if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), demoJobSource().Archive) {
+ t.Fatalf("%d %s", w.Code, w.Body)
+ }
+}
+
+func TestAppSourceLegacyArtifactPin(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ if _, err := s.store.db.Exec(`INSERT INTO demo_claim_progress(operation_id,copied) VALUES(?,1)`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ op.Version = "v0.0.0-demo.999"
+ if err := s.pinDemoClaim(t.Context(), &op); err == nil {
+ t.Fatal("legacy copied artifact rebound")
+ }
+}
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go
index 8fbeac7a8..8984a5dbc 100644
--- a/internal/console/appsettings.go
+++ b/internal/console/appsettings.go
@@ -1038,6 +1038,11 @@ func (s *Server) appPolicyState(ctx context.Context, acct *Account, name string)
// behind, and the moved app, which no create clears for, would take up an
// earlier app's at the destination. "" means the move may go ahead.
func (s *Server) movePolicyRefusal(ctx context.Context, from, to *Account, app string) string {
+ if has, err := s.store.hasClaimedSource(from.ID, app); err != nil {
+ return sourceUnavailable
+ } else if has {
+ return sourceMoveRefused
+ }
for _, acct := range []*Account{from, to} {
present, err := s.appPolicyState(ctx, acct, app)
switch {
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index 589f5d1d5..f33b71d0e 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -452,7 +452,11 @@ func (s *Server) cliRoute(pattern string, allow svcrole.Set, h http.HandlerFunc)
s.cliRoles = map[string]svcrole.Set{}
}
s.cliRoles[pattern] = allow
- s.registerRoute(pattern, s.cliGate(allow, h))
+ gate := s.cliGate(allow, h)
+ if pattern == "GET /api/cli/apps/{account}/{app}/source" {
+ gate = s.sourceAdmission(gate, true)
+ }
+ s.registerRoute(pattern, gate)
}
// cliRouteJournaled is cliRoute whose role gate, when it refuses a service
@@ -594,6 +598,7 @@ func (s *Server) registerCLIRoutes() {
// The app's region, the default for its NEW instances (appregionset.go).
// A person only: an account owner or a deployment operator may change
// it, so no service role reaches either door.
+ s.cliRoute("GET /api/cli/apps/{account}/{app}/source", svcrole.Set{}, s.handleAPIAppSource)
s.cliRoute("GET /api/cli/apps/{account}/{app}/region", svcrole.Set{}, s.handleAPIAppRegionGet)
s.cliRoute("PUT /api/cli/apps/{account}/{app}/region", svcrole.Set{}, s.handleAPIAppRegionSet)
s.cliRoute("GET /api/cli/apps/{account}/{app}/channels", svcrole.Allow(svcrole.Publish, svcrole.Deploy), s.handleAPIChannels)
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index c43bbfcad..b848a2e97 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -731,6 +731,8 @@ func (cx *claimCase) crashedRestore(t *testing.T) {
// ---- the table ----------------------------------------------------------------
var claimFixtures = map[string]claimFixture{
+ "route GET /a/{sqid}/apps/{app}/source": claimSourceDownloadFixture(true),
+ "route GET /api/cli/apps/{account}/{app}/source": claimSourceDownloadFixture(false),
"route POST /api/fleet/replicas/{account}/{app}/{host}/coordinator": {door: claimReplicaDoor("coordinator")},
"route POST /api/fleet/replicas/{account}/{app}/{host}/release": {door: claimReplicaDoor("release")},
"route GET /accounts": claimRead("renders only the signed-in person’s account memberships"),
diff --git a/internal/console/claim_invariant_source_test.go b/internal/console/claim_invariant_source_test.go
new file mode 100644
index 000000000..0db59e65d
--- /dev/null
+++ b/internal/console/claim_invariant_source_test.go
@@ -0,0 +1,64 @@
+package console
+
+import (
+ "encoding/json"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demobuild"
+)
+
+// Source download is a GET with an app-scoped audit write. Exercise its
+// real success and its foreign-exclusive refusal, like the DB download.
+func claimSourceDownloadFixture(browser bool) claimFixture {
+ return claimFixture{door: &claimDoor{
+ apps: claimRefs("bab/titogo"),
+ setup: func(t *testing.T, cx *claimCase) {
+ id, err := cx.st.ClaimAppID(OpsAccountID, "titogo")
+ if err != nil {
+ t.Fatal(err)
+ }
+ life, err := cx.st.AppLife(OpsAccountID, "titogo")
+ if err != nil {
+ t.Fatal(err)
+ }
+ op, err := demobuild.NewJobID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ src := demoJobSource()
+ raw, err := json.Marshal(claimedSource{Schema: 1, Operation: op, Lifetime: life.Lifetime, Job: op, SHA256: src.SHA256, Bytes: int64(len(src.Archive)), Version: "v0.0.0-demo.1", ClaimedAt: time.Now().UTC()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ scope := []claimSQLScope{{AccountID: OpsAccountID, App: "titogo", AppID: id, Mode: claimModeEffect}}
+ err = cx.st.withClaimSQL(gateCtx(t), scope, allowAllClaimSQL, func(v *Store) error {
+ _, err := v.db.Exec(`UPDATE apps SET claimed_source=? WHERE account_id=? AND app=?`, string(raw), OpsAccountID, "titogo")
+ return err
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = cx.rel.Put(t.Context(), claimedSourceKey("bab", "titogo", op), src.Archive, ""); err != nil {
+ t.Fatal(err)
+ }
+ },
+ do: func(t *testing.T, cx *claimCase) int {
+ if browser {
+ return cx.pageReply(t, "/a/bab/apps/titogo/source").Status
+ }
+ return cx.api(t, http.MethodGet, "/api/cli/apps/bab/titogo/source", "")
+ },
+ check: func(t *testing.T, cx *claimCase, open bool) string {
+ n := cx.sqlCount(t, `SELECT COUNT(*) FROM audit WHERE account_id=? AND app=? AND action='app-source-download'`, OpsAccountID, "titogo")
+ if open && n != 1 {
+ return "source download did not write exactly one audit row"
+ }
+ if !open && n != 0 {
+ return "source download audited under a foreign exclusive operation"
+ }
+ return ""
+ },
+ }}
+}
diff --git a/internal/console/demo_claim_browser_test.go b/internal/console/demo_claim_browser_test.go
index e32dc4174..24589e52b 100644
--- a/internal/console/demo_claim_browser_test.go
+++ b/internal/console/demo_claim_browser_test.go
@@ -321,7 +321,7 @@ func TestDemoClaimBrowserStatus(t *testing.T) {
if w.Code != 200 {
t.Fatalf("%s status: %d", phase, w.Code)
}
- if phase == "done" && (!strings.Contains(w.Body.String(), op.Target.Host) || !strings.Contains(w.Body.String(), op.Target.App) || !strings.Contains(w.Body.String(), "carlos auth login --console "+s.cfg.Origin)) {
+ if phase == "done" && (!strings.Contains(w.Body.String(), op.Target.Host) || !strings.Contains(w.Body.String(), op.Target.App) || !strings.Contains(w.Body.String(), sourceMissing)) {
t.Fatalf("result missing: %s", w.Body.String())
}
}
diff --git a/internal/console/demo_claim_csp_test.go b/internal/console/demo_claim_csp_test.go
index 9c45a6b09..9e80f62af 100644
--- a/internal/console/demo_claim_csp_test.go
+++ b/internal/console/demo_claim_csp_test.go
@@ -130,15 +130,14 @@ func TestDemoClaimMobileMarkup(t *testing.T) {
}
func TestDemoClaimCommandMarkup(t *testing.T) {
- p := demoClaimPageData{State: "claimed", Copy: demoClaimBrowserCopy()}
- p.Copy["next"] = "carlos auth login --console https://console.example.com"
+ p := demoClaimPageData{State: "claimed", Copy: demoClaimBrowserCopy(), AccountSqid: "byv", SourceSteps: claimSourceSteps("kept", "byv", "https://console.example.com")}
var body strings.Builder
if err := demoClaimPageTemplate.ExecuteTemplate(&body, "demo_claim.html", p); err != nil {
t.Fatal(err)
}
for _, want := range []string{
- `<p>Sign in once, then send changes with carlos deploy.</p>`,
- `<pre><code id="claim-cli-command">` + p.Copy["next"] + `</code></pre>`,
+ `<p>Sign in to the console with the CLI.</p>`,
+ `<pre><code id="claim-cli-command">` + strings.ReplaceAll(p.SourceSteps[0].Command, "'", "&#39;") + `</code></pre>`,
`data-copy="Copy" data-copied="Copied" aria-live="polite" hidden>Copy</button>`,
} {
if !strings.Contains(body.String(), want) {
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index f70fe3ad9..c3c4c6ef7 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -34,6 +34,8 @@ var demoClaimStyleHash = func() string {
}()
type demoClaimPageData struct {
+ SourceSteps []claimSourceStep
+ AccountName, AccountSqid string
AutoSubmit bool
SelectedAccount string
Chrome page
@@ -141,6 +143,21 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
p.State = "claimed"
p.App = op.Target.App
p.URL = "https://" + op.Target.Host
+ if acct, err := s.store.AccountByID(op.Target.AccountID); err == nil && acct != nil && acct.Sqid == op.Target.Sqid {
+ p.AccountName, p.AccountSqid = acct.Name, acct.Sqid
+ p.Copy["sameChat"] = "Still in the chat where you built it?"
+ p.Copy["sameChatLine"] = fmt.Sprintf("Tell your agent: “I kept %s. It now lives at %s in my account %s.”", p.App, p.URL, acct.Name)
+ p.Copy["agentHeading"] = "Starting fresh, in a new chat or with another agent?"
+ p.Copy["agentDetail"] = "Give your agent this prompt so it can help you sign in, fetch the source, and deploy changes to this app."
+ p.Copy["agentLine"] = fmt.Sprintf("Continue app %s in account %s (ID %s) on console %s. Follow https://carlosframework.com/start#after-you-keep-it to help me sign in, fetch its claimed source, then build and deploy my changes to that existing app.", p.App, acct.Name, acct.Sqid, s.cfg.Origin)
+ p.Copy["sourceNote"] = "Source was saved when you kept this app. Later deployments do not update it."
+ if has, err := s.store.hasClaimedSource(acct.ID, p.App); err == nil && has {
+ p.SourceSteps = claimSourceSteps(p.App, acct.Sqid, s.cfg.Origin)
+ } else {
+ p.Copy["sourceNote"] = "No saved source for this app."
+ p.Copy["agentLine"] = ""
+ }
+ }
}
if op.Phase == "aborted" {
p.State = "aborted"
@@ -219,7 +236,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
p.EndTime = time.Unix(p.ExpiresAt, 0).UTC().Format(time.RFC3339)
}
p.Copy["completeHeading"] = strings.ReplaceAll(demoClaimUX43, "{app}", p.App)
- p.Copy["agentLine"] = strings.ReplaceAll(demoClaimUX50, "{app}", p.App)
+
p.Copy["accountsIntro"] = strings.ReplaceAll(demoClaimUX25, "{used}", fmt.Sprint(len(p.Accounts)))
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err = demoClaimPageTemplate.ExecuteTemplate(w, "demo_claim.html", p); err != nil {
@@ -689,3 +706,15 @@ func (s *Server) demoClaimAccountView(ctx context.Context, a Account, count bool
}
return c
}
+
+type claimSourceStep struct{ ID, Label, Instruction, Command string }
+
+func sourceShellQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'" }
+func claimSourceSteps(app, sqid, origin string) []claimSourceStep {
+ a, c, o := sourceShellQuote(app), sourceShellQuote(sqid), sourceShellQuote(origin)
+ return []claimSourceStep{
+ {"claim-cli-command", "Sign in", "Sign in to the console with the CLI.", "carlos auth login --console " + o},
+ {"claim-source-command", "Fetch the source", "Download the saved source and unpack it into a new folder.", "carlos apps source pull --console " + o + " --account-id " + c + " --app " + a + "\nmkdir " + a + "\ntar --no-same-owner --no-same-permissions -xzf " + sourceShellQuote(app+"-source.tar.gz") + " -C " + a + "\ncd " + a},
+ {"claim-deploy-command", "Deploy changes", "Inspect and edit the source, then build and deploy changes to this app.", "CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -buildvcs=false -o app .\ncarlos deploy --console " + o + " --account-id " + c + " --app " + a + " --channel edge --kind binary --target linux-arm64 --version v1 --swap hold --no-assets ./app"},
+ }
+}
diff --git a/internal/console/demo_claim_resume_browser_test.go b/internal/console/demo_claim_resume_browser_test.go
index 065f8e69c..bebf6a2b0 100644
--- a/internal/console/demo_claim_resume_browser_test.go
+++ b/internal/console/demo_claim_resume_browser_test.go
@@ -78,6 +78,9 @@ func TestDemoClaimSelectStepUpHeadless(t *testing.T) {
if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase=?`, phase); err != nil {
t.Error(err)
}
+ if phase == "done" {
+ stampSourcePageFixture(t, s)
+ }
}
if strings.HasPrefix(r.URL.Path, "/auth/") {
if _, err := r.Cookie(browserClaimCookieName); err == nil {
diff --git a/internal/console/demo_claim_store.go b/internal/console/demo_claim_store.go
index 452bfba3e..4edffc636 100644
--- a/internal/console/demo_claim_store.go
+++ b/internal/console/demo_claim_store.go
@@ -50,6 +50,11 @@ func (s *Store) migrateDemoClaims() error {
return err
}
for _, stmt := range []string{
+ `ALTER TABLE apps ADD COLUMN claimed_source TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE demo_claim_ops ADD COLUMN source_job_id TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE demo_claim_ops ADD COLUMN source_sha256 TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE demo_claim_ops ADD COLUMN source_bytes INTEGER NOT NULL DEFAULT 0`,
+ `ALTER TABLE demo_claim_progress ADD COLUMN source_copied INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE demo_claim_progress ADD COLUMN hold_cleared INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE demo_claim_progress ADD COLUMN retry_delay INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE demo_claim_progress ADD COLUMN target_generation INTEGER NOT NULL DEFAULT 0`,
@@ -132,12 +137,12 @@ func newDemoClaimFlow(raw, address string, d DemoRow, life AppLife, now time.Tim
return f
}
-const demoClaimOpColumns = `id,flow_hash,demo_id,source_lifetime,source_box,person,version,artifact_sha256,phase,generation,account_id,target_sqid,app,host,target_lifetime,region,seed_id,deadline,source_expires_at`
+const demoClaimOpColumns = `id,flow_hash,demo_id,source_lifetime,source_box,person,version,artifact_sha256,phase,generation,account_id,target_sqid,app,host,target_lifetime,region,seed_id,deadline,source_expires_at,source_job_id,source_sha256,source_bytes`
func scanDemoClaimOp(row interface{ Scan(...any) error }) (claimOp, error) {
var op claimOp
var deadline int64
- err := row.Scan(&op.ID, &op.FlowHash, &op.DemoID, &op.SourceLifetime, &op.SourceBox, &op.Person, &op.Version, &op.ArtifactSHA256, &op.Phase, &op.Generation, &op.Target.AccountID, &op.Target.Sqid, &op.Target.App, &op.Target.Host, &op.Target.Lifetime, &op.Target.Region, &op.Target.SeedID, &deadline, &op.SourceExpiresAt)
+ err := row.Scan(&op.ID, &op.FlowHash, &op.DemoID, &op.SourceLifetime, &op.SourceBox, &op.Person, &op.Version, &op.ArtifactSHA256, &op.Phase, &op.Generation, &op.Target.AccountID, &op.Target.Sqid, &op.Target.App, &op.Target.Host, &op.Target.Lifetime, &op.Target.Region, &op.Target.SeedID, &deadline, &op.SourceExpiresAt, &op.SourceJobID, &op.SourceSHA256, &op.SourceBytes)
op.Deadline = time.Unix(deadline, 0)
return op, err
}
@@ -205,7 +210,7 @@ func (s *Store) reserveDemoClaimRows(ctx context.Context, f claimFlow, op claimO
if err = tx.QueryRowContext(ctx, `SELECT lifetime FROM apps WHERE account_id=? AND app=?`, op.Target.AccountID, op.Target.App).Scan(&op.Target.Lifetime); err != nil {
return claimOp{}, err
}
- _, err = tx.ExecContext(ctx, `INSERT INTO demo_claim_ops (`+demoClaimOpColumns+`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, op.ID, op.FlowHash, op.DemoID, op.SourceLifetime, op.SourceBox, op.Person, op.Version, op.ArtifactSHA256, op.Phase, op.Generation, op.Target.AccountID, op.Target.Sqid, op.Target.App, op.Target.Host, op.Target.Lifetime, op.Target.Region, op.Target.SeedID, op.Deadline.Unix(), op.SourceExpiresAt)
+ _, err = tx.ExecContext(ctx, `INSERT INTO demo_claim_ops (`+demoClaimOpColumns+`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, op.ID, op.FlowHash, op.DemoID, op.SourceLifetime, op.SourceBox, op.Person, op.Version, op.ArtifactSHA256, op.Phase, op.Generation, op.Target.AccountID, op.Target.Sqid, op.Target.App, op.Target.Host, op.Target.Lifetime, op.Target.Region, op.Target.SeedID, op.Deadline.Unix(), op.SourceExpiresAt, op.SourceJobID, op.SourceSHA256, op.SourceBytes)
if err != nil {
return claimOp{}, err
}
diff --git a/internal/console/demo_claim_target.go b/internal/console/demo_claim_target.go
index a9f1d0ec0..10033b496 100644
--- a/internal/console/demo_claim_target.go
+++ b/internal/console/demo_claim_target.go
@@ -23,6 +23,8 @@ type claimTarget struct {
Sqid, App, Host, Lifetime, Region, SeedID string
}
type claimOp struct {
+ SourceJobID, SourceSHA256 string
+ SourceBytes int64
ID, FlowHash, DemoID, SourceLifetime, SourceBox, Person, Version, ArtifactSHA256, Phase string
Generation int64
Target claimTarget
diff --git a/internal/console/demo_claim_transfer.go b/internal/console/demo_claim_transfer.go
index 4e0a3afeb..33822745e 100644
--- a/internal/console/demo_claim_transfer.go
+++ b/internal/console/demo_claim_transfer.go
@@ -5,6 +5,7 @@ import (
"crypto/sha256"
"database/sql"
"encoding/hex"
+ "encoding/json"
"errors"
"io"
"log"
@@ -23,6 +24,7 @@ import (
)
type demoClaimProgress struct {
+ SourceCopied bool
Wire []byte
Action, SHA, Reason string
HoldReady, HoldAck, Copied, Cleanup, AbortAck, HoldCleared bool
@@ -34,7 +36,7 @@ func (s *Store) demoClaimOp(ctx context.Context, id string) (claimOp, error) {
}
func (s *Server) claimProgress(ctx context.Context, id string) (demoClaimProgress, error) {
var p demoClaimProgress
- err := s.store.db.QueryRowContext(ctx, `SELECT work,action,hold_ready,hold_ack,snapshot_sha,snapshot_bytes,copied,cleanup,abort_ack,reason,retry_at,phase_until,hold_cleared FROM demo_claim_progress WHERE operation_id=?`, id).Scan(&p.Wire, &p.Action, &p.HoldReady, &p.HoldAck, &p.SHA, &p.Bytes, &p.Copied, &p.Cleanup, &p.AbortAck, &p.Reason, &p.RetryAt, &p.Until, &p.HoldCleared)
+ err := s.store.db.QueryRowContext(ctx, `SELECT work,action,hold_ready,hold_ack,snapshot_sha,snapshot_bytes,copied,cleanup,abort_ack,reason,retry_at,phase_until,hold_cleared,source_copied FROM demo_claim_progress WHERE operation_id=?`, id).Scan(&p.Wire, &p.Action, &p.HoldReady, &p.HoldAck, &p.SHA, &p.Bytes, &p.Copied, &p.Cleanup, &p.AbortAck, &p.Reason, &p.RetryAt, &p.Until, &p.HoldCleared, &p.SourceCopied)
return p, err
}
func (s *Server) claimBoundary(at string) error {
@@ -106,6 +108,10 @@ func (s *Server) advanceDemoClaimLocked(ctx context.Context, id string) error {
bounded, cancel := context.WithDeadline(ctx, op.Deadline)
defer cancel()
ctx = bounded
+ // Older in-flight claims must not cross the new commit prerequisite.
+ if op.Phase != "reserved" && !p.SourceCopied {
+ return s.beginDemoClaimAbort(ctx, op, "source_unready")
+ }
switch op.Phase {
case "reserved":
if !s.demoClaimEnabled() {
@@ -117,6 +123,17 @@ func (s *Server) advanceDemoClaimLocked(ctx context.Context, id string) error {
if err = s.pinDemoClaim(ctx, &op); err != nil {
return s.beginDemoClaimAbort(ctx, op, "source_unready")
}
+ if err = s.claimBoundary("source-pin"); err != nil {
+ return err
+ }
+ if !p.SourceCopied {
+ if err = s.copyDemoClaimSource(ctx, &op); err != nil {
+ if errors.Is(err, errClaimSourceInvalid) || errors.Is(err, os.ErrNotExist) {
+ return s.beginDemoClaimAbort(ctx, op, "source_unready")
+ }
+ return err
+ }
+ }
if _, err = release.SetPipeline(ctx, s.cfg.Releases, s.cfg.Key, op.Target.Sqid, op.Target.App, release.DefaultPipelineChannels(), op.Person); err != nil {
return err
}
@@ -256,22 +273,46 @@ func (s *Server) pinDemoClaim(ctx context.Context, op *claimOp) error {
if m.Kind != "binary" || len(m.Artifacts) != 1 || !demobuild.ValidDigest(art.SHA256) || art.Size <= 0 || art.Size > demobuild.BinaryMaxBytes {
return ErrDemoToken
}
- var published int
- if err = s.store.db.QueryRowContext(ctx, `SELECT count(*) FROM demo_jobs WHERE demo_id=? AND state='published' AND binary_sha256=?`, d.ID, art.SHA256).Scan(&published); err != nil {
+ rows, err := s.store.db.QueryContext(ctx, `SELECT id,job FROM demo_jobs WHERE demo_id=? AND state='published' AND binary_sha256=? AND ('v0.0.0-demo.' || generation)=?`, d.ID, art.SHA256, ptr.Version)
+ if err != nil {
return err
}
- if published == 0 {
- return ErrDemoToken
+ var selected demobuild.Job
+ count := 0
+ for rows.Next() {
+ var id string
+ var raw []byte
+ if err = rows.Scan(&id, &raw); err != nil {
+ break
+ }
+ var j demobuild.Job
+ if json.Unmarshal(raw, &j) != nil || j.ID != id || j.DemoID != d.ID || j.Account != d.AccountSqid || j.App != d.App || j.Lifetime != op.SourceLifetime || demoVersion(j) != ptr.Version || !demobuild.ValidJobID(j.ID) || !demobuild.ValidDigest(j.SourceSHA256) {
+ err = ErrDemoToken
+ break
+ }
+ selected = j
+ count++
}
- p, err := s.claimProgress(ctx, op.ID)
+ err = errors.Join(err, rows.Err(), rows.Close())
if err != nil {
return err
}
- if p.Copied && (op.Version != ptr.Version || op.ArtifactSHA256 != art.SHA256) {
+ if count != 1 {
+ return ErrDemoToken
+ }
+ var artifactCopied bool
+ if err = s.store.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM demo_claim_progress WHERE operation_id=? AND copied=1)`, op.ID).Scan(&artifactCopied); err != nil {
+ return err
+ }
+ if artifactCopied && (op.Version != ptr.Version || op.ArtifactSHA256 != art.SHA256) {
+ return ErrDemoToken
+ }
+ if op.SourceJobID != "" && (op.SourceJobID != selected.ID || op.SourceSHA256 != selected.SourceSHA256 || op.Version != ptr.Version || op.ArtifactSHA256 != art.SHA256) {
return ErrDemoToken
}
op.Version, op.ArtifactSHA256 = ptr.Version, art.SHA256
- _, err = s.store.db.ExecContext(ctx, `UPDATE demo_claim_ops SET version=?,artifact_sha256=? WHERE id=? AND phase='reserved'`, op.Version, op.ArtifactSHA256, op.ID)
+ op.SourceJobID, op.SourceSHA256 = selected.ID, selected.SourceSHA256
+ _, err = s.store.db.ExecContext(ctx, `UPDATE demo_claim_ops SET version=?,artifact_sha256=?,source_job_id=?,source_sha256=? WHERE id=? AND phase='reserved'`, op.Version, op.ArtifactSHA256, op.SourceJobID, op.SourceSHA256, op.ID)
return err
}
func demoClaimSourceMatches(op claimOp, d DemoRow, life *AppLife) bool {
@@ -653,7 +694,7 @@ func (s *Server) commitDemoClaim(ctx context.Context, op claimOp) error {
JOIN accounts c ON c.id=o.account_id
JOIN demo_apps d ON d.demo_id=o.demo_id JOIN apps src ON src.account_id=d.account_id AND src.app=d.app
WHERE o.id=? AND o.phase='verifying' AND o.deadline>? AND o.source_expires_at>?
- AND p.hold_ack=1 AND p.snapshot_sha!='' AND p.phase_until>?
+ AND p.source_copied=1 AND o.source_job_id!='' AND o.source_sha256!='' AND o.source_bytes>0 AND p.hold_ack=1 AND p.snapshot_sha!='' AND p.phase_until>?
AND a.demo_claim_op=o.id AND a.lifetime=o.target_lifetime AND a.deleted_at=0 AND a.expires_at=0 AND a.demo_id='' AND a.restoring=0
AND c.deleted_at=0 AND c.sqid=o.target_sqid AND m.role IN ('owner','member')
AND d.state='anonymous' AND d.purged_at=0 AND d.active_job_id='' AND d.claim_token_hash IS NOT NULL
@@ -671,11 +712,20 @@ func (s *Server) commitDemoClaim(ctx context.Context, op claimOp) error {
if err = reserveDemoMovedCapacity(ctx, tx, nil, time.Now()); err != nil {
return err
}
+ snapshot := claimedSource{Schema: 1, Operation: op.ID, Lifetime: op.Target.Lifetime, Job: op.SourceJobID, SHA256: op.SourceSHA256, Bytes: op.SourceBytes, Version: op.Version, ClaimedAt: time.Now().UTC().Truncate(time.Second)}
+ if !snapshot.valid() {
+ return ErrDemoToken
+ }
+ descriptor, err := json.Marshal(snapshot)
+ if err != nil {
+ return err
+ }
for _, q := range []struct {
sql string
args []any
}{
- {`INSERT INTO demo_claim_commits(operation_id,demo_id,committed_at) VALUES(?,?,?)`, []any{op.ID, op.DemoID, time.Now().Unix()}},
+ {`UPDATE apps SET claimed_source=? WHERE account_id=? AND app=? AND demo_claim_op=?`, []any{string(descriptor), op.Target.AccountID, op.Target.App, op.ID}},
+ {`INSERT INTO demo_claim_commits(operation_id,demo_id,committed_at) VALUES(?,?,?)`, []any{op.ID, op.DemoID, snapshot.ClaimedAt.Unix()}},
{`UPDATE demo_claim_ops SET phase='committed' WHERE id=?`, []any{op.ID}},
{`INSERT INTO demo_spent_tokens(hash,reason,spent_at) SELECT claim_token_hash,'kept',? FROM demo_apps WHERE demo_id=? AND claim_token_hash IS NOT NULL`, []any{time.Now().Unix(), op.DemoID}},
{`UPDATE demo_apps SET claim_token_hash=NULL WHERE demo_id=?`, []any{op.DemoID}},
diff --git a/internal/console/demo_claim_transfer_test.go b/internal/console/demo_claim_transfer_test.go
index e6dba1560..90db78a27 100644
--- a/internal/console/demo_claim_transfer_test.go
+++ b/internal/console/demo_claim_transfer_test.go
@@ -19,6 +19,7 @@ import (
"time"
lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/carlosframework/platform/internal/demobuild"
"github.com/carlosframework/platform/internal/democlaim"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
@@ -26,6 +27,10 @@ import (
)
func claimTransferFixture(t *testing.T, flowOut ...*string) (*Server, claimOp, []byte) {
+ t.Helper()
+ return claimTransferFixtureBefore(t, nil, flowOut...)
+}
+func claimTransferFixtureBefore(t *testing.T, before func(*Server, DemoRow, demobuild.Job, demobuild.Result), flowOut ...*string) (*Server, claimOp, []byte) {
t.Helper()
s, d, j, out := demoPublishFixture(t)
s.demoClaimTestEnabled = true
@@ -40,6 +45,14 @@ func claimTransferFixture(t *testing.T, flowOut ...*string) (*Server, claimOp, [
if _, err := s.store.db.Exec(`UPDATE demo_apps SET active_job_id='' WHERE demo_id=?`, d.ID); err != nil {
t.Fatal(err)
}
+ if before != nil {
+ before(s, d, j, out)
+ var err error
+ d, err = s.store.demoByID(t.Context(), d.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
raw, _ := randomToken()
if len(flowOut) > 0 {
*flowOut[0] = raw
diff --git a/internal/console/demo_claim_ux_test.go b/internal/console/demo_claim_ux_test.go
index 86dc45dd9..cef83bb9f 100644
--- a/internal/console/demo_claim_ux_test.go
+++ b/internal/console/demo_claim_ux_test.go
@@ -43,7 +43,7 @@ func TestDemoClaimUXProductionPages(t *testing.T) {
t.Error("ticket lost after selection")
}
if phase == "done" {
- for _, want := range []string{"Open your app", "Keep building with your agent", `<details class="claim-command">`, `data-state="claimed"`} {
+ for _, want := range []string{"Open your app", "Still in the chat where you built it?", "No saved source for this app.", `data-state="claimed"`} {
if !strings.Contains(body, want) {
t.Errorf("result missing %q", want)
}
diff --git a/internal/console/demo_jobs_test.go b/internal/console/demo_jobs_test.go
index 35642151a..737881514 100644
--- a/internal/console/demo_jobs_test.go
+++ b/internal/console/demo_jobs_test.go
@@ -71,8 +71,16 @@ func (s *demoCountingStore) Put(ctx context.Context, key string, b []byte, tag s
}
return s.Store.Put(ctx, key, b, tag)
}
-func demoJobSource() demobuild.Source {
- b := []byte("validated test source")
+func demoJobSource(extra ...string) demobuild.Source {
+ var buf bytes.Buffer
+ gz := gzip.NewWriter(&buf)
+ tw := tar.NewWriter(gz)
+ body := []byte("package main\nfunc main() {}\n" + strings.Join(extra, ""))
+ _ = tw.WriteHeader(&tar.Header{Name: "main.go", Mode: 0600, Size: int64(len(body))})
+ _, _ = tw.Write(body)
+ _ = tw.Close()
+ _ = gz.Close()
+ b := buf.Bytes()
hash := sha256.Sum256(b)
return demobuild.Source{Archive: b, SHA256: hex.EncodeToString(hash[:])}
}
diff --git a/internal/console/server.go b/internal/console/server.go
index bb4db0a20..94ef25e75 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -998,6 +998,7 @@ type Config struct {
// Server is the console's http.Handler.
type Server struct {
+ sourceDownloads sourceDownloads
haPools map[string][]string
haScopeInvalid bool
capacityStart sync.Once
@@ -2047,6 +2048,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
s.registerRoute("GET /a/{sqid}/apps/new", s.handleNewAppForm)
s.registerRoute("POST /a/{sqid}/apps/new", s.handleNewApp)
s.registerRoute("POST /a/{sqid}/apps/new/region", s.handleNewAppRegion)
+ s.registerRoute("GET /a/{sqid}/apps/{app}/source", s.sourceAdmission(s.handleAppSource, false))
s.registerRoute("GET /a/{sqid}/apps/{app}", s.handleApp)
s.registerRoute("GET /a/{sqid}/apps/{app}/index", s.handleAppIndex)
s.registerRoute("GET /a/{sqid}/apps/{app}/releases", s.handleAppReleases)
@@ -2450,7 +2452,8 @@ func normalizeHost(host string) string {
// page is the one bag every template reads from; unused fields are ignored.
type page struct {
- RegionPicker *regionPickerView // new-app page: nil = no picker
+ HasClaimedSource bool
+ RegionPicker *regionPickerView // new-app page: nil = no picker
// NewAppAnalytics is the new-app page's analytics checkbox: nil = no
// checkbox, and the app follows the account (analyticsonramp.go).
NewAppAnalytics *newAppAnalyticsView
@@ -4455,6 +4458,9 @@ func (s *Server) appPage(w http.ResponseWriter, r *http.Request, tab string) (pa
p := s.accountPage(w, r, addr, raw, acct, role)
p.Title = app
p.AppName = app
+ if role == RoleOwner || role == RoleMember {
+ p.HasClaimedSource, _ = s.store.hasClaimedSource(acct.ID, app)
+ }
p.ActiveTab = tab
p.ActiveNav = "apps"
p.Detail = &views[0]
diff --git a/internal/console/static/demo_claim.js b/internal/console/static/demo_claim.js
index 465e589da..731780d73 100644
--- a/internal/console/static/demo_claim.js
+++ b/internal/console/static/demo_claim.js
@@ -53,20 +53,23 @@
HTMLFormElement.prototype.submit.call(form);
});
}
- for (const copy of document.querySelectorAll("[data-copy-target]")) {
- const command = document.getElementById(copy.dataset.copyTarget);
- if (!command || typeof navigator.clipboard?.writeText !== "function") continue;
- copy.hidden = false;
- let reset;
- copy.addEventListener("click", async () => {
- try {
- await navigator.clipboard.writeText(command.textContent);
- copy.textContent = copy.dataset.copied;
- clearTimeout(reset);
- reset = setTimeout(() => { copy.textContent = copy.dataset.copy; }, 2000);
- } catch (_) { copy.hidden = true; }
- });
- }
+ const bindCopies = root => {
+ for (const copy of root.querySelectorAll("[data-copy-target]")) {
+ const command = document.getElementById(copy.dataset.copyTarget);
+ if (!command || typeof navigator.clipboard?.writeText !== "function") continue;
+ copy.hidden = false;
+ let reset;
+ copy.addEventListener("click", async () => {
+ try {
+ await navigator.clipboard.writeText(command.textContent);
+ copy.textContent = copy.dataset.copied;
+ clearTimeout(reset);
+ reset = setTimeout(() => { copy.textContent = copy.dataset.copy; }, 2000);
+ } catch (_) { copy.hidden = true; }
+ });
+ }
+ };
+ bindCopies(document);
const choice = document.querySelector('form[action="/demo/claim/select"]');
if (choice) {
const radios = choice.querySelectorAll('input[type="radio"]:not(:disabled)');
@@ -115,7 +118,15 @@
// Never advance beyond the server's last reported stage.
while (stage < target) { await hold(); await setStage(stage + 1); }
};
- const finish = result => {
+ const finish = async result => {
+ const response = await fetch("/demo/claim", {credentials:"same-origin", mode:"same-origin", cache:"no-store", signal:AbortSignal.timeout(10000)});
+ if (!response.ok) throw new Error();
+ const page = new DOMParser().parseFromString(await response.text(), "text/html");
+ if (page.getElementById("claim")?.dataset.state !== "claimed") throw new Error();
+ const next = page.querySelector(".claim-next");
+ if (!next) throw new Error();
+ claim.querySelector(".claim-next").replaceWith(next);
+ bindCopies(next);
const url = new URL(result.url);
if (url.protocol !== "https:" || url.username || url.password) throw new Error();
const finished = document.getElementById("claim-finished");
@@ -154,7 +165,7 @@
if (result.state === "aborted") return;
} else {
await advance(result.step);
- if (result.state === "claimed") { await hold(); finish(result); return; }
+ if (result.state === "claimed") { await hold(); await finish(result); return; }
}
failures = 0;
} catch (_) {
diff --git a/internal/console/store.go b/internal/console/store.go
index ad99449b1..7803e63d6 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -2399,6 +2399,13 @@ func (s *Store) moveApp(app string, from, to int64) error {
if atSrc == 0 {
return fmt.Errorf("console: account %d does not claim %q", from, app)
}
+ var savedSource string
+ if err := tx.QueryRow(`SELECT claimed_source FROM apps WHERE account_id=? AND app=?`, from, app).Scan(&savedSource); err != nil {
+ return err
+ }
+ if savedSource != "" {
+ return errors.New(sourceMoveRefused)
+ }
var srcExpires int64
if err := tx.QueryRow(`SELECT expires_at FROM apps WHERE app = ? AND account_id = ?`, app, from).Scan(&srcExpires); err != nil {
return err
@@ -2543,14 +2550,18 @@ func (s *Store) renameAppIn(accountID int64, from, to string, undo bool) error {
return err
}
defer tx.Rollback()
+ var savedSource string
var createdAt, expiresAt int64
- err = tx.QueryRow(`SELECT created_at, expires_at FROM apps WHERE account_id = ? AND app = ? AND deleted_at = 0`,
- accountID, from).Scan(&createdAt, &expiresAt)
+ err = tx.QueryRow(`SELECT created_at, expires_at, claimed_source FROM apps WHERE account_id = ? AND app = ? AND deleted_at = 0`,
+ accountID, from).Scan(&createdAt, &expiresAt, &savedSource)
if err == sql.ErrNoRows {
return fmt.Errorf("console: this account does not claim %q", from)
} else if err != nil {
return err
}
+ if savedSource != "" {
+ return errors.New("This app has shipped — its name is baked into its releases' bucket keys, so renaming it is not supported. Create a new app and ship there instead.")
+ }
if expiresAt > 0 {
return ErrTemporaryApp
}
diff --git a/internal/console/templates/app_overview.html b/internal/console/templates/app_overview.html
index 5436d95ff..df7a9df6f 100644
--- a/internal/console/templates/app_overview.html
+++ b/internal/console/templates/app_overview.html
@@ -2,6 +2,8 @@
{{if .Flash}}<p class="banner">{{.Flash}}</p>{{end}}
{{if .FlashErr}}<p class="banner error">{{.FlashErr}}</p>{{end}}
{{template "appnav" .}}
+{{if .HasClaimedSource}}<section class="card"><p><a class="btn btn-secondary" href="/a/{{.Account.Sqid}}/apps/{{.AppName}}/source">Download source</a></p><p>Download the source saved when you kept this app. Later deployments do not update it.</p></section>{{end}}
+
{{template "accountreviewbanner" .}}
{{with .Overview}}
<section class="pagehead" aria-label="App status">
diff --git a/internal/console/templates/demo_claim.html b/internal/console/templates/demo_claim.html
index 9bd379816..4f2e39f93 100644
--- a/internal/console/templates/demo_claim.html
+++ b/internal/console/templates/demo_claim.html
@@ -173,12 +173,15 @@
<div id="claim-finished"{{if ne .State "claimed"}} hidden{{end}}>
<p>{{.Copy.completeDetail}}</p>
<p class="claim-result"><a class="btn claim-open" href="{{.URL}}" rel="noreferrer">{{.Copy.open}}</a></p><p class="claim-result-address">{{.URL}}</p>
-<section class="claim-next"><h2>{{.Copy.keepGoing}}</h2><h3>{{.Copy.agentHeading}}</h3><p>{{.Copy.agentDetail}}</p>
-<div class="claim-paste"><code id="claim-agent-command">{{.Copy.agentLine}}</code><button class="btn-sm btn-secondary" type="button" data-copy-target="claim-agent-command" data-copy="{{.Copy.copy}}" data-copied="{{.Copy.copied}}" hidden>{{.Copy.copy}}</button></div>
-<details class="claim-command"><summary>{{.Copy.cliHeading}}</summary>
-<p>{{.Copy.cliCommandLabel}}</p><pre><code id="claim-cli-command">{{.Copy.next}}</code></pre>
-<button id="claim-copy" data-copy-target="claim-cli-command" class="btn-sm btn-secondary" type="button" data-copy="{{.Copy.copy}}" data-copied="{{.Copy.copied}}" aria-live="polite" hidden>{{.Copy.copy}}</button>
-</details><p class="claim-detail">{{.Copy.oldAddress}}</p></section></div>
+<section class="claim-next"><h2>{{.Copy.keepGoing}}</h2>
+{{if .AccountSqid}}<h3>{{.Copy.sameChat}}</h3><p>{{.Copy.sameChatLine}}</p>
+{{if .SourceSteps}}<h3>{{.Copy.agentHeading}}</h3><p>{{.Copy.agentDetail}}</p>
+<div class="claim-paste"><code id="claim-agent-command">{{.Copy.agentLine}}</code><button class="btn-sm btn-secondary" type="button" data-copy-target="claim-agent-command" data-copy="{{.Copy.copy}}" data-copied="{{.Copy.copied}}" hidden>{{.Copy.copy}}</button></div>{{end}}
+<p class="claim-detail">{{.Copy.sourceNote}}</p>
+{{if .SourceSteps}}<details class="claim-command"><summary>{{.Copy.cliHeading}}</summary>
+{{range .SourceSteps}}<h3>{{.Label}}</h3><p>{{.Instruction}}</p><pre><code id="{{.ID}}">{{.Command}}</code></pre>
+<button data-copy-target="{{.ID}}" class="btn-sm btn-secondary" type="button" data-copy="{{$.Copy.copy}}" data-copied="{{$.Copy.copied}}" aria-live="polite" hidden>{{$.Copy.copy}}</button>{{end}}
+</details>{{end}}{{end}}<p class="claim-detail">{{.Copy.oldAddress}}</p></section></div>
{{end}}
{{if and .HasIntent .CanClaim}}
{{if .Address}}
diff --git a/internal/console/testdata/app_source_browser.mjs b/internal/console/testdata/app_source_browser.mjs
new file mode 100644
index 000000000..ea0a1869e
--- /dev/null
+++ b/internal/console/testdata/app_source_browser.mjs
@@ -0,0 +1,83 @@
+import {spawn} from 'node:child_process';
+import assert from 'node:assert/strict';
+import {writeFile} from 'node:fs/promises';
+import {captureClaim, watchClaimCSP} from './demo_claim_layout.mjs';
+
+const [binary, profile, origin, cookie, token, appPath, screenshots] = process.argv.slice(2);
+const chrome = spawn(binary, ['--headless', '--no-sandbox', '--disable-gpu',
+ '--disable-dev-shm-usage', '--disable-background-networking', '--disable-component-update',
+ '--disable-default-apps', '--disable-extensions', '--disable-sync', '--no-proxy-server',
+ '--no-first-run', '--no-default-browser-check', '--remote-debugging-pipe',
+ '--user-data-dir=' + profile], {stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe']});
+let sequence = 0, buffered = '', session;
+const pending = new Map();
+chrome.stdio[4].on('data', bytes => {
+ buffered += bytes.toString();
+ let end;
+ while ((end = buffered.indexOf('\0')) !== -1) {
+ const message = JSON.parse(buffered.slice(0, end));
+ buffered = buffered.slice(end + 1);
+ const resolve = pending.get(message.id);
+ if (resolve) { pending.delete(message.id); resolve(message); }
+ }
+});
+async function call(method, params = {}, attached = true) {
+ const id = ++sequence;
+ const result = new Promise(resolve => pending.set(id, resolve));
+ chrome.stdio[3].write(JSON.stringify({id, method, params, ...(attached && session ? {sessionId:session} : {})}) + '\0');
+ const message = await result;
+ assert.equal(message.error, undefined, JSON.stringify(message.error));
+ return message.result;
+}
+async function evaluate(expression) {
+ const result = await call('Runtime.evaluate', {expression, returnByValue:true});
+ assert.equal(result.exceptionDetails, undefined);
+ return result.result.value;
+}
+async function until(expression) {
+ for (let i = 0; i < 150; i++) {
+ if (await evaluate(expression)) return;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ throw Error('browser_condition_timeout: ' + await evaluate('JSON.stringify({text:document.body.innerText,email:document.getElementById("email")?.value,focus:document.activeElement.tagName,valid:document.querySelector("form")?.checkValidity()})'));
+}
+async function key(key, code, number) {
+ await call('Input.dispatchKeyEvent', {type:key === 'Enter' ? 'keyDown' : 'rawKeyDown', key, code, windowsVirtualKeyCode:number, ...(key === 'Enter' ? {text:'\r', unmodifiedText:'\r'} : {})});
+ await call('Input.dispatchKeyEvent', {type:'keyUp', key, code, windowsVirtualKeyCode:number});
+}
+
+const timer=setTimeout(()=>{chrome.kill('SIGKILL');process.exitCode=1},80000);
+try {
+ const created=await call('Target.createTarget',{url:'about:blank'},false);
+ session=(await call('Target.attachToTarget',{targetId:created.targetId,flatten:true},false)).sessionId;
+ await call('Page.enable');
+ await call('Page.addScriptToEvaluateOnNewDocument',{source:watchClaimCSP});
+ await call('Browser.grantPermissions',{origin,permissions:['clipboardReadWrite','clipboardSanitizedWrite']},false);
+ await call('Network.setCookie',{name:'carlos_demo_claim_flow',value:cookie,url:origin,path:'/demo/claim'});
+ await call('Network.setCookie',{name:'carlos_console_session',value:token,url:origin,path:'/'});
+ await call('Page.navigate',{url:origin+'/demo/claim'});
+ await until('document.readyState === "complete" && document.querySelector(".claim-next [data-copy-target]")?.hidden === false');
+ assert.equal(await evaluate('document.querySelector(".claim-command").open'),false);
+ await captureClaim(call,evaluate,screenshots,'done-closed');
+ await evaluate('document.querySelector(".claim-command").open=true');
+ await captureClaim(call,evaluate,screenshots,'done-open');
+ const ids=await evaluate('Array.from(document.querySelectorAll(".claim-next [data-copy-target]"),b=>b.dataset.copyTarget)');
+ assert.equal(ids.length,4);
+ for (const id of ids) {
+ const expected=await evaluate(`document.getElementById(${JSON.stringify(id)}).textContent`);
+ await call('Runtime.evaluate',{expression:`document.querySelector('[data-copy-target="${id}"]').click()`,userGesture:true});
+ await new Promise(resolve=>setTimeout(resolve,100));
+ const copied=await call('Runtime.evaluate',{expression:'navigator.clipboard.readText()',awaitPromise:true,returnByValue:true,userGesture:true});
+ assert.equal(copied.result.value,expected);
+ }
+ await call('Page.navigate',{url:origin+appPath});
+ await until('document.readyState === "complete" && Array.from(document.querySelectorAll("a")).some(a=>a.textContent==="Download source")');
+ assert.equal(await evaluate('Array.from(document.querySelectorAll("a")).find(a=>a.textContent==="Download source").getAttribute("href")'),appPath+'/source');
+ await captureClaim(call,evaluate,screenshots,'app-source');
+ assert.deepEqual(await evaluate('window.claimCSPViolations'),[]);
+ process.stdout.write('12 screenshots; four Copy buttons; zero CSP violations\n');
+} finally {
+ clearTimeout(timer);
+ await call('Browser.close',{},false).catch(()=>{});
+ chrome.kill();
+}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index f04729465..e5b489801 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -42,6 +42,7 @@ route GET /a/{sqid}/apps/{app}/releases
route GET /a/{sqid}/apps/{app}/settings
route GET /a/{sqid}/apps/{app}/settings/index
route GET /a/{sqid}/apps/{app}/settings/{section}
+route GET /a/{sqid}/apps/{app}/source
route GET /a/{sqid}/billing
route GET /a/{sqid}/billing/continue
route GET /a/{sqid}/billing/done
@@ -109,6 +110,7 @@ route GET /api/cli/apps/{account}/{app}/routes
route GET /api/cli/apps/{account}/{app}/schedules
route GET /api/cli/apps/{account}/{app}/sidecars
route GET /api/cli/apps/{account}/{app}/sidecars/{name}
+route GET /api/cli/apps/{account}/{app}/source
route GET /api/cli/apps/{account}/{app}/store
route GET /api/cli/apps/{account}/{app}/store/scan
route GET /api/cli/apps/{account}/{app}/store/scan/object
diff --git a/internal/console/testdata/demo_claim_browser.mjs b/internal/console/testdata/demo_claim_browser.mjs
index c22c0c43f..91953663a 100644
--- a/internal/console/testdata/demo_claim_browser.mjs
+++ b/internal/console/testdata/demo_claim_browser.mjs
@@ -166,7 +166,7 @@ async function runUX(scenes) {
await call('Page.reload');
await until('document.readyState === "complete" && document.getElementById("claim")?.dataset.state === "claimed"');
assert.equal(await evaluate('document.getElementById("claim").classList.contains("is-celebrating")'),false);
- assert.equal(await evaluate('document.querySelector(".claim-command").open'),false);
+ assert.equal(await evaluate('document.querySelector(".claim-command")?.open ?? false'),false);
}
await captureClaim(call,evaluate,screenshots,scene.Name,[390,1280]);
if (scene.Name === 'fast') await liveMotion(scene);
diff --git a/internal/console/testdata/demo_claim_resume_browser.mjs b/internal/console/testdata/demo_claim_resume_browser.mjs
index 016410fb3..0de1d29b7 100644
--- a/internal/console/testdata/demo_claim_resume_browser.mjs
+++ b/internal/console/testdata/demo_claim_resume_browser.mjs
@@ -186,24 +186,24 @@ try {
await evaluate('document.querySelector(".claim-command").open = true');
assert.equal(security.length,0,JSON.stringify(security));
process.stdout.write('progress: polled to step 2 and done automatically; no CSP violations\n');
- assert.equal(await evaluate('document.getElementById("claim-copy").hidden'), false);
- await evaluate('document.getElementById("claim-copy").click()');
- await until('document.getElementById("claim-copy").textContent === "Copied"');
- assert.equal(await evaluate('window.claimClipboard'), 'carlos auth login --console '+target);
- await until('document.getElementById("claim-copy").textContent === "Copy"');
+ assert.equal(await evaluate('document.querySelector("[data-copy-target=claim-cli-command]").hidden'), false);
+ await evaluate('document.querySelector("[data-copy-target=claim-cli-command]").click()');
+ await until('document.querySelector("[data-copy-target=claim-cli-command]").textContent === "Copied"');
+ assert.equal(await evaluate('window.claimClipboard'), "carlos auth login --console '"+target+"'");
+ await until('document.querySelector("[data-copy-target=claim-cli-command]").textContent === "Copy"');
await call('Page.removeScriptToEvaluateOnNewDocument', {identifier:clipboardStub.identifier});
const noClipboard = await call('Page.addScriptToEvaluateOnNewDocument', {source:
"Object.defineProperty(navigator, 'clipboard', {value:undefined})"});
await call('Page.navigate', {url:target+'/demo/claim'});
- await until('document.readyState === "complete" && !!document.getElementById("claim-copy")');
- assert.equal(await evaluate('document.getElementById("claim-copy").getBoundingClientRect().height'), 0);
- assert.equal(await evaluate('document.getElementById("claim-cli-command").textContent'), 'carlos auth login --console '+target);
+ await until('document.readyState === "complete" && !!document.querySelector("[data-copy-target=claim-cli-command]")');
+ assert.equal(await evaluate('document.querySelector("[data-copy-target=claim-cli-command]").getBoundingClientRect().height'), 0);
+ assert.equal(await evaluate('document.getElementById("claim-cli-command").textContent'), "carlos auth login --console '"+target+"'");
await call('Page.removeScriptToEvaluateOnNewDocument', {identifier:noClipboard.identifier});
await call('Network.setBlockedURLs', {urls:['*demo_claim.js*']});
await call('Page.navigate', {url:target+'/demo/claim'});
- await until('document.readyState === "complete" && !!document.getElementById("claim-copy")');
- assert.equal(await evaluate('document.getElementById("claim-copy").getBoundingClientRect().height'), 0);
- assert.equal(await evaluate('document.getElementById("claim-cli-command").textContent'), 'carlos auth login --console '+target);
+ await until('document.readyState === "complete" && !!document.querySelector("[data-copy-target=claim-cli-command]")');
+ assert.equal(await evaluate('document.querySelector("[data-copy-target=claim-cli-command]").getBoundingClientRect().height'), 0);
+ assert.equal(await evaluate('document.getElementById("claim-cli-command").textContent'), "carlos auth login --console '"+target+"'");
await call('Network.setBlockedURLs', {urls:[]});
assert.deepEqual(await evaluate('window.claimCSPViolations'), []);
process.stdout.write('clipboard: copied command, reset label, hidden without clipboard or script\n');
diff --git a/internal/demobuild/source.go b/internal/demobuild/source.go
index 8debef255..d628e3216 100644
--- a/internal/demobuild/source.go
+++ b/internal/demobuild/source.go
@@ -44,18 +44,27 @@ type SourceFile struct {
SHA256 string
}
+func ValidateArchive(r io.Reader) (Source, error) {
+ src, _, err := validateSource(r, Lock{}, true)
+ return src, err
+}
+
// ValidateSource never extracts files or executes tools. Archive contains the
// accepted original gzip bytes. Files is a sorted inventory of regular files;
// consumers must revalidate stored bytes before extracting in their sandbox.
// Extraction must use fixed safe modes and ownership, ignoring tar metadata.
func ValidateSource(r io.Reader, lock Lock) (Source, []Diagnostic, error) {
+ return validateSource(r, lock, false)
+}
+
+func validateSource(r io.Reader, lock Lock, archiveOnly bool) (Source, []Diagnostic, error) {
refuse := func(file string, line int) (Source, []Diagnostic, error) {
if !safeDiagnosticFile(file) {
file, line = "", 0
}
return Source{}, []Diagnostic{{File: file, Line: line, Message: "DEMO-SOURCE"}}, ErrSource
}
- if err := lock.validate(); err != nil {
+ if err := lock.validate(); !archiveOnly && err != nil {
return Source{}, nil, ErrLock
}
original, err := io.ReadAll(io.LimitReader(r, demo.SourceMaxBytes+1))
@@ -67,6 +76,9 @@ func ValidateSource(r io.Reader, lock Lock) (Source, []Diagnostic, error) {
if err != nil {
return refuse("", 0)
}
+ if archiveOnly && len(gz.Extra) != 0 {
+ return refuse("", 0)
+ }
gz.Multistream(false)
expanded, readErr := io.ReadAll(io.LimitReader(gz, tarMaxBytes+1))
closeErr := gz.Close()
@@ -129,6 +141,10 @@ func ValidateSource(r io.Reader, lock Lock) (Source, []Diagnostic, error) {
}
}
}
+ if archiveOnly {
+ digest := sha256.Sum256(original)
+ return Source{Archive: original, SHA256: hex.EncodeToString(digest[:])}, nil, nil
+ }
if !validModule(files["go.mod"], files["go.sum"], lock) {
return refuse("go.mod", 0)
}
diff --git a/internal/demobuild/source_test.go b/internal/demobuild/source_test.go
index a4d4d0dbc..ac6348bd8 100644
--- a/internal/demobuild/source_test.go
+++ b/internal/demobuild/source_test.go
@@ -367,3 +367,39 @@ func TestDemoImports(t *testing.T) {
}
})
}
+
+func TestClaimedSourceArchive(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ entries []archiveEntry
+ ok bool
+ }{
+ {"no-current-lock", []archiveEntry{{"go.mod", "module old.example/app\ngo 1.22\n", tar.TypeReg}, {".env", "TOKEN=exact-source-secret", tar.TypeReg}}, true},
+ {"traversal", []archiveEntry{{"../escape", "bad", tar.TypeReg}}, false},
+ {"absolute", []archiveEntry{{"/escape", "bad", tar.TypeReg}}, false},
+ {"windows", []archiveEntry{{"C:/escape", "bad", tar.TypeReg}}, false},
+ {"link", []archiveEntry{{"link", "", tar.TypeSymlink}}, false},
+ {"hardlink", []archiveEntry{{"link", "", tar.TypeLink}}, false},
+ {"fifo", []archiveEntry{{"fifo", "", tar.TypeFifo}}, false},
+ {"duplicate", []archiveEntry{{"file", "a", tar.TypeReg}, {"file", "b", tar.TypeReg}}, false},
+ {"parent-file", []archiveEntry{{"file", "a", tar.TypeReg}, {"file/child", "b", tar.TypeReg}}, false},
+ {"file-cap", []archiveEntry{{"big", strings.Repeat("x", FileMaxBytes+1), tar.TypeReg}}, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ b := gzipBytes(t, tarBytes(t, tc.entries))
+ src, err := ValidateArchive(bytes.NewReader(b))
+ if (err == nil) != tc.ok {
+ t.Fatal(err)
+ }
+ if tc.ok && !bytes.Equal(src.Archive, b) {
+ t.Fatal("archive changed")
+ }
+ })
+ }
+ b := gzipBytes(t, tarBytes(t, []archiveEntry{{"a", "b", tar.TypeReg}}))
+ for _, bad := range [][]byte{append(append([]byte{}, b...), b...), append(append([]byte{}, b...), 1), b[:len(b)-1]} {
+ if _, err := ValidateArchive(bytes.NewReader(bad)); err == nil {
+ t.Fatal("gzip framing accepted")
+ }
+ }
+}
diff --git a/internal/provision/claim_source_census_test.go b/internal/provision/claim_source_census_test.go
new file mode 100644
index 000000000..b3ac8f9ac
--- /dev/null
+++ b/internal/provision/claim_source_census_test.go
@@ -0,0 +1,28 @@
+package provision
+
+// The source PUT is create-only at the validated reserved target's
+// source/claims/<operation>/source.tar.gz key. It never writes an instance
+// record. The route registries add person-only source GET doors and retain
+// their existing instance/sidecar registrations. These are author
+// classifications; independent approval remains pending.
+func claimSourceWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), regionHAG2FixesWriteCensusInventory()...)
+ for _, next := range []censusEntry{
+ {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "0a4379408122d8252e77f108c512c537fea272b830315a5d61354f6e57ce6151"},
+ {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "552c144a06bd68e0663f18310e3a042ed42dd08418e138a31c11de633e171ecb"},
+ {"internal/console/app_source.go", "Server.copyDemoClaimSource", "nonrecord", "sel:Put", "d4f17ca3c5009fbef5c419ad5335178868361a409426a861b66180b6e733f36e"},
+ } {
+ found := false
+ for i, old := range entries {
+ if old.File == next.File && old.Unit == next.Unit {
+ entries[i] = next
+ found = true
+ break
+ }
+ }
+ if !found {
+ entries = append(entries, next)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 205059a69..5f3d95215 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := regionHAG2FixesWriteCensusInventory()
+ inventory := claimSourceWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index ac3afe699..9db885c48 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -116,3 +116,4 @@ plan14-root-reads-fix-incomplete-domains-pass.tsv 61027a32e31cb7ce017304f526f668
plan14-root-reads-signin-first-run-mobile.tsv 61027a32e31cb7ce017304f526f668c26980999e2699a3013a82e2630164143e
plan14-root-reads-claim-ux-edge.tsv 889ce9f72f93b581b29527e5c5d4410b47732424ce8ce45c080904ebb6c52195
plan14-root-reads-region-ha-g3-fixes.tsv cd001bf3a9a8871f12d1ca9cfa0a925760c1fc345dc911246ffaabc235dfabf6
+plan14-root-reads-claim-source.tsv 5558a3fa153fc1ef971756b4bf20bca57c2a1c80348556b9ffdff86b0d5b149f
diff --git a/internal/provision/testdata/plan14-root-reads-claim-source.tsv b/internal/provision/testdata/plan14-root-reads-claim-source.tsv
new file mode 100644
index 000000000..b03b3644b
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-claim-source.tsv
@@ -0,0 +1,11 @@
+# Census overlay claim-source, written by census-propose (#369). census-ruling-claim-source, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-claim-source.md.
+# 0 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 3 new dispositions: 0 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 1 quiet units retired while they read nothing, 0 other.
+@legacy aef8585951ea488700e67e0f5bd308abcda89b3e88c21c05d6d99e833939880b apps_source.go pullAppSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=Person CLI downloads a bounded authenticated response, verifies archive, digest and size, and exclusively creates an operator-selected mode-0600 output; removes partial output. No extraction or execution. file:OpenFile@181,file:ReadAll@1155,file:ReadAll@1735 9a5e7d16099332410d2bd3ad816175083a17bc9207d15865e87d39c714c61633
+@legacy e80b48ae75821759c1a9c721bd8623626b3e54a92ae3750d1022518352441213 internal/demobuild/source.go validateSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=Moves existing bounded gzip/tar parsing into a shared validator; structural-only path does not enforce today’s dependency lock. No extraction or execution; source build validation retains its dependency checks. file:ReadAll@2075,file:ReadAll@430,file:ReadAll@799 6861ec4bf8a9871bb33dc22199c17ab74afc481d7d09eb86951715504e6746a2
+apps_source.go pullAppSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=Person CLI downloads a bounded authenticated response, verifies archive, digest and size, and exclusively creates an operator-selected mode-0600 output; removes partial output. No extraction or execution. file:OpenFile@181,file:ReadAll@1155,file:ReadAll@1735 9a5e7d16099332410d2bd3ad816175083a17bc9207d15865e87d39c714c61633
+internal/demobuild/source.go validateSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=Moves existing bounded gzip/tar parsing into a shared validator; structural-only path does not enforce today’s dependency lock. No extraction or execution; source build validation retains its dependency checks. file:ReadAll@2075,file:ReadAll@430,file:ReadAll@799 6861ec4bf8a9871bb33dc22199c17ab74afc481d7d09eb86951715504e6746a2
+@remove internal/demobuild/source.go ValidateSource
+@removed internal/demobuild/source.go ValidateSource H3 census-ruling-claim-source;basis=Delegates existing build validation to validateSource with archiveOnly=false; direct reads moved to that helper.
+@coverage . d273744eb9d288a168f8854c864455a710c1bf26762bfcf0a22d984ff6486853
+@coverage internal/demobuild 53fcaf03fe6e54b587259981799462edd33660d373b2fb80e91351a8b66e95fb