oficina / equipo Public

hostedctl: derive proxy codes; durable proxy_silent alerts

Task 4 review round 1. The proxy code is HMAC-SHA256 of the launch ID
under a new required proxy-code key, so no table holds it: the intent
saves its bootstrap without the code and each provider call derives it
again, keeping replays byte-identical; a changed key abandons the intent
as config_changed. The code window opens only at Refresh's first running
sighting, never from GET /v1/vms. Silence episodes keep a pending-delivery
flag in the store, are delivered by the next reaper pass (after a restart
too), and an episode overdue before a restart keeps its deadline.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b3aea40da6ad44d173f62f47df25abb782f399b6 parent 665b5c3
22 files changed, +496 −88
  • .rastrillo/budgets.txt +1 −1
  • cmd/equipo-hosted-controller/config.go +21 −1
  • cmd/equipo-hosted-controller/config_test.go +21 −1
  • cmd/equipo-hosted-controller/crashpoint_test.go +1 −1
  • cmd/equipo-hosted-controller/main_test.go +1 −1
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +21 −0
  • internal/hostedclient/client_test.go +1 −1
  • internal/hostedctl/controller.go +6 −0
  • internal/hostedctl/ctlproxy/ca.go +56 −13
  • internal/hostedctl/ctlproxy/ctlproxytest/ctlproxytest.go +4 −0
  • internal/hostedctl/ctlproxy/env_test.go +87 −14
  • internal/hostedctl/ctlproxy/feed.go +63 −15
  • internal/hostedctl/ctlproxy/feed_test.go +134 −0
  • internal/hostedctl/egress_test.go +4 −0
  • internal/hostedctl/http.go +2 −1
  • internal/hostedctl/launch.go +25 −13
  • internal/hostedctl/launch_test.go +7 −1
  • internal/hostedctl/proxy.go +22 −15
  • internal/hostedctl/schema/0004_proxy.sql +10 −7
  • internal/hostedctl/sim_test.go +1 −1
  • internal/hostedctl/store.go +2 −1
  • internal/hostedctl/store_test.go +6 −1
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index b4ad89df..7f946e58 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -84,4 +84,4 @@ perf GET /native/preview/exchange skip Rejects GET with 404; only a same-origin,
# branch uses an indexed primary-key lookup, one current-member/device check,
# and the same bounded cardView as the snapshot; no list scan or new route.
perf GET /api/v1/tasks/{id}/changes/diff skip Device-only bounded display patch JSON: indexed step/attempt lookup, 64 KiB patch and 128 KiB response, no Git or network work at read time; not an HTML screen.
-size internal/hostedctl 5662 9340 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340.
+size internal/hostedctl 5689 9355 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355.
diff --git a/cmd/equipo-hosted-controller/config.go b/cmd/equipo-hosted-controller/config.go
index 24649b79..556001e9 100644
--- a/cmd/equipo-hosted-controller/config.go
+++ b/cmd/equipo-hosted-controller/config.go
@@ -76,6 +76,10 @@ type fileConfig struct {
// must not be able to read.
ProxyCACertFile string `json:"proxy_ca_cert_file"`
ProxyCAKeyFile string `json:"proxy_ca_key_file"`
+ // ProxyCodeKeyFile holds the proxy-code key (32 bytes, standard
+ // base64), which derives each launch's proxy code. Group and others
+ // must not be able to read it.
+ ProxyCodeKeyFile string `json:"proxy_code_key_file"`
}
// keyEntry is one verify key: its ID, role (instance, operator or proxy)
@@ -147,7 +151,7 @@ func (fc fileConfig) check() (config, error) {
for name, v := range map[string]string{"tls_cert_file": fc.TLSCertFile, "tls_key_file": fc.TLSKeyFile,
"database": fc.Database, "signing_key_file": fc.SigningKeyFile, "sns_topic_arn": fc.SNSTopicARN,
"egress_manifest_file": fc.EgressManifestFile, "cert_keys_file": fc.CertKeysFile, "certificates_file": fc.CertificatesFile,
- "proxy_ca_cert_file": fc.ProxyCACertFile, "proxy_ca_key_file": fc.ProxyCAKeyFile} {
+ "proxy_ca_cert_file": fc.ProxyCACertFile, "proxy_ca_key_file": fc.ProxyCAKeyFile, "proxy_code_key_file": fc.ProxyCodeKeyFile} {
if v == "" {
return config{}, fmt.Errorf("%s is required", name)
}
@@ -172,6 +176,9 @@ func (fc fileConfig) check() (config, error) {
if c.ctl.ProxyCA, err = readProxyCA(fc.ProxyCACertFile, fc.ProxyCAKeyFile); err != nil {
return config{}, err
}
+ if c.ctl.ProxyCodeKey, err = readProxyCodeKey(fc.ProxyCodeKeyFile); err != nil {
+ return config{}, err
+ }
return c, nil
}
@@ -193,6 +200,19 @@ func readProxyCA(certPath, keyPath string) (*ctlproxy.CA, error) {
return ca, nil
}
+// readProxyCodeKey reads the base64 proxy-code key in path.
+func readProxyCodeKey(path string) ([]byte, error) {
+ raw, err := readPrivate(path, "proxy code key")
+ if err != nil {
+ return nil, err
+ }
+ key, err := base64.StdEncoding.Strict().DecodeString(strings.TrimSpace(string(raw)))
+ if err != nil || len(key) != ctlproxy.CodeKeySize {
+ return nil, fmt.Errorf("proxy code key %s must hold %d bytes in base64", path, ctlproxy.CodeKeySize)
+ }
+ return key, nil
+}
+
// readPrivate reads the secret file at path, refusing one that group or
// others may read. what names it in errors.
func readPrivate(path, what string) ([]byte, error) {
diff --git a/cmd/equipo-hosted-controller/config_test.go b/cmd/equipo-hosted-controller/config_test.go
index cf8d9408..0e6e46a9 100644
--- a/cmd/equipo-hosted-controller/config_test.go
+++ b/cmd/equipo-hosted-controller/config_test.go
@@ -58,6 +58,10 @@ func validConfig(t *testing.T, dir string) fileConfig {
if err := os.WriteFile(caKeyPath, caKey, 0o600); err != nil {
t.Fatal(err)
}
+ codeKeyPath := filepath.Join(dir, "proxy-code.key")
+ if err := os.WriteFile(codeKeyPath, []byte(base64.StdEncoding.EncodeToString(ctlproxytest.CodeKey())+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
return fileConfig{
Listen: "127.0.0.1:8443", MetricsListen: "100.119.180.57:9090",
TLSCertFile: "/etc/equipo/tls.crt", TLSKeyFile: "/etc/equipo/tls.key", Database: "/var/lib/equipo/hosted.db",
@@ -77,6 +81,7 @@ func validConfig(t *testing.T, dir string) fileConfig {
CertificatesFile: certsPath,
ProxyCACertFile: caCertPath,
ProxyCAKeyFile: caKeyPath,
+ ProxyCodeKeyFile: codeKeyPath,
}
}
@@ -326,6 +331,12 @@ func TestConfigRefusesMissingListenOrKeys(t *testing.T) {
"no SNS topic": func(f *fileConfig) { f.SNSTopicARN = "" },
"no proxy CA": func(f *fileConfig) { f.ProxyCACertFile = "" },
"no proxy CA key": func(f *fileConfig) { f.ProxyCAKeyFile = "" },
+ "no proxy code key": func(f *fileConfig) { f.ProxyCodeKeyFile = "" },
+ "short proxy code key": func(f *fileConfig) {
+ if err := os.WriteFile(f.ProxyCodeKeyFile, []byte("AAAA"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ },
"proxy CA not a CA": func(f *fileConfig) {
cert, key := ctlproxytest.SelfSigned(false)
writePair(t, f, cert, key)
@@ -361,11 +372,20 @@ func TestConfigRefusesMissingListenOrKeys(t *testing.T) {
if _, err := loadFC(t, sub, fc); err == nil || !strings.Contains(err.Error(), "proxy client CA key") {
t.Errorf("group-readable proxy CA key: %v, want a refusal", err)
}
+ sub = t.TempDir()
+ fc = validConfig(t, sub)
+ if err := os.Chmod(fc.ProxyCodeKeyFile, 0o604); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := loadFC(t, sub, fc); err == nil || !strings.Contains(err.Error(), "proxy code key") {
+ t.Errorf("world-readable proxy code key: %v, want a refusal", err)
+ }
// A proxy key loads, and the CA is the controller's.
sub = t.TempDir()
fc = validConfig(t, sub)
fc.VerifyKeys = append(fc.VerifyKeys, keyEntry{ID: "proxy-1", Role: "proxy", PublicKey: pubB64(4)})
- if c, err := loadFC(t, sub, fc); err != nil || c.keys["proxy-1"].Role != hostedwire.RoleProxy || c.ctl.ProxyCA == nil {
+ if c, err := loadFC(t, sub, fc); err != nil || c.keys["proxy-1"].Role != hostedwire.RoleProxy || c.ctl.ProxyCA == nil ||
+ !bytes.Equal(c.ctl.ProxyCodeKey, ctlproxytest.CodeKey()) {
t.Errorf("config with a proxy key: %v, keys %v; want it to load with the proxy CA", err, c.keys)
}
diff --git a/cmd/equipo-hosted-controller/crashpoint_test.go b/cmd/equipo-hosted-controller/crashpoint_test.go
index b423e65f..c61355de 100644
--- a/cmd/equipo-hosted-controller/crashpoint_test.go
+++ b/cmd/equipo-hosted-controller/crashpoint_test.go
@@ -29,7 +29,7 @@ func crashCtl(t *testing.T, path string, clk *isolatedjobtest.FakeClock, run iso
t.Fatal(err)
}
t.Cleanup(func() { _ = store.Close() }) // a second Close does nothing
- c, err := hostedctl.New(hostedctl.Config{Enabled: true, Certs: testCerts(), ProxyCA: ctlproxytest.CA(),
+ c, err := hostedctl.New(hostedctl.Config{Enabled: true, Certs: testCerts(), ProxyCA: ctlproxytest.CA(), ProxyCodeKey: ctlproxytest.CodeKey(),
ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
Manifest: testEgress},
hostedctl.Deps{Store: store, Runner: run, Auditor: fake, Alerter: nopAlerter{}})
diff --git a/cmd/equipo-hosted-controller/main_test.go b/cmd/equipo-hosted-controller/main_test.go
index fe80d12a..4efe524a 100644
--- a/cmd/equipo-hosted-controller/main_test.go
+++ b/cmd/equipo-hosted-controller/main_test.go
@@ -63,7 +63,7 @@ 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, Certs: testCerts(), ProxyCA: ctlproxytest.CA(),
+ c, err := hostedctl.New(hostedctl.Config{Enabled: true, Certs: testCerts(), ProxyCA: ctlproxytest.CA(), ProxyCodeKey: ctlproxytest.CodeKey(),
ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
Manifest: testEgress},
hostedctl.Deps{Store: store, Runner: run, Auditor: fake, Alerter: nopAlerter{}})
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 09f5786f..8a30428d 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -119,3 +119,24 @@ Mutation checks (each applied by script, the named test run, then restored and c
14. (extra) The feed route takes the instance role (`proxy.go`). Command: `... -run 'TestProxyRoleOnlyOnProxyRoutes' -count=1`. Observed: FAIL, `feed_test.go:155: GET /v1/proxy/feed by inst-1 = 200 {"version":1,...}` and `feed_test.go:165: feed by a proxy key = 403 {"code":"forbidden",...}, want 200`. Restored.
Also run: `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedclient ./internal/hostedwire ./cmd/equipo-hosted-controller -count=1` ok (TestLifecycleSimulation included; hostedctl 8.4 s); `go vet -tags hostedlive` on hostedclient and the cmd ok; staticcheck v0.7.0 on `./internal/hostedctl/... ./internal/hostedclient ./cmd/equipo-hosted-controller` (and with `-tags hostedlive`) ok; `make budget build vet` ok after raising the `internal/hostedctl` record to 5662/9340.
+
+### Task 4 review round 1 (t4-r1.md: findings 1 to 3 by ruling; 4 and 5 not acted on)
+
+1. The proxy code is derived, never stored: `ProxyCode = base64url(HMAC-SHA256(k, "equipo-proxy-code-v1\n" + launch_id))` (`ctlproxy.DeriveCode`), with `k` the new required `Config.ProxyCodeKey` (32 bytes; controller config `proxy_code_key_file`, standard base64, not readable by group or others). `saveIntent` saves the bootstrap with the code emptied (`ctlproxy.StripCode`) and the code's SHA-256 in `proxy_codes`; `dispatch` derives it again into the saved bootstrap just before each provider call (`ctlproxy.WithCode`), so Launch and Replay send identical bytes. An intent whose saved hash the current key no longer derives is abandoned in dispatch's transaction as `config_changed` (alerted), never sent with a code it cannot redeem. `noCodeStored` now scans every column of every table and the bootstrap decoded from each `jobs.spec_json`, with no exemption.
+2. Contract narrowed by ruling: the window opens at the first Refresh that sees the VM running; `GET /v1/vms` does not open it (comment on `ListVMs`). New test TestVMListDoesNotOpenCodeWindow.
+3. Silence alerts are durable: `proxy_polls` gains `alert_pending` and `alerted_t` (in the unreleased `0004_proxy.sql`). `ctlproxy.MarkSilent` opens an episode (alerted and pending, in one transaction); `checkProxies` then delivers every pending alert from the store, this run's or an earlier run's, and clears it (`ctlproxy.Delivered`) only after the alerter takes it, so the first reaper pass after a start re-sends what a failed delivery left. Across a restart the allowance restarts at `OpenedAt` only for a proxy not already overdue at the last controller time the previous run recorded (`Store.lastRun`, the checkpoint Open found); an overdue episode keeps its deadline.
+
+New tests: TestProxySilentAlertSurvivesRestart, TestProxySilentOverdueAtStartup, TestVMListDoesNotOpenCodeWindow, TestProxyCodeKeyChangeAbandons (ctlproxy); TestReplaySendsSnapshotServices also checks the code is the derived one; TestNewRefusesNilDependency gains a 31-byte key; TestLaunchSavesIntentBeforeProvider and TestLaunchSnapshotsServices compare the saved bootstrap with the code derived in; the controller config test gains a missing, short and world-readable code key.
+
+Mutation checks (each applied by script, then restored and checked byte for byte):
+
+15. Store the code in the snapshot (the `StripCode` call removed from `saveIntent`). Command: `CGO_ENABLED=0 go test ./internal/hostedctl/ctlproxy -run 'TestRedeemSingleUse|TestReplaySendsSnapshotServices' -count=1`. Observed: FAIL, `env_test.go:420: the saved spec's bootstrap holds the proxy code: {"v":2,"purpose":"checks",...,"proxy_code":"8AYXxNXn-...` (both tests). Restored.
+16. The VM list opens the window (`ListVMs` called `ctlproxy.SeenRunning` for each owned running VM). Command: `... -run 'TestVMListDoesNotOpenCodeWindow' -count=1`. Observed: FAIL, `feed_test.go:384: redemption after only the VM list saw it running = 200 {"cert":...`. Restored.
+17. A refused alert is marked delivered (the `continue` after a failed `Alert` removed, `proxy.go`). Command: `... -run 'TestProxySilentAlertSurvivesRestart' -count=1`. Observed: FAIL, `feed_test.go:334: Reap with the alerter down = <nil>, want the failed proxy_silent delivery` (the pending alert was gone on the second pass). Restored.
+18. Every restart restarts the allowance (`if from+SilentAfter > lastRun` became `if true`, `ctlproxy/feed.go`). Command: `... -run 'TestProxySilentOverdueAtStartup' -count=1`. Observed: FAIL, `feed_test.go:364: proxy_silent alerts = [], want one each for [proxy-1]`. Restored.
+19. (extra) A changed key does not abandon (`false && reason == "" && !same`, `launch.go`). Command: `... -run 'TestProxyCodeKeyChangeAbandons' -count=1`. Observed: FAIL, `feed_test.go:417: att-1 after Replay under another key = ({... State:starting VMRef:vm-0001 ...}, <nil>), want abandoned`. Restored.
+20. (recheck) Mutation 4 against the new dispatch path (services rebuilt from the current manifest after `decodeSpec`). Command: `... -run 'TestReplaySendsSnapshotServices' -count=1`. Observed: FAIL, `feed_test.go:263: launches sent for att-1 = 2, bootstraps equal false; want 2, byte for byte`. Restored.
+
+A first rejected attempt at 17 (widening `Delivered`'s UPDATE) passed, since it only acts after a successful delivery; it is not a guard and was replaced by the mutation above.
+
+Also run: `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedclient ./internal/hostedwire ./cmd/equipo-hosted-controller -count=1` ok (hostedctl 10.6 s and 16.9 s on a box at load average 21 to 40; 8.3 s before at low load); `go vet -tags hostedlive` ok; staticcheck v0.7.0 ok; `make budget build vet` ok after raising the `internal/hostedctl` record to 5689/9355. One full run before the fix hit `TestReapLoopRunsPassesUntilDone: read unmatched_vms = ... cannot start a transaction within a transaction` under that load; `-run TestReapLoopRunsPassesUntilDone -count=200` then passed. It cancels the loop mid-pass and is untouched by this task.
diff --git a/internal/hostedclient/client_test.go b/internal/hostedclient/client_test.go
index 0d04e5cd..c9c15a0b 100644
--- a/internal/hostedclient/client_test.go
+++ b/internal/hostedclient/client_test.go
@@ -79,7 +79,7 @@ func newCtlEnvManifest(t *testing.T, m ctlegress.Manifest) *ctlEnv {
t.Cleanup(func() { _ = store.Close() })
fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits())
c, err := hostedctl.New(hostedctl.Config{Enabled: true, Certs: ctlcerttest.Set(ctlcerttest.Cert(imgA, "equipo.example.com")),
- ProxyCA: ctlproxytest.CA(),
+ ProxyCA: ctlproxytest.CA(), ProxyCodeKey: ctlproxytest.CodeKey(),
ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
Manifest: m},
hostedctl.Deps{Store: store, Runner: fake, Auditor: fake, Alerter: nopAlerter{}})
diff --git a/internal/hostedctl/controller.go b/internal/hostedctl/controller.go
index 4c3ef66f..e972da6f 100644
--- a/internal/hostedctl/controller.go
+++ b/internal/hostedctl/controller.go
@@ -51,6 +51,9 @@ type Config struct {
// ProxyCA is the egress proxies' client CA: it signs each VM's
// certificate when the VM redeems its proxy code (ctlproxy).
ProxyCA *ctlproxy.CA
+ // ProxyCodeKey (ctlproxy.CodeKeySize bytes) derives each launch's proxy
+ // code, so no table holds the code (ctlproxy.DeriveCode).
+ ProxyCodeKey []byte
}
// ErrProviderMismatch: the database belongs to another provider namespace
@@ -118,6 +121,8 @@ func New(cfg Config, d Deps) (*Controller, error) {
return nil, errors.New("hostedctl: controller needs a certificate set")
case cfg.ProxyCA == nil:
return nil, errors.New("hostedctl: controller needs a proxy client CA")
+ case len(cfg.ProxyCodeKey) != ctlproxy.CodeKeySize:
+ return nil, errors.New("hostedctl: controller needs a 32-byte proxy code key")
}
if err := d.Store.bindProvider(context.Background(), cfg.ProviderNamespace); err != nil {
return nil, err
@@ -127,6 +132,7 @@ func New(cfg Config, d Deps) (*Controller, error) {
}
cfg.Egress = slices.Clone(cfg.Egress)
cfg.Manifest = cfg.Manifest.Clone()
+ cfg.ProxyCodeKey = slices.Clone(cfg.ProxyCodeKey)
log := d.Log
if log == nil {
log = slog.New(slog.DiscardHandler)
diff --git a/internal/hostedctl/ctlproxy/ca.go b/internal/hostedctl/ctlproxy/ca.go
index 6ac89623..f3926276 100644
--- a/internal/hostedctl/ctlproxy/ca.go
+++ b/internal/hostedctl/ctlproxy/ca.go
@@ -19,6 +19,7 @@ import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
+ "crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
@@ -28,6 +29,7 @@ import (
"database/sql"
"encoding/base64"
"encoding/hex"
+ "encoding/json"
"errors"
"fmt"
"math/big"
@@ -177,15 +179,21 @@ func ParseLaunchURI(u *url.URL) (LaunchIdentity, error) {
return LaunchIdentity{LaunchID: u.Hostname(), AttemptID: attempt, VMRef: isolatedjob.Ref(ref), Epoch: epoch}, nil
}
-// NewCode draws a proxy code (32 random bytes in unpadded base64url) and
-// returns it with its hash, CodeHash(code).
-func NewCode() (code, hash string, err error) {
- var b [32]byte
- if _, err := rand.Read(b[:]); err != nil {
- return "", "", fmt.Errorf("ctlproxy: proxy code: %w", err)
- }
- code = base64.RawURLEncoding.EncodeToString(b[:])
- return code, CodeHash(code), nil
+// CodeKeySize is the length of the proxy-code key, a controller secret.
+const CodeKeySize = 32
+
+// codeDomain separates proxy codes from any other use of the key.
+const codeDomain = "equipo-proxy-code-v1\n"
+
+// DeriveCode is launchID's proxy code: base64url (unpadded) of
+// HMAC-SHA256(key, "equipo-proxy-code-v1\n" + launchID). Deriving it means
+// no table holds it: the intent saves its bootstrap without the code
+// (StripCode), and each provider call derives it again (WithCode), so a
+// replay sends the same bytes.
+func DeriveCode(key []byte, launchID string) string {
+ m := hmac.New(sha256.New, key)
+ _, _ = m.Write([]byte(codeDomain + launchID))
+ return base64.RawURLEncoding.EncodeToString(m.Sum(nil))
}
// CodeHash is the hex SHA-256 of a proxy code's text: all the controller
@@ -195,10 +203,30 @@ func CodeHash(code string) string {
return hex.EncodeToString(sum[:])
}
-// SaveCode keeps the hash of a new launch intent's proxy code. The code
-// itself is only in the intent's bootstrap, inside the saved provider
-// request (jobs.spec_json) that Replay re-sends as it is, as the instance
-// code already is.
+// StripCode returns boot, a BootstrapV2's JSON, with the proxy code
+// emptied: the form an intent saves.
+func StripCode(boot []byte) ([]byte, error) {
+ var b hostedwire.BootstrapV2
+ if err := json.Unmarshal(boot, &b); err != nil {
+ return nil, fmt.Errorf("ctlproxy: bootstrap to save is unreadable: %w", err)
+ }
+ b.ProxyCode = ""
+ return json.Marshal(b)
+}
+
+// WithCode returns a saved bootstrap with its launch's proxy code derived
+// under key, encoded (BootstrapV2.Encode) as the provider receives it.
+func WithCode(boot, key []byte) ([]byte, error) {
+ var b hostedwire.BootstrapV2
+ if err := json.Unmarshal(boot, &b); err != nil {
+ return nil, fmt.Errorf("ctlproxy: saved bootstrap is unreadable: %w", err)
+ }
+ b.ProxyCode = DeriveCode(key, b.LaunchID)
+ return b.Encode()
+}
+
+// SaveCode keeps the hash of a new launch intent's proxy code; the code
+// itself is kept nowhere (DeriveCode).
func SaveCode(ctx context.Context, tx *sql.Tx, launchID, attemptID, hash string) error {
if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_codes (launch_id, attempt_id, code_sha256) VALUES (?, ?, ?)`,
launchID, attemptID, hash); err != nil {
@@ -207,6 +235,21 @@ func SaveCode(ctx context.Context, tx *sql.Tx, launchID, attemptID, hash string)
return nil
}
+// CodeMatches reports whether key derives the code whose hash launchID's
+// intent saved. An intent with no saved code (from before proxy codes)
+// matches: its other gates keep it from launching.
+func CodeMatches(ctx context.Context, tx *sql.Tx, launchID string, key []byte) (bool, error) {
+ var hash string
+ err := tx.QueryRowContext(ctx, `SELECT code_sha256 FROM proxy_codes WHERE launch_id = ?`, launchID).Scan(&hash)
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
+ return true, nil
+ case err != nil:
+ return false, fmt.Errorf("ctlproxy: read proxy code of %s: %w", launchID, err)
+ }
+ return hash == CodeHash(DeriveCode(key, launchID)), nil
+}
+
// SeenRunning opens attempt's code window at now, the first time the
// controller sees its VM running; later sightings change nothing.
func SeenRunning(ctx context.Context, tx *sql.Tx, attempt string, now time.Duration) error {
diff --git a/internal/hostedctl/ctlproxy/ctlproxytest/ctlproxytest.go b/internal/hostedctl/ctlproxy/ctlproxytest/ctlproxytest.go
index af8db1e9..d68d0a7c 100644
--- a/internal/hostedctl/ctlproxy/ctlproxytest/ctlproxytest.go
+++ b/internal/hostedctl/ctlproxy/ctlproxytest/ctlproxytest.go
@@ -4,6 +4,7 @@
package ctlproxytest
import (
+ "bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
@@ -76,6 +77,9 @@ func selfSigned(k *ecdsa.PrivateKey, ca bool) (cert, key []byte) {
pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pk})
}
+// CodeKey returns a fixed test proxy-code key (ctlproxy.CodeKeySize bytes).
+func CodeKey() []byte { return bytes.Repeat([]byte{0x7c}, ctlproxy.CodeKeySize) }
+
// CSR returns a fresh VM key and a certificate request signed with it, in
// DER, as a VM sends it.
func CSR() (*ecdsa.PrivateKey, []byte) {
diff --git a/internal/hostedctl/ctlproxy/env_test.go b/internal/hostedctl/ctlproxy/env_test.go
index 40ace291..f442ecdc 100644
--- a/internal/hostedctl/ctlproxy/env_test.go
+++ b/internal/hostedctl/ctlproxy/env_test.go
@@ -7,6 +7,7 @@ import (
"crypto/x509"
"database/sql"
"encoding/json"
+ "errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -100,17 +101,27 @@ func (r *recorder) sent(attempt string) []isolatedjob.LaunchSpec {
}
type alertLog struct {
- mu sync.Mutex
- got []hostedctl.Alert
+ mu sync.Mutex
+ got []hostedctl.Alert
+ fail bool // refuse every alert, as an alerter that is down
}
func (a *alertLog) Alert(_ context.Context, al hostedctl.Alert) error {
a.mu.Lock()
defer a.mu.Unlock()
+ if a.fail {
+ return errors.New("alerter down")
+ }
a.got = append(a.got, al)
return nil
}
+func (a *alertLog) setFail(fail bool) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.fail = fail
+}
+
// kinds returns the alerts of kind delivered so far, and forgets them.
func (a *alertLog) take(kind string) []hostedctl.Alert {
a.mu.Lock()
@@ -130,6 +141,7 @@ func (a *alertLog) take(kind string) []hostedctl.Alert {
type env struct {
t *testing.T
ctx context.Context
+ path string
clk *isolatedjobtest.FakeClock
fake *isolatedjob.Fake
rec *recorder
@@ -152,15 +164,33 @@ func newEnv(t *testing.T) *env {
ProviderFingerprint: func(d isolatedjob.ImageDigest, s isolatedjob.Size) string {
return "fp/" + string(d) + "/" + string(s)
},
- Manifest: manifest(host, "ab", "10.42.1.10"), ProxyCA: ctlproxytest.CA()}}
- s, err := hostedctl.Open(e.ctx, filepath.Join(t.TempDir(), "hosted.db"), clk)
+ Manifest: manifest(host, "ab", "10.42.1.10"), ProxyCA: ctlproxytest.CA(), ProxyCodeKey: ctlproxytest.CodeKey()}}
+ e.path = filepath.Join(t.TempDir(), "hosted.db")
+ e.open()
+ e.build()
+ return e
+}
+
+func (e *env) open() {
+ e.t.Helper()
+ s, err := hostedctl.Open(e.ctx, e.path, e.clk)
if err != nil {
- t.Fatalf("Open = %v", err)
+ e.t.Fatalf("Open = %v", err)
}
- t.Cleanup(func() { _ = s.Close() })
+ e.t.Cleanup(func() { _ = s.Close() })
e.store = s
+}
+
+// restart closes the store, as a controller that exits, lets down pass
+// with the controller down, then opens it again under a new controller.
+func (e *env) restart(down time.Duration) {
+ e.t.Helper()
+ if err := e.store.Close(); err != nil {
+ e.t.Fatalf("Close = %v", err)
+ }
+ e.advance(down)
+ e.open()
e.build()
- return e
}
// build makes a controller over e.store with e.cfg and serves its API.
@@ -338,18 +368,61 @@ func (e *env) tx(fn func(*sql.Tx) error) {
}
}
-// noCodeStored wants no table but the saved spec to hold code.
+// noCodeStored wants no value in any table to hold code: every column of
+// every row as text, and the bootstrap inside each saved spec (base64 in
+// jobs.spec_json) decoded.
func (e *env) noCodeStored(code string) {
e.t.Helper()
e.tx(func(tx *sql.Tx) error {
- for _, q := range []string{`SELECT count(*) FROM audit WHERE reason LIKE '%' || ? || '%'`,
- `SELECT count(*) FROM proxy_codes WHERE code_sha256 = ?`} {
- var n int
- if err := tx.QueryRowContext(e.ctx, q, code).Scan(&n); err != nil {
+ tables, err := tx.QueryContext(e.ctx, `SELECT name FROM sqlite_master WHERE type = 'table'`)
+ if err != nil {
+ return err
+ }
+ var names []string
+ for tables.Next() {
+ var n string
+ if err := tables.Scan(&n); err != nil {
return err
}
- if n != 0 {
- e.t.Fatalf("%s found the proxy code", q)
+ names = append(names, n)
+ }
+ if err := tables.Close(); err != nil {
+ return err
+ }
+ for _, n := range names {
+ rows, err := tx.QueryContext(e.ctx, `SELECT * FROM "`+n+`"`)
+ if err != nil {
+ return err
+ }
+ cols, _ := rows.Columns()
+ for rows.Next() {
+ vals := make([]any, len(cols))
+ ptrs := make([]any, len(cols))
+ for i := range vals {
+ ptrs[i] = &vals[i]
+ }
+ if err := rows.Scan(ptrs...); err != nil {
+ return err
+ }
+ for i, v := range vals {
+ text := fmt.Sprint(v)
+ if b, ok := v.([]byte); ok {
+ text = string(b)
+ }
+ if strings.Contains(text, code) {
+ e.t.Fatalf("table %s column %s holds the proxy code", n, cols[i])
+ }
+ var spec struct {
+ Bootstrap []byte `json:"bootstrap"`
+ }
+ if n == "jobs" && cols[i] == "spec_json" && json.Unmarshal([]byte(text), &spec) == nil &&
+ strings.Contains(string(spec.Bootstrap), code) {
+ e.t.Fatalf("the saved spec's bootstrap holds the proxy code: %s", spec.Bootstrap)
+ }
+ }
+ }
+ if err := rows.Close(); err != nil {
+ return err
}
}
return nil
diff --git a/internal/hostedctl/ctlproxy/feed.go b/internal/hostedctl/ctlproxy/feed.go
index 3c34110f..8d58a9af 100644
--- a/internal/hostedctl/ctlproxy/feed.go
+++ b/internal/hostedctl/ctlproxy/feed.go
@@ -92,34 +92,82 @@ func column(ctx context.Context, tx *sql.Tx, q string, args ...any) ([]string, e
return out, rows.Err()
}
-// Silent returns the keys among proxies that have not asked for the feed
-// for SilentAfter or more at now, counting from their last request or from
-// since (the controller's start), whichever is later, and have not been
-// alerted for this silence; it marks them alerted. A key's next feed
-// request ends its silence, so each silence is alerted once.
-func Silent(ctx context.Context, tx *sql.Tx, proxies []hostedwire.KeyID, now, since time.Duration) ([]hostedwire.KeyID, error) {
- var out []hostedwire.KeyID
+// MarkSilent opens a silence episode for each of proxies that has not
+// asked for the feed for SilentAfter or more at now and has no open
+// episode: it is marked alerted, with its alert pending delivery (Pending,
+// Delivered), so each silence raises one alert, and a restart neither loses
+// it nor raises it again. A key's next feed request closes the episode.
+//
+// The allowance runs from the key's last request. Across a restart, the
+// time the controller was down does not count against a proxy (it could not
+// ask), so the allowance restarts at opened, the controller's start, unless
+// the episode was already overdue at lastRun, the last controller time the
+// previous run recorded: then its deadline stands. A key that never asked
+// counts from opened.
+func MarkSilent(ctx context.Context, tx *sql.Tx, proxies []hostedwire.KeyID, now, opened, lastRun time.Duration) error {
for _, id := range proxies {
var last sql.NullInt64
var alerted bool
err := tx.QueryRowContext(ctx, `SELECT last_t, silent_alerted FROM proxy_polls WHERE key_id = ?`, string(id)).Scan(&last, &alerted)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
- return nil, fmt.Errorf("ctlproxy: read last feed request of %s: %w", id, err)
+ return fmt.Errorf("ctlproxy: read last feed request of %s: %w", id, err)
}
- from := since
+ from := opened
if last.Valid {
- from = max(from, time.Duration(last.Int64))
+ from = time.Duration(last.Int64)
+ if from+SilentAfter > lastRun { // not overdue before the restart
+ from = max(from, opened)
+ }
}
if alerted || now-from < SilentAfter {
continue
}
- if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_polls (key_id, silent_alerted) VALUES (?, 1)
- ON CONFLICT (key_id) DO UPDATE SET silent_alerted = 1`, string(id)); err != nil {
- return nil, fmt.Errorf("ctlproxy: mark %s alerted: %w", id, err)
+ if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_polls (key_id, silent_alerted, alert_pending, alerted_t) VALUES (?, 1, 1, ?)
+ ON CONFLICT (key_id) DO UPDATE SET silent_alerted = 1, alert_pending = 1, alerted_t = excluded.alerted_t`,
+ string(id), int64(now)); err != nil {
+ return fmt.Errorf("ctlproxy: mark %s silent: %w", id, err)
}
- out = append(out, id)
}
- return out, nil
+ return nil
+}
+
+// Silence is one proxy_silent alert waiting for delivery.
+type Silence struct {
+ Key hostedwire.KeyID
+ At time.Duration // when the episode was raised, controller time
+}
+
+// Detail is the alert's text.
+func (s Silence) Detail() string {
+ return fmt.Sprintf("proxy %s has not asked for the launch feed for %v or more", s.Key, SilentAfter)
+}
+
+// Pending returns the silences whose alert has not been delivered, by key.
+func Pending(ctx context.Context, tx *sql.Tx) ([]Silence, error) {
+ rows, err := tx.QueryContext(ctx, `SELECT key_id, alerted_t FROM proxy_polls WHERE alert_pending = 1 ORDER BY key_id`)
+ if err != nil {
+ return nil, fmt.Errorf("ctlproxy: read pending silence alerts: %w", err)
+ }
+ defer rows.Close()
+ var out []Silence
+ for rows.Next() {
+ var s Silence
+ if err := rows.Scan(&s.Key, &s.At); err != nil {
+ return nil, fmt.Errorf("ctlproxy: read pending silence alerts: %w", err)
+ }
+ out = append(out, s)
+ }
+ return out, rows.Err()
+}
+
+// Delivered records that s's alert was delivered. A later episode of the
+// same key, raised since, stays pending.
+func Delivered(ctx context.Context, tx *sql.Tx, s Silence) error {
+ if _, err := tx.ExecContext(ctx, `UPDATE proxy_polls SET alert_pending = 0 WHERE key_id = ? AND alerted_t = ?`,
+ string(s.Key), int64(s.At)); err != nil {
+ return fmt.Errorf("ctlproxy: mark the silence alert of %s delivered: %w", s.Key, err)
+ }
+ return nil
}
// ProxyKeys returns the IDs of the proxy keys in keys, sorted.
diff --git a/internal/hostedctl/ctlproxy/feed_test.go b/internal/hostedctl/ctlproxy/feed_test.go
index e70aaf78..4a089f48 100644
--- a/internal/hostedctl/ctlproxy/feed_test.go
+++ b/internal/hostedctl/ctlproxy/feed_test.go
@@ -15,6 +15,7 @@ import (
"amadan.net/oficina/equipo/internal/hostedctl"
"amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
)
@@ -274,6 +275,9 @@ func TestReplaySendsSnapshotServices(t *testing.T) {
if _, err := b.Encode(); err != nil {
t.Fatalf("replayed bootstrap does not encode: %v", err)
}
+ if b.ProxyCode != ctlproxy.DeriveCode(ctlproxytest.CodeKey(), v.LaunchID) {
+ t.Fatalf("proxy code %q is not the one the key derives for launch %s", b.ProxyCode, v.LaunchID)
+ }
var hash string
e.tx(func(tx *sql.Tx) error {
return tx.QueryRowContext(e.ctx, `SELECT code_sha256 FROM proxy_codes WHERE launch_id = ?`, v.LaunchID).Scan(&hash)
@@ -289,3 +293,133 @@ func TestReplaySendsSnapshotServices(t *testing.T) {
t.Fatalf("new launch's bootstrap = %+v, want the current manifest and a code of its own", got)
}
}
+
+func (e *env) poll(id hostedwire.KeyID, key []byte) {
+ e.t.Helper()
+ if status, body := e.do(http.MethodGet, "/v1/proxy/feed", nil, id, key); status != http.StatusOK {
+ e.t.Fatalf("feed by %s = %d %s", id, status, body)
+ }
+}
+
+// reapAlerts runs a reaper pass and wants exactly one proxy_silent alert
+// delivered for each of want, in order.
+func (e *env) reapAlerts(want ...hostedwire.KeyID) {
+ e.t.Helper()
+ if _, err := e.c.Reap(e.ctx); err != nil {
+ e.t.Fatalf("Reap = %v", err)
+ }
+ got := e.alerts.take(ctlproxy.AlertProxySilent)
+ if len(got) != len(want) {
+ e.t.Fatalf("proxy_silent alerts = %+v, want one each for %v", got, want)
+ }
+ for i, a := range got {
+ if !strings.Contains(a.Detail, string(want[i])) {
+ e.t.Fatalf("alert %+v, want it to name %s", a, want[i])
+ }
+ }
+}
+
+// TestProxySilentAlertSurvivesRestart: an alert the alerter refused stays
+// pending in the store, is delivered by the first pass after a restart, and
+// only once.
+func TestProxySilentAlertSurvivesRestart(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ e.poll(idProxy, keyProxy)
+ e.poll(idProxy2, keyProxy2)
+ e.alerts.setFail(true)
+ e.advance(ctlproxy.SilentAfter)
+ for range 2 {
+ if _, err := e.c.Reap(e.ctx); err == nil || !strings.Contains(err.Error(), ctlproxy.AlertProxySilent) {
+ t.Fatalf("Reap with the alerter down = %v, want the failed proxy_silent delivery", err)
+ }
+ }
+ if got := e.alerts.take(ctlproxy.AlertProxySilent); len(got) != 0 {
+ t.Fatalf("alerts delivered while the alerter was down: %+v", got)
+ }
+
+ e.restart(time.Minute)
+ e.alerts.setFail(false)
+ e.reapAlerts(idProxy, idProxy2)
+ e.reapAlerts()
+ e.restart(time.Minute)
+ e.reapAlerts()
+}
+
+// TestProxySilentOverdueAtStartup: a restart does not give back the
+// allowance of a silence already overdue before it, but does give a full
+// one to a proxy whose allowance ran out only while the controller was
+// down.
+func TestProxySilentOverdueAtStartup(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ e.poll(idProxy, keyProxy) // deadline 3m
+ e.advance(time.Minute)
+ e.poll(idProxy2, keyProxy2) // deadline 4m
+ e.advance(2*time.Minute + 30*time.Second)
+ if err := e.store.Checkpoint(e.ctx); err != nil { // the run ends at 3m30 with no reaper pass since 0
+ t.Fatal(err)
+ }
+ e.restart(10 * time.Minute)
+ e.reapAlerts(idProxy)
+ e.advance(ctlproxy.SilentAfter - time.Second)
+ e.reapAlerts()
+ e.advance(time.Second)
+ e.reapAlerts(idProxy2)
+}
+
+// TestVMListDoesNotOpenCodeWindow: the operator's VM list may show the VM
+// running, but only a Refresh opens the proxy code's window.
+func TestVMListDoesNotOpenCodeWindow(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ v := e.launch("att-1", 2*time.Hour)
+ e.fake.Tick()
+ status, body := e.do(http.MethodGet, "/v1/vms", nil, idOp, keyOp)
+ if status != http.StatusOK || !strings.Contains(string(body), `"state":"running","attempt_id":"att-1"`) {
+ t.Fatalf("GET /v1/vms = %d %s, want att-1's VM running", status, body)
+ }
+ code := e.boot("att-1").ProxyCode
+ status, _, body = e.redeem(v.LaunchID, v.VMRef, code)
+ e.wantRefused("redemption after only the VM list saw it running", status, body, "not seen running")
+
+ e.advance(ctlproxy.CodeWindow + time.Second)
+ if err := e.c.Refresh(e.ctx); err != nil {
+ t.Fatal(err)
+ }
+ if status, _, body := e.redeem(v.LaunchID, v.VMRef, code); status != http.StatusOK {
+ t.Fatalf("redemption after the first Refresh = %d %s, want 200: the window opens there", status, body)
+ }
+}
+
+// TestProxyCodeKeyChangeAbandons: an intent whose saved code hash the
+// current key no longer derives is abandoned with a config_changed alert,
+// and its VM is never asked for with a code it cannot redeem.
+func TestProxyCodeKeyChangeAbandons(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ if err := e.c.RunAudit(e.ctx); err != nil {
+ t.Fatal(err)
+ }
+ e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
+ if v, err := e.c.Launch(e.ctx, idInst, instance, request("att-1", 2*time.Hour)); err != nil || v.State != hostedctl.JobWaiting {
+ t.Fatalf("throttled Launch = (%+v, %v), want waiting", v, err)
+ }
+ e.cfg.ProxyCodeKey = bytes.Repeat([]byte{0x11}, ctlproxy.CodeKeySize)
+ e.build()
+ if err := e.c.RunAudit(e.ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err := e.c.Replay(e.ctx); err != nil {
+ t.Fatalf("Replay = %v", err)
+ }
+ if v, err := e.c.Get(e.ctx, idInst, "att-1"); err != nil || v.State != hostedctl.JobAbandoned {
+ t.Fatalf("att-1 after Replay under another key = (%+v, %v), want abandoned", v, err)
+ }
+ if n := len(e.rec.sent("att-1")); n != 1 {
+ t.Fatalf("provider launches for att-1 = %d, want only the throttled one", n)
+ }
+ if got := e.alerts.take(hostedctl.AlertConfigChanged); len(got) != 1 || !strings.Contains(got[0].Detail, "proxy code key") {
+ t.Fatalf("config_changed alerts = %+v, want one naming the proxy code key", got)
+ }
+}
diff --git a/internal/hostedctl/egress_test.go b/internal/hostedctl/egress_test.go
index 9c82d68f..ce4e63bb 100644
--- a/internal/hostedctl/egress_test.go
+++ b/internal/hostedctl/egress_test.go
@@ -12,6 +12,7 @@ import (
"time"
"amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
)
@@ -138,6 +139,9 @@ func TestLaunchSnapshotsServices(t *testing.T) {
t.Fatalf("Replay provider calls = %d, want 1: the snapshot, not the current manifest, governs a saved intent", len(seen))
}
sent, err := decodeSpec(saved.specJSON, "att-1")
+ if err == nil {
+ sent.Bootstrap, err = ctlproxy.WithCode(sent.Bootstrap, e.cfg.ProxyCodeKey)
+ }
if err != nil || !bytes.Equal(sent.Bootstrap, seen[0].spec.Bootstrap) || !reflect.DeepEqual(e.services("att-1"), svc("one.example.com")) {
t.Fatalf("Replay sent %+v (decode %v), saved %+v, services %+v; want the saved spec and snapshot", seen[0].spec, err, sent, e.services("att-1"))
}
diff --git a/internal/hostedctl/http.go b/internal/hostedctl/http.go
index ee0029b7..4da24f3c 100644
--- a/internal/hostedctl/http.go
+++ b/internal/hostedctl/http.go
@@ -548,7 +548,8 @@ func serveVMs(ctx context.Context, c *Controller, _ hostedwire.KeyID, _ hostedwi
// ListVMs returns every VM the provider lists, each with the attempt whose
// saved Ref it is, or "" when it is no job's. A VM a launch intent may own
// but has no Ref saved yet shows "". It makes one provider List and changes
-// nothing.
+// nothing: a VM it shows running does not open its proxy code's window,
+// which only Refresh's first running sighting opens (mirrorState).
func (c *Controller) ListVMs(ctx context.Context) ([]hostedwire.VMView, error) {
vms, err := c.runner.List(ctx)
if err != nil {
diff --git a/internal/hostedctl/launch.go b/internal/hostedctl/launch.go
index 43ae7e17..5633f470 100644
--- a/internal/hostedctl/launch.go
+++ b/internal/hostedctl/launch.go
@@ -76,7 +76,7 @@ const (
)
// AlertConfigChanged: a launch intent was abandoned because the provider
-// settings it was saved with changed (ruling R29).
+// settings it was saved with (ruling R29), or the proxy code key, changed.
const AlertConfigChanged = "config_changed"
// LaunchRequest asks for one VM for one task attempt. InstanceCode is a
@@ -361,10 +361,12 @@ func decodeSpec(text, attempt string) (isolatedjob.LaunchSpec, error) {
// saveIntent is transaction 1. It returns the existing job's view when the
// same request was saved before (created false), or draws a launch ID and a
-// proxy code, builds the spec (its bootstrap holds the code, the current
-// manifest's proxies and services), saves the new intent with its services
+// proxy code (derived, ctlproxy.DeriveCode), builds the spec (its bootstrap
+// holds the code, the current manifest's proxies and services), saves the
+// new intent with the bootstrap stripped of the code, its services
// snapshot, certificate digest and launch-by time, and the code's hash
-// (ctlproxy.SaveCode), and returns its view (created true). A conflict or a
+// (ctlproxy.SaveCode), and returns its view (created true). dispatch
+// derives the code again for each provider call. A conflict or a
// live replaced attempt is audited, committed, and returned as the error.
func (c *Controller) saveIntent(ctx context.Context, by hostedwire.KeyID, q LaunchRequest, services []hostedwire.Service, cert string) (JobView, bool, error) {
hash := requestHash(by, q)
@@ -407,12 +409,12 @@ func (c *Controller) saveIntent(ctx context.Context, by hostedwire.KeyID, q Laun
if err != nil {
return err
}
- code, codeHash, err := ctlproxy.NewCode()
+ code := ctlproxy.DeriveCode(c.cfg.ProxyCodeKey, launchID)
+ spec, err := buildSpec(q, launchID, code, c.cfg.Manifest, services)
if err != nil {
return err
}
- spec, err := buildSpec(q, launchID, code, c.cfg.Manifest, services)
- if err != nil {
+ if spec.Bootstrap, err = ctlproxy.StripCode(spec.Bootstrap); err != nil { // saved without the code
return err
}
specJSON, err := encodeSpec(spec)
@@ -430,7 +432,7 @@ func (c *Controller) saveIntent(ctx context.Context, by hostedwire.KeyID, q Laun
JobWaiting, int64(now), int64(deadline), int64(drain), int64(stop)); err != nil {
return fmt.Errorf("hostedctl: save launch intent: %w", err)
}
- if err := ctlproxy.SaveCode(ctx, tx, launchID, q.AttemptID, codeHash); err != nil {
+ if err := ctlproxy.SaveCode(ctx, tx, launchID, q.AttemptID, ctlproxy.CodeHash(code)); err != nil {
return err
}
a.Action = actionLaunchIntent
@@ -479,13 +481,15 @@ func checkReplaces(ctx context.Context, tx *sql.Tx, by hostedwire.KeyID, attempt
// or holding a Ref, is returned as it stands. A stop asked for, the stop
// time reached, or the launch-by time passed (wall clock) marks it
// JobAbandoned with an audit row; so does a provider
-// fingerprint other than the one saved with the intent (R29), which also
+// fingerprint other than the one saved with the intent (R29), or a proxy
+// code key that no longer derives the saved code's hash, 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 records the dispatch marker (markDispatch,
// R19), checks the stop and launch-by times and the transient gates again
-// once the marker has committed, and only then calls the provider and
+// once the marker has committed, and only then derives the proxy code
+// into the saved bootstrap (ctlproxy.WithCode), calls the provider and
// settles the answer.
func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attempt string, replay bool) (view JobView, gate, err error) {
// The attempt's lock (R18) is held from the gate check to the settled
@@ -523,6 +527,11 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem
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 same, err := ctlproxy.CodeMatches(ctx, tx, j.launchID, c.cfg.ProxyCodeKey); err != nil {
+ return err
+ } else if reason == "" && !same {
+ reason, changed = reasonConfigChanged+": the proxy code key changed since the intent was saved", true
+ }
if reason != "" {
if late != "" && !replay {
expired = late
@@ -567,6 +576,9 @@ func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attem
// R21: c.runner bounds the call by ProviderLaunchTimeout, so no launch
// call this process makes can outlive the Ref-less proof fence
// (ReflessProofDelay) that starts at its dispatch.
+ if spec.Bootstrap, err = ctlproxy.WithCode(spec.Bootstrap, c.cfg.ProxyCodeKey); err != nil {
+ return JobView{}, nil, err
+ }
ref, perr := c.runner.Launch(ctx, spec)
// Record the answer even if the caller has gone: a VM may now exist.
view, err = c.settle(context.WithoutCancel(ctx), actor, attempt, ref, perr, replay)
@@ -696,8 +708,8 @@ func (c *Controller) saveRef(ctx context.Context, actor hostedwire.KeyID, attemp
// re-checked:
//
// - a stop asked for, the intent's stop time reached, its launch-by time
-// passed (wall clock), or provider settings changed since it was saved
-// (config_changed, alerted): the intent is marked JobAbandoned and
+// passed (wall clock), or provider settings or the proxy code key changed
+// since it was saved (config_changed, alerted): the intent is marked JobAbandoned and
// audited, and never replayed again; a VM a lost reply made for it is
// an orphan, which the reaper stops;
// - launches switched off, its certificate no longer valid, or no passing
@@ -804,7 +816,7 @@ func (c *Controller) abandonDue(ctx context.Context, actor hostedwire.KeyID, att
// 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",
+ "launch intent %s (launch %s) was abandoned: the provider settings or the proxy code key 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)
diff --git a/internal/hostedctl/launch_test.go b/internal/hostedctl/launch_test.go
index 1ec5f273..0f930158 100644
--- a/internal/hostedctl/launch_test.go
+++ b/internal/hostedctl/launch_test.go
@@ -16,6 +16,7 @@ import (
"time"
"amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
"amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
@@ -61,7 +62,7 @@ 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, Certs: testCerts(), ProxyCA: ctlproxytest.CA(),
+ cfg: Config{Enabled: true, Certs: testCerts(), ProxyCA: ctlproxytest.CA(), ProxyCodeKey: ctlproxytest.CodeKey(),
ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint, Manifest: testManifest("equipo.example.com")},
}
e.store = openStore(t, e.path, e.gc)
@@ -300,6 +301,11 @@ func TestLaunchSavesIntentBeforeProvider(t *testing.T) {
if err != nil {
t.Fatalf("decode saved spec = %v", err)
}
+ // The intent saves its bootstrap without the proxy code; the call
+ // derives it.
+ if saved.Bootstrap, err = ctlproxy.WithCode(saved.Bootstrap, e.cfg.ProxyCodeKey); err != nil {
+ t.Fatalf("saved bootstrap with its code = %v", err)
+ }
if saved.AttemptID != seen.spec.AttemptID || saved.Image != seen.spec.Image || saved.Size != seen.spec.Size ||
saved.MaxLifetime != seen.spec.MaxLifetime || !bytes.Equal(saved.Bootstrap, seen.spec.Bootstrap) {
t.Fatalf("saved spec %+v differs from the one sent %+v", saved, seen.spec)
diff --git a/internal/hostedctl/proxy.go b/internal/hostedctl/proxy.go
index 1467f282..b9367815 100644
--- a/internal/hostedctl/proxy.go
+++ b/internal/hostedctl/proxy.go
@@ -85,27 +85,34 @@ func (c *Controller) watchProxies(keys map[hostedwire.KeyID]hostedwire.VerifyKey
c.proxies.Store(&ids)
}
-// checkProxies queues one ctlproxy.AlertProxySilent alert for each
-// configured proxy silent for ctlproxy.SilentAfter, counting from its last
-// feed request or this process's Open; ctlproxy.Silent marks each so it is
-// alerted once per silence. The reaper delivers the queue.
+// checkProxies opens a silence episode (ctlproxy.MarkSilent) for each
+// configured proxy silent for ctlproxy.SilentAfter, then delivers every
+// ctlproxy.AlertProxySilent alert still pending, this run's or an earlier
+// run's, marking each delivered only once the alerter took it. One the
+// alerter refuses stays pending for the next pass.
func (c *Controller) checkProxies(ctx context.Context) error {
- ids := c.proxies.Load()
- if ids == nil || len(*ids) == 0 {
- return nil
+ var ids []hostedwire.KeyID
+ if p := c.proxies.Load(); p != nil {
+ ids = *p
}
- var silent []hostedwire.KeyID
- now := c.store.Clock().Now()
+ var pending []ctlproxy.Silence
err := c.store.Tx(ctx, func(tx *sql.Tx) error {
- var err error
- silent, err = ctlproxy.Silent(ctx, tx, *ids, time.Duration(now), time.Duration(c.store.OpenedAt()))
+ err := ctlproxy.MarkSilent(ctx, tx, ids, time.Duration(c.store.Clock().Now()), time.Duration(c.store.OpenedAt()),
+ time.Duration(c.store.lastRun))
+ if err == nil {
+ pending, err = ctlproxy.Pending(ctx, tx)
+ }
return err
})
- for _, id := range silent {
- c.reap.raise(Alert{Kind: ctlproxy.AlertProxySilent, At: now,
- Detail: fmt.Sprintf("proxy %s has not asked for the launch feed for %v or more", id, ctlproxy.SilentAfter)})
+ errs := []error{err}
+ for _, s := range pending {
+ if err := c.alerter.Alert(ctx, Alert{Kind: ctlproxy.AlertProxySilent, At: T(s.At), Detail: s.Detail()}); err != nil {
+ errs = append(errs, fmt.Errorf("hostedctl: deliver %s alert: %w", ctlproxy.AlertProxySilent, err))
+ continue
+ }
+ errs = append(errs, c.store.Tx(ctx, func(tx *sql.Tx) error { return ctlproxy.Delivered(ctx, tx, s) }))
}
- return err
+ return errors.Join(errs...)
}
// proxyLastFeeds returns, for each configured proxy that has asked for the
diff --git a/internal/hostedctl/schema/0004_proxy.sql b/internal/hostedctl/schema/0004_proxy.sql
index 6302d617..d51708cf 100644
--- a/internal/hostedctl/schema/0004_proxy.sql
+++ b/internal/hostedctl/schema/0004_proxy.sql
@@ -1,10 +1,10 @@
-- Schema version 4: the controller as the egress proxies' client CA
-- (package ctlproxy). Controller times end _t, as in version 1.
--- One proxy code per launch intent, saved with it. Only the code's SHA-256
--- (of its base64url text) is kept here. The code itself is in the VM's
--- bootstrap, inside jobs.spec_json: the provider request the intent
--- re-sends as it is on replay, which holds the instance code too.
+-- One proxy code per launch intent. Only the code's SHA-256 (of its
+-- base64url text) is kept, here. The code itself is stored nowhere: it is
+-- derived from the launch ID under the controller's proxy-code key, and the
+-- bootstrap saved in jobs.spec_json leaves it out (ctlproxy.DeriveCode).
CREATE TABLE proxy_codes (
launch_id TEXT PRIMARY KEY REFERENCES jobs(launch_id),
attempt_id TEXT NOT NULL UNIQUE REFERENCES jobs(attempt_id),
@@ -37,12 +37,15 @@ CREATE TABLE proxy_certs (
CREATE INDEX proxy_certs_attempt ON proxy_certs(attempt_id);
CREATE INDEX proxy_certs_revoked ON proxy_certs(not_after_t) WHERE revoked_t IS NOT NULL;
--- Each proxy key's last feed request, and whether its current silence has
--- been alerted (proxy_silent fires once per silence).
+-- Each proxy key's last feed request, and its silence episode:
+-- proxy_silent is raised once per silence (silent_alerted), and stays
+-- pending (alert_pending) until the alerter takes it, across restarts.
CREATE TABLE proxy_polls (
key_id TEXT PRIMARY KEY,
last_t INTEGER, -- absent for a key alerted before it ever asked
- silent_alerted INTEGER NOT NULL DEFAULT 0 CHECK (silent_alerted IN (0, 1))
+ silent_alerted INTEGER NOT NULL DEFAULT 0 CHECK (silent_alerted IN (0, 1)),
+ alert_pending INTEGER NOT NULL DEFAULT 0 CHECK (alert_pending IN (0, 1)),
+ alerted_t INTEGER -- when the current episode was raised; absent before any
);
-- The last feed serial: one row. Each feed takes the next.
diff --git a/internal/hostedctl/sim_test.go b/internal/hostedctl/sim_test.go
index 30a196c7..a3f8b8b5 100644
--- a/internal/hostedctl/sim_test.go
+++ b/internal/hostedctl/sim_test.go
@@ -229,7 +229,7 @@ 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, Certs: ctlcerttest.Set(ctlcerttest.Cert(imgA, "equipo.example.com")), ProxyCA: ctlproxytest.CA(),
+ cfg: Config{Enabled: true, Certs: ctlcerttest.Set(ctlcerttest.Cert(imgA, "equipo.example.com")), ProxyCA: ctlproxytest.CA(), ProxyCodeKey: ctlproxytest.CodeKey(),
ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint, Manifest: testManifest("equipo.example.com")},
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 e621d7bd..fa833636 100644
--- a/internal/hostedctl/store.go
+++ b/internal/hostedctl/store.go
@@ -65,6 +65,7 @@ type Store struct {
host isolatedjob.Clock
clock *CtlClock
restarted bool
+ lastRun T // the checkpoint Open found: the last controller time the previous run recorded (0 when fresh)
mu sync.Mutex
pending []outboxAlert // undelivered rows of alert_outbox, oldest first
@@ -247,7 +248,7 @@ func (s *Store) restoreClock(ctx context.Context) error {
return fmt.Errorf("hostedctl: restore clock: %w", err)
}
s.clock = &CtlClock{base: base, monoAtOpen: monoNow, c: s.host}
- s.restarted = restarted
+ s.restarted, s.lastRun = restarted, T(cpT)
s.pending = pending
return nil
}
diff --git a/internal/hostedctl/store_test.go b/internal/hostedctl/store_test.go
index a5077226..fb21f170 100644
--- a/internal/hostedctl/store_test.go
+++ b/internal/hostedctl/store_test.go
@@ -557,7 +557,7 @@ func testFingerprint(d isolatedjob.ImageDigest, s isolatedjob.Size) string {
// testConfig is a Config with only the required fields set.
func testConfig() Config {
- return Config{ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint, Certs: testCerts(), ProxyCA: ctlproxytest.CA()}
+ return Config{ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint, Certs: testCerts(), ProxyCA: ctlproxytest.CA(), ProxyCodeKey: ctlproxytest.CodeKey()}
}
func TestNewRefusesNilDependency(t *testing.T) {
@@ -595,6 +595,11 @@ func TestNewRefusesNilDependency(t *testing.T) {
if got, err := New(noCA, full); err == nil || got != nil || !strings.Contains(err.Error(), "proxy client CA") {
t.Errorf("New with no proxy client CA = (%v, %v), want (nil, an error naming the CA)", got, err)
}
+ shortKey := testConfig()
+ shortKey.ProxyCodeKey = shortKey.ProxyCodeKey[:31]
+ if got, err := New(shortKey, full); err == nil || got != nil || !strings.Contains(err.Error(), "proxy code key") {
+ t.Errorf("New with a 31-byte proxy code key = (%v, %v), want (nil, an error naming the key)", got, err)
+ }
}
// TestProviderNamespaceBound: the first controller binds the database to its