carlos / platform Public

feat: enforce demo instance size and deny-all networking

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 9cb0b47b574ca22a93d4bebe09683051a6e431b1 parent dd97bf2
38 files changed, +1,425 −22
  • internal/activator/demo_policy_test.go +18 −0
  • internal/activator/size.go +4 −0
  • internal/apppolicy/apppolicy.go +12 −0
  • internal/apppolicy/demo_test.go +42 −0
  • internal/console/apidemo.go +1 −0
  • internal/console/apipolicy.go +11 −0
  • internal/console/demo_policy.go +60 −0
  • internal/console/demo_policy_test.go +45 −0
  • internal/demo/descriptor.go +55 −0
  • internal/demo/descriptor_test.go +31 −0
  • internal/host/agent.go +1 −1
  • internal/host/bootstrap.go +7 −0
  • internal/host/claimstop_run.go +11 −2
  • internal/host/claimunit.go +20 −3
  • internal/host/demo_policy.go +80 −0
  • internal/host/demo_policy_linux_test.go +146 −0
  • internal/host/demo_policy_test.go +138 −0
  • internal/host/demo_units/demo.conf +7 −0
  • internal/host/systemapply.go +9 −0
  • internal/host/systemunits.go +16 −2
  • internal/instancectl/demo_policy.go +116 −0
  • internal/instancectl/demo_policy_test.go +146 −0
  • internal/instancectl/gen.go +16 −0
  • internal/instancectl/rootfs.go +4 −0
  • internal/instancectl/server.go +39 −1
  • internal/instancectl/size.go +3 −0
  • internal/provision/apppolicy_reconcile.go +8 −0
  • internal/provision/demo_policy.go +105 −0
  • internal/provision/demo_policy_test.go +149 −0
  • internal/provision/forward.go +4 −2
  • internal/provision/lifetime.go +1 −1
  • internal/provision/provision.go +6 −0
  • internal/provision/reconcile.go +9 −1
  • internal/provision/record_sequence.go +6 −0
  • internal/registry/demo.go +7 −0
  • internal/registry/demo_test.go +63 −0
  • internal/registry/forward.go +7 −1
  • internal/registry/registry.go +22 −8

CI cancelled — superseded by a newer push — run details

Intent

Human

<task-notification> <task-id>af579ba069f0f2781</task-id> <tool-use-id>toolu_017ao9F3bfk5XEFAmFnbZ3ee</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/af579ba069f0f2781.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 2 fix round 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- P2-1: ADDRESSED (internal/demobuild/source.go:221: `.pgo` is now a forbidden extension; the tests are at source_test.go:250-257) - P2-2: ADDRESSED (internal/demobuild/source_test.go:197-219, :264-274, :316-331: every case now starts from a valid starter archive, which is accepted before the mutation) - New breakage in the fix diff: none (P1 none, P2 none, P3 none) Verdict: READY The review is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-1/.superpowers/sdd/2026-11-02-agent-start-demo-1-anonymous-apps/task-2-review-r2.md`.</result> <usage><subagent_tokens>52067</subagent_tokens><tool_uses>4</tool_uses><duration_ms>44249</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a3c0e223a11531f77</task-id> <tool-use-id>toolu_01EGQ9BCnddkrcnu8GJULu3y</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/a3c0e223a11531f77.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 1 fix round 2" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **P2-N1: ADDRESSED.** `internal/console/apidemo.go:197-235` caches the verdict for 45 s, with one shared check at a time and a log line only when the result changes. The cheap refusals now run before that check: update at `apidemo.go:303-310`, create at `:317-324`. Startup fills the same cache at `server.go:1804`. - **P3, Validate ordering: ADDRESSED.** `internal/demo/config.go:62-91` uses ordered slices. - **Fail-closed: OK.** A cached failure keeps refusing until it expires, and a failed check replaces an earlier success. A success can be up to 45 s old, which is within the 30 to 60 s window round 2 asked for. - **Single-flight: OK.** It cannot deadlock (no re-entry) and cannot leak. The lock is held for one check at most, and the S3 LIST inside it has a 10 s timeout. - **New P2-R3-1 (`apidemo.go:311,325` → `:143`, `:174`, `:229-231`).** The check runs on the caller's request context. One anonymous caller who still has budget can send a create just after the cache expires and then drop the connection. The S3 LIST then fails with "context canceled", and that failure is cached for everyone. Every create and update gets 503 for the next 45 s. The 503 comes before any budget is spent, so the caller can repeat this every 45 s for free. The same thing happens by accident when the first caller after expiry times out or leaves. - Fix: run the check on `context.WithoutCancel(ctx)` with the existing 10 s timeout, or don't cache the caller's own cancellation errors. Add a test for it. - Fault family: a single request's context leaks into a verdict shared by all callers. - **Two P3s (follow-up list).** - Callers waiting on the lock can't give up early (`:213`). - Duplicate failures are spotted by comparing error text, so an S3 error carrying a request ID logs again every refresh (`:218-226`). That is at most one line per 45 s. **Verdict: READY AFTER FIXES.** There is no P1, so the shared-cause question doesn't apply. Rounds 1 to 3 found no P1 at all. The review is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-1/.superpowers/sdd/2026-11-02-agent-start-demo-1-anonymous-apps/task-1-review-r3.md`.</result> <usage><subagent_tokens>57339</subagent_tokens><tool_uses>6</tool_uses><duration_ms>86034</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bh4ifmxth</task-id> <tool-use-id>toolu_017cgW3LTgRaYWtHSSFMjwge</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/bh4ifmxth.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 3 Codex run" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/activator/demo_policy_test.go b/internal/activator/demo_policy_test.go
new file mode 100644
index 000000000..c261b5b4c
--- /dev/null
+++ b/internal/activator/demo_policy_test.go
@@ -0,0 +1,18 @@
+package activator
+
+import (
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/registry"
+ "testing"
+)
+
+func TestDemoPolicySize(t *testing.T) {
+ large, _ := cgroup.SizeByName("xlarge")
+ small, _ := cgroup.SizeByName("small")
+ if got := SizedLimit(registry.Route{DemoID: "demo", Size: "xlarge"}, large.Limit); got != small.Limit {
+ t.Fatalf("demo size %v", got)
+ }
+ if got := SizedLimit(registry.Route{}, large.Limit); got != large.Limit {
+ t.Fatalf("ordinary fallback changed: %v", got)
+ }
+}
diff --git a/internal/activator/size.go b/internal/activator/size.go
index 8d3fcda1b..3b7f8eece 100644
--- a/internal/activator/size.go
+++ b/internal/activator/size.go
@@ -23,6 +23,10 @@ var unknownSizes sync.Map
// non-empty name this box does not know (a newer console's size) logs once
// per host and value and falls back too.
func SizedLimit(rt registry.Route, fallback cgroup.Limit) cgroup.Limit {
+ if rt.IsDemo() {
+ small, _ := cgroup.SizeByName("small")
+ return small.Limit
+ }
if rt.Size == "" {
return fallback
}
diff --git a/internal/apppolicy/apppolicy.go b/internal/apppolicy/apppolicy.go
index 8b05743f9..97df1976a 100644
--- a/internal/apppolicy/apppolicy.go
+++ b/internal/apppolicy/apppolicy.go
@@ -20,6 +20,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/controlname"
+ "github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/egressaddr"
"github.com/carlosframework/platform/internal/release"
)
@@ -50,6 +51,8 @@ func Key(sqid, app string) string { return release.AppPolicyKey(sqid, app) }
// Policy is one app's signed operator policy. Account and App bind the
// record to its key; Revision only increases; SignedAt starts its Lifetime.
type Policy struct {
+ EgressMode string `json:"egress_mode,omitempty"`
+ Demo *demo.Descriptor `json:"demo,omitempty"`
V int `json:"v"`
Account string `json:"account"`
App string `json:"app"`
@@ -75,6 +78,15 @@ type SizeOverride struct {
// whether an address may be granted (the door does, with
// egressaddr.Normalize) and does not look at the signing fields.
func (p Policy) Validate() error {
+ if p.Demo != nil || p.EgressMode != "" {
+ if p.Demo == nil || p.EgressMode != "deny-all" || p.DefaultSize != "small" || len(p.EgressAllow) != 0 || len(p.Sizes) != 0 {
+ return demo.ErrPolicy
+ }
+ if err := demo.ValidateBinding(*p.Demo, p.Account, p.App, p.Demo.Host, p.Demo.Lifetime, "demo"); err != nil {
+ return err
+ }
+ }
+
if p.V != 1 {
return fmt.Errorf("%w: version %d", ErrInvalid, p.V)
}
diff --git a/internal/apppolicy/demo_test.go b/internal/apppolicy/demo_test.go
new file mode 100644
index 000000000..889de3939
--- /dev/null
+++ b/internal/apppolicy/demo_test.go
@@ -0,0 +1,42 @@
+package apppolicy
+
+import (
+ "crypto/ed25519"
+ "crypto/rand"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+)
+
+func TestDemoPolicyRoundTrip(t *testing.T) {
+ pub, key, _ := ed25519.GenerateKey(rand.Reader)
+ id, err := demo.NewIdentity(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now().UTC()
+ d := demo.Descriptor{ID: id.ID, Host: id.Name + ".example.com", Lifetime: "life", ExpiresAt: now.Add(time.Hour).Unix()}
+ p := Policy{V: 1, Account: "shop", App: id.App, Revision: 1, SignedAt: now, Demo: &d, EgressMode: "deny-all", DefaultSize: "small"}
+ wire, err := Sign(key, p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := VerifyKey(pub, wire, now, p.Account, p.App)
+ if err != nil || got.Demo == nil || *got.Demo != d {
+ t.Fatalf("round trip: %+v %v", got, err)
+ }
+ for _, change := range []func(*Policy){func(p *Policy) { p.Demo = nil }, func(p *Policy) { p.EgressMode = "" }, func(p *Policy) { p.DefaultSize = "large" }, func(p *Policy) { p.EgressAllow = []string{"10.0.0.1"} }, func(p *Policy) { p.Demo = &demo.Descriptor{} }} {
+ bad := p
+ change(&bad)
+ if _, err := Sign(key, bad); err == nil {
+ t.Fatalf("signed unsafe demo: %+v", bad)
+ }
+ }
+ p.Demo = nil
+ p.EgressMode = ""
+ p.DefaultSize = ""
+ if _, err := Sign(key, p); err != nil {
+ t.Fatal("ordinary policy changed", err)
+ }
+}
diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go
index 91379111f..f680afc6e 100644
--- a/internal/console/apidemo.go
+++ b/internal/console/apidemo.go
@@ -24,6 +24,7 @@ import (
// DEMO-LIVE-LIMIT uses a read-only pre-check before spending an attempt and
// a five-minute retry; ReserveDemo still enforces the ceiling transactionally.
var demoCopy = map[string]string{
+ "DEMO-POLICY": "This demo cannot start because its required restrictions could not be verified.",
"DEMO-CONFIG": "Demo settings are incomplete or inconsistent. Check the holding account, fleet and domain.",
"DEMO-CREATE-LIMIT": "The daily demo creation limit has been reached. Try again after 24 hours.",
"DEMO-LIVE-LIMIT": "All demo places are in use. Existing demos are kept. Try again later.",
diff --git a/internal/console/apipolicy.go b/internal/console/apipolicy.go
index 218568e04..f9177aae9 100644
--- a/internal/console/apipolicy.go
+++ b/internal/console/apipolicy.go
@@ -54,6 +54,7 @@ import (
"github.com/carlosframework/platform/internal/apppolicy"
"github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/egressaddr"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
@@ -587,6 +588,13 @@ func (s *Server) handleAPIPolicyPut(w http.ResponseWriter, r *http.Request) {
// record, and the publication. A refusal says what the caller answers.
func (s *Server) writePolicy(ctx context.Context, acct *Account, app, addr string, hold policyHolding,
p apppolicy.Policy, next uint64, etag, detail string) (policyReply, *doorRefusal) {
+ life, lifeErr := s.store.AppLife(acct.ID, app)
+ if lifeErr != nil || life != nil && life.DemoID != "" && (p.Demo == nil || p.Demo.ID != life.DemoID || p.Demo.Lifetime != life.Lifetime || p.Demo.ExpiresAt != life.ExpiresAt) {
+ return policyReply{}, &doorRefusal{http.StatusForbidden, demoCopy["DEMO-POLICY"]}
+ }
+ if p.Demo != nil && (life == nil || life.DemoID != p.Demo.ID || !life.Temporary()) {
+ return policyReply{}, &doorRefusal{http.StatusForbidden, demo.ErrPolicy.Error()}
+ }
_, done, ref := s.policyAttempt(ctx, hold)
done()
if ref != nil {
@@ -1018,6 +1026,9 @@ func (s *Server) policyOtherIncarnation(acct *Account, app string, row AppPolicy
// gone or was recreated dropped, so no member door ever writes the object. A
// non-zero status refuses with msg.
func (s *Server) applyPolicyChange(ctx context.Context, acct *Account, app string, base apppolicy.Policy, req policyPutReq) (apppolicy.Policy, int, string) {
+ if base.Demo != nil || base.EgressMode != "" {
+ return base, http.StatusForbidden, demoCopy["DEMO-POLICY"]
+ }
p := base
p.EgressAllow = slices.Clone(base.EgressAllow)
p.Sizes = maps.Clone(base.Sizes)
diff --git a/internal/console/demo_policy.go b/internal/console/demo_policy.go
new file mode 100644
index 000000000..883a89ad5
--- /dev/null
+++ b/internal/console/demo_policy.go
@@ -0,0 +1,60 @@
+package console
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+)
+
+// writeDemoPolicy runs under the caller's app lifecycle lock (withDemoLocked).
+// The policy lock, writer lease, revision log, audit and publication are the
+// same ones the operator policy door uses. A retry never reduces a revision.
+func (s *Server) writeDemoPolicy(ctx context.Context, d DemoRow, life AppLife) error {
+ if s.cfg.HostClaim || !demoLifeValid(d, &life, time.Now()) {
+ return demo.ErrPolicy
+ }
+ current, err := s.store.AppLife(d.AccountID, d.App)
+ if err != nil {
+ return err
+ }
+ if current == nil || *current != life {
+ return demo.ErrPolicy
+ }
+ descriptor := demo.Descriptor{ID: d.ID, Host: d.Host, Lifetime: life.Lifetime, ExpiresAt: life.ExpiresAt}
+ if err := s.cfg.Demo.ValidateBinding(descriptor, d.AccountSqid, d.App, d.Host, life.Lifetime, d.Fleet); err != nil {
+ return err
+ }
+ acct, err := s.store.AccountBySqid(d.AccountSqid)
+ if err != nil {
+ return err
+ }
+ if acct == nil || acct.ID != d.AccountID {
+ return demo.ErrPolicy
+ }
+ mu := s.policyLock(acct.ID, d.App)
+ mu.Lock()
+ defer mu.Unlock()
+ hold, ref := s.policyWriter(ctx)
+ if ref != nil {
+ return fmt.Errorf("%w: writer lease: %s", demo.ErrPolicy, ref.Msg)
+ }
+ base, etag, next, _, err := s.policyBase(ctx, acct, d.App, hold, true)
+ if err != nil {
+ return err
+ }
+ if base.Demo != nil && *base.Demo != descriptor {
+ return demo.ErrPolicy
+ }
+ base.Demo = &descriptor
+ base.EgressMode = "deny-all"
+ base.DefaultSize = "small"
+ base.EgressAllow = nil
+ base.Sizes = nil
+ _, ref = s.writePolicy(ctx, acct, d.App, "demo", hold, base, next, etag, "demo deny-all small policy")
+ if ref != nil {
+ return fmt.Errorf("%w: policy write: %s", demo.ErrPolicy, ref.Msg)
+ }
+ return nil
+}
diff --git a/internal/console/demo_policy_test.go b/internal/console/demo_policy_test.go
new file mode 100644
index 000000000..64e3901c4
--- /dev/null
+++ b/internal/console/demo_policy_test.go
@@ -0,0 +1,45 @@
+package console
+
+import (
+ "crypto/ed25519"
+ "crypto/rand"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/apppolicy"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestDemoPolicyRoundTrip(t *testing.T) {
+ st, _ := demoTestStore(t)
+ cfg := demoTestConfig(t)
+ in := demoTestAdmission(t, cfg)
+ row, err := st.ReserveDemo(t.Context(), in)
+ if err != nil {
+ t.Fatal(err)
+ }
+ life, err := st.AppLife(row.AccountID, row.App)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, key, _ := ed25519.GenerateKey(rand.Reader)
+ store := release.NewDirStore(t.TempDir())
+ s := &Server{store: st, cfg: Config{Demo: cfg, Key: key, Releases: store}}
+ for rev := uint64(1); rev <= 2; rev++ {
+ if err := s.writeDemoPolicy(t.Context(), row, *life); err != nil {
+ t.Fatal(err)
+ }
+ p, _, err := apppolicy.Get(t.Context(), store, pub, row.AccountSqid, row.App, time.Now())
+ if err != nil || p.Demo == nil || p.Demo.ID != row.ID || p.Demo.Lifetime != life.Lifetime || p.Revision != rev || p.DefaultSize != "small" || p.EgressMode != "deny-all" {
+ t.Fatalf("policy %+v %v", p, err)
+ }
+ saved, err := st.AppPolicyRecordContext(t.Context(), row.AccountID, row.App)
+ if err != nil || saved.Revision != rev {
+ t.Fatalf("revision not recorded: %+v %v", saved, err)
+ }
+ }
+ life.Lifetime = "wrong"
+ if err := s.writeDemoPolicy(t.Context(), row, *life); err == nil {
+ t.Fatal("stale lifecycle accepted")
+ }
+}
diff --git a/internal/demo/descriptor.go b/internal/demo/descriptor.go
new file mode 100644
index 000000000..cbc69cd43
--- /dev/null
+++ b/internal/demo/descriptor.go
@@ -0,0 +1,55 @@
+package demo
+
+import (
+ "encoding/base64"
+ "errors"
+ "strings"
+)
+
+var ErrPolicy = errors.New("DEMO-POLICY")
+
+// Descriptor carries public identity only. The console's apps row owns expiry.
+type Descriptor struct {
+ ID string `json:"id"`
+ Host string `json:"host"`
+ Lifetime string `json:"lifetime"`
+ ExpiresAt int64 `json:"expires_at"`
+}
+
+// ValidateBinding checks structure, not placement authority. Callers must also
+// compare account, fleet and the host suffix with their configured demo values;
+// Config.ValidateBinding does both. A name alone never grants demo authority.
+func ValidateBinding(d Descriptor, account, app, host, lifetime, fleet string) error {
+ name, domain, ok := strings.Cut(host, ".")
+ id, err := base64.RawURLEncoding.DecodeString(d.ID)
+ if err != nil || len(id) != 16 || base64.RawURLEncoding.EncodeToString(id) != d.ID || !ok || !ValidPublicName(name) || !ValidDomain(domain) || app != AppPrefix+name || d.Host != host || lifetime == "" || d.Lifetime != lifetime || d.ExpiresAt <= 0 || !validLabel(account, 32) || !validLabel(fleet, 32) {
+ return ErrPolicy
+ }
+ return nil
+}
+
+func (c Config) ValidateBinding(d Descriptor, account, app, host, lifetime, fleet string) error {
+ if err := ValidateBinding(d, account, app, host, lifetime, fleet); err != nil {
+ return err
+ }
+ _, domain, _ := strings.Cut(host, ".")
+ if account != c.Account || fleet != c.Fleet || domain != c.Domain {
+ return ErrPolicy
+ }
+ return nil
+}
+
+// BoxConfig reads only the root-owned box identity settings. Any partial or
+// malformed configuration refuses startup, even with admission switched off.
+func BoxConfig(getenv func(string) string) (Config, error) {
+ c := Config{Account: getenv("CARLOS_DEMO_ACCOUNT"), Fleet: getenv("CARLOS_DEMO_FLEET"), Domain: getenv("CARLOS_DEMO_DOMAIN")}
+ if c.Account == "" && c.Fleet == "" && c.Domain == "" {
+ return c, nil
+ }
+ if !validLabel(c.Account, 32) || !validLabel(c.Fleet, 32) || !ValidDomain(c.Domain) {
+ return Config{}, ErrConfig
+ }
+ return c, nil
+}
+
+func (c Config) BoxMode() bool { return c.Account != "" || c.Fleet != "" || c.Domain != "" }
diff --git a/internal/demo/descriptor_test.go b/internal/demo/descriptor_test.go
new file mode 100644
index 000000000..6c22c0985
--- /dev/null
+++ b/internal/demo/descriptor_test.go
@@ -0,0 +1,31 @@
+package demo
+
+import (
+ "crypto/rand"
+ "testing"
+ "time"
+)
+
+func TestDemoPolicyFailClosed(t *testing.T) {
+ id, _ := NewIdentity(rand.Reader)
+ cfg := Config{Account: "shop", Fleet: "demo", Domain: "example.com"}
+ d := Descriptor{ID: id.ID, Host: id.Name + ".example.com", Lifetime: "life", ExpiresAt: time.Now().Add(time.Hour).Unix()}
+ if err := cfg.ValidateBinding(d, "shop", id.App, d.Host, "life", "demo"); err != nil {
+ t.Fatal(err)
+ }
+ for _, args := range [][5]string{{"other", id.App, d.Host, "life", "demo"}, {"shop", "shop", d.Host, "life", "demo"}, {"shop", id.App, "nested." + d.Host, "life", "demo"}, {"shop", id.App, d.Host, "other", "demo"}, {"shop", id.App, d.Host, "life", "other"}} {
+ if err := cfg.ValidateBinding(d, args[0], args[1], args[2], args[3], args[4]); err == nil {
+ t.Fatalf("accepted %v", args)
+ }
+ }
+ for _, env := range []map[string]string{{}, {"CARLOS_DEMO_FLEET": "demo"}, {"CARLOS_DEMO_ACCOUNT": "shop", "CARLOS_DEMO_FLEET": "demo", "CARLOS_DEMO_DOMAIN": "example.com"}} {
+ c, err := BoxConfig(func(k string) string { return env[k] })
+ if len(env) == 1 {
+ if err == nil {
+ t.Fatal("partial box config accepted")
+ }
+ } else if err != nil || c.BoxMode() != (len(env) > 0) {
+ t.Fatalf("box config %+v: %v", c, err)
+ }
+ }
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 9bc90380f..39b6b797b 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -623,7 +623,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// instance's database, the build state names it, under the lease. A
// store that failed to start refuses every spawn (never "run
// unrecorded"). Set before Start, like Routes.
- svc.BeforeExec = buildStateHook(bs, bsErr)
+ svc.BeforeExec = demoPolicyHook(os.Getenv, reg, buildStateHook(bs, bsErr))
// The held wake check (settings spec §4.3 rule 3): a held instance
// never wakes on an installed build other than its target. The copy
// is refreshed before every wake that could be held (wakeTarget), and
diff --git a/internal/host/bootstrap.go b/internal/host/bootstrap.go
index a889c110b..48ed5652e 100644
--- a/internal/host/bootstrap.go
+++ b/internal/host/bootstrap.go
@@ -11,6 +11,7 @@ package host
import (
"github.com/carlosframework/platform/internal/cliflag"
+ "github.com/carlosframework/platform/internal/demo"
"bytes"
"embed"
@@ -376,6 +377,9 @@ func bootstrapWith(root string, consumers []string, planJSON bool) error {
hostEnv = claimBootstrapHostEnv
}
claimSettings, settingsErr := readClaimUnitSettings(hostEnv)
+ if settingsErr != nil && errors.Is(settingsErr, demo.ErrConfig) {
+ return settingsErr
+ }
if settingsErr != nil {
fmt.Fprintf(os.Stderr, "bootstrap: instance-control unit settings: %v\n", settingsErr)
claimSettings = claimUnitSettings{}
@@ -532,6 +536,9 @@ func bootstrapWith(root string, consumers []string, planJSON bool) error {
}
fmt.Fprintf(out, " wrote %s\n", path)
}
+ if err := installDemoUnits(root, claimSettings.demo); err != nil {
+ return err
+ }
// Units an earlier build installed and this one no longer ships
// (retiredunits.go): disabled, stopped and removed, so they are not
// left armed behind the units above.
diff --git a/internal/host/claimstop_run.go b/internal/host/claimstop_run.go
index 25aedcb23..6daf12a1f 100644
--- a/internal/host/claimstop_run.go
+++ b/internal/host/claimstop_run.go
@@ -8,6 +8,7 @@ import (
"path/filepath"
"time"
+ "github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/hostwrite"
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/moves"
@@ -17,6 +18,10 @@ import (
)
func RunInstanceControl(args []string) {
+ cfg, err := demo.BoxConfig(os.Getenv)
+ if err != nil || cfg.BoxMode() && hostwrite.Enabled(os.Getenv) {
+ log.Fatal("instance-control: demo box configuration refused")
+ }
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := registerProductionLaunchVerifier(); err != nil {
@@ -28,14 +33,18 @@ func RunInstanceControl(args []string) {
return
}
}
- ctx, err := claimEntryContext(ctx, os.Getenv, openDeployStore)
+ ctx, err = claimEntryContext(ctx, os.Getenv, openDeployStore)
if err != nil {
log.Fatal(err)
}
if !hostwrite.Enabled(claimEntryEnv(ctx)) {
// Pre-claim egress (#328): the agent-written registry's columns,
// read-only, behind the wholly-nested rail.
- instancectl.RunWithRegistryView(args, instancectl.RegistryView{HostApp: instanceRegistryHostApp(nil), HostRuntime: instanceRegistryHostRuntime}, newEgressAsserter(registryEgressSource(dataDir(), time.Now), registryEgressHosts(dataDir())))
+ var egress *instancectl.EgressAsserter
+ if !cfg.BoxMode() {
+ egress = newEgressAsserter(registryEgressSource(dataDir(), time.Now), registryEgressHosts(dataDir()))
+ }
+ instancectl.RunWithRegistryView(args, instancectl.RegistryView{HostApp: instanceRegistryHostApp(nil), HostRuntime: instanceRegistryHostRuntime}, egress)
return
}
reg, err := openServiceRegistry(filepath.Join(dataDir(), "registry.db"))
diff --git a/internal/host/claimunit.go b/internal/host/claimunit.go
index 5ad6a66df..296177d09 100644
--- a/internal/host/claimunit.go
+++ b/internal/host/claimunit.go
@@ -10,6 +10,7 @@ import (
"strconv"
"strings"
+ "github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/hostwrite"
)
@@ -21,14 +22,20 @@ var readClaimUnitFile = os.ReadFile
const claimControlEnvironment = "EnvironmentFile=-/etc/carlos/host.env\n"
type claimUnitSettings struct {
+ demo demo.Config
enabled bool
rootRetry bool
data, opt string
}
-func readClaimUnitSettings(path string) (claimUnitSettings, error) {
- values := map[string]string{"CARLOS_HOST_CLAIM": "", "CARLOS_DATA_DIR": "", "CARLOS_OPT_DIR": ""}
+func readClaimUnitSettings(path string) (settings claimUnitSettings, readErr error) {
+ values := map[string]string{"CARLOS_HOST_CLAIM": "", "CARLOS_DATA_DIR": "", "CARLOS_OPT_DIR": "", "CARLOS_DEMO_ACCOUNT": "", "CARLOS_DEMO_FLEET": "", "CARLOS_DEMO_DOMAIN": ""}
raw, err := readClaimUnitFile(path)
+ defer func() {
+ if readErr != nil && bytes.Contains(raw, []byte("CARLOS_DEMO_")) {
+ readErr = fmt.Errorf("%w: %v", demo.ErrConfig, readErr)
+ }
+ }()
if err != nil && !errors.Is(err, os.ErrNotExist) {
return claimUnitSettings{}, err
}
@@ -71,6 +78,10 @@ func readClaimUnitSettings(path string) (claimUnitSettings, error) {
}
}
cfg := claimUnitSettings{enabled: hostwrite.Enabled(func(k string) string { return values[k] }), data: values["CARLOS_DATA_DIR"], opt: values["CARLOS_OPT_DIR"]}
+ cfg.demo, err = demo.BoxConfig(func(k string) string { return values[k] })
+ if err != nil {
+ return claimUnitSettings{}, err
+ }
if cfg.data == "" {
cfg.data = "/data"
}
@@ -94,7 +105,13 @@ func readClaimUnitSettings(path string) (claimUnitSettings, error) {
}
func claimUnitContent(name string, content []byte, cfg claimUnitSettings) []byte {
- if name != claimControlUnit || !cfg.enabled {
+ if name != claimControlUnit {
+ return content
+ }
+ if !cfg.enabled {
+ if cfg.demo.BoxMode() {
+ return bytes.Replace(content, []byte("[Service]\n"), []byte("[Service]\n"+claimControlEnvironment), 1)
+ }
return content
}
quote := func(p string) string {
diff --git a/internal/host/demo_policy.go b/internal/host/demo_policy.go
new file mode 100644
index 000000000..77153b221
--- /dev/null
+++ b/internal/host/demo_policy.go
@@ -0,0 +1,80 @@
+package host
+
+import (
+ "bytes"
+ "context"
+ _ "embed"
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/hostwrite"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+//go:embed demo_units/demo.conf
+var demoNetworkDropIn string
+
+// installDemoUnits is bootstrap's demo-only template installation. The root
+// service verifies these effective properties before every permitted start.
+func installDemoUnits(root string, cfg demo.Config) error {
+ _, err := installDemoUnitsIn(filepath.Join(root, "etc/systemd/system"), cfg)
+ return err
+}
+
+func installDemoUnitsIn(unitDir string, cfg demo.Config) (bool, error) {
+ if !cfg.BoxMode() {
+ return false, nil
+ }
+ small, _ := cgroup.SizeByName("small")
+ content := []byte(demoNetworkDropIn + fmt.Sprintf("MemoryMax=%d\nMemoryHigh=%d\nMemorySwapMax=%d\nCPUWeight=%d\nCPUQuota=%d%%\nIOWeight=%d\n", small.Limit.MemoryMax, cgroup.HighOf(small.Limit.MemoryMax), small.Limit.MemoryMax, small.Shares.CPUWeight, small.Shares.CPUQuotaPercent, small.Shares.IOWeight))
+ changed := false
+ for _, unit := range []string{"carlos-instance@.service", "carlos-instance-gen@.service"} {
+ dir := filepath.Join(unitDir, unit+".d")
+ path := filepath.Join(dir, "90-carlos-demo.conf")
+ before, err := os.ReadFile(path)
+ if err == nil && bytes.Equal(before, content) {
+ continue
+ }
+ if err != nil && !os.IsNotExist(err) {
+ return changed, err
+ }
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return changed, err
+ }
+ if err := writeFileDurable(path, content, 0644); err != nil {
+ return changed, err
+ }
+ changed = true
+ }
+ return changed, nil
+}
+
+// demoPolicyHook shares the changed-app cache. It never fetches an object or
+// starts a watcher; an unverified or not-yet-cached demo waits for reconcile.
+func demoPolicyHook(getenv func(string) string, reg *registry.Registry, next func(context.Context, string, string) error) func(context.Context, string, string) error {
+ cfg, configErr := demo.BoxConfig(getenv)
+ claims := hostwrite.Enabled(getenv)
+ return func(ctx context.Context, host, build string) error {
+ if configErr != nil {
+ return configErr
+ }
+ rt, err := reg.Get(host)
+ if err != nil {
+ return err
+ }
+ if rt == nil {
+ return demo.ErrPolicy
+ }
+ if err := armedPolicyCache.Load().AssertDemoRoute(cfg, *rt, claims, time.Now()); err != nil {
+ return err
+ }
+ if next != nil {
+ return next(ctx, host, build)
+ }
+ return nil
+ }
+}
diff --git a/internal/host/demo_policy_linux_test.go b/internal/host/demo_policy_linux_test.go
new file mode 100644
index 000000000..9a54da7e3
--- /dev/null
+++ b/internal/host/demo_policy_linux_test.go
@@ -0,0 +1,146 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+)
+
+func TestDemoDenyAllKernel(t *testing.T) {
+ if os.Getenv("CARLOS_DEMO_KERNEL_WITNESS") != "1" {
+ t.Skip("kernel witness outstanding: needs a designated systemd sandbox (not evidence)")
+ }
+ if os.Geteuid() != 0 {
+ t.Fatal("designated systemd sandbox must run witness as root")
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
+ defer cancel()
+ run := func(args ...string) string {
+ t.Helper()
+ out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
+ if err != nil {
+ t.Fatalf("systemctl %v: %s: %v", args, out, err)
+ }
+ return string(out)
+ }
+ root := t.TempDir()
+ if err := installDemoUnits(root, demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}); err != nil {
+ t.Fatal(err)
+ }
+ drop, err := os.ReadFile(filepath.Join(root, "etc/systemd/system/carlos-instance@.service.d/90-carlos-demo.conf"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ sock := filepath.Join(root, "app.sock")
+ ln, err := net.Listen("unix", sock)
+ if err != nil {
+ t.Fatal(err)
+ }
+ server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) })}
+ done := make(chan struct{})
+ go func() { defer close(done); _ = server.Serve(ln) }()
+ defer func() { _ = server.Close(); <-done }()
+ name := fmt.Sprintf("carlos-demo-witness-%d", os.Getpid())
+ slice, unit := name+".slice", name+".service"
+ files := []string{filepath.Join("/run/systemd/system", slice), filepath.Join("/run/systemd/system", unit)}
+ // O_EXCL protects a pre-existing unit. Cleanup removes only files we created.
+ var created []string
+ defer func() {
+ cleanup, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ for i := len(created) - 1; i >= 0; i-- {
+ u := filepath.Base(created[i])
+ _, _ = exec.CommandContext(cleanup, "systemctl", "stop", u).CombinedOutput()
+ _, _ = exec.CommandContext(cleanup, "systemctl", "reset-failed", u).CombinedOutput()
+ }
+ for _, p := range created {
+ _ = os.Remove(p)
+ }
+ _, _ = exec.CommandContext(cleanup, "systemctl", "daemon-reload").CombinedOutput()
+ }()
+ contents := []string{"[Slice]\nIPAddressAllow=192.0.2.53 192.0.2.10\n", fmt.Sprintf("[Unit]\nRequires=%s\nAfter=%s\n[Service]\nType=oneshot\nRemainAfterExit=yes\nSlice=%s\nExecStart=%q -test.run=^TestDemoDenyAllKernelHelper$\nEnvironment=CARLOS_DEMO_KERNEL_HELPER=%s\n", slice, slice, slice, exe, sock) + string(drop)}
+ for i, p := range files {
+ f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ created = append(created, p)
+ _, err = f.WriteString(contents[i])
+ closeErr := f.Close()
+ if err != nil || closeErr != nil {
+ t.Fatalf("write unit: %v %v", err, closeErr)
+ }
+ }
+ run("daemon-reload")
+ show := run("show", unit, "-p", "PrivateNetwork,RestrictAddressFamilies,IPAddressDeny,IPAddressAllow,MemoryMax,CPUWeight,CPUQuotaPerSecUSec,IOWeight")
+ for _, line := range []string{"PrivateNetwork=yes", "RestrictAddressFamilies=AF_UNIX", "IPAddressAllow=", "MemoryMax=268435456", "CPUWeight=50", "CPUQuotaPerSecUSec=500ms", "IOWeight=50"} {
+ if !strings.Contains("\n"+show, "\n"+line+"\n") {
+ t.Fatalf("effective property missing %q: %s", line, show)
+ }
+ }
+ if !strings.Contains(show, "IPAddressDeny=0.0.0.0/0 ::/0") && !strings.Contains(show, "IPAddressDeny=::/0 0.0.0.0/0") {
+ t.Fatalf("deny readback: %s", show)
+ }
+ run("start", unit)
+ if got := strings.TrimSpace(run("show", unit, "-p", "Result", "--value")); got != "success" {
+ t.Fatalf("witness result %s", got)
+ }
+}
+
+func TestDemoDenyAllKernelHelper(t *testing.T) {
+ sock := os.Getenv("CARLOS_DEMO_KERNEL_HELPER")
+ if sock == "" {
+ t.Skip("kernel helper only")
+ }
+ for _, addr := range []string{"203.0.113.1:80", "[2001:db8::1]:80", "127.0.0.1:80", "169.254.169.254:80", "192.0.2.53:53", "192.0.2.10:80"} {
+ conn, err := net.DialTimeout("tcp", addr, time.Second)
+ if conn != nil {
+ conn.Close()
+ t.Fatalf("network connection succeeded: %s", addr)
+ }
+ if !errors.Is(err, syscall.EAFNOSUPPORT) && !errors.Is(err, syscall.EPERM) && !errors.Is(err, syscall.EACCES) {
+ t.Fatalf("%s: refusal does not prove filtering: %v", addr, err)
+ }
+ }
+ transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "unix", sock)
+ }}
+ defer transport.CloseIdleConnections()
+ client := &http.Client{Transport: transport, Timeout: time.Second}
+ resp, err := client.Get("http://app/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatal(resp.Status)
+ }
+ if os.Getenv("CARLOS_DEMO_KERNEL_CHILD") == "" {
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cmd := exec.Command(exe, "-test.run=^TestDemoDenyAllKernelHelper$")
+ cmd.Env = append(os.Environ(), "CARLOS_DEMO_KERNEL_CHILD=1")
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("child network witness: %s: %v", out, err)
+ }
+ }
+}
diff --git a/internal/host/demo_policy_test.go b/internal/host/demo_policy_test.go
new file mode 100644
index 000000000..d9a560364
--- /dev/null
+++ b/internal/host/demo_policy_test.go
@@ -0,0 +1,138 @@
+package host
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/demo"
+)
+
+func TestDemoPolicyRoundTrip(t *testing.T) {
+ root := t.TempDir()
+ cfg := demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}
+ if err := installDemoUnits(root, cfg); err != nil {
+ t.Fatal(err)
+ }
+ for _, unit := range []string{"carlos-instance@.service", "carlos-instance-gen@.service"} {
+ raw, err := os.ReadFile(filepath.Join(root, "etc/systemd/system", unit+".d/90-carlos-demo.conf"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{"PrivateNetwork=yes", "RestrictAddressFamilies=\nRestrictAddressFamilies=AF_UNIX", "IPAddressAllow=\n", "IPAddressDeny=any", "MemoryMax=268435456", "CPUWeight=50", "CPUQuota=50%", "IOWeight=50"} {
+ if !strings.Contains(string(raw), want) {
+ t.Fatalf("missing %q in %s", want, raw)
+ }
+ }
+ }
+ ordinary := t.TempDir()
+ if err := installDemoUnits(ordinary, demo.Config{}); err != nil {
+ t.Fatal(err)
+ }
+ entries, err := os.ReadDir(ordinary)
+ if err != nil || len(entries) != 0 {
+ t.Fatalf("ordinary install: %v %v", entries, err)
+ }
+}
+
+func TestDemoPolicyBoxEnvironment(t *testing.T) {
+ root := t.TempDir()
+ env := filepath.Join(root, "host.env")
+ if err := os.WriteFile(env, []byte("CARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=demo\nCARLOS_DEMO_DOMAIN=example.com\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ cfg, err := readClaimUnitSettings(env)
+ if err != nil || !cfg.demo.BoxMode() {
+ t.Fatalf("config %+v %v", cfg, err)
+ }
+ raw, err := unitsFS.ReadFile("units/" + claimControlUnit)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rendered := claimUnitContent(claimControlUnit, raw, cfg)
+ if !strings.Contains(string(rendered), claimControlEnvironment) {
+ t.Fatal("root did not receive demo configuration")
+ }
+ if strings.Contains(string(rendered), "StateDirectory=carlos-claims") {
+ t.Fatal("demo mode enabled claims machinery")
+ }
+ if err := os.WriteFile(env, []byte("CARLOS_DEMO_FLEET=demo\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readClaimUnitSettings(env); err == nil {
+ t.Fatal("partial config accepted")
+ }
+}
+
+func TestDemoPolicyMalformedEnvironment(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "host.env")
+ if err := os.WriteFile(path, []byte("CARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=\"demo\nCARLOS_DEMO_DOMAIN=example.com\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readClaimUnitSettings(path); !errors.Is(err, demo.ErrConfig) {
+ t.Fatalf("malformed demo configuration could use ordinary bootstrap fallback: %v", err)
+ }
+}
+
+func TestDemoPolicyBoxInstallers(t *testing.T) {
+ writeEnv := func(etc string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Join(etc, "carlos"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(etc, "carlos/host.env"), []byte("CARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=demo\nCARLOS_DEMO_DOMAIN=example.com\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ check := func(etc string) {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join(etc, "systemd/system", claimControlUnit))
+ if err != nil || !strings.Contains(string(raw), claimControlEnvironment) {
+ t.Fatalf("root environment: %s %v", raw, err)
+ }
+ for _, unit := range []string{"carlos-instance@.service", "carlos-instance-gen@.service"} {
+ raw, err := os.ReadFile(filepath.Join(etc, "systemd/system", unit+".d/90-carlos-demo.conf"))
+ if err != nil || !strings.Contains(string(raw), "PrivateNetwork=yes") {
+ t.Fatalf("%s: %s %v", unit, raw, err)
+ }
+ }
+ }
+ stage := t.TempDir()
+ writeEnv(filepath.Join(stage, "etc"))
+ if err := bootstrap(stage, nil); err != nil {
+ t.Fatal(err)
+ }
+ check(filepath.Join(stage, "etc"))
+ f := newApplyFixture(t, "stable", "v1.0.0")
+ writeEnv(f.a.etcDir)
+ if err := f.a.installUnits(t.Context(), stage, nil); err != nil {
+ t.Fatal(err)
+ }
+ check(f.a.etcDir)
+ etc := t.TempDir()
+ writeEnv(etc)
+ var calls []string
+ ctl := func(args ...string) (string, error) { calls = append(calls, strings.Join(args, " ")); return "", nil }
+ probe := func(args ...string) (string, error) {
+ if args[1] == dbReadSocketUnit {
+ if args[0] == "is-active" {
+ return "inactive\n", systemctlExit(3)
+ }
+ return "disabled\n", systemctlExit(1)
+ }
+ if args[0] == "is-active" {
+ return "active\n", nil
+ }
+ return "enabled\n", nil
+ }
+ lock := filepath.Join(t.TempDir(), "lock")
+ ensureSystemUnits(etc, lock, ctl, probe, t.Logf)
+ check(etc)
+ calls = nil
+ ensureSystemUnits(etc, lock, ctl, probe, t.Logf)
+ if len(calls) != 0 {
+ t.Fatalf("unchanged demo rewrote units: %v", calls)
+ }
+}
diff --git a/internal/host/demo_units/demo.conf b/internal/host/demo_units/demo.conf
new file mode 100644
index 000000000..33de5a0f3
--- /dev/null
+++ b/internal/host/demo_units/demo.conf
@@ -0,0 +1,7 @@
+[Service]
+PrivateNetwork=yes
+RestrictAddressFamilies=
+RestrictAddressFamilies=AF_UNIX
+IPAddressAllow=
+IPAddressDeny=
+IPAddressDeny=any
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go
index a3a209695..7a2fb2250 100644
--- a/internal/host/systemapply.go
+++ b/internal/host/systemapply.go
@@ -23,6 +23,7 @@ import (
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/cliflag"
+ "github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/hostfloor"
"github.com/carlosframework/platform/internal/hostwrite"
"github.com/carlosframework/platform/internal/layout"
@@ -1380,6 +1381,9 @@ func (a *systemApplier) installUnits(ctx context.Context, stagedRoot string, rem
claimSettings, settingsErr := readClaimUnitSettings(filepath.Join(a.etcDir, "carlos", "host.env"))
if settingsErr != nil {
a.ops.logf("system apply: instance-control unit settings: %v", settingsErr)
+ if errors.Is(settingsErr, demo.ErrConfig) {
+ return settingsErr
+ }
}
unitDir := filepath.Join(a.etcDir, "systemd", "system")
if err := os.MkdirAll(unitDir, 0o755); err != nil {
@@ -1426,6 +1430,11 @@ func (a *systemApplier) installUnits(ctx context.Context, stagedRoot string, rem
return err
}
}
+ if settingsErr == nil {
+ if _, err := installDemoUnitsIn(unitDir, claimSettings.demo); err != nil {
+ return err
+ }
+ }
sys := filepath.Join(stagedRoot, "etc", "sysusers.d", "carlos.conf")
if _, err := os.Stat(sys); err == nil {
if err := os.MkdirAll(filepath.Join(a.etcDir, "sysusers.d"), 0o755); err != nil {
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go
index d1150ee72..d3b5d50c2 100644
--- a/internal/host/systemunits.go
+++ b/internal/host/systemunits.go
@@ -2,11 +2,14 @@ package host
import (
"bytes"
+ "errors"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
+
+ "github.com/carlosframework/platform/internal/demo"
)
// systemRecoverUnit is carlos-system-recover.service, spelled out once
@@ -74,6 +77,9 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st
claimSettings, settingsErr := readClaimUnitSettings(filepath.Join(etcDir, "carlos", "host.env"))
if settingsErr != nil {
logf("adopt: instance-control unit settings: %v", settingsErr)
+ if errors.Is(settingsErr, demo.ErrConfig) {
+ return
+ }
}
unitDir := filepath.Join(etcDir, "systemd", "system")
// systemctl answers these two in stdout and spends its EXIT STATUS on
@@ -140,12 +146,20 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st
logf("adopt: instance-control unit: %v", err)
return
}
- controlChanged := settingsErr == nil && (claimSettings.enabled || bytes.Contains(installed, []byte(claimControlEnvironment))) && (err != nil || !bytes.Equal(installed, claimUnitContent(claimControlUnit, control, claimSettings)))
+ controlChanged := settingsErr == nil && (claimSettings.enabled || claimSettings.demo.BoxMode() || bytes.Contains(installed, []byte(claimControlEnvironment))) && (err != nil || !bytes.Equal(installed, claimUnitContent(claimControlUnit, control, claimSettings)))
dbrEnabled := parseIsEnabled(dbrEnabledOut)
// Dark: neither listening nor enabled for the next boot.
dbrDark := !*dbrActive && (dbrEnabled == nil || !*dbrEnabled)
dbrSettled := (dbrWant && *dbrActive) || (!dbrWant && dbrDark)
- if !missing && !controlChanged && *isActive && isEnabled != nil && *isEnabled && *ctlActive && dbrSettled {
+ demoChanged := false
+ if settingsErr == nil {
+ demoChanged, err = installDemoUnitsIn(unitDir, claimSettings.demo)
+ if err != nil {
+ logf("adopt: demo unit settings: %v", err)
+ return
+ }
+ }
+ if !demoChanged && !missing && !controlChanged && *isActive && isEnabled != nil && *isEnabled && *ctlActive && dbrSettled {
return
}
if err := os.MkdirAll(unitDir, 0o755); err != nil {
diff --git a/internal/instancectl/demo_policy.go b/internal/instancectl/demo_policy.go
new file mode 100644
index 000000000..61e8952a4
--- /dev/null
+++ b/internal/instancectl/demo_policy.go
@@ -0,0 +1,116 @@
+package instancectl
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/demo"
+)
+
+// demoHandler refuses unsupported launch and mutation doors before dispatch.
+// DemoBox comes only from this root service's environment, never a request.
+func (s *Server) demoHandler(next http.Handler) http.Handler {
+ if !s.DemoBox {
+ return next
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasPrefix(r.URL.Path, "/claim/") || r.Method == "POST" && (r.URL.Path == "/cmd" || r.URL.Path == "/tty" || r.URL.Path == "/seed") {
+ http.Error(w, demo.ErrPolicy.Error(), http.StatusForbidden)
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+func (s *Server) assertDemoPolicy(ctx context.Context, host string) error {
+ if !s.DemoBox {
+ return nil
+ }
+ small, _ := cgroup.SizeByName("small")
+ if err := s.setTier(ctx, host, small.Limit); err != nil {
+ return fmt.Errorf("%w: small tier: %v", demo.ErrPolicy, err)
+ }
+ return nil
+}
+
+// assertDemoUnit proves the unit properties before each start, including a
+// generation whose own drop-in was just reloaded. Missing properties fail.
+func (s *Server) assertDemoUnit(ctx context.Context, host, unit string) error {
+ if !s.DemoBox {
+ return nil
+ }
+ out, err := s.Systemctl(ctx, "show", unit, "-p", "PrivateNetwork,RestrictAddressFamilies,IPAddressDeny,IPAddressAllow,MemoryMax,CPUWeight,CPUQuotaPerSecUSec,IOWeight,Slice")
+ if err != nil {
+ return fmt.Errorf("%w: unit readback: %v", demo.ErrPolicy, err)
+ }
+ m := parseShow(out)
+ deny := strings.Fields(m["IPAddressDeny"])
+ all := len(deny) == 1 && deny[0] == "any" || len(deny) == 2 && (deny[0] == "0.0.0.0/0" && deny[1] == "::/0" || deny[1] == "0.0.0.0/0" && deny[0] == "::/0")
+ if m["PrivateNetwork"] != "yes" || strings.TrimSpace(m["RestrictAddressFamilies"]) != "AF_UNIX" || !all || m["IPAddressAllow"] != "" {
+ return fmt.Errorf("%w: network readback", demo.ErrPolicy)
+ }
+ if _, present := m["IPAddressAllow"]; !present {
+ return demo.ErrPolicy
+ }
+ if m["Slice"] != SliceName(host) {
+ return fmt.Errorf("%w: unit slice", demo.ErrPolicy)
+ }
+ if err := demoSizeShown(out); err != nil {
+ return err
+ }
+ out, err = s.Systemctl(ctx, "show", SliceName(host), "-p", "MemoryMax,CPUWeight,CPUQuotaPerSecUSec,IOWeight")
+ if err != nil {
+ return fmt.Errorf("%w: slice readback: %v", demo.ErrPolicy, err)
+ }
+ return demoSizeShown(out)
+}
+
+func demoSizeShown(out string) error {
+ small, _ := cgroup.SizeByName("small")
+ rb := parseSizeShow(out)
+ if rb.SliceMemoryMax != small.Limit.MemoryMax || rb.CPUWeight != small.Shares.CPUWeight || rb.CPUQuotaPercent != small.Shares.CPUQuotaPercent || rb.IOWeight != small.Shares.IOWeight {
+ return fmt.Errorf("%w: size readback", demo.ErrPolicy)
+ }
+ return nil
+}
+
+// demoCgroup checks kernel values after launch, before reporting success.
+// Paths are derived from validated platform unit names, never systemd output.
+func (s *Server) demoCgroup(host, unit string) error {
+ if !s.DemoBox {
+ return nil
+ }
+ if s.CgroupRoot == "" {
+ return demo.ErrPolicy
+ }
+ small, _ := cgroup.SizeByName("small")
+ for _, dir := range []string{filepath.Join(s.CgroupRoot, parentSlices, SliceName(host)), filepath.Join(s.CgroupRoot, parentSlices, SliceName(host), unit)} {
+ read := func(name string) (string, error) {
+ b, e := os.ReadFile(filepath.Join(dir, name))
+ return strings.TrimSpace(string(b)), e
+ }
+ for name, want := range map[string]string{"memory.max": strconv.FormatInt(small.Limit.MemoryMax, 10), "cpu.weight": strconv.Itoa(small.Shares.CPUWeight), "io.weight": "default " + strconv.Itoa(small.Shares.IOWeight)} {
+ got, err := read(name)
+ if err != nil || got != want {
+ return fmt.Errorf("%w: %s kernel readback", demo.ErrPolicy, name)
+ }
+ }
+ raw, err := read("cpu.max")
+ fields := strings.Fields(raw)
+ if err != nil || len(fields) != 2 {
+ return fmt.Errorf("%w: cpu.max readback", demo.ErrPolicy)
+ }
+ quota, e1 := strconv.ParseInt(fields[0], 10, 64)
+ period, e2 := strconv.ParseInt(fields[1], 10, 64)
+ if e1 != nil || e2 != nil || quota <= 0 || period <= 0 || period > 1_000_000 || quota > 1_000_000 || quota*100 != period*int64(small.Shares.CPUQuotaPercent) {
+ return fmt.Errorf("%w: cpu.max readback", demo.ErrPolicy)
+ }
+ }
+ return nil
+}
diff --git a/internal/instancectl/demo_policy_test.go b/internal/instancectl/demo_policy_test.go
new file mode 100644
index 000000000..bb436c609
--- /dev/null
+++ b/internal/instancectl/demo_policy_test.go
@@ -0,0 +1,146 @@
+package instancectl
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+)
+
+func TestDemoPolicyFailClosed(t *testing.T) {
+ for _, path := range []string{"/seed?host=shop.example.com", "/cmd?host=shop.example.com", "/tty?host=shop.example.com", "/claim/launch", "/start?host=shop.example.com&role=sidecar", "/start?host=shop.example.com&role=worker", "/start?host=shop.example.com&runtime=rootfs"} {
+ t.Run(path, func(t *testing.T) {
+ calls := 0
+ s := &Server{DemoBox: true, Systemctl: func(context.Context, ...string) (string, error) { calls++; return "", nil }}
+ w := httptest.NewRecorder()
+ s.Handler().ServeHTTP(w, httptest.NewRequest("POST", path, nil))
+ if w.Code < 400 || calls != 0 {
+ t.Fatalf("unsupported start: status=%d calls=%d", w.Code, calls)
+ }
+ })
+ }
+ good := "Slice=" + SliceName("shop.example.com") + "\nPrivateNetwork=yes\nRestrictAddressFamilies=AF_UNIX\nIPAddressDeny=0.0.0.0/0 ::/0\nIPAddressAllow=\nMemoryMax=268435456\nCPUWeight=50\nCPUQuotaPerSecUSec=500ms\nIOWeight=50\n"
+ for _, field := range []string{"", "PrivateNetwork=yes", "RestrictAddressFamilies=AF_UNIX", "IPAddressDeny=0.0.0.0/0 ::/0", "IPAddressAllow=", "MemoryMax=268435456", "CPUWeight=50", "CPUQuotaPerSecUSec=500ms", "IOWeight=50", "readError"} {
+ t.Run("readback/"+field, func(t *testing.T) {
+ s := &Server{DemoBox: true, Systemctl: func(context.Context, ...string) (string, error) {
+ if field == "readError" {
+ return "", errors.New("read failed")
+ }
+ if field == "" {
+ return good, nil
+ }
+ return strings.ReplaceAll(good, field+"\n", strings.Split(field, "=")[0]+"=unexpected\n"), nil
+ }}
+ err := s.assertDemoUnit(t.Context(), "shop.example.com", "carlos-instance@shop.example.com.service")
+ if (err == nil) != (field == "") {
+ t.Fatalf("readback error=%v", err)
+ }
+ })
+ }
+ t.Run("ordinaryNoPolicyUnits", func(t *testing.T) {
+ s := &Server{Systemctl: func(context.Context, ...string) (string, error) { t.Fatal("ordinary unit queried"); return "", nil }}
+ if err := s.assertDemoUnit(t.Context(), "shop.example.com", "unit"); err != nil {
+ t.Fatal(err)
+ }
+ })
+ t.Run("sizeAndParent", func(t *testing.T) {
+ for _, path := range []string{"/size?host=shop.example.com&size=xlarge", "/parent?host=shop.example.com&memory_max=4294967296"} {
+ var writes []string
+ s := &Server{DemoBox: true, Systemctl: func(_ context.Context, args ...string) (string, error) {
+ if args[0] == "set-property" {
+ writes = append(writes, strings.Join(args, " "))
+ }
+ return good, nil
+ }}
+ w := httptest.NewRecorder()
+ s.Handler().ServeHTTP(w, httptest.NewRequest("POST", path, nil))
+ if w.Code >= 400 {
+ t.Fatalf("%s: %d %s", path, w.Code, w.Body)
+ }
+ small, _ := cgroup.SizeByName("small")
+ if len(writes) != 1 || strings.Contains(writes[0], "4294967296") || strings.Contains(writes[0], "CPUWeight=200") || small.Limit.MemoryMax != 268435456 {
+ t.Fatalf("uncapped writes %v", writes)
+ }
+ }
+ })
+}
+
+func TestDemoPolicyStartReadback(t *testing.T) {
+ const host = "shop.example.com"
+ for _, generation := range []bool{false, true} {
+ for _, failure := range []string{"", "network", "memory.max", "cpu.weight", "cpu.max", "io.weight"} {
+ t.Run(fmt.Sprintf("generation=%v/%s", generation, failure), func(t *testing.T) {
+ root := t.TempDir()
+ unit := UnitName(RoleRun, host)
+ query := "/start?host=" + host + "&role=run&memory_max=2147483648"
+ if generation {
+ unit = GenUnitName(host, 7)
+ query += "&gen=7"
+ }
+ small, _ := cgroup.SizeByName("small")
+ good := "Slice=" + SliceName(host) + "\nPrivateNetwork=yes\nRestrictAddressFamilies=AF_UNIX\nIPAddressDeny=0.0.0.0/0 ::/0\nIPAddressAllow=\nMemoryMax=268435456\nCPUWeight=50\nCPUQuotaPerSecUSec=500ms\nIOWeight=50\n"
+ started, stopped := false, false
+ s := &Server{DemoBox: true, CgroupRoot: root, DropInDir: t.TempDir(), ExeRoot: t.TempDir()}
+ for _, dir := range []string{filepath.Join(root, parentSlices, SliceName(host)), filepath.Join(root, parentSlices, SliceName(host), unit)} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ for f, v := range map[string]string{"memory.max": "268435456", "cpu.weight": "50", "cpu.max": "50000 100000", "io.weight": "default 50", "cgroup.events": "populated 0"} {
+ if f == failure {
+ v = "wrong"
+ }
+ if err := os.WriteFile(filepath.Join(dir, f), []byte(v), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ s.Systemctl = func(_ context.Context, args ...string) (string, error) {
+ line := strings.Join(args, " ")
+ if args[0] == "start" {
+ started = true
+ return "", nil
+ }
+ if args[0] == "stop" {
+ stopped = true
+ return "", nil
+ }
+ if strings.HasPrefix(line, "show -p Slice,NeedDaemonReload") {
+ return "Slice=" + SliceName(host) + "\nNeedDaemonReload=no\nMemoryMax=268435456\nMemoryHigh=" + strconv.FormatInt(cgroup.HighOf(small.Limit.MemoryMax), 10) + "\nMemorySwapMax=268435456\n", nil
+ }
+ if strings.Contains(line, "PrivateNetwork") && failure == "network" {
+ return strings.ReplaceAll(good, "PrivateNetwork=yes", "PrivateNetwork=no"), nil
+ }
+ if strings.Contains(line, "InvocationID") {
+ return "inv", nil
+ }
+ if args[0] == "set-property" && strings.Contains(line, "MemoryMax=2147483648") {
+ t.Fatal("request tier escaped cap")
+ }
+ return good, nil
+ }
+ w := httptest.NewRecorder()
+ s.Handler().ServeHTTP(w, httptest.NewRequest("POST", query, nil))
+ if failure == "" {
+ if w.Code != 200 || !started || stopped {
+ t.Fatalf("start: status=%d started=%v stopped=%v body=%s", w.Code, started, stopped, w.Body)
+ }
+ } else if failure == "network" {
+ if w.Code < 400 || started {
+ t.Fatalf("network failure started: %d %v %s", w.Code, started, w.Body)
+ }
+ } else {
+ if w.Code < 400 || !started || !stopped {
+ t.Fatalf("kernel mismatch not stopped: %d %v %v %s", w.Code, started, stopped, w.Body)
+ }
+ }
+ })
+ }
+ }
+}
diff --git a/internal/instancectl/gen.go b/internal/instancectl/gen.go
index db2bcf326..06ffc4572 100644
--- a/internal/instancectl/gen.go
+++ b/internal/instancectl/gen.go
@@ -391,11 +391,23 @@ func (s *Server) startGen(w http.ResponseWriter, r *http.Request, req request) {
// answer says. A failure past this point kills it and proves it empty
// before its files go; one that cannot prove that keeps the files and
// says so (statusGenUnproven).
+ if err := s.assertDemoPolicy(ctx, req.host); err != nil {
+ fail(http.StatusBadGateway, err.Error())
+ return
+ }
+ if err := s.assertDemoUnit(ctx, req.host, unit); err != nil {
+ fail(http.StatusBadGateway, err.Error())
+ return
+ }
startAt := time.Now()
if out, err := s.Systemctl(ctx, "start", unit); err != nil {
s.abandonGen(ctx, w, req.host, unit, "start: "+strings.TrimSpace(out+" "+err.Error()))
return
}
+ if err := s.demoCgroup(req.host, unit); err != nil {
+ s.abandonGen(ctx, w, req.host, unit, err.Error())
+ return
+ }
inv, err := s.Systemctl(ctx, "show", "-p", "InvocationID", "--value", unit)
if err != nil {
s.abandonGen(ctx, w, req.host, unit, "show: "+err.Error())
@@ -705,6 +717,10 @@ func (s *Server) handleParent(w http.ResponseWriter, r *http.Request) {
http.Error(w, "memory_max "+strconv.Quote(q.Get("memory_max"))+" is not one tier or two", http.StatusBadRequest)
return
}
+ if s.DemoBox {
+ small, _ := cgroup.SizeByName("small")
+ n = small.Limit.MemoryMax
+ }
max := strconv.FormatInt(n, 10)
defer s.lockSliceWrites(host)()
if out, err := s.Systemctl(r.Context(), "set-property", "--runtime", SliceName(host),
diff --git a/internal/instancectl/rootfs.go b/internal/instancectl/rootfs.go
index efb836217..8643ee1e5 100644
--- a/internal/instancectl/rootfs.go
+++ b/internal/instancectl/rootfs.go
@@ -1217,6 +1217,10 @@ func (s *Server) setRootfsReport(r ProbeReport) {
// drop-in: it proves the default (R11). Whatever goes wrong is a failing
// line, so readiness is never the default.
func (s *Server) runRootfsProbe(ctx context.Context) {
+ if s.DemoBox {
+ s.setRootfsReport(ProbeReport{Lines: []VerdictLine{{Check: "demo", Verdict: "fail", Detail: "DEMO-POLICY"}}})
+ return
+ }
if s.ProbeImage == nil {
s.setRootfsReport(ProbeReport{Lines: []VerdictLine{{Check: "rootfs-probe", Verdict: "unverified", Detail: "no probe image on this service"}}})
return
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index fffc3337f..fa40dd0ae 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -25,6 +25,8 @@ import (
"github.com/carlosframework/platform/internal/cgroup"
"github.com/carlosframework/platform/internal/cliflag"
"github.com/carlosframework/platform/internal/controlsock"
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/hostwrite"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/version"
@@ -38,6 +40,9 @@ import (
// UnitName/SliceName, and every allowed address comes from the egress
// source; nothing from a request reaches systemctl as a string.
type Server struct {
+ // DemoBox is fixed from root-owned environment at service startup.
+ DemoBox bool
+
ClaimStop http.Handler
// ClaimHeldRelease is the moves held-release route's handler (moves
// Task 7b), registered only when set: the host sets it with both
@@ -254,7 +259,16 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV
if os.Geteuid() != 0 {
log.Fatal("instance-control: this is the root service behind carlos-instance-control.socket; it is not for operators")
}
+ cfg, cfgErr := demo.BoxConfig(os.Getenv)
+ if cfgErr != nil || cfg.BoxMode() && hostwrite.Enabled(os.Getenv) {
+ log.Fatal("instance-control: demo box configuration refused")
+ }
+ if cfg.BoxMode() {
+ // Fixed demo unit restrictions need no registry-derived allow or restart sweep.
+ egress = nil
+ }
s := &Server{
+ DemoBox: cfg.BoxMode(),
ClaimStop: claim,
ClaimHeldRelease: heldRelease,
Systemctl: func(ctx context.Context, args ...string) (string, error) {
@@ -433,7 +447,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("POST /egress", s.handleEgress)
mux.HandleFunc("GET /egress", s.handleEgressStatus)
mux.HandleFunc("GET "+RootfsReadyPath, s.handleReadyRootfs)
- return mux
+ return s.demoHandler(mux)
}
// handleEgress re-asserts one host's slice now (the agent's nudge after
@@ -679,6 +693,10 @@ func parseQuery(host string, q url.Values, v verbShape) (request, error) {
// memory caps, and the CPU and IO shares that follow from the same tier
// (#214 item 1). Seed, instance and sidecar share all of it.
func (s *Server) setTier(ctx context.Context, host string, tier cgroup.Limit) error {
+ if s.DemoBox {
+ small, _ := cgroup.SizeByName("small")
+ tier = small.Limit
+ }
return sliceTier(ctx, s.Systemctl, host, tier)
}
@@ -718,6 +736,14 @@ func (s *Server) handleStart(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
+ if s.DemoBox {
+ if req.rootfs() || req.role != RoleRun {
+ http.Error(w, demo.ErrPolicy.Error(), http.StatusForbidden)
+ return
+ }
+ small, _ := cgroup.SizeByName("small")
+ req.tier = small.Limit
+ }
if req.rootfs() {
s.startRootfs(w, r, req)
return
@@ -790,10 +816,22 @@ func (s *Server) handleStart(w http.ResponseWriter, r *http.Request) {
http.Error(w, "start: cancelled before it was submitted: "+err.Error(), http.StatusConflict)
return
}
+ if err := s.assertDemoPolicy(ctx, req.host); err != nil {
+ http.Error(w, err.Error(), http.StatusBadGateway)
+ return
+ }
+ if err := s.assertDemoUnit(ctx, req.host, unit); err != nil {
+ http.Error(w, err.Error(), http.StatusBadGateway)
+ return
+ }
if out, err := s.Systemctl(ctx, "start", unit); err != nil {
http.Error(w, "start: "+strings.TrimSpace(out+" "+err.Error()), http.StatusBadGateway)
return
}
+ if err := s.demoCgroup(req.host, unit); err != nil {
+ s.abandonUnit(ctx, w, req.host, unit, err.Error(), func(...string) error { return nil })
+ return
+ }
inv, err := s.Systemctl(ctx, "show", "-p", "InvocationID", "--value", unit)
if err != nil {
http.Error(w, "show: "+err.Error(), http.StatusBadGateway)
diff --git a/internal/instancectl/size.go b/internal/instancectl/size.go
index e7e02fd65..b5e2e881a 100644
--- a/internal/instancectl/size.go
+++ b/internal/instancectl/size.go
@@ -71,6 +71,9 @@ func (s *Server) handleSize(w http.ResponseWriter, r *http.Request) {
http.Error(w, "size "+strconv.Quote(q.Get("size"))+" is not a platform size", http.StatusBadRequest)
return
}
+ if s.DemoBox {
+ size, _ = cgroup.SizeByName("small")
+ }
// /parent writes the same slice; the read-back is never taken in the
// middle of another writer's call.
defer s.lockSliceWrites(host)()
diff --git a/internal/provision/apppolicy_reconcile.go b/internal/provision/apppolicy_reconcile.go
index 179564d06..bcd66ba7b 100644
--- a/internal/provision/apppolicy_reconcile.go
+++ b/internal/provision/apppolicy_reconcile.go
@@ -112,6 +112,14 @@ func (c appPolicyCols) expiresCol() string {
// policyColsFor is rec's row's columns under r.
func policyColsFor(r policyRead, rec Record) appPolicyCols {
+ if rec.Demo != nil {
+ cols := appPolicyCols{Known: true, Size: "small"}
+ if r.state == policyAbsentKnown && r.p != nil && r.p.Demo != nil && *r.p.Demo == *rec.Demo && r.p.EgressMode == "deny-all" {
+ cols.ExpiresAt = r.p.SignedAt.Add(apppolicy.Lifetime).Unix()
+ }
+ return cols
+ }
+
switch r.state {
case policyAbsentKnown:
if r.p == nil {
diff --git a/internal/provision/demo_policy.go b/internal/provision/demo_policy.go
new file mode 100644
index 000000000..e0828662c
--- /dev/null
+++ b/internal/provision/demo_policy.go
@@ -0,0 +1,105 @@
+package provision
+
+import (
+ "encoding/json"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func validateDemoRecord(rec Record) error {
+ if rec.Demo == nil {
+ return nil
+ }
+ if rec.Retired {
+ return demo.ValidateBinding(*rec.Demo, rec.Account, rec.App, rec.Host, rec.Demo.Lifetime, "retired")
+ }
+ fleet, ok := registry.FleetPlacement(rec.Region)
+ if !ok || rec.FleetBox == "" || rec.FleetBoxMoved || rec.Move != nil || rec.Runtime != "" || rec.KindOrDefault() != "instance" || rec.Unit != "" || rec.Role != "" || len(rec.Replicas) != 0 || rec.Pool != "" || rec.Seed != nil || len(rec.AddrsOrDefault()) != 0 || !rec.HibernateOrDefault() {
+ return demo.ErrPolicy
+ }
+ return demo.ValidateBinding(*rec.Demo, rec.Account, rec.App, rec.Host, rec.Demo.Lifetime, fleet)
+}
+
+// demoFixed protects identity through the common sequenced record writer.
+// Ordinary read/modify/write operations must retain it, including tombstones.
+func demoFixed(before, after []byte) error {
+ var oldMark, newMark struct {
+ Demo *demo.Descriptor `json:"demo"`
+ }
+ if err := json.Unmarshal(before, &oldMark); err != nil {
+ return err
+ }
+ if err := json.Unmarshal(after, &newMark); err != nil {
+ return err
+ }
+ if oldMark.Demo == nil && newMark.Demo == nil {
+ return nil
+ }
+ var a, b Record
+ if len(before) > 0 {
+ if err := json.Unmarshal(before, &a); err != nil {
+ return err
+ }
+ }
+ if err := json.Unmarshal(after, &b); err != nil {
+ return err
+ }
+ if a.Demo != nil {
+ if b.Demo == nil || *a.Demo != *b.Demo {
+ return demo.ErrPolicy
+ }
+ next, _, err := RecordSequence(after)
+ if err != nil {
+ return err
+ }
+ if isTombstoneOf(before, next) {
+ return nil
+ }
+ if a.Retired || a.Account != b.Account || a.App != b.App || a.Host != b.Host || a.Region != b.Region || a.FleetBox != b.FleetBox {
+ return demo.ErrPolicy
+ }
+ }
+ return validateDemoRecord(b)
+}
+
+func stampDemoRoute(rt *registry.Route, rec Record) {
+ if rec.Demo == nil {
+ return
+ }
+ rt.DemoID, rt.DemoHost, rt.DemoLifetime, rt.DemoExpiresAt = rec.Demo.ID, rec.Demo.Host, rec.Demo.Lifetime, rec.Demo.ExpiresAt
+}
+
+// AssertDemoRoute is the agent's before-exec gate over the existing verified
+// cache. Root independently caps every instance on a configured demo box.
+func (c *PolicyCache) AssertDemoRoute(cfg demo.Config, rt registry.Route, claims bool, now time.Time) error {
+ if !cfg.BoxMode() && !rt.IsDemo() {
+ return nil
+ }
+ if !cfg.BoxMode() || claims || !rt.IsDemo() || rt.Runtime != "" || rt.Kind != "instance" || rt.Unit != "" || rt.Replica || rt.Replicas != "" || rt.Seed != "" || rt.SeedSource != "" || rt.Socket != NestedSocket(rt.Host) || rt.Moved {
+ return demo.ErrPolicy
+ }
+ fleet, ok := registry.FleetPlacement(rt.Region)
+ if !ok {
+ return demo.ErrPolicy
+ }
+ d := demo.Descriptor{ID: rt.DemoID, Host: rt.DemoHost, Lifetime: rt.DemoLifetime, ExpiresAt: rt.DemoExpiresAt}
+ if err := cfg.ValidateBinding(d, rt.Account, rt.App, rt.Host, rt.DemoLifetime, fleet); err != nil {
+ return err
+ }
+ if now.Unix() >= d.ExpiresAt || c == nil {
+ return demo.ErrPolicy
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ e := c.entries[[2]string{rt.Account, rt.App}]
+ if e == nil || e.read.state != policyAbsentKnown || e.read.p == nil {
+ return demo.ErrPolicy
+ }
+ p := e.read.p
+ if p.Expired(now) || p.Revision == 0 || p.Demo == nil || *p.Demo != d || p.EgressMode != "deny-all" || p.Validate() != nil {
+ return demo.ErrPolicy
+ }
+ return nil
+}
diff --git a/internal/provision/demo_policy_test.go b/internal/provision/demo_policy_test.go
new file mode 100644
index 000000000..388fcf504
--- /dev/null
+++ b/internal/provision/demo_policy_test.go
@@ -0,0 +1,149 @@
+package provision
+
+import (
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/apppolicy"
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func TestDemoPolicyRoundTrip(t *testing.T) {
+ id, _ := demo.NewIdentity(rand.Reader)
+ rec := Record{Account: "shop", App: id.App, Host: id.Name + ".example.com", Region: "fleet/demo", FleetBox: "box", Demo: &demo.Descriptor{ID: id.ID, Host: id.Name + ".example.com", Lifetime: "life", ExpiresAt: time.Now().Add(time.Hour).Unix()}}
+ before, _ := json.Marshal(rec)
+ rec.Channel = "edge"
+ after, _ := json.Marshal(rec)
+ if err := demoFixed(before, after); err != nil {
+ t.Fatal(err)
+ }
+ rt := RouteFor(rec, t.TempDir(), "", true, nil)
+ if !rt.IsDemo() || rt.DemoID != id.ID || rt.DemoLifetime != "life" {
+ t.Fatalf("descriptor lost: %+v", rt)
+ }
+ fw := forwardRowFor(rec)
+ if !fw.IsDemo() || fw.DemoID != id.ID {
+ t.Fatal("forward lost demo")
+ }
+ rec.Demo = nil
+ after, _ = json.Marshal(rec)
+ if err := demoFixed(before, after); err == nil {
+ t.Fatal("downgrade accepted")
+ }
+ if err := demoFixed([]byte(`{}`), []byte(`{"channel":"edge"}`)); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDemoPolicyFailClosed(t *testing.T) {
+ pub, key, _ := ed25519.GenerateKey(rand.Reader)
+ now := time.Now().UTC()
+ id, _ := demo.NewIdentity(rand.Reader)
+ d := demo.Descriptor{ID: id.ID, Host: id.Name + ".example.com", Lifetime: "life", ExpiresAt: now.Add(time.Hour).Unix()}
+ cfg := demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}
+ p := apppolicy.Policy{V: 1, Account: "shop", App: id.App, Revision: 1, SignedAt: now, Demo: &d, EgressMode: "deny-all", DefaultSize: "small"}
+ rec := Record{Account: "shop", App: id.App, Host: d.Host, Region: "fleet/demo", FleetBox: "box", Demo: &d}
+ rt := RouteFor(rec, t.TempDir(), "", true, nil)
+ for _, name := range []string{"valid", "absent", "expired", "badSignature", "wrongLifetime", "wrongFleet", "missingMarker", "flat", "claimsMode", "nonDemoBox", "transient"} {
+ t.Run(name, func(t *testing.T) {
+ store := dirStore(t)
+ policy := p
+ route := rt
+ box := cfg
+ claims := false
+ if name == "expired" {
+ policy.SignedAt = now.Add(-apppolicy.Lifetime - time.Second)
+ }
+ wire, err := apppolicy.Sign(key, policy)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if name == "badSignature" {
+ wire[len(wire)/2] ^= 1
+ }
+ if name != "absent" {
+ if _, err := store.Put(t.Context(), apppolicy.Key(p.Account, p.App), wire, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ cache := NewPolicyCache(nil)
+ cache.read(t.Context(), store, pub, [][2]string{{p.Account, p.App}}, now, readScope{})
+ switch name {
+ case "wrongLifetime":
+ route.DemoLifetime = "other"
+ case "wrongFleet":
+ route.Region = "fleet/other"
+ case "missingMarker":
+ route.DemoID = ""
+ case "flat":
+ route.Socket = DefaultSocket(route.Host)
+ case "claimsMode":
+ claims = true
+ case "nonDemoBox":
+ box = demo.Config{}
+ case "transient":
+ cache.entries[[2]string{p.Account, p.App}].read = policyRead{state: policyTransient}
+ }
+ err = cache.AssertDemoRoute(box, route, claims, now)
+ if (err == nil) != (name == "valid") {
+ t.Fatalf("error=%v", err)
+ }
+ })
+ }
+ var cache *PolicyCache
+ if err := cache.AssertDemoRoute(demo.Config{}, registry.Route{Host: "shop.example.com"}, false, now); err != nil {
+ t.Fatal("ordinary no policy", err)
+ }
+}
+
+func TestDemoPolicyRecordWriters(t *testing.T) {
+ id, _ := demo.NewIdentity(rand.Reader)
+ rec := Record{Schema: 1, Account: "shop", App: id.App, Host: id.Name + ".example.com", Slug: id.App, Region: "fleet/demo", FleetBox: "box", CreatedAt: time.Now().UTC(), Demo: &demo.Descriptor{ID: id.ID, Host: id.Name + ".example.com", Lifetime: "life", ExpiresAt: time.Now().Add(time.Hour).Unix()}}
+ store := dirStore(t)
+ key := RecordKey(rec.Account, rec.App, rec.Host)
+ before, _ := json.Marshal(rec)
+ etag, _, err := WriteRecord(t.Context(), store, key, []byte(`{}`), before, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec.Channel = "edge"
+ if err := UpdateRecord(t.Context(), store, rec, etag); err != nil {
+ t.Fatal(err)
+ }
+ got, _, err := GetRecordETag(t.Context(), store, rec.Account, rec.App, rec.Host)
+ if err != nil || got.Demo == nil || *got.Demo != *rec.Demo {
+ t.Fatalf("writer roundtrip: %+v %v", got, err)
+ }
+ for _, change := range []func(*Record){func(r *Record) { r.Demo = nil }, func(r *Record) { r.FleetBox = "other" }, func(r *Record) { r.Region = "fleet/other" }, func(r *Record) { r.Runtime = RuntimeRootfsV1 }, func(r *Record) { r.Kind = "service" }, func(r *Record) { r.Move = &MoveState{} }} {
+ bad := rec
+ change(&bad)
+ raw, _ := json.Marshal(bad)
+ if err := demoFixed(before, raw); err == nil {
+ t.Fatalf("changed authority accepted: %+v", bad)
+ }
+ }
+ tomb, err := TombstoneBody(before)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var retired Record
+ if err := json.Unmarshal(tomb, &retired); err != nil {
+ t.Fatal(err)
+ }
+ if retired.Demo == nil || *retired.Demo != *rec.Demo {
+ t.Fatal("tombstone lost descriptor")
+ }
+ if err := demoFixed(before, tomb); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDemoPolicyOrdinaryRecordBaseline(t *testing.T) {
+ if err := demoFixed([]byte(`{"created_at":"opaque"}`), []byte(`{"created_at":"opaque","channel":"edge"}`)); err != nil {
+ t.Fatalf("demo gate parsed unrelated ordinary fields: %v", err)
+ }
+}
diff --git a/internal/provision/forward.go b/internal/provision/forward.go
index 4740de4f4..207bd6c89 100644
--- a/internal/provision/forward.go
+++ b/internal/provision/forward.go
@@ -26,7 +26,7 @@ import (
// FleetBox is that label, which is what PutForward stores; an unlabelled
// row's FleetBox is the bindings pass's.
func forwardRowFor(rec Record) registry.Route {
- return registry.Route{
+ rt := registry.Route{
Host: rec.Host,
Kind: registry.KindForward,
Slug: rec.Slug,
@@ -40,6 +40,8 @@ func forwardRowFor(rec Record) registry.Route {
FleetLabel: rec.FleetBox,
FleetBox: rec.FleetBox,
}
+ stampDemoRoute(&rt, rec)
+ return rt
}
// forwardCurrent reports whether existing already is want: an inert forward
@@ -49,7 +51,7 @@ func forwardRowFor(rec Record) registry.Route {
// again, so a pass with nothing changing writes nothing (and wakes no
// registry watcher).
func forwardCurrent(existing, want registry.Route) bool {
- return existing.InertForward() &&
+ return existing.DemoID == want.DemoID && existing.DemoHost == want.DemoHost && existing.DemoLifetime == want.DemoLifetime && existing.DemoExpiresAt == want.DemoExpiresAt && existing.InertForward() &&
existing.Status == want.Status &&
existing.Provisioned == want.Provisioned &&
existing.Slug == want.Slug &&
diff --git a/internal/provision/lifetime.go b/internal/provision/lifetime.go
index ce79ae718..066b4c9da 100644
--- a/internal/provision/lifetime.go
+++ b/internal/provision/lifetime.go
@@ -154,7 +154,7 @@ func TombstoneBody(before []byte) ([]byte, error) {
return nil, err
}
out := map[string]json.RawMessage{}
- for _, name := range []string{"schema", "host", "account", "app", "incarnation", "record_seq"} {
+ for _, name := range []string{"schema", "host", "account", "app", "incarnation", "record_seq", "demo"} {
if v, ok := fields[name]; ok {
out[name] = v
}
diff --git a/internal/provision/provision.go b/internal/provision/provision.go
index aee65eb33..5855e52b4 100644
--- a/internal/provision/provision.go
+++ b/internal/provision/provision.go
@@ -26,6 +26,7 @@ import (
"github.com/carlosframework/platform/internal/controlname"
"github.com/carlosframework/platform/internal/controlsock"
+ "github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/ratelimit"
"github.com/carlosframework/platform/internal/registry"
@@ -40,6 +41,7 @@ import (
// Account vs the key's segments); GetRecord and ListRecords enforce that, a
// record that lies about identity is never guessed at (design §3.2).
type Record struct {
+ Demo *demo.Descriptor `json:"demo,omitempty"`
Coordinator *replicas.Coordinator `json:"coordinator,omitempty"`
ReplicaDeploy *replicas.Deploy `json:"replica_deploy,omitempty"`
// RecordSeq is advanced by every record writer once present; absent is legacy zero.
@@ -671,6 +673,10 @@ const MaxUpstreams = 16
// value that reaches the row unvalidated is discovered months later as an
// adopt pass that restarted nothing (the `-backing unti` incident, cli.go).
func ValidateShape(rec Record) error {
+ if err := validateDemoRecord(rec); err != nil {
+ return err
+ }
+
if !ValidKind(rec.Kind) {
return fmt.Errorf("kind %q: want instance, service or static (empty means instance)", rec.Kind)
}
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go
index 24f761168..12a820876 100644
--- a/internal/provision/reconcile.go
+++ b/internal/provision/reconcile.go
@@ -24,6 +24,7 @@ import (
"sync"
"time"
+ "github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/domains"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -596,6 +597,7 @@ func RouteFor(rec Record, dataDir, seed string, nested bool, policy *UpdatePolic
Assigned: rec.FleetBoxAt,
Moved: rec.FleetBoxMoved,
}
+ stampDemoRoute(&rt, rec)
if rec.DerivesPaths() {
rt.Socket = DefaultSocket(rec.Host)
rt.DBPath = DefaultDBPath(dataDir, rec.Host)
@@ -605,7 +607,7 @@ func RouteFor(rec Record, dataDir, seed string, nested bool, policy *UpdatePolic
// nested whatever nested says (#446): it wakes only nested (region
// HA P1a), and a fresh box mints before its first nested-default
// decision, so a flat mint could never wake on it.
- if (nested || rec.HA) && rt.Hibernate {
+ if (nested || rec.HA || rec.Demo != nil) && rt.Hibernate {
rt.Socket = NestedSocket(rec.Host)
rt.DBPath = NestedDBPath(dataDir, rec.Host)
}
@@ -878,6 +880,12 @@ func shapeMismatch(existing, want registry.Route) string {
// policyKnown false the update settings were not judged at all, which the
// caller has to count for itself. A dry run writes nothing and returns nil.
func convergeOwned(reg *registry.Registry, existing registry.Route, rec Record, policy *UpdatePolicy, policyKnown bool, ap appPolicyCols, dryRun bool) (policyMoved bool, err error) {
+ if existing.IsDemo() || rec.Demo != nil {
+ if rec.Demo == nil || existing.DemoID != rec.Demo.ID || existing.DemoHost != rec.Demo.Host || existing.DemoLifetime != rec.Demo.Lifetime || existing.DemoExpiresAt != rec.Demo.ExpiresAt {
+ return false, demo.ErrPolicy
+ }
+ }
+
var errs []error
if rec.Channel != "" && existing.Channel != rec.Channel {
if dryRun {
diff --git a/internal/provision/record_sequence.go b/internal/provision/record_sequence.go
index e5c5ca584..019e3630c 100644
--- a/internal/provision/record_sequence.go
+++ b/internal/provision/record_sequence.go
@@ -143,6 +143,9 @@ func WriteRecord(ctx context.Context, s release.Store, key string, before, body
if err := replicaFieldsFixed(ctx, before, body); err != nil {
return "", 0, err
}
+ if err := demoFixed(before, body); err != nil {
+ return "", 0, err
+ }
if err := runtimeFixed(before, body); err != nil {
return "", 0, err
}
@@ -168,6 +171,9 @@ func WriteRecord(ctx context.Context, s release.Store, key string, before, body
}
p.body, p.seq, p.sequenced = append([]byte(nil), body...), base+1, true
}
+ if err := demoFixed(before, body); err != nil {
+ return "", 0, err
+ }
if err := runtimeFixed(before, body); err != nil {
return "", 0, err // the bytes Put stores, after any sequencing, pass too
}
diff --git a/internal/registry/demo.go b/internal/registry/demo.go
new file mode 100644
index 000000000..9f5f88095
--- /dev/null
+++ b/internal/registry/demo.go
@@ -0,0 +1,7 @@
+package registry
+
+// IsDemo treats any partial descriptor as marked, so malformed data cannot
+// select ordinary activation. Full validation belongs to the policy gate.
+func (t Route) IsDemo() bool {
+ return t.DemoID != "" || t.DemoHost != "" || t.DemoLifetime != "" || t.DemoExpiresAt != 0
+}
diff --git a/internal/registry/demo_test.go b/internal/registry/demo_test.go
new file mode 100644
index 000000000..70743c82a
--- /dev/null
+++ b/internal/registry/demo_test.go
@@ -0,0 +1,63 @@
+package registry
+
+import (
+ "path/filepath"
+ "testing"
+)
+
+func TestDemoPolicyRoundTrip(t *testing.T) {
+ for _, forward := range []bool{false, true} {
+ r, err := Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer r.Close()
+ rt := Route{Host: "shop.example.com", Kind: "instance", Account: "shop", App: "shop", Region: "fleet/demo", DemoID: "identity", DemoHost: "shop.example.com", DemoLifetime: "life", DemoExpiresAt: 1}
+ write := r.Upsert
+ if forward {
+ rt.Kind = KindForward
+ write = r.PutForward
+ }
+ if err := write(rt); err != nil {
+ t.Fatal(err)
+ }
+ got, err := r.Get(rt.Host)
+ if err != nil || got.DemoID != rt.DemoID || got.DemoHost != rt.DemoHost || got.DemoLifetime != rt.DemoLifetime || got.DemoExpiresAt != 1 {
+ t.Fatalf("stored descriptor: %+v %v", got, err)
+ }
+ old, err := r.Fingerprint()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := r.sql.Exec("UPDATE routes SET demo_expires_at=2 WHERE host=?", rt.Host); err != nil {
+ t.Fatal(err)
+ }
+ next, err := r.Fingerprint()
+ if err != nil || old == next {
+ t.Fatal("demo metadata invisible to reload", err)
+ }
+ rt.DemoID = ""
+ rt.DemoHost = ""
+ rt.DemoLifetime = ""
+ rt.DemoExpiresAt = 0
+ if err := write(rt); err == nil {
+ t.Fatal("downgrade succeeded")
+ }
+ }
+}
+
+func TestDemoPolicyPartialMarkerCannotDowngrade(t *testing.T) {
+ r, err := Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer r.Close()
+ rt := Route{Host: "shop.example.com", Kind: "instance", DemoHost: "shop.example.com"}
+ if err := r.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ rt.DemoHost = ""
+ if err := r.Upsert(rt); err == nil {
+ t.Fatal("partial demo marker silently downgraded")
+ }
+}
diff --git a/internal/registry/forward.go b/internal/registry/forward.go
index a0d4d9184..923ad287a 100644
--- a/internal/registry/forward.go
+++ b/internal/registry/forward.go
@@ -99,6 +99,7 @@ var ErrHostHeld = errors.New("registry: another row holds the host")
// WakeIncarnation is not persisted and is not listed. A field added to Route
// fails TestForwardShapeClassesEveryField until it is classed here.
var forwardShape = map[string]string{
+ "DemoID": "declared", "DemoHost": "declared", "DemoLifetime": "declared", "DemoExpiresAt": "declared",
"Host": "declared", "Kind": "declared", "Slug": "declared", "App": "declared",
"Account": "declared", "Region": "declared", "Channel": "declared",
"RateLimit": "declared", "Status": "declared", "Provisioned": "declared",
@@ -285,6 +286,10 @@ type forwardKeptColumn struct{ Field, Column, OnConflict string }
// PRAGMA table_info(routes), so a column a migration adds is either classed
// here or fails that test.
var forwardKept = []forwardKeptColumn{
+ {"DemoID", "demo_id", "excluded.demo_id"},
+ {"DemoHost", "demo_host", "excluded.demo_host"},
+ {"DemoLifetime", "demo_lifetime", "excluded.demo_lifetime"},
+ {"DemoExpiresAt", "demo_expires_at", "excluded.demo_expires_at"},
{"Host", "host", ""},
{"Kind", "kind", "excluded.kind"},
{"Slug", "slug", "excluded.slug"},
@@ -331,7 +336,7 @@ var putForwardSQL = func() string {
VALUES (` + placeholders(routeColCount) + `)
ON CONFLICT(host) DO UPDATE SET
` + strings.Join(set, ",\n ") + `
-WHERE routes.kind = 'forward'`
+WHERE routes.kind = 'forward' AND ((routes.demo_id = '' AND routes.demo_host = '' AND routes.demo_lifetime = '' AND routes.demo_expires_at = 0) OR (routes.demo_id = excluded.demo_id AND routes.demo_host = excluded.demo_host AND routes.demo_lifetime = excluded.demo_lifetime AND routes.demo_expires_at = excluded.demo_expires_at AND routes.account = excluded.account AND routes.app = excluded.app))`
}()
// PutForward writes rt as a forward row (spec §4.2), in one transaction. It
@@ -363,6 +368,7 @@ func (r *Registry) PutForward(rt Route) error {
}
w := Route{
+ DemoID: rt.DemoID, DemoHost: rt.DemoHost, DemoLifetime: rt.DemoLifetime, DemoExpiresAt: rt.DemoExpiresAt,
Host: rt.Host,
Kind: KindForward,
Slug: rt.Slug,
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index 3228385d3..aaa5e8ade 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -41,6 +41,11 @@ type Registry struct {
// serves no requests and that nothing can dial (kind "sidecar" — its
// next_due wake, via DueInstances, is its only timer wake source).
type Route struct {
+ // Demo identity is preserved by route writers and omitted on ordinary wires.
+ DemoID string `json:",omitempty"`
+ DemoHost string `json:",omitempty"`
+ DemoLifetime string `json:",omitempty"`
+ DemoExpiresAt int64 `json:",omitempty"`
ClaimOwnership
// WakeIncarnation is transient request state and is never persisted.
@@ -683,6 +688,10 @@ func (c addedColumn) spec() string {
// reader stands each one's default in for a column the agent has not
// added yet (readCols, #433).
var routeAddedColumns = []addedColumn{
+ {Name: "demo_id", Type: "TEXT", Default: "''"},
+ {Name: "demo_host", Type: "TEXT", Default: "''"},
+ {Name: "demo_lifetime", Type: "TEXT", Default: "''"},
+ {Name: "demo_expires_at", Type: "INTEGER", Default: "0"},
{Name: "slug", Type: "TEXT", Default: "''"},
{Name: "addr", Type: "TEXT", Default: "''"},
{Name: "app", Type: "TEXT", Default: "''"},
@@ -1087,10 +1096,10 @@ provisioned, seed, unit, fleet_box, addrs, health, steering, gate, created_at,
args, idle_seconds, max_run_seconds, replicas, replica, claim_incarnation, claim_stamp, claim_owner, claim_row_id, hold_op,
good_version, good_digest, good_demand, serving_version, update_settings, build_state,
seed_source, import_gate, runtime, rate_limit, assets_off, asset_gen, incarnation, serving_seq,
-egress_allow, size, policy_expires_at, ha, fleet_assigned, fleet_moved, fleet_label, stateless`
+egress_allow, size, policy_expires_at, ha, fleet_assigned, fleet_moved, fleet_label, stateless, demo_id, demo_host, demo_lifetime, demo_expires_at`
// routeColCount is the number of names in routeCols.
-const routeColCount = 69
+const routeColCount = 73
// placeholders is n comma-joined bind parameters.
func placeholders(n int) string {
@@ -1109,7 +1118,7 @@ func scanRoute(scan func(...any) error) (Route, error) {
&t.Args, &t.IdleSeconds, &t.MaxRunSeconds, &t.Replicas, &rep, &t.ClaimIncarnation, &t.ClaimStamp, &t.ClaimOwner, &t.ClaimRowID, &t.HoldOp,
&t.GoodVersion, &t.GoodDigest, &t.GoodDemand, &t.ServingVersion, &t.UpdateSettings, &t.BuildState,
&t.SeedSource, &t.ImportGate, &t.Runtime, &t.RateLimit, &assetsOff, &t.AssetGen, &t.Incarnation, &t.ServingSeq,
- &t.EgressAllow, &t.Size, &t.PolicyExpiresAt, &ha, &t.Assigned, &moved, &t.FleetLabel, &stateless)
+ &t.EgressAllow, &t.Size, &t.PolicyExpiresAt, &ha, &t.Assigned, &moved, &t.FleetLabel, &stateless, &t.DemoID, &t.DemoHost, &t.DemoLifetime, &t.DemoExpiresAt)
t.Stateless = stateless != 0
t.HA = ha != 0
t.Moved = moved != 0
@@ -1552,6 +1561,7 @@ func upsertRoute(db txer, t Route, guard string) error {
INSERT INTO routes (`+routeCols+`)
VALUES (`+placeholders(routeColCount)+`)
ON CONFLICT(host) DO UPDATE SET
+ demo_id=excluded.demo_id, demo_host=excluded.demo_host, demo_lifetime=excluded.demo_lifetime, demo_expires_at=excluded.demo_expires_at,
slug=excluded.slug, kind=excluded.kind, socket=excluded.socket,
addr=excluded.addr,
status=CASE WHEN routes.hold_op != '' THEN routes.status ELSE excluded.status END,
@@ -1608,7 +1618,7 @@ ON CONFLICT(host) DO UPDATE SET
ELSE MAX(routes.fleet_moved, excluded.fleet_moved) END
WHERE routes.claim_incarnation=excluded.claim_incarnation AND routes.claim_stamp=excluded.claim_stamp
AND routes.claim_owner=excluded.claim_owner AND routes.claim_row_id=excluded.claim_row_id
-AND routes.kind <> 'forward'`+guard,
+AND routes.kind <> 'forward' AND ((routes.demo_id = '' AND routes.demo_host = '' AND routes.demo_lifetime = '' AND routes.demo_expires_at = 0) OR (routes.demo_id = excluded.demo_id AND routes.demo_host = excluded.demo_host AND routes.demo_lifetime = excluded.demo_lifetime AND routes.demo_expires_at = excluded.demo_expires_at AND routes.account = excluded.account AND routes.app = excluded.app))`+guard,
routeArgs(normalizeRoute(t))...)
if err != nil {
return err
@@ -1679,7 +1689,7 @@ func routeArgs(t Route) []any {
t.Replicas, b2iDB(t.Replica), t.ClaimIncarnation, t.ClaimStamp, t.ClaimOwner, t.ClaimRowID, t.HoldOp,
t.GoodVersion, t.GoodDigest, t.GoodDemand, t.ServingVersion, t.UpdateSettings, t.BuildState,
t.SeedSource, t.ImportGate, t.Runtime, t.RateLimit, b2iDB(t.AssetsOff), t.AssetGen, t.Incarnation, t.ServingSeq,
- t.EgressAllow, t.Size, t.PolicyExpiresAt, b2iDB(t.HA), t.Assigned, b2iDB(t.Moved), t.FleetLabel, b2iDB(t.Stateless),
+ t.EgressAllow, t.Size, t.PolicyExpiresAt, b2iDB(t.HA), t.Assigned, b2iDB(t.Moved), t.FleetLabel, b2iDB(t.Stateless), t.DemoID, t.DemoHost, t.DemoLifetime, t.DemoExpiresAt,
}
}
@@ -3944,7 +3954,7 @@ SELECT rowid, status, socket, addr, version, hibernate, channel, backing, tunnel
db_path, region, fleet_box, addrs, health, gate, hold_op, import_gate, rate_limit,
claim_incarnation, claim_stamp, claim_owner, claim_row_id,
assets_off, asset_gen, incarnation, serving_seq,
- host, kind, account, app, platform, fleet_label, stateless,
+ host, kind, account, app, platform, fleet_label, stateless, demo_id, demo_host, demo_lifetime, demo_expires_at,
` + fingerprintForwardInert + `
FROM routes ORDER BY rowid`)
if err != nil {
@@ -3959,12 +3969,13 @@ FROM routes ORDER BY rowid`)
var claim ClaimOwnership
var assetGen string
var status, socket, addr, version, channel, backing, tunnel, dbPath, region, fleetBox, addrs, health, gate, holdOp, importGate, rateLimit string
- var host, kind, account, app, fleetLabel string
+ var host, kind, account, app, fleetLabel, demoID, demoHost, demoLifetime string
+ var demoExpiresAt int64
if err := rows.Scan(&rowid, &status, &socket, &addr, &version, &hibernate,
&channel, &backing, &tunnel, &dbPath, &region, &fleetBox, &addrs, &health, &gate, &holdOp, &importGate, &rateLimit,
&claim.ClaimIncarnation, &claim.ClaimStamp, &claim.ClaimOwner, &claim.ClaimRowID,
&assetsOff, &assetGen, &pair.Incarnation, &pair.ServingSeq,
- &host, &kind, &account, &app, &platform, &fleetLabel, &stateless, &forwardInert); err != nil {
+ &host, &kind, &account, &app, &platform, &fleetLabel, &stateless, &demoID, &demoHost, &demoLifetime, &demoExpiresAt, &forwardInert); err != nil {
return "", err
}
fmt.Fprintf(h, "%d\x1f%s\x1f%s\x1f%s\x1f%s\x1f%d\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s",
@@ -3976,6 +3987,9 @@ FROM routes ORDER BY rowid`)
// digest of a replaced or re-owned row matches the old one and the
// edge keeps serving its old map. Each is tagged and quoted.
fmt.Fprintf(h, "\x1fhost=%q\x1fkind=%q\x1faccount=%q\x1fapp=%q", host, kind, account, app)
+ if demoID != "" || demoHost != "" || demoLifetime != "" || demoExpiresAt != 0 {
+ fmt.Fprintf(h, "\x1fdemo=%q,%q,%q,%d", demoID, demoHost, demoLifetime, demoExpiresAt)
+ }
// The platform mark decides the platform-alias fold (PlatformAliasFold),
// and a refused source refuses its alias with it; folded only when set.
if stateless != 0 {