oficina / equipo Public

hostedctl: bind the provider namespace and fingerprint each intent

A1 (R28): the database is bound to the provider namespace the first
controller names (aws:ACCOUNT:REGION from STS in main); New refuses any
other with ErrProviderMismatch before anything reads the provider, so
references read in the wrong account or region never become stop proof.

A2 (R29): each launch intent keeps the provider fingerprint it was saved
with (awsjob: region, connector, image ARN and version for the size).
Dispatch abandons an intent whose fingerprint changed as config_changed,
with an alert and no provider call; its lost reply's VM is an orphan.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c53d99b1a9d4b66c9538ff37a23761c00fd1a845 parent 32816eb
17 files changed, +367 −42
  • cmd/equipo-hosted-controller/config.go +1 −0
  • cmd/equipo-hosted-controller/config_test.go +3 −0
  • cmd/equipo-hosted-controller/main.go +27 −0
  • cmd/equipo-hosted-controller/main_test.go +33 −1
  • docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md +21 −0
  • go.mod +1 −1
  • internal/hostedctl/clock_test.go +5 −5
  • internal/hostedctl/controller.go +24 −0
  • internal/hostedctl/launch.go +67 −29
  • internal/hostedctl/launch_test.go +39 −1
  • internal/hostedctl/refresh.go +5 −0
  • internal/hostedctl/schema/0001_jobs.sql +19 −2
  • internal/hostedctl/sim_test.go +2 −1
  • internal/hostedctl/store.go +22 −0
  • internal/hostedctl/store_test.go +53 −2
  • internal/isolatedjob/awsjob/runner.go +12 −0
  • internal/isolatedjob/awsjob/runner_test.go +33 −0
diff --git a/cmd/equipo-hosted-controller/config.go b/cmd/equipo-hosted-controller/config.go
index 1267b309..5e716042 100644
--- a/cmd/equipo-hosted-controller/config.go
+++ b/cmd/equipo-hosted-controller/config.go
@@ -138,6 +138,7 @@ func (fc fileConfig) check() (config, error) {
c.ctl.Images[d] = true
}
c.ctl.Egress = c.aws.Egress
+ c.ctl.ProviderFingerprint = c.aws.Fingerprint
return c, nil
}
diff --git a/cmd/equipo-hosted-controller/config_test.go b/cmd/equipo-hosted-controller/config_test.go
index 8f4e1417..10b03c54 100644
--- a/cmd/equipo-hosted-controller/config_test.go
+++ b/cmd/equipo-hosted-controller/config_test.go
@@ -78,6 +78,9 @@ func TestConfigRefusesMissingListenOrKeys(t *testing.T) {
!c.ctl.Images[testDigest] || len(c.ctl.Egress) != 1 || len(c.signing) != ed25519.PrivateKeySize {
t.Fatalf("valid config loaded as %+v", c)
}
+ if c.ctl.ProviderFingerprint == nil || c.ctl.ProviderFingerprint(testDigest, "small") != c.aws.Fingerprint(testDigest, "small") {
+ t.Fatal("valid config: the controller's provider fingerprint is not the adapter's")
+ }
for name, edit := range map[string]func(*fileConfig){
"no listen": func(f *fileConfig) { f.Listen = "" },
diff --git a/cmd/equipo-hosted-controller/main.go b/cmd/equipo-hosted-controller/main.go
index 27e77e22..96b75e3f 100644
--- a/cmd/equipo-hosted-controller/main.go
+++ b/cmd/equipo-hosted-controller/main.go
@@ -27,11 +27,13 @@ import (
"amadan.net/oficina/equipo/internal/hostedctl"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/oficina/equipo/internal/isolatedjob/awsjob"
+ "github.com/aws/aws-sdk-go-v2/aws"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/lambdacore"
"github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
"github.com/aws/aws-sdk-go-v2/service/sns"
+ "github.com/aws/aws-sdk-go-v2/service/sts"
)
// shutdownTimeout bounds how long the servers get to finish requests in
@@ -94,6 +96,9 @@ func run(path string) error {
if err != nil {
return err
}
+ if cfg.ctl.ProviderNamespace, err = providerNamespace(ctx, sts.NewFromConfig(awsCfg), cfg.aws.Region); err != nil {
+ return err
+ }
metrics := hostedctl.NewMetrics()
alerter := metrics.CountAlerts(snsAlerter{pub: awsjob.SNSPublisher{TopicARN: cfg.topicARN, Client: sns.NewFromConfig(awsCfg)}})
c, err := hostedctl.New(cfg.ctl, hostedctl.Deps{Store: store, Runner: runner, Auditor: runner, Alerter: alerter})
@@ -108,6 +113,28 @@ func run(path string) error {
return serve(ctx, c, newAPIServer(api, cert), apiLn, newMetricsServer(metrics.Handler(c)), metricsLn, shutdownTimeout)
}
+// callerIdentity is the STS call providerNamespace makes.
+// *sts.Client satisfies it.
+type callerIdentity interface {
+ GetCallerIdentity(context.Context, *sts.GetCallerIdentityInput, ...func(*sts.Options)) (*sts.GetCallerIdentityOutput, error)
+}
+
+// providerNamespace is "aws:ACCOUNT:REGION" for the account the credentials
+// belong to: MicroVM IDs are only found there, so the controller binds its
+// database to it (ruling R28). The call is bounded like any provider call.
+func providerNamespace(ctx context.Context, c callerIdentity, region string) (string, error) {
+ ctx, cancel := context.WithTimeout(ctx, hostedctl.ProviderCallTimeout)
+ defer cancel()
+ out, err := c.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{})
+ if err != nil {
+ return "", fmt.Errorf("AWS caller identity: %w", err)
+ }
+ if aws.ToString(out.Account) == "" || region == "" {
+ return "", errors.New("AWS caller identity names no account, or no region is set")
+ }
+ return "aws:" + aws.ToString(out.Account) + ":" + region, nil
+}
+
// newAPIServer is the HTTPS API server. DisableGeneralOptionsHandler hands
// "OPTIONS *" to the API handler, which verifies it like any request,
// instead of Go answering it unsigned.
diff --git a/cmd/equipo-hosted-controller/main_test.go b/cmd/equipo-hosted-controller/main_test.go
index 0e943374..aedca95c 100644
--- a/cmd/equipo-hosted-controller/main_test.go
+++ b/cmd/equipo-hosted-controller/main_test.go
@@ -8,6 +8,7 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/json"
+ "errors"
"io"
"math/big"
"net"
@@ -22,6 +23,7 @@ import (
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
+ "github.com/aws/aws-sdk-go-v2/service/sts"
)
var (
@@ -60,7 +62,8 @@ func newTestCtl(t *testing.T, wrap func(*isolatedjob.Fake) isolatedjob.Runner) *
t.Fatal(err)
}
t.Cleanup(func() { _ = store.Close() })
- c, err := hostedctl.New(hostedctl.Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{testDigest: true}},
+ c, err := hostedctl.New(hostedctl.Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{testDigest: true},
+ ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" }},
hostedctl.Deps{Store: store, Runner: run, Auditor: fake, Alerter: nopAlerter{}})
if err != nil {
t.Fatal(err)
@@ -173,6 +176,35 @@ func TestOptionsStarVerified(t *testing.T) {
}
}
+// identityStub answers GetCallerIdentity with account and err, and records
+// whether the call had a deadline.
+type identityStub struct {
+ account string
+ err error
+ deadline bool
+}
+
+func (s *identityStub) GetCallerIdentity(ctx context.Context, _ *sts.GetCallerIdentityInput, _ ...func(*sts.Options)) (*sts.GetCallerIdentityOutput, error) {
+ _, s.deadline = ctx.Deadline()
+ return &sts.GetCallerIdentityOutput{Account: &s.account}, s.err
+}
+
+// TestProviderNamespace: the namespace is the credentials' account and the
+// region, read with a bounded call; no account is an error, not an empty
+// namespace (ruling R28).
+func TestProviderNamespace(t *testing.T) {
+ t.Parallel()
+ s := &identityStub{account: "123456789012"}
+ if ns, err := providerNamespace(context.Background(), s, "eu-west-1"); ns != "aws:123456789012:eu-west-1" || err != nil || !s.deadline {
+ t.Fatalf("providerNamespace = (%q, %v), deadline %v; want aws:123456789012:eu-west-1 from a bounded call", ns, err, s.deadline)
+ }
+ for _, bad := range []*identityStub{{account: ""}, {account: "1", err: errors.New("denied")}} {
+ if ns, err := providerNamespace(context.Background(), bad, "eu-west-1"); ns != "" || err == nil {
+ t.Errorf("providerNamespace(account %q, error %v) = (%q, %v), want an error", bad.account, bad.err, ns, err)
+ }
+ }
+}
+
// blockingRunner holds every Launch until its context ends, then takes a
// while more to return, like a provider call settling.
type blockingRunner struct {
diff --git a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
index e4caa414..cf2f9e27 100644
--- a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
@@ -900,3 +900,24 @@ The round 0 rows above give line numbers from before this round.
| --- | --- | --- | --- |
| Wrap the raw error again (`%w` of err in `transportError`) | `go test ./internal/hostedclient -run '^TestTransportErrorsHoldNoServerBytes$' -count=1` | `client_test.go:365: malformed status: error "... get: sending: net/http: HTTP/1.x transport connection broken: malformed HTTP status code \"EVIL\"" holds bytes the server sent`, the same for the header (`missing colon: \"EVIL-HEADER-NO-COLON\"`) and the trailer (`reading the body: malformed MIME header: missing colon: \"EVIL-TRAILER\"`) | yes, passes |
| Deadline classification dropped | `go test ./internal/hostedclient -run '^TestClientHonoursTimeoutAndCancel$' -count=1` | `client_test.go:387: Get past the HTTP timeout = hostedclient: the exchange with the controller failed: get: sending: network timeout after 100.7ms, want context.DeadlineExceeded within 2 s` | yes, passes |
+
+## Final fix wave
+
+Findings from the final whole-branch review (final-A, B1, B2, C), fixed under rulings R26 to R31.
+
+### A1 + A2: provider namespace binding and launch fingerprint (R28, R29)
+
+- `provider_binding` (one row, never updated) holds the namespace; `New` needs
+ `Config.ProviderNamespace` and `Config.ProviderFingerprint`, binds a fresh database, and returns
+ `ErrProviderMismatch` for another namespace before anything reads the provider. Main resolves
+ `aws:ACCOUNT:REGION` with a bounded STS GetCallerIdentity.
+- Each intent saves `provider_fingerprint` (immutable with the spec). `dispatch` abandons an intent
+ whose fingerprint differs from the current one (reason `config_changed`, an AlertConfigChanged
+ alert, no provider call); the lost reply's VM is then an orphan. `awsjob.Config.Fingerprint` is
+ region, connector, image ARN and the size's version.
+
+| Mutation | Command | Observed failure | Restored |
+| --- | --- | --- | --- |
+| Accept a mismatched binding (`bound != ns && false`) | `go test ./internal/hostedctl -run 'TestProviderNamespaceBound$' -count=1` | `store_test.go:605: New for another namespace = (&{...test:account-2:region-1...}, <nil>), want ErrProviderMismatch` | yes, passes |
+| Skip the fingerprint check in `dispatch` | `go test ./internal/hostedctl -run 'TestReplayRefusesChangedProviderConfig$' -count=1` | `launch_test.go:555: provider launches = 2, want only the lost one` | yes, passes |
+| Leave the version out of `awsjob.Config.Fingerprint` | `go test ./internal/isolatedjob/awsjob -run 'TestFingerprint$' -count=1` | `runner_test.go:252: small and large share a fingerprint, though their versions differ` | yes, passes |
diff --git a/go.mod b/go.mod
index 4ee99b64..ae376137 100644
--- a/go.mod
+++ b/go.mod
@@ -25,6 +25,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/lambdacore v1.14.0
github.com/aws/aws-sdk-go-v2/service/lambdamicrovms v1.13.0
github.com/aws/aws-sdk-go-v2/service/sns v1.48.0
+ github.com/aws/aws-sdk-go-v2/service/sts v1.53.0
github.com/aws/smithy-go v1.28.9
github.com/sqids/sqids-go v0.4.1
golang.org/x/crypto v0.53.0
@@ -49,7 +50,6 @@ require (
github.com/aws/aws-sdk-go-v2/service/signin v1.14.0 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 // indirect
- github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/bodgit/plumbing v1.3.0 // indirect
github.com/bodgit/sevenzip v1.6.0 // indirect
diff --git a/internal/hostedctl/clock_test.go b/internal/hostedctl/clock_test.go
index beedcfbd..62f27d82 100644
--- a/internal/hostedctl/clock_test.go
+++ b/internal/hostedctl/clock_test.go
@@ -168,10 +168,10 @@ func TestRestartWithRollback(t *testing.T) {
rec := &recordingAlerter{}
deps := Deps{Store: s, Runner: nopRunner{}, Auditor: nopAuditor{}, Alerter: rec}
- if _, err := New(Config{}, deps); err != nil {
+ if _, err := New(testConfig(), deps); err != nil {
t.Fatalf("New = %v", err)
}
- if _, err := New(Config{}, deps); err != nil {
+ if _, err := New(testConfig(), deps); err != nil {
t.Fatalf("second New = %v", err)
}
if len(rec.got) != 1 || rec.got[0] != alerts[0] {
@@ -195,7 +195,7 @@ func TestRestartWithRollback(t *testing.T) {
t.Fatalf("StartupAlerts after a second rollback = %+v, want one", pending)
}
down := errors.New("alert channel down")
- c, err := New(Config{}, Deps{Store: s, Runner: nopRunner{}, Auditor: nopAuditor{}, Alerter: &recordingAlerter{fail: down}})
+ c, err := New(testConfig(), Deps{Store: s, Runner: nopRunner{}, Auditor: nopAuditor{}, Alerter: &recordingAlerter{fail: down}})
if c != nil || !errors.Is(err, down) {
t.Fatalf("New with an undeliverable rollback alert = (%v, %v), want (nil, the alert error)", c, err)
}
@@ -203,7 +203,7 @@ func TestRestartWithRollback(t *testing.T) {
s = openStore(t, path, isolatedjobtest.NewFakeClock(testWall.Add(-2*time.Hour)))
rec = &recordingAlerter{}
- if _, err := New(Config{}, Deps{Store: s, Runner: nopRunner{}, Auditor: nopAuditor{}, Alerter: rec}); err != nil || len(rec.got) != 1 || rec.got[0] != pending[0] {
+ if _, err := New(testConfig(), Deps{Store: s, Runner: nopRunner{}, Auditor: nopAuditor{}, Alerter: rec}); err != nil || len(rec.got) != 1 || rec.got[0] != pending[0] {
t.Fatalf("New after a crash = %v with alerts %+v, want nil and exactly [%+v]", err, rec.got, pending[0])
}
if !strings.HasPrefix(pending[0].Detail, "alert ") || pending[0].Detail == alerts[0].Detail {
@@ -213,7 +213,7 @@ func TestRestartWithRollback(t *testing.T) {
s = openStore(t, path, isolatedjobtest.NewFakeClock(testWall.Add(-2*time.Hour)))
rec = &recordingAlerter{}
- if _, err := New(Config{}, Deps{Store: s, Runner: nopRunner{}, Auditor: nopAuditor{}, Alerter: rec}); err != nil || len(rec.got) != 0 {
+ if _, err := New(testConfig(), Deps{Store: s, Runner: nopRunner{}, Auditor: nopAuditor{}, Alerter: rec}); err != nil || len(rec.got) != 0 {
t.Fatalf("New after the alert was delivered and the store reopened = %v with alerts %+v, want nil and none", err, rec.got)
}
}
diff --git a/internal/hostedctl/controller.go b/internal/hostedctl/controller.go
index bf271b1a..a6cc4683 100644
--- a/internal/hostedctl/controller.go
+++ b/internal/hostedctl/controller.go
@@ -27,8 +27,23 @@ type Config struct {
Enabled bool // launches allowed; only EQUIPO_HOSTED_ENABLED=1 sets it
Images map[isolatedjob.ImageDigest]bool // image digests launches may use
Egress []netip.AddrPort // the exact egress set the network audit expects
+ // ProviderNamespace names where the runner's VM references live (for
+ // AWS, the account and region). New binds the database to it on first
+ // use and refuses any other (ruling R28): a reference read in another
+ // namespace is not found, which would pass for proof that its VM is gone.
+ ProviderNamespace string
+ // ProviderFingerprint names the provider settings a launch of an image
+ // at a size would use beyond the spec (for AWS, the connector and the
+ // image ARN and version). Each intent keeps the one it was saved with;
+ // a dispatch under a different one abandons the intent (ruling R29), as
+ // re-sending it would not repeat the request a lost reply answered.
+ ProviderFingerprint func(isolatedjob.ImageDigest, isolatedjob.Size) string
}
+// ErrProviderMismatch: the database belongs to another provider namespace
+// than the controller's config names.
+var ErrProviderMismatch = errors.New("hostedctl: database belongs to another provider namespace")
+
// Deps are the controller's collaborators. Every one is required.
type Deps struct {
Store *Store
@@ -57,6 +72,10 @@ type Controller struct {
// d.Alerter, once each; if one cannot be delivered New returns that error
// and no controller, so a controller never runs with an undelivered rollback
// alert. A later New on the same store retries only the undelivered alerts.
+//
+// New needs cfg.ProviderNamespace and cfg.ProviderFingerprint. It binds the
+// store to the namespace the first time and, on a store bound to another,
+// returns ErrProviderMismatch before anything reads the provider.
func New(cfg Config, d Deps) (*Controller, error) {
switch {
case d.Store == nil:
@@ -67,6 +86,11 @@ func New(cfg Config, d Deps) (*Controller, error) {
return nil, errors.New("hostedctl: controller needs a network auditor")
case isNil(d.Alerter):
return nil, errors.New("hostedctl: controller needs an alerter")
+ case cfg.ProviderNamespace == "" || cfg.ProviderFingerprint == nil:
+ return nil, errors.New("hostedctl: controller needs a provider namespace and fingerprint")
+ }
+ if err := d.Store.bindProvider(context.Background(), cfg.ProviderNamespace); err != nil {
+ return nil, err
}
if err := d.Store.deliverStartupAlerts(context.Background(), d.Alerter); err != nil {
return nil, err
diff --git a/internal/hostedctl/launch.go b/internal/hostedctl/launch.go
index 034443be..c1f3ac04 100644
--- a/internal/hostedctl/launch.go
+++ b/internal/hostedctl/launch.go
@@ -70,8 +70,13 @@ const (
actionVMAfterAbandon = "vm_after_abandon"
providerFailureReason = "provider error; intent kept for replay"
providerThrottleReason = "provider throttled; intent kept for replay"
+ reasonConfigChanged = "config_changed"
)
+// AlertConfigChanged: a launch intent was abandoned because the provider
+// settings it was saved with changed (ruling R29).
+const AlertConfigChanged = "config_changed"
+
// LaunchRequest asks for one VM for one task attempt. InstanceCode is a
// secret: it goes into the VM's bootstrap and the saved spec, and nowhere
// else.
@@ -358,10 +363,10 @@ func (c *Controller) saveIntent(ctx context.Context, by hostedwire.KeyID, q Laun
deadline, drain, stop := Deadlines(now, spec.MaxLifetime)
replaces := sql.NullString{String: q.Replaces, Valid: q.Replaces != ""}
if _, err := tx.ExecContext(ctx, `INSERT INTO jobs (attempt_id, launch_id, task_id, account_id, actor_key,
- purpose, replaces_attempt, spec_json, spec_sha256, state, launched_t, deadline_t, drain_t, stop_t)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ purpose, replaces_attempt, spec_json, spec_sha256, provider_fingerprint, state, launched_t, deadline_t, drain_t, stop_t)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
q.AttemptID, launchID, q.TaskID, q.Account, string(by), purposeTask, replaces, specJSON, hash,
- JobWaiting, int64(now), int64(deadline), int64(drain), int64(stop)); err != nil {
+ c.cfg.ProviderFingerprint(spec.Image, spec.Size), JobWaiting, int64(now), int64(deadline), int64(drain), int64(stop)); err != nil {
return fmt.Errorf("hostedctl: save launch intent: %w", err)
}
a.Action = actionLaunchIntent
@@ -408,7 +413,9 @@ func checkReplaces(ctx context.Context, tx *sql.Tx, by hostedwire.KeyID, attempt
//
// In its own transaction it re-reads the row. An intent no longer waiting,
// or holding a Ref, is returned as it stands. A stop asked for, or the stop
-// time reached, marks it JobAbandoned with an audit row. Then, outside the
+// time reached, marks it JobAbandoned with an audit row; so does a provider
+// fingerprint other than the one saved with the intent (R29), which also
+// raises an AlertConfigChanged alert. Then, outside the
// transaction and just before the call, it checks the transient gates
// (creatable); a failure is returned as gate with the waiting view and no
// provider call. Otherwise it calls the provider and settles the answer.
@@ -422,9 +429,9 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem
// wait for it never lets a gate that passed go stale before the call.
defer c.ownership.rlock()()
var spec isolatedjob.LaunchSpec
- ready := false
+ ready, changed := false, false
err = c.store.Tx(ctx, func(tx *sql.Tx) error {
- ready = false
+ ready, changed = false, false
j, found, err := loadJob(ctx, tx, attempt)
if err != nil {
return err
@@ -437,27 +444,18 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem
view = j.view(now)
return nil
}
- if reason := abandonReason(j, now); reason != "" {
- res, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1
- WHERE attempt_id = ? AND state = ? AND vm_ref IS NULL`, JobAbandoned, attempt, JobWaiting)
- if err != nil {
- return fmt.Errorf("hostedctl: abandon %s: %w", attempt, err)
- }
- if n, err := res.RowsAffected(); err != nil || n != 1 {
- return fmt.Errorf("hostedctl: abandon %s: %d rows (%v)", attempt, n, err)
- }
- action := actionLaunchAbandoned
- if replay {
- action = actionReplayAbandoned
- }
- j.state = JobAbandoned
- view = j.view(now)
- return appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: attempt,
- Action: action, Reason: reason, At: now})
- }
if spec, err = decodeSpec(j.specJSON, attempt); err != nil {
return err
}
+ reason := abandonReason(j, now)
+ if fp := c.cfg.ProviderFingerprint(spec.Image, spec.Size); reason == "" && fp != j.fingerprint {
+ reason, changed = fmt.Sprintf("%s: the provider settings for image %s at size %s changed since the intent was saved (%q, now %q)",
+ reasonConfigChanged, spec.Image, spec.Size, j.fingerprint, fp), true
+ }
+ if reason != "" {
+ view, err = abandonIntent(ctx, tx, actor, j, replay, reason, now)
+ return err
+ }
view = j.view(now)
ready = true
return nil
@@ -465,6 +463,9 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem
if err != nil {
return JobView{}, nil, err
}
+ if changed {
+ return view, nil, c.alertConfigChanged(ctx, attempt, view)
+ }
if !ready {
return view, nil, nil
}
@@ -605,8 +606,9 @@ func (c *Controller) saveRef(ctx context.Context, actor hostedwire.KeyID, attemp
// with its saved spec, through dispatch. Before each provider call the
// gates are re-checked:
//
-// - a stop asked for, or the intent's stop time reached: the intent is
-// marked JobAbandoned and audited, and never replayed again;
+// - a stop asked for, the intent's stop time reached, or provider
+// settings changed since it was saved (config_changed, alerted): the
+// intent is marked JobAbandoned and audited, and never replayed again;
// - launches switched off, the image no longer allowed, or no passing
// audit begun within AuditMaxAge: the intent stays JobWaiting for a later
// pass, with no audit row, as nothing changed.
@@ -649,6 +651,40 @@ func (c *Controller) Replay(ctx context.Context) error {
return errors.Join(errs...)
}
+// abandonIntent marks waiting intent j JobAbandoned inside tx, with an audit
+// row giving reason, and returns its view. It is never launched again; a VM
+// a lost reply made for it is an orphan.
+func abandonIntent(ctx context.Context, tx *sql.Tx, actor hostedwire.KeyID, j jobRow, replay bool, reason string, now T) (JobView, error) {
+ res, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1
+ WHERE attempt_id = ? AND state = ? AND vm_ref IS NULL`, JobAbandoned, j.attempt, JobWaiting)
+ if err != nil {
+ return JobView{}, fmt.Errorf("hostedctl: abandon %s: %w", j.attempt, err)
+ }
+ if n, err := res.RowsAffected(); err != nil || n != 1 {
+ return JobView{}, fmt.Errorf("hostedctl: abandon %s: %d rows (%v)", j.attempt, n, err)
+ }
+ action := actionLaunchAbandoned
+ if replay {
+ action = actionReplayAbandoned
+ }
+ j.state = JobAbandoned
+ return j.view(now), appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: j.attempt,
+ Action: action, Reason: reason, At: now})
+}
+
+// alertConfigChanged sends the AlertConfigChanged alert for an intent
+// abandoned because the provider settings changed, even if the caller has
+// gone. The abandonment is already committed and audited.
+func (c *Controller) alertConfigChanged(ctx context.Context, attempt string, v JobView) error {
+ err := c.alerter.Alert(context.WithoutCancel(ctx), Alert{Kind: AlertConfigChanged, At: c.store.Clock().Now(), Detail: fmt.Sprintf(
+ "launch intent %s (launch %s) was abandoned: the provider settings changed since it was saved; a VM its lost reply made is reaped as an orphan",
+ attempt, v.LaunchID)})
+ if err != nil {
+ return fmt.Errorf("hostedctl: deliver %s alert for %s: %w", AlertConfigChanged, attempt, err)
+ }
+ return nil
+}
+
// abandonReason returns why a waiting intent must never be launched, or ""
// when nothing stops it: a stop was asked for, or its stop time has come.
func abandonReason(j jobRow, now T) string {
@@ -676,6 +712,7 @@ func (c *Controller) creatable(img isolatedjob.ImageDigest, now T) error {
// jobRow is the part of a jobs row that launches read.
type jobRow struct {
attempt, launchID, task, account, actor, state, specJSON, specSHA string
+ fingerprint string // provider_fingerprint
ref sql.NullString
launchedT, deadlineT, drainT, stopT, epoch int64
stopRequested sql.NullInt64
@@ -686,9 +723,10 @@ type jobRow struct {
func loadJob(ctx context.Context, tx *sql.Tx, attempt string) (jobRow, bool, error) {
var j jobRow
err := tx.QueryRowContext(ctx, `SELECT attempt_id, launch_id, task_id, account_id, actor_key, state,
- spec_json, spec_sha256, vm_ref, launched_t, deadline_t, drain_t, stop_t, epoch, stop_requested_t, stop_proof_json
- FROM jobs WHERE attempt_id = ?`, attempt).Scan(&j.attempt, &j.launchID, &j.task, &j.account, &j.actor, &j.state,
- &j.specJSON, &j.specSHA, &j.ref, &j.launchedT, &j.deadlineT, &j.drainT, &j.stopT, &j.epoch, &j.stopRequested, &j.stopProof)
+ spec_json, spec_sha256, provider_fingerprint, vm_ref, launched_t, deadline_t, drain_t, stop_t, epoch, stop_requested_t,
+ stop_proof_json FROM jobs WHERE attempt_id = ?`, attempt).Scan(&j.attempt, &j.launchID, &j.task, &j.account, &j.actor,
+ &j.state, &j.specJSON, &j.specSHA, &j.fingerprint, &j.ref, &j.launchedT, &j.deadlineT, &j.drainT, &j.stopT, &j.epoch,
+ &j.stopRequested, &j.stopProof)
switch {
case errors.Is(err, sql.ErrNoRows):
return jobRow{}, false, nil
diff --git a/internal/hostedctl/launch_test.go b/internal/hostedctl/launch_test.go
index 05dd1e76..ffb3aba2 100644
--- a/internal/hostedctl/launch_test.go
+++ b/internal/hostedctl/launch_test.go
@@ -55,7 +55,8 @@ func newLaunchEnv(t *testing.T) *launchEnv {
e := &launchEnv{
t: t, ctx: context.Background(), path: filepath.Join(t.TempDir(), "hosted.db"),
clk: clk, gc: &gateClock{FakeClock: clk}, fake: fake, run: fake,
- cfg: Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true, imgB: true}},
+ cfg: Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true, imgB: true},
+ ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint},
}
e.store = openStore(t, e.path, e.gc)
e.newController()
@@ -533,6 +534,43 @@ func TestCrashBetweenLaunchAndSave(t *testing.T) {
e.noCodeInAudit()
}
+// TestReplayRefusesChangedProviderConfig: a launch reply is lost, then the
+// controller restarts with other provider settings for the image (another
+// image version, say). Replay must not re-send the intent, which would ask
+// for a different VM under the same client token: it abandons the intent as
+// config_changed, with an alert and no provider call, and the VM the lost
+// reply made is reaped as an orphan (R29).
+func TestReplayRefusesChangedProviderConfig(t *testing.T) {
+ t.Parallel()
+ e := newLaunchEnv(t)
+ ref := e.lostLaunch("att-1")
+ e.down()
+ e.cfg.ProviderFingerprint = func(d isolatedjob.ImageDigest, s isolatedjob.Size) string { return testFingerprint(d, s) + "/v2" }
+ e.up()
+ e.audit()
+ if err := e.c.Replay(e.ctx); err != nil {
+ t.Fatalf("Replay = %v", err)
+ }
+ if n := e.fake.Calls(isolatedjob.OpLaunch); n != 1 {
+ t.Fatalf("provider launches = %d, want only the lost one", n)
+ }
+ if j, _ := e.job("att-1"); j.state != JobAbandoned || j.ref.Valid {
+ t.Fatalf("att-1 after Replay: state %q ref %v; want abandoned with no ref", j.state, j.ref)
+ }
+ if !e.hasAudit("", "att-1", actionReplayAbandoned, reasonConfigChanged) {
+ t.Fatalf("no %s audit row naming %s", actionReplayAbandoned, reasonConfigChanged)
+ }
+ if a := e.alerts(AlertConfigChanged); len(a) != 1 || !strings.Contains(a[0].Detail, "att-1") {
+ t.Fatalf("%s alerts = %+v, want one naming att-1", AlertConfigChanged, a)
+ }
+ e.reap()
+ e.clk.AdvanceMono(OrphanGrace)
+ if r := e.reap(); r.OrphansStopped != 1 || r.OrphansDeferred != 0 {
+ t.Fatalf("pass after the grace = %+v, want the lost reply's VM stopped as an orphan", r)
+ }
+ e.wantStops(ref)
+}
+
// TestLaunchRechecksGatesBeforeDispatch: a launch passes its gates, then
// queues for transaction 1 while the audit goes stale. Once the intent is
// saved it must not reach the provider.
diff --git a/internal/hostedctl/refresh.go b/internal/hostedctl/refresh.go
index 5722646f..279d3fc2 100644
--- a/internal/hostedctl/refresh.go
+++ b/internal/hostedctl/refresh.go
@@ -23,6 +23,11 @@ const ReflessProofDelay = 2 * time.Minute
// can prove its job has no VM.
const ProviderLaunchTimeout = 60 * time.Second
+// ProviderCallTimeout bounds every other provider call (Get, List, Stop,
+// Suspend, Resume and the network audit), retries included (ruling R27), so
+// no stalled call holds an attempt lock or a reaper pass for longer.
+const ProviderCallTimeout = 30 * time.Second
+
// RestartGetTries is how many Refresh passes in a row may fail to read a
// pre-restart job's VM before the controller stops it as elapsed_unknown
// (R20).
diff --git a/internal/hostedctl/schema/0001_jobs.sql b/internal/hostedctl/schema/0001_jobs.sql
index 7ad194a1..e4dd4c72 100644
--- a/internal/hostedctl/schema/0001_jobs.sql
+++ b/internal/hostedctl/schema/0001_jobs.sql
@@ -15,6 +15,7 @@ CREATE TABLE jobs (
replaces_attempt TEXT, -- absent unless this attempt replaces another
spec_json TEXT NOT NULL,
spec_sha256 TEXT NOT NULL,
+ provider_fingerprint TEXT NOT NULL DEFAULT '', -- the provider settings the spec launches with (Config.ProviderFingerprint)
state TEXT NOT NULL,
launched_t INTEGER NOT NULL,
deadline_t INTEGER NOT NULL,
@@ -36,10 +37,12 @@ CREATE TABLE jobs (
CREATE INDEX jobs_state ON jobs(state);
--- The launch spec is what the provider was asked for; it never changes.
+-- The launch spec is what the provider was asked for, with the provider
+-- settings it launches under; it never changes.
CREATE TRIGGER jobs_spec_immutable
-BEFORE UPDATE OF spec_json, spec_sha256 ON jobs
+BEFORE UPDATE OF spec_json, spec_sha256, provider_fingerprint ON jobs
WHEN NEW.spec_json IS NOT OLD.spec_json OR NEW.spec_sha256 IS NOT OLD.spec_sha256
+ OR NEW.provider_fingerprint IS NOT OLD.provider_fingerprint
BEGIN
SELECT RAISE(ABORT, 'spec is immutable');
END;
@@ -112,6 +115,20 @@ CREATE TABLE clock (
wall_unix_ns INTEGER NOT NULL
);
+-- The provider namespace (for AWS, account and region) the VM references in
+-- this database belong to: one row, written by the first controller and
+-- never changed. A controller set up for another namespace refuses to start.
+CREATE TABLE provider_binding (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ namespace TEXT NOT NULL CHECK (namespace <> '')
+);
+
+CREATE TRIGGER provider_binding_fixed
+BEFORE UPDATE ON provider_binding
+BEGIN
+ SELECT RAISE(ABORT, 'provider binding is fixed');
+END;
+
-- Alerts raised where no Alerter exists yet (Open), kept until delivered.
-- Delivery is at least once; the id is the alert's stable event ID.
CREATE TABLE alert_outbox (
diff --git a/internal/hostedctl/sim_test.go b/internal/hostedctl/sim_test.go
index 819cb5bc..ce6d7af5 100644
--- a/internal/hostedctl/sim_test.go
+++ b/internal/hostedctl/sim_test.go
@@ -222,7 +222,8 @@ func newSimWorld(dir string, seed int64) *simWorld {
w := &simWorld{
seed: seed, rng: rand.New(rand.NewSource(seed)), ctx: context.Background(),
path: filepath.Join(dir, fmt.Sprintf("sim-%d.db", seed)), clk: clk, fake: fake,
- cfg: Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true}},
+ cfg: Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true},
+ ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint},
m: simModel{req: map[string]LaunchRequest{}, stopAt: map[string]T{}, pause: map[string]*simPause{},
ops: map[string][]string{}, done: map[[2]string]int64{}, deferral: map[isolatedjob.Ref]*simDeferral{}},
}
diff --git a/internal/hostedctl/store.go b/internal/hostedctl/store.go
index 0bff3620..b47d3f2c 100644
--- a/internal/hostedctl/store.go
+++ b/internal/hostedctl/store.go
@@ -357,6 +357,28 @@ func (s *Store) deliverStartupAlerts(ctx context.Context, a Alerter) error {
return nil
}
+// bindProvider binds the database to provider namespace ns, with an audit
+// row, when it has no binding yet, and returns ErrProviderMismatch when it is
+// bound to another (ruling R28).
+func (s *Store) bindProvider(ctx context.Context, ns string) error {
+ return s.Tx(ctx, func(tx *sql.Tx) error {
+ var bound string
+ err := tx.QueryRowContext(ctx, `SELECT namespace FROM provider_binding WHERE id = 1`).Scan(&bound)
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
+ if _, err := tx.ExecContext(ctx, `INSERT INTO provider_binding (id, namespace) VALUES (1, ?)`, ns); err != nil {
+ return fmt.Errorf("hostedctl: bind provider namespace: %w", err)
+ }
+ return appendAudit(tx, Audit{Action: "provider_bound", Reason: "database bound to provider namespace " + ns, At: s.clock.Now()})
+ case err != nil:
+ return fmt.Errorf("hostedctl: read provider binding: %w", err)
+ case bound != ns:
+ return fmt.Errorf("%w: bound to %q, configured for %q", ErrProviderMismatch, bound, ns)
+ }
+ return nil
+ })
+}
+
// Tx runs fn in one write transaction, which holds SQLite's write lock from
// the start. It rolls back when fn returns an error (returned as is) or
// panics, and otherwise checkpoints controller time and commits. Use the tx
diff --git a/internal/hostedctl/store_test.go b/internal/hostedctl/store_test.go
index d10e6127..d7debb1a 100644
--- a/internal/hostedctl/store_test.go
+++ b/internal/hostedctl/store_test.go
@@ -210,6 +210,7 @@ func TestSpecImmutable(t *testing.T) {
`UPDATE jobs SET spec_json = '{"image":"b"}' WHERE attempt_id = 'att-1'`,
`UPDATE jobs SET spec_sha256 = 'bbbb' WHERE attempt_id = 'att-1'`,
`UPDATE jobs SET spec_json = NULL WHERE attempt_id = 'att-1'`,
+ `UPDATE jobs SET provider_fingerprint = 'other' WHERE attempt_id = 'att-1'`,
} {
err := s.Tx(ctx, func(tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, change)
@@ -545,10 +546,23 @@ func (r *recordingAlerter) Alert(_ context.Context, a Alert) error {
type nopRunner struct{ isolatedjob.Runner }
type nopAuditor struct{ isolatedjob.NetworkAuditor }
+// testNamespace is the provider namespace test controllers are set up for.
+const testNamespace = "test:account-1:region-1"
+
+// testFingerprint is the test controllers' ProviderFingerprint.
+func testFingerprint(d isolatedjob.ImageDigest, s isolatedjob.Size) string {
+ return "fp/" + string(d) + "/" + string(s)
+}
+
+// testConfig is a Config with only the required provider fields set.
+func testConfig() Config {
+ return Config{ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint}
+}
+
func TestNewRefusesNilDependency(t *testing.T) {
s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), isolatedjobtest.NewFakeClock(testWall))
full := Deps{Store: s, Runner: nopRunner{}, Auditor: nopAuditor{}, Alerter: &recordingAlerter{}}
- if _, err := New(Config{}, full); err != nil {
+ if _, err := New(testConfig(), full); err != nil {
t.Fatalf("New with every dependency = %v, want nil", err)
}
for _, c := range []struct {
@@ -563,7 +577,7 @@ func TestNewRefusesNilDependency(t *testing.T) {
{"typed nil auditor", "auditor", Deps{Store: s, Runner: full.Runner, Auditor: (*nopAuditor)(nil), Alerter: full.Alerter}},
{"typed nil alerter", "alerter", Deps{Store: s, Runner: full.Runner, Auditor: full.Auditor, Alerter: (*recordingAlerter)(nil)}},
} {
- got, err := New(Config{}, c.d)
+ got, err := New(testConfig(), c.d)
if err == nil || got != nil {
t.Errorf("New with %s = (%v, %v), want (nil, an error)", c.name, got, err)
} else if !strings.Contains(err.Error(), c.want) {
@@ -572,6 +586,43 @@ func TestNewRefusesNilDependency(t *testing.T) {
}
}
+// TestProviderNamespaceBound: the first controller binds the database to its
+// provider namespace. After a restart, a controller set up for another (an
+// account or region where every saved Ref reads as not found) refuses to
+// start, so it never reconciles, proves or dispatches anything (R28); one
+// with no namespace or fingerprint refuses too; the right one starts.
+func TestProviderNamespaceBound(t *testing.T) {
+ t.Parallel()
+ e := newLaunchEnv(t)
+ e.launchWith("att-1", 2*time.Hour)
+ reads := e.fake.Calls(isolatedjob.OpGet) + e.fake.Calls(isolatedjob.OpList)
+ e.down()
+ e.store = openStore(t, e.path, e.clk)
+ deps := Deps{Store: e.store, Runner: e.fake, Auditor: e.fake, Alerter: &recordingAlerter{}}
+ other := e.cfg
+ other.ProviderNamespace = "test:account-2:region-1"
+ if c, err := New(other, deps); c != nil || !errors.Is(err, ErrProviderMismatch) {
+ t.Fatalf("New for another namespace = (%v, %v), want ErrProviderMismatch", c, err)
+ }
+ for _, cfg := range []Config{{ProviderNamespace: testNamespace}, {ProviderFingerprint: testFingerprint}} {
+ if c, err := New(cfg, deps); c != nil || err == nil {
+ t.Fatalf("New with namespace %q and fingerprint set %v = (%v, %v), want an error",
+ cfg.ProviderNamespace, cfg.ProviderFingerprint != nil, c, err)
+ }
+ }
+ if n := e.fake.Calls(isolatedjob.OpGet) + e.fake.Calls(isolatedjob.OpList); n != reads {
+ t.Fatalf("provider reads after the refused starts = %d, want %d", n, reads)
+ }
+ e.newController()
+ e.refresh()
+ if s := e.stopCols("att-1"); s.proof.Valid || s.notFoundSince.Valid {
+ t.Fatalf("att-1 under its own namespace = %+v, want no proof and no not-found", s)
+ }
+ if !e.hasAudit("", "", "provider_bound", testNamespace) {
+ t.Fatal("no provider_bound audit row for the first binding")
+ }
+}
+
func TestStoreRefusesNilClock(t *testing.T) {
ctx := context.Background()
for name, c := range map[string]isolatedjob.Clock{
diff --git a/internal/isolatedjob/awsjob/runner.go b/internal/isolatedjob/awsjob/runner.go
index 720d9f4a..892a86e5 100644
--- a/internal/isolatedjob/awsjob/runner.go
+++ b/internal/isolatedjob/awsjob/runner.go
@@ -174,6 +174,18 @@ func qualifiedConnector(arn, region string) bool {
return true
}
+// Fingerprint names what a launch of image d at size s sends to AWS beyond
+// the spec: the region (and with it the NO_INGRESS connector), the egress
+// connector, and the image ARN and version. The controller keeps it with
+// each launch intent and refuses to replay an intent under another one
+// (hostedctl Config.ProviderFingerprint). An image or size with no version
+// gives a fingerprint with empty fields, which a configured one never
+// matches.
+func (c Config) Fingerprint(d isolatedjob.ImageDigest, s isolatedjob.Size) string {
+ img := c.Images[d]
+ return fmt.Sprintf("region=%q connector=%q image=%q version=%q", c.Region, c.ConnectorID, img.ARN, img.Versions[s])
+}
+
// NoIngressConnectorARN is the Lambda-provided NO_INGRESS connector in
// region, in the form the developer guide prints for the managed ingress
// connectors (doc.go, Connectors). The guide does not print this one; the
diff --git a/internal/isolatedjob/awsjob/runner_test.go b/internal/isolatedjob/awsjob/runner_test.go
index a6754d0c..739bd728 100644
--- a/internal/isolatedjob/awsjob/runner_test.go
+++ b/internal/isolatedjob/awsjob/runner_test.go
@@ -244,6 +244,39 @@ func TestNew(t *testing.T) {
}
}
+// TestFingerprint: every setting a launch sends beyond the spec changes the
+// fingerprint of the image and size it applies to; nothing else does.
+func TestFingerprint(t *testing.T) {
+ base := testConfig().Fingerprint(testDigest, isolatedjob.SizeSmall)
+ if base == testConfig().Fingerprint(testDigest, isolatedjob.SizeLarge) {
+ t.Fatal("small and large share a fingerprint, though their versions differ")
+ }
+ for name, c := range map[string]struct {
+ change func(*Config)
+ same bool
+ }{
+ "region": {func(c *Config) { c.Region = "us-east-1" }, false},
+ "connector": {func(c *Config) { c.ConnectorID = strings.Replace(testConnector, ":3", ":4", 1) }, false},
+ "image ARN": {func(c *Config) {
+ c.Images[testDigest] = Image{ARN: testImageARN + "-2", Versions: c.Images[testDigest].Versions}
+ }, false},
+ "small version": {func(c *Config) { c.Images[testDigest].Versions[isolatedjob.SizeSmall] = "5" }, false},
+ "image dropped": {func(c *Config) { delete(c.Images, testDigest) }, false},
+ "large version": {func(c *Config) { c.Images[testDigest].Versions[isolatedjob.SizeLarge] = "5" }, true},
+ "egress": {func(c *Config) { c.Egress = nil }, true},
+ "security group": {func(c *Config) { c.VMSecurityGroupID = "sg-2" }, true},
+ "another digest": {func(c *Config) {
+ c.Images[otherDigest] = Image{ARN: "x", Versions: map[isolatedjob.Size]string{isolatedjob.SizeSmall: "1"}}
+ }, true},
+ } {
+ cfg := testConfig()
+ c.change(&cfg)
+ if got := cfg.Fingerprint(testDigest, isolatedjob.SizeSmall); (got == base) != c.same {
+ t.Errorf("%s changed: fingerprint %q (was %q), want same %v", name, got, base, c.same)
+ }
+ }
+}
+
func TestLimits(t *testing.T) {
want := isolatedjob.Limits{MaxLifetime: 28800 * time.Second, MaxBootstrapBytes: 4096, SuspendUsesLifetime: true, ConnectionsSurvive: false}
if got := newTestRunner(t, &stub{}).Limits(); got != want {