carlos / platform Public

Fix claimed source privacy, download locks and archive compatibility

codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev 08bf81931c93e7ead403243c38eeca27500af825 parent 5b8d7b6
15 files changed, +352 −86
  • apps_source.go +17 −9
  • apps_source_e2e_test.go +10 −0
  • apps_source_test.go +40 −5
  • docs/superpowers/notes/census-proposal-claim-source.md +2 −2
  • internal/console/app_source.go +47 −37
  • internal/console/app_source_test.go +95 −1
  • internal/console/demo_claim_kept_test.go +63 −2
  • internal/console/demo_claim_page.go +20 −13
  • internal/console/static/demo_claim.js +6 −3
  • internal/console/svcroutes_test.go +3 −0
  • internal/console/templates/demo_claim.html +2 −2
  • internal/demobuild/source.go +1 −4
  • internal/demobuild/source_test.go +38 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-claim-source.tsv +7 −7

CI failed — run details

diff --git a/apps_source.go b/apps_source.go
index d0e3c1bdf..14e797d53 100644
--- a/apps_source.go
+++ b/apps_source.go
@@ -10,6 +10,7 @@ import (
"log"
"net/http"
"os"
+ "path/filepath"
"strings"
"time"
@@ -66,19 +67,18 @@ func runAppsSource(args []string) {
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 := os.Lstat(output); err == nil {
+ return "", errors.New(sourceExists)
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return "", errors.New(sourceTemporary)
+ }
+ f, err := os.CreateTemp(filepath.Dir(output), ".carlos-source-*")
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)
- }
+ _ = os.Remove(f.Name())
}()
req, err := http.NewRequestWithContext(ctx, "GET", c.base+path, nil)
if err != nil {
@@ -128,6 +128,14 @@ func pullAppSource(ctx context.Context, c *consoleClient, path, output string) (
if err = f.Close(); err != nil {
return "", errors.New(sourceTemporary)
}
- saved = true
+ if err = ctx.Err(); err != nil {
+ return "", errors.New(sourceTemporary)
+ }
+ if err = os.Link(f.Name(), output); err != nil {
+ if errors.Is(err, os.ErrExist) {
+ return "", errors.New(sourceExists)
+ }
+ return "", errors.New(sourceTemporary)
+ }
return at.UTC().Format(time.RFC3339), nil
}
diff --git a/apps_source_e2e_test.go b/apps_source_e2e_test.go
index 95f51d4d8..e46ec6315 100644
--- a/apps_source_e2e_test.go
+++ b/apps_source_e2e_test.go
@@ -135,6 +135,16 @@ func TestAppsSourceThreeSteps(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ for _, token := range []string{"", "expired-token"} {
+ out := filepath.Join(dir, "unsigned-source.tar.gz")
+ _, err := pullAppSource(ctx, newConsoleClient(api.URL, token), "/api/cli/apps/"+account+"/"+app+"/source?exact=sqid", out)
+ if err == nil || err.Error() != "Sign in with `carlos auth login --console "+api.URL+"`." {
+ t.Fatalf("production 401 sign-in branch: %v", err)
+ }
+ if _, err := os.Lstat(out); !os.IsNotExist(err) {
+ t.Fatal("unsigned output created", 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) {
diff --git a/apps_source_test.go b/apps_source_test.go
index 64278e5d1..a8e48923b 100644
--- a/apps_source_test.go
+++ b/apps_source_test.go
@@ -40,14 +40,34 @@ func sourceCLIArchive(t *testing.T) []byte {
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"} {
+ for _, mode := range []string{"ok", "digest", "length", "oversize", "archive", "timestamp", "encoding", "redirect", "truncated", "exists", "symlink", "unauthorized", "cancel", "racing-output"} {
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
+ dir := t.TempDir()
+ out := filepath.Join(dir, "source.tar.gz")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests++
+ if _, err := os.Lstat(out); !os.IsNotExist(err) {
+ t.Error("output visible before verification", err)
+ }
+ if mode == "unauthorized" {
+ http.Error(w, "not signed in", 401)
+ return
+ }
+ if mode == "cancel" {
+ cancel()
+ return
+ }
+ if mode == "racing-output" {
+ if err := os.WriteFile(out, []byte("keep"), 0600); err != nil {
+ t.Error(err)
+ }
+ }
if r.URL.Path != "/api/cli/apps/account/demo/source" || r.Header.Get("Authorization") != "Bearer local-token" {
t.Error("wrong request")
}
@@ -83,8 +103,6 @@ func TestAppsSourcePull(t *testing.T) {
_, _ = 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)
@@ -95,7 +113,7 @@ func TestAppsSourcePull(t *testing.T) {
t.Fatal(err)
}
}
- at, err := pullAppSource(context.Background(), newConsoleClient(server.URL, "local-token"), "/api/cli/apps/account/demo/source", out)
+ at, err := pullAppSource(ctx, 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)
@@ -112,7 +130,15 @@ func TestAppsSourcePull(t *testing.T) {
if err == nil {
t.Fatal("accepted bad download")
}
- if mode == "exists" || mode == "symlink" {
+ if mode == "unauthorized" && err.Error() != "Sign in with `carlos auth login --console "+server.URL+"`." {
+ t.Fatal("wrong sign-in refusal", err)
+ }
+ if mode == "racing-output" {
+ got, readErr := os.ReadFile(out)
+ if readErr != nil || string(got) != "keep" || err.Error() != sourceExists {
+ t.Fatal("raced output clobbered", string(got), err, readErr)
+ }
+ } else if mode == "exists" || mode == "symlink" {
if requests != 0 {
t.Fatal("clobber attempted")
}
@@ -120,6 +146,15 @@ func TestAppsSourcePull(t *testing.T) {
t.Fatal("partial file survived", err)
}
}
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, entry := range entries {
+ if entry.Name() != "source.tar.gz" {
+ t.Errorf("temporary file survived: %s", entry.Name())
+ }
+ }
if targetCalls != 0 {
t.Fatal(targetCalls)
}
diff --git a/docs/superpowers/notes/census-proposal-claim-source.md b/docs/superpowers/notes/census-proposal-claim-source.md
index aa88466eb..889152d96 100644
--- a/docs/superpowers/notes/census-proposal-claim-source.md
+++ b/docs/superpowers/notes/census-proposal-claim-source.md
@@ -8,10 +8,10 @@ Review: a model from the other family than the author reads the branch's diff ag
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 `apps_source.go:pullAppSource`: reads +file:CreateTemp, +file:Lstat, +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: `5b31785441c6a48ddae93e9f3c0f8962f7983b55d89b3acb90d9a6b505647b36` → `0a426869fb12be5b647ebc775694447766b88993111dcf6aee4e5d5c7af9bfcf`.
+Seal: `5b31785441c6a48ddae93e9f3c0f8962f7983b55d89b3acb90d9a6b505647b36` → `7868de86ba3ff8e973713f04081f76ea003380ca5b7a6db7e0f5d20d10d535d8`.
Overlay: `internal/provision/testdata/plan14-root-reads-claim-source.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/console/app_source.go b/internal/console/app_source.go
index 62868a853..fe654201d 100644
--- a/internal/console/app_source.go
+++ b/internal/console/app_source.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"io"
+ "log"
"net/http"
"strconv"
"sync"
@@ -171,8 +172,12 @@ func (s *Server) sourceAdmission(next http.HandlerFunc, cli bool) http.HandlerFu
return
}
if cli {
+ // No usable credential is the gate's own question: it answers
+ // 401 "not signed in" exactly as at every other CLI door. A real
+ // principal that is not a person (a service or app credential)
+ // gets the same 404 as a stranger, before any storage read.
p, ok := s.store.CLIPrincipal(bearer(r), time.Now())
- if !ok || p.Kind != PrincipalUser {
+ if ok && p.Kind != PrincipalUser {
http.NotFound(w, r)
return
}
@@ -221,42 +226,47 @@ func (s *Server) sourceForMember(ctx context.Context, actor string, acct *Accoun
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)
+ var c claimedSource
+ var b []byte
+ status, message := func() (int, string) {
+ defer s.lockMembers(acct.Sqid)()
+ defer s.lockAccount(acct.Sqid)()
+ defer s.lockApp(acct.Sqid, app)()
+ var raw string
+ var err error
+ c, raw, err = s.sourceForMember(ctx, actor, acct, app)
+ if err != nil {
+ return 404, "404 page not found"
+ }
+ if raw == "" {
+ return 404, sourceMissing
+ }
+ done, ok := s.sourceDownloads.take(actor+"\x00"+acct.Sqid+"\x00"+app, time.Now())
+ if !ok {
+ return 429, sourceRateLimited
+ }
+ defer done()
+ b, err = readClaimedSource(ctx, s.cfg.Releases, claimedSourceKey(acct.Sqid, app, c.Operation), c.SHA256, c.Bytes)
+ if err != nil {
+ log.Printf("app source download: storage read failed account=%s app=%s", acct.Sqid, app)
+ return 503, sourceUnavailable
+ }
+ // Recheck membership and snapshot under the lifecycle locks before audit.
+ _, current, err := s.sourceForMember(ctx, actor, acct, app)
+ if err != nil || current != raw {
+ return 404, "404 page not found"
+ }
+ if ctx.Err() != nil {
+ return 503, sourceUnavailable
+ }
+ 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 {
+ return 503, sourceUnavailable
+ }
+ return 200, ""
+ }()
+ _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(30 * time.Second))
+ if status != 200 {
+ http.Error(w, message, status)
return
}
w.Header().Set("Content-Type", "application/gzip")
diff --git a/internal/console/app_source_test.go b/internal/console/app_source_test.go
index 1a431779a..c556cc6f5 100644
--- a/internal/console/app_source_test.go
+++ b/internal/console/app_source_test.go
@@ -13,6 +13,7 @@ import (
"github.com/carlosframework/platform/internal/s3fake"
"github.com/carlosframework/platform/internal/svcrole"
"io"
+ "log"
"net/http"
"net/http/httptest"
"os"
@@ -150,7 +151,7 @@ func TestAppSourceDoors(t *testing.T) {
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", ""} {
+ 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)
@@ -161,6 +162,23 @@ func TestAppSourceDoors(t *testing.T) {
t.Fatalf("%s %s: %d %q reads=%d", door, person, w.Code, w.Body, count.reads)
}
}
+ for _, token := range []string{"", "invalid-demo-capability"} {
+ count.reads = 0
+ w := sourceRequest(t, s, op, door, "", token)
+ want, cache := 404, "private, no-store"
+ if door == "cli" {
+ want, cache = 401, "no-store"
+ }
+ if w.Code != want || count.reads != 0 || w.Header().Get("Cache-Control") != cache {
+ t.Fatalf("%s no credential: %d %s reads=%d", door, w.Code, w.Body, count.reads)
+ }
+ if door == "cli" && !strings.Contains(w.Body.String(), "not signed in") {
+ t.Fatal("missing standard sign-in refusal", w.Body)
+ }
+ if door == "browser" && w.Body.String() != "404 page not found\n" {
+ t.Fatal("browser refusal changed", w.Body)
+ }
+ }
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 {
@@ -836,3 +854,79 @@ func TestAppSourceLegacyArtifactPin(t *testing.T) {
t.Fatal("legacy copied artifact rebound")
}
}
+
+type sourceStalledWriter struct {
+ *httptest.ResponseRecorder
+ started, resume chan struct{}
+ deadline time.Time
+}
+
+func (w *sourceStalledWriter) SetWriteDeadline(deadline time.Time) error {
+ w.deadline = deadline
+ return nil
+}
+func (w *sourceStalledWriter) Write(b []byte) (int, error) {
+ close(w.started)
+ <-w.resume
+ return w.ResponseRecorder.Write(b)
+}
+func TestAppSourceStalledReaderReleasesLocks(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)
+ r := httptest.NewRequest("GET", "/api/cli/apps/"+op.Target.Sqid+"/"+op.Target.App+"/source?exact=sqid", nil)
+ r.Header.Set("Authorization", "Bearer "+token)
+ w := &sourceStalledWriter{ResponseRecorder: httptest.NewRecorder(), started: make(chan struct{}), resume: make(chan struct{})}
+ finished := make(chan struct{})
+ go func() { defer close(finished); s.ServeHTTP(w, r) }()
+ defer func() { close(w.resume); <-finished }()
+ select {
+ case <-w.started:
+ case <-time.After(10 * time.Second):
+ t.Fatal("write never started")
+ }
+ if w.deadline.IsZero() || time.Until(w.deadline) > 30*time.Second {
+ t.Error("response has no bounded write deadline")
+ }
+ acquired := make(chan struct{})
+ go func() {
+ defer s.lockMembers(op.Target.Sqid)()
+ defer s.lockAccount(op.Target.Sqid)()
+ defer s.lockApp(op.Target.Sqid, op.Target.App)()
+ close(acquired)
+ }()
+ select {
+ case <-acquired:
+ case <-time.After(time.Second):
+ t.Error("stalled response blocks account locks")
+ }
+ s.sourceDownloads.mu.Lock()
+ active := s.sourceDownloads.active
+ s.sourceDownloads.mu.Unlock()
+ if active != 0 {
+ t.Error("stalled response holds buffer slot", active)
+ }
+}
+func TestAppSourceStorageFailureLogged(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)
+ s.cfg.Releases = &sourceCountStore{Store: s.cfg.Releases, failRead: true}
+ var logs bytes.Buffer
+ before := log.Writer()
+ log.SetOutput(&logs)
+ defer log.SetOutput(before)
+ w := sourceRequest(t, s, op, "cli", "", token)
+ if w.Code != 503 || !strings.Contains(logs.String(), "app source download: storage read failed") {
+ t.Fatalf("storage refusal not logged: %d %s", w.Code, logs.String())
+ }
+ for _, secret := range []string{token, string(demoJobSource().Archive)} {
+ if strings.Contains(logs.String(), secret) {
+ t.Fatal("source or secret in log")
+ }
+ }
+}
diff --git a/internal/console/demo_claim_kept_test.go b/internal/console/demo_claim_kept_test.go
index b385271d7..6846d9806 100644
--- a/internal/console/demo_claim_kept_test.go
+++ b/internal/console/demo_claim_kept_test.go
@@ -8,6 +8,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
+ "regexp"
"strings"
"testing"
"time"
@@ -25,7 +26,10 @@ func keptFixture(t *testing.T) (*Server, string, string, claimOp) {
}
s.demoClaimTestEnabled = true
f, flow := claimProved(t, s, demoToken, "kept-person@example.com")
- a := claimAccount(t, s, 801, f.Person, RoleOwner)
+ a, _, err := s.chooseDemoClaimAccount(t.Context(), f, "")
+ if err != nil {
+ t.Fatal(err)
+ }
w := claimPost(s, "/api/demo/claims/select", map[string]string{"flowToken": flow, "accountId": a.Sqid})
if w.Code != 202 {
t.Fatalf("create: %d %s", w.Code, w.Body)
@@ -48,6 +52,10 @@ func keptFixture(t *testing.T) (*Server, string, string, claimOp) {
if err != nil {
t.Fatal(err)
}
+ acct, err := s.store.AccountByID(op.Target.AccountID)
+ if err != nil || acct == nil || acct.Name != f.Person {
+ t.Fatal("fixture must mint an account named by the claimant email", err)
+ }
return s, token, flow, op
}
@@ -104,6 +112,14 @@ func TestDemoClaimKeptExchange(t *testing.T) {
if !strings.Contains(page, `data-state="claimed"`) || strings.Contains(page, `data-reveal="true"`) {
t.Fatal("reload must be settled after progress")
}
+ if keptPageHasAccountID(page, op) {
+ t.Fatal("status cookie leaked account ID outside public app URL")
+ }
+ for _, private := range []string{op.Person, `class="claim-next"`, `id="claim-agent-command"`, `id="claim-source-command"`} {
+ if strings.Contains(page, private) {
+ t.Fatalf("status cookie that did not complete the claim leaked %q", private)
+ }
+ }
}
replay := claimPost(s, "/api/demo/claims/select", map[string]string{"flowToken": flow, "accountId": op.Target.Sqid})
r := httptest.NewRequest("GET", "/api/demo/claims/status", nil)
@@ -249,7 +265,10 @@ func TestDemoClaimKeptDoneAndAtomic(t *testing.T) {
if !strings.Contains(page, `data-state="claimed"`) || strings.Contains(page, `data-reveal="true"`) != (i == 0) {
t.Fatal("reveal not once")
}
- for _, secret := range []string{token, op.Person, `action="/demo/claim/select"`} {
+ if keptPageHasAccountID(page, op) {
+ t.Fatal("kept page leaked account ID outside public app URL")
+ }
+ for _, secret := range []string{token, op.Person, `class="claim-next"`, `id="claim-agent-command"`, `id="claim-source-command"`, `action="/demo/claim/select"`} {
if strings.Contains(page, secret) {
t.Fatal("status page leaked authority/identity")
}
@@ -505,3 +524,45 @@ func TestDemoClaimKeptExchangeRollback(t *testing.T) {
t.Fatal("expired status credential retained")
}
}
+
+func TestDemoClaimKeptContinuationMembership(t *testing.T) {
+ s, token, _, op := keptFixture(t)
+ stampSourcePageFixture(t, s)
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase='done' WHERE id=?`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ b := &claimBrowser{t: t, s: s}
+ b.request("GET", "/demo/claim/kept", nil)
+ if w := b.post("/demo/claim/kept", url.Values{"keptToken": {token}}); w.Code != 303 {
+ t.Fatal(w.Code)
+ }
+ for _, role := range []string{"", RoleMember, RoleOwner, "unknown"} {
+ person := "viewer@example.com"
+ if role != "" {
+ if err := s.store.AddMember(op.Target.AccountID, person, RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`UPDATE memberships SET role=? WHERE account_id=? AND address=?`, role, op.Target.AccountID, person); err != nil {
+ t.Fatal(err)
+ }
+ }
+ b.login(person, MethodEmail, false)
+ page := b.request("GET", "/demo/claim", nil).Body.String()
+ authorized := role == RoleOwner || role == RoleMember
+ if keptPageHasAccountID(page, op) != authorized {
+ t.Errorf("role %q: account ID visibility outside public app URL", role)
+ }
+ for _, private := range []string{op.Person, `class="claim-next"`, `id="claim-agent-command"`, `id="claim-source-command"`} {
+ if strings.Contains(page, private) != authorized {
+ t.Errorf("role %q: private continuation visibility for %q", role, private)
+ }
+ }
+ }
+}
+
+// The public app URL already contains the sqid. Check all other occurrences
+// as identifiers, so a short sqid such as "bac" does not match CSS "background".
+func keptPageHasAccountID(page string, op claimOp) bool {
+ page = strings.ReplaceAll(page, op.Target.Host, "public-app-host")
+ return regexp.MustCompile(`\b` + regexp.QuoteMeta(op.Target.Sqid) + `\b`).MatchString(page)
+}
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index 70d459a41..d118f3846 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -155,19 +155,26 @@ 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"] = ""
+ canContinue := keptErr != nil && err == nil && hash == op.FlowHash && op.Person != ""
+ if !canContinue && address != "" {
+ role, roleErr := s.store.Role(op.Target.AccountID, address)
+ canContinue = roleErr == nil && (role == RoleOwner || role == RoleMember)
+ }
+ if canContinue {
+ 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"] = ""
+ }
}
}
}
diff --git a/internal/console/static/demo_claim.js b/internal/console/static/demo_claim.js
index 01f972073..d0239811b 100644
--- a/internal/console/static/demo_claim.js
+++ b/internal/console/static/demo_claim.js
@@ -155,9 +155,12 @@
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 previous = claim.querySelector(".claim-next");
+ if (next) {
+ if (previous) previous.replaceWith(next);
+ else document.getElementById("claim-finished").append(next);
+ bindCopies(next);
+ } else previous?.remove();
const url = new URL(result.url);
if (url.protocol !== "https:" || url.username || url.password) throw new Error();
const finished = document.getElementById("claim-finished");
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 3fa8c1bab..79b81e57d 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -100,6 +100,9 @@ var (
// Only an equality catches both; "no empty Sets" catches neither, and "these
// are empty" catches only the first.
var closedDoors = []string{
+ // Claimed app source: people (owners and members) only; no service or
+ // app credential may fetch an app's source.
+ "GET /api/cli/apps/{account}/{app}/source",
"GET /api/cli/fleets/{account}/{fleet}",
"GET /api/cli/system/managed-fleets",
"PUT /api/cli/system/managed-fleets",
diff --git a/internal/console/templates/demo_claim.html b/internal/console/templates/demo_claim.html
index 34249f44f..a22f78dab 100644
--- a/internal/console/templates/demo_claim.html
+++ b/internal/console/templates/demo_claim.html
@@ -173,7 +173,7 @@
<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>
+{{if .AccountSqid}}<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}}
@@ -181,7 +181,7 @@
{{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>
+</details>{{end}}{{end}}<p class="claim-detail">{{.Copy.oldAddress}}</p></section>{{end}}</div>
{{end}}
{{if and .HasIntent .CanClaim}}
{{if .Address}}
diff --git a/internal/demobuild/source.go b/internal/demobuild/source.go
index d628e3216..bcbfc5927 100644
--- a/internal/demobuild/source.go
+++ b/internal/demobuild/source.go
@@ -76,9 +76,6 @@ func validateSource(r io.Reader, lock Lock, archiveOnly bool) (Source, []Diagnos
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()
@@ -113,7 +110,7 @@ func validateSource(r io.Reader, lock Lock, archiveOnly bool) (Source, []Diagnos
return refuse(name, 0)
}
isDir := h.Typeflag == tar.TypeDir
- if forbiddenFile(name, isDir) {
+ if !archiveOnly && forbiddenFile(name, isDir) {
return refuse(name, 0)
}
entries[name] = isDir
diff --git a/internal/demobuild/source_test.go b/internal/demobuild/source_test.go
index ac6348bd8..40c072664 100644
--- a/internal/demobuild/source_test.go
+++ b/internal/demobuild/source_test.go
@@ -12,6 +12,7 @@ import (
"slices"
"strings"
"testing"
+ "time"
"github.com/carlosframework/platform/internal/demo"
)
@@ -403,3 +404,40 @@ func TestClaimedSourceArchive(t *testing.T) {
}
}
}
+
+func TestClaimedSourcePublishedStructure(t *testing.T) {
+ for _, header := range []gzip.Header{{}, {Extra: []byte("legal extra")}, {Name: "source.tar", Comment: "source", ModTime: time.Unix(123, 0), OS: 3}, {Extra: []byte("extra"), Name: "source.tar", Comment: "source"}} {
+ var b bytes.Buffer
+ gz := gzip.NewWriter(&b)
+ gz.Header = header
+ if _, err := gz.Write(tarBytes(t, starter(t))); err != nil {
+ t.Fatal(err)
+ }
+ if err := gz.Close(); err != nil {
+ t.Fatal(err)
+ }
+ published, _, err := ValidateSource(bytes.NewReader(b.Bytes()), testLock(t))
+ if err != nil {
+ t.Fatal("publish", err)
+ }
+ claimed, err := ValidateArchive(bytes.NewReader(published.Archive))
+ if err != nil || claimed.SHA256 != published.SHA256 || !bytes.Equal(claimed.Archive, published.Archive) {
+ t.Errorf("published gzip header %+v rejected or changed: %v", header, err)
+ }
+ }
+}
+
+func TestClaimedSourceIgnoresPublishFilePolicy(t *testing.T) {
+ for _, name := range []string{"vendor/old.go", ".git/config", "go.work", "nested/go.mod", "native.c"} {
+ t.Run(name, func(t *testing.T) {
+ b := gzipBytes(t, tarBytes(t, append(starter(t), archiveEntry{name, "historical source", tar.TypeReg})))
+ if _, _, err := ValidateSource(bytes.NewReader(b), testLock(t)); err == nil {
+ t.Fatal("publish policy not exercised")
+ }
+ got, err := ValidateArchive(bytes.NewReader(b))
+ if err != nil || !bytes.Equal(got.Archive, b) {
+ t.Fatal("historical snapshot rejected by publish policy", err)
+ }
+ })
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 4e70c04ed..009790e13 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -117,4 +117,4 @@ plan14-root-reads-signin-first-run-mobile.tsv 61027a32e31cb7ce017304f526f668c269
plan14-root-reads-claim-ux-edge.tsv 889ce9f72f93b581b29527e5c5d4410b47732424ce8ce45c080904ebb6c52195
plan14-root-reads-region-ha-g3-fixes.tsv cd001bf3a9a8871f12d1ca9cfa0a925760c1fc345dc911246ffaabc235dfabf6
plan14-root-reads-claim-countdown.tsv 5b31785441c6a48ddae93e9f3c0f8962f7983b55d89b3acb90d9a6b505647b36
-plan14-root-reads-claim-source.tsv 0a426869fb12be5b647ebc775694447766b88993111dcf6aee4e5d5c7af9bfcf
+plan14-root-reads-claim-source.tsv 7868de86ba3ff8e973713f04081f76ea003380ca5b7a6db7e0f5d20d10d535d8
diff --git a/internal/provision/testdata/plan14-root-reads-claim-source.tsv b/internal/provision/testdata/plan14-root-reads-claim-source.tsv
index ebf1700cd..2bcc45d5f 100644
--- a/internal/provision/testdata/plan14-root-reads-claim-source.tsv
+++ b/internal/provision/testdata/plan14-root-reads-claim-source.tsv
@@ -1,11 +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 b6bb7fcedd1d2c6914a955d15f9f8ae473ba5909ec1cf6dd6352cde0d5de123d apps_source.go pullAppSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=New CLI command carlos apps source pull: reads the HTTPS response body from the console (bounded, digest-checked) and creates the operator-chosen output file exclusively (O_EXCL, 0600, refuses existing files and symlinks); never extracts or executes the archive. file:OpenFile@181,file:ReadAll@1155,file:ReadAll@1735 9a5e7d16099332410d2bd3ad816175083a17bc9207d15865e87d39c714c61633
-@legacy 3073800f724e1f14027fcdb4db6fb061943ef00f0c9d18d2e439e2cc37d2926f internal/demobuild/source.go validateSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=Shared archive validator split out of ValidateSource: reads only the in-memory gzip/tar stream (bounded), rejects traversal, absolute paths, links, special files, duplicates and oversized expansion; no filesystem paths opened. 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=New CLI command carlos apps source pull: reads the HTTPS response body from the console (bounded, digest-checked) and creates the operator-chosen output file exclusively (O_EXCL, 0600, refuses existing files and symlinks); never extracts or executes the archive. 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=Shared archive validator split out of ValidateSource: reads only the in-memory gzip/tar stream (bounded), rejects traversal, absolute paths, links, special files, duplicates and oversized expansion; no filesystem paths opened. file:ReadAll@2075,file:ReadAll@430,file:ReadAll@799 6861ec4bf8a9871bb33dc22199c17ab74afc481d7d09eb86951715504e6746a2
+@legacy 23488c3daf17a026e331999b5389879bc3f7262018b0a5f4ac506e0548067297 apps_source.go pullAppSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=CLI-only download checks the operator-selected output with Lstat before HTTP, creates an exclusive mode-0600 temporary file in the same directory, validates bounded response bytes, then links without overwriting; no archive extraction or execution. New reads: Lstat and CreateTemp replace direct output OpenFile; response ReadAll sites unchanged. file:CreateTemp@353,file:Lstat@184,file:ReadAll@1211,file:ReadAll@1791 02308bb42402538daf2374f6e6843700e5e71d2dd1434bdeba014ddd371fdac5
+@legacy 0d4248779bccad094b2b7093f67727ed213cd82ec79faa44173d18d0fd266c0e internal/demobuild/source.go validateSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=Shared bounded parser accepts the same gzip framing for publish and retrieval, including FEXTRA; structural archive validation retains path, type, duplicate, expansion, framing and size checks. Publish-only forbiddenFile policy is skipped for historical downloads; publish validation remains unchanged. Existing ReadAll sites only. file:ReadAll@2025,file:ReadAll@430,file:ReadAll@733 4676f3aecb28adbda6fdb84d909ba2f5448ac3e763a9024a50afc419481d145f
+apps_source.go pullAppSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=CLI-only download checks the operator-selected output with Lstat before HTTP, creates an exclusive mode-0600 temporary file in the same directory, validates bounded response bytes, then links without overwriting; no archive extraction or execution. New reads: Lstat and CreateTemp replace direct output OpenFile; response ReadAll sites unchanged. file:CreateTemp@353,file:Lstat@184,file:ReadAll@1211,file:ReadAll@1791 02308bb42402538daf2374f6e6843700e5e71d2dd1434bdeba014ddd371fdac5
+internal/demobuild/source.go validateSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=Shared bounded parser accepts the same gzip framing for publish and retrieval, including FEXTRA; structural archive validation retains path, type, duplicate, expansion, framing and size checks. Publish-only forbiddenFile policy is skipped for historical downloads; publish validation remains unchanged. Existing ReadAll sites only. file:ReadAll@2025,file:ReadAll@430,file:ReadAll@733 4676f3aecb28adbda6fdb84d909ba2f5448ac3e763a9024a50afc419481d145f
@remove internal/demobuild/source.go ValidateSource
-@removed internal/demobuild/source.go ValidateSource H3 census-ruling-claim-source;basis=Now a thin wrapper over validateSource; reads nothing itself.
-@coverage . d273744eb9d288a168f8854c864455a710c1bf26762bfcf0a22d984ff6486853
-@coverage internal/demobuild 53fcaf03fe6e54b587259981799462edd33660d373b2fb80e91351a8b66e95fb
+@removed internal/demobuild/source.go ValidateSource H3 census-ruling-claim-source;basis=Publication delegates to validateSource with archiveOnly=false; all publish-time file exclusions and dependency checks remain enforced. No direct reads.
+@coverage . 202c387d274562d8b7d9274012e0b448f7c34ba859f7ff9d1d9e7ae85b6e26c1
+@coverage internal/demobuild 43b41e2ef861a0bced6f3cc11eaf25ae1949c8d9d8b9961ca768a2c58eeda78d