oficina / equipo Public

hostedctl: proxy client certificates and the signed launch feed

The controller is the egress proxies' client CA (ctlproxy). Proxy-only
routes: GET /v1/proxy/feed, POST /v1/proxy/redeem and /v1/proxy/renew.
A VM's single-use proxy code (stored as SHA-256) buys a 15-minute
certificate, capped at the job's deadline, bound by its URI SAN to
launch, attempt, VM and epoch; the code's two-minute window opens when
the controller first sees the VM running. Renewal once per serial, same
epoch; stop, stop proof and a new epoch revoke every serial. The feed
lists live launches and revoked serials, signed per request. A proxy
silent for 3 minutes raises proxy_silent once; its last feed is a metric.

The launch payload is now hostedwire.BootstrapV2: services from the
intent's snapshot, proxies from the manifest at save, a fresh proxy
code; Replay re-sends the saved payload. Migration 0004_proxy.sql; the
controller config gains the proxy CA files; hostedctl's budget record
rises for the wiring.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 665b5c375f99cee70773f5a5e36d47c9f41693e6 parent e26edd0
29 files changed, +2,107 −62
  • .rastrillo/budgets.txt +1 −1
  • cmd/equipo-hosted-controller/config.go +52 −12
  • cmd/equipo-hosted-controller/config_test.go +50 −0
  • cmd/equipo-hosted-controller/crashpoint_test.go +3 −2
  • cmd/equipo-hosted-controller/main_test.go +4 −3
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +29 −0
  • internal/hostedclient/client.go +1 −0
  • internal/hostedclient/client_test.go +3 −1
  • internal/hostedclient/driver_test.go +10 −1
  • internal/hostedctl/controller.go +12 −0
  • internal/hostedctl/ctlproxy/ca.go +466 −0
  • internal/hostedctl/ctlproxy/ca_test.go +292 −0
  • internal/hostedctl/ctlproxy/ctlproxytest/ctlproxytest.go +91 −0
  • internal/hostedctl/ctlproxy/env_test.go +357 −0
  • internal/hostedctl/ctlproxy/feed.go +151 −0
  • internal/hostedctl/ctlproxy/feed_test.go +291 −0
  • internal/hostedctl/http.go +15 −5
  • internal/hostedctl/launch.go +49 −23
  • internal/hostedctl/launch_test.go +16 −8
  • internal/hostedctl/metrics.go +8 −0
  • internal/hostedctl/proxy.go +125 −0
  • internal/hostedctl/reaper.go +1 −0
  • internal/hostedctl/resume.go +4 −0
  • internal/hostedctl/schema/0004_proxy.sql +52 −0
  • internal/hostedctl/sim_model_test.go +1 −1
  • internal/hostedctl/sim_test.go +2 −1
  • internal/hostedctl/stop.go +13 −2
  • internal/hostedctl/store.go +1 −1
  • internal/hostedctl/store_test.go +7 −1
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 295d74d0..b4ad89df 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 5465 9325 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.
+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.
diff --git a/cmd/equipo-hosted-controller/config.go b/cmd/equipo-hosted-controller/config.go
index 96d2a942..24649b79 100644
--- a/cmd/equipo-hosted-controller/config.go
+++ b/cmd/equipo-hosted-controller/config.go
@@ -14,6 +14,7 @@ import (
"amadan.net/oficina/equipo/internal/hostedctl"
"amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
"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"
"amadan.net/oficina/equipo/internal/isolatedjob/awsjob"
@@ -69,10 +70,17 @@ type fileConfig struct {
// starting.
CertKeysFile string `json:"cert_keys_file"`
CertificatesFile string `json:"certificates_file"`
+ // ProxyCACertFile and ProxyCAKeyFile are the egress proxies' client CA
+ // (ctlproxy.NewCA), which signs each VM's proxy certificate: one PEM
+ // certificate, and its ECDSA P-256 key in PEM, which group and others
+ // must not be able to read.
+ ProxyCACertFile string `json:"proxy_ca_cert_file"`
+ ProxyCAKeyFile string `json:"proxy_ca_key_file"`
}
-// keyEntry is one verify key: its ID, role (instance or operator) and
-// ed25519 public key in standard base64.
+// keyEntry is one verify key: its ID, role (instance, operator or proxy)
+// and ed25519 public key in standard base64. The proxy keys are also the
+// proxies the controller expects to ask for the launch feed.
type keyEntry struct {
ID string `json:"id"`
Role string `json:"role"`
@@ -138,7 +146,8 @@ 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} {
+ "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} {
if v == "" {
return config{}, fmt.Errorf("%s is required", name)
}
@@ -160,9 +169,47 @@ func (fc fileConfig) check() (config, error) {
if c.ctl.Certs, err = readCerts(fc.CertKeysFile, fc.CertificatesFile, c.aws.ImageVersion); err != nil {
return config{}, err
}
+ if c.ctl.ProxyCA, err = readProxyCA(fc.ProxyCACertFile, fc.ProxyCAKeyFile); err != nil {
+ return config{}, err
+ }
return c, nil
}
+// readProxyCA reads the proxies' client CA. A key file that group or others
+// may read is refused.
+func readProxyCA(certPath, keyPath string) (*ctlproxy.CA, error) {
+ cert, err := os.ReadFile(certPath)
+ if err != nil {
+ return nil, fmt.Errorf("proxy client CA: %w", err)
+ }
+ key, err := readPrivate(keyPath, "proxy client CA key")
+ if err != nil {
+ return nil, err
+ }
+ ca, err := ctlproxy.NewCA(cert, key)
+ if err != nil {
+ return nil, fmt.Errorf("proxy client CA %s (key %s): %w", certPath, keyPath, err)
+ }
+ return ca, 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) {
+ info, err := os.Stat(path)
+ if err != nil {
+ return nil, fmt.Errorf("%s: %w", what, err)
+ }
+ if info.Mode().Perm()&0o077 != 0 {
+ return nil, fmt.Errorf("%s %s is readable by group or others (mode %v)", what, path, info.Mode().Perm())
+ }
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return nil, fmt.Errorf("%s: %w", what, err)
+ }
+ return raw, nil
+}
+
// readCerts reads the certificate key file and certificate file into a new
// set bound to the adapter's image versions: a certificate whose signed
// image version is not what images launches its digest with, at some size,
@@ -224,16 +271,9 @@ func checkListen(name, addr string) (string, error) {
// readSigningKey reads the base64 seed in path. A file that group or others
// may read is refused.
func readSigningKey(path string) (ed25519.PrivateKey, error) {
- info, err := os.Stat(path)
+ raw, err := readPrivate(path, "signing key")
if err != nil {
- return nil, fmt.Errorf("signing key: %w", err)
- }
- if info.Mode().Perm()&0o077 != 0 {
- return nil, fmt.Errorf("signing key %s is readable by group or others (mode %v)", path, info.Mode().Perm())
- }
- raw, err := os.ReadFile(path)
- if err != nil {
- return nil, fmt.Errorf("signing key: %w", err)
+ return nil, err
}
seed, err := base64.StdEncoding.Strict().DecodeString(strings.TrimSpace(string(raw)))
if err != nil || len(seed) != ed25519.SeedSize {
diff --git a/cmd/equipo-hosted-controller/config_test.go b/cmd/equipo-hosted-controller/config_test.go
index b8f63e44..cf8d9408 100644
--- a/cmd/equipo-hosted-controller/config_test.go
+++ b/cmd/equipo-hosted-controller/config_test.go
@@ -16,6 +16,7 @@ import (
"amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
"amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
"amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/rastrillo/rastrillo/budget"
@@ -49,6 +50,14 @@ func validConfig(t *testing.T, dir string) fileConfig {
if err := os.WriteFile(certsPath, ctlcerttest.CertsJSON(testCert), 0o600); err != nil {
t.Fatal(err)
}
+ caCert, caKey := ctlproxytest.PEM()
+ caCertPath, caKeyPath := filepath.Join(dir, "proxy-ca.crt"), filepath.Join(dir, "proxy-ca.key")
+ if err := os.WriteFile(caCertPath, caCert, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(caKeyPath, caKey, 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",
@@ -66,6 +75,8 @@ func validConfig(t *testing.T, dir string) fileConfig {
EgressManifestFile: manifestPath,
CertKeysFile: certKeysPath,
CertificatesFile: certsPath,
+ ProxyCACertFile: caCertPath,
+ ProxyCAKeyFile: caKeyPath,
}
}
@@ -252,6 +263,19 @@ func load(t *testing.T, dir string, body []byte) (config, error) {
return loadConfig(path, func(string) string { return "" })
}
+// writePair overwrites fc's proxy CA files with cert and key, each only
+// when given.
+func writePair(t *testing.T, fc *fileConfig, cert, key []byte) {
+ t.Helper()
+ for path, b := range map[string][]byte{fc.ProxyCACertFile: cert, fc.ProxyCAKeyFile: key} {
+ if b != nil {
+ if err := os.WriteFile(path, b, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+}
+
func loadFC(t *testing.T, dir string, fc fileConfig) (config, error) {
t.Helper()
b, err := json.Marshal(fc)
@@ -300,6 +324,16 @@ func TestConfigRefusesMissingListenOrKeys(t *testing.T) {
"unqualified connector": func(f *fileConfig) { f.ConnectorARN = "arn:aws:lambda:eu-west-1:123456789012:network-connector:egress" },
"egress in slice 1a": func(f *fileConfig) { f.Egress = []string{"10.0.1.5:443"} },
"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 = "" },
+ "proxy CA not a CA": func(f *fileConfig) {
+ cert, key := ctlproxytest.SelfSigned(false)
+ writePair(t, f, cert, key)
+ },
+ "proxy CA key of another": func(f *fileConfig) {
+ _, other := ctlproxytest.SelfSigned(true)
+ writePair(t, f, nil, other)
+ },
} {
sub := t.TempDir()
fc := validConfig(t, sub)
@@ -318,6 +352,22 @@ func TestConfigRefusesMissingListenOrKeys(t *testing.T) {
if _, err := loadFC(t, sub, fc); err == nil || !strings.Contains(err.Error(), "readable") {
t.Errorf("world-readable signing key: %v, want a refusal", err)
}
+ // So is a proxy CA key others may read.
+ sub = t.TempDir()
+ fc = validConfig(t, sub)
+ if err := os.Chmod(fc.ProxyCAKeyFile, 0o640); err != nil {
+ t.Fatal(err)
+ }
+ 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)
+ }
+ // 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 {
+ t.Errorf("config with a proxy key: %v, keys %v; want it to load with the proxy CA", err, c.keys)
+ }
// The file is decoded strictly.
b, _ := json.Marshal(validConfig(t, sub))
diff --git a/cmd/equipo-hosted-controller/crashpoint_test.go b/cmd/equipo-hosted-controller/crashpoint_test.go
index 791d902a..b423e65f 100644
--- a/cmd/equipo-hosted-controller/crashpoint_test.go
+++ b/cmd/equipo-hosted-controller/crashpoint_test.go
@@ -11,6 +11,7 @@ import (
"time"
"amadan.net/oficina/equipo/internal/hostedctl"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
@@ -28,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(),
+ c, err := hostedctl.New(hostedctl.Config{Enabled: true, Certs: testCerts(), ProxyCA: ctlproxytest.CA(),
ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
Manifest: testEgress},
hostedctl.Deps{Store: store, Runner: run, Auditor: fake, Alerter: nopAlerter{}})
@@ -60,7 +61,7 @@ func TestCrashAfterLaunch(t *testing.T) {
path := filepath.Join(t.TempDir(), "hosted.db")
key := hostedwire.VerifyKey{Public: instKey.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}
q := hostedctl.LaunchRequest{AttemptID: "crash-1", TaskID: "task-1", Account: "acct-1", Image: testDigest,
- Size: isolatedjob.SizeSmall, MaxLifetime: time.Hour, InstanceCode: "code-1",
+ Size: isolatedjob.SizeSmall, MaxLifetime: time.Hour, InstanceCode: "aW5zdGFuY2UtY29kZS0xLTAwMDAwMDAwMDAwMC0wMDQ",
Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: 1796083200000}
t.Setenv(crashAfterLaunchEnv, "1")
diff --git a/cmd/equipo-hosted-controller/main_test.go b/cmd/equipo-hosted-controller/main_test.go
index b4cb3433..fe80d12a 100644
--- a/cmd/equipo-hosted-controller/main_test.go
+++ b/cmd/equipo-hosted-controller/main_test.go
@@ -20,6 +20,7 @@ import (
"time"
"amadan.net/oficina/equipo/internal/hostedctl"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
@@ -62,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(),
+ c, err := hostedctl.New(hostedctl.Config{Enabled: true, Certs: testCerts(), ProxyCA: ctlproxytest.CA(),
ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
Manifest: testEgress},
hostedctl.Deps{Store: store, Runner: run, Auditor: fake, Alerter: nopAlerter{}})
@@ -235,7 +236,7 @@ func TestShutdownCancelsReaperWithRequests(t *testing.T) {
tc := newTestCtl(t, func(f *isolatedjob.Fake) isolatedjob.Runner { gb.Runner = f; return gb })
if _, err := tc.c.Launch(context.Background(), instID, hostedwire.VerifyKey{Role: hostedwire.RoleInstance},
hostedctl.LaunchRequest{AttemptID: "a1", TaskID: "t1", Account: "acct", Image: testDigest,
- Size: isolatedjob.SizeSmall, MaxLifetime: 2 * time.Hour, InstanceCode: "code-1",
+ Size: isolatedjob.SizeSmall, MaxLifetime: 2 * time.Hour, InstanceCode: "aW5zdGFuY2UtY29kZS0xLTAwMDAwMDAwMDAwMC0wMDQ",
Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: 1796083200000}); err != nil {
t.Fatal(err)
}
@@ -322,7 +323,7 @@ func TestShutdownDrainsRequests(t *testing.T) {
}()
body, _ := json.Marshal(hostedwire.LaunchRequest{AttemptID: "a1", TaskID: "t1", Account: "acct", Image: testDigest,
- Size: isolatedjob.SizeSmall, MaxLifetimeMS: (2 * time.Hour).Milliseconds(), InstanceCode: "code-1",
+ Size: isolatedjob.SizeSmall, MaxLifetimeMS: (2 * time.Hour).Milliseconds(), InstanceCode: "aW5zdGFuY2UtY29kZS0xLTAwMDAwMDAwMDAwMC0wMDQ",
Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: 1796083200000})
req, err := http.NewRequest(http.MethodPost, "https://"+apiLn.Addr().String()+"/v1/jobs", bytes.NewReader(body))
if err != nil {
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index b3e5c905..09f5786f 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -90,3 +90,32 @@ Also run: `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hos
17. The old coupling restored: the stop-time branch of `abandonReason` returned `""` for the expiry. Command: `go test ./internal/hostedctl -run 'TestLaunchByEnforced|TestLaunchExpiredDuringDispatchOverHTTP' -count=1`. Observed: FAIL, `admission_test.go:340: TestLaunchByEnforced/stop_time_and_launch-by_pass_while_the_dispatch_is_recorded: Launch = ({... State:abandoned ... StopIn:0s}, <nil>), want (zero view, ErrLaunchExpired)` and `admission_test.go:473: launch with both deadlines passing at dispatch = 200 {"attempt_id":"a1",...,"state":"abandoned",...}, want a signed 409 launch_expired`. Restored.
Also run: `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedclient ./cmd/equipo-hosted-controller ./internal/isolatedjob/awsjob -count=1` ok; staticcheck v0.7.0 on `./internal/hostedctl/...` ok; `make budget build vet` ok after raising the `internal/hostedctl` record to 5465/9325.
+
+## Task 4
+
+The controller as the proxies' client CA, the signed launch feed, and the BootstrapV2 launch payload. New package `internal/hostedctl/ctlproxy` (`ca.go`, `feed.go`; test CA and CSRs in `ctlproxytest`): `CA` (`NewCA` from a PEM certificate and ECDSA P-256 key, refusing a non-CA or a mismatched key), `Redeem`, `Renew`, `Feed`, `Revoke`, `SeenRunning`, `Silent`, `FeedAges`, `LaunchIdentity.URI`/`ParseLaunchURI` (`equipo-launch://<launch_id>/<attempt_id>/<vm_ref>/<epoch>`, attempt and VM path-escaped), `CertLifetime` 15 min, `FeedLifetime` 5 min, `CodeWindow` 2 min, `SilentAfter` 3 min, `AlertProxySilent` = `proxy_silent`. Migration `internal/hostedctl/schema/0004_proxy.sql` (ruling: 0004, as 0003 is Task 3's): `proxy_codes` (SHA-256 of the code's text only; immutable), `proxy_certs`, `proxy_polls`, `proxy_feed`. hostedctl wiring only (`proxy.go`, budget record raised to 5662/9340 with the reason): routes `GET /v1/proxy/feed`, `POST /v1/proxy/redeem`, `POST /v1/proxy/renew` for the `proxy` role only (`CheckVerifyKeys` accepts it; the existing role check gives every other key 403 there, and a proxy key 403 everywhere else); `cert-report` is left to Task 13. A refusal is signed 403 `proxy_refused` (all reasons alike), audited `proxy_refused`; `hostedclient` maps the code to `ErrForbidden`. `Config.ProxyCA` is required. Launch payload: `buildSpec` writes a `hostedwire.BootstrapV2` (services from the snapshot, proxies and CA pin from the manifest at save, a proxy code minted in transaction 1, the instance code from the request); `checkSpec` sizes it with placeholders after the services are known; `Replay` re-sends the saved `spec_json` unchanged. The code's plaintext lives only in that saved provider request, as the instance code already did; `proxy_codes` keeps its hash. The code window opens when `mirrorState` first records the VM running (Refresh); a later sighting does not move it. Revocation: on a stop request (`requestStop`), on stop proof (`writeProof`, so a VM that ends on its own) and on a new epoch (`commitResume`). The reaper pass queues one `proxy_silent` per silence for each configured proxy key (from the Handler's key table) silent for 3 minutes since its last feed request or the controller's start; metric `equipo_hosted_proxy_last_feed_seconds{proxy}`. The controller config gains `proxy_ca_cert_file` and `proxy_ca_key_file` (required; the key must not be readable by group or others). Test instance codes are now 32 bytes in base64url, as BootstrapV2 needs.
+
+RED: `go test ./internal/hostedctl/... -run 'TestRedeem|TestCertCapped|TestRenew|TestStopRevokes|TestFeed|TestProxyRole|TestProxySilent|TestReplaySendsSnapshotServices' -count=1` failed to build: `no non-test Go files in .../internal/hostedctl/ctlproxy` (ctlproxy and ctlproxytest build failed).
+
+GREEN: `go test ./internal/hostedctl/... -run 'TestRedeem|TestCertCapped|TestRenew|TestStopRevokes|TestFeed|TestProxyRole|TestProxySilent' -count=1`: `ok internal/hostedctl/ctlproxy` (TestRedeemSingleUse, TestRedeemBindsVMRef, TestRedeemExpires, TestCertCappedAtDeadline, TestRenewOncePerSerial, TestRenewNeedsCurrentEpoch, TestStopRevokesSerials, TestFeedSignedAndListsOnlyLive, TestProxyRoleOnlyOnProxyRoutes, TestProxySilentAlertOnce). Also new: TestReplaySendsSnapshotServices, TestNewCARefuses, TestLaunchURI (ctlproxy); TestNewRefusesNilDependency gains "no proxy client CA"; TestLaunchSavesIntentBeforeProvider checks the V2 bootstrap; TestConfigRefusesMissingListenOrKeys gains the CA files, a group-readable CA key and a proxy key.
+
+The suite caught one bug while wiring: the code hash shadowed the request hash in `saveIntent` (TestLaunchIdempotentOnAttempt, TestConcurrentLaunchSameAttempt, TestLaunchSnapshotsServices failed with `conflict: attempt att-1 was asked for with a different request`); renamed to `codeHash`.
+
+Mutation checks (each applied by script, the named test run, then restored and checked byte for byte against the saved file):
+
+1. Skip the VM reference check (`case false && l.VMRef != q.VMRef`, `ctlproxy/ca.go` Redeem). Command: `CGO_ENABLED=0 go test ./internal/hostedctl/ctlproxy -run 'TestRedeemBindsVMRef' -count=1`. Observed: FAIL, `ca_test.go:112: att-1's code from att-2's VM = 200 {"cert":"MIIB9T...","not_after_ns":900000000000}, want 403 proxy_refused`. Restored.
+2. Allow a second renewal of a serial (`case renewed:` became `case false:`, `case revoked.Valid:` became `case revoked.Valid && !renewed:`, and the renewal UPDATE lost `AND renewed = 0 AND revoked_t IS NULL`). Command: `... -run 'TestRenewOncePerSerial' -count=1`. Observed: FAIL, `ca_test.go:210: second renewal of one serial = 200 {"cert":"MIIB9T...`, want 403 proxy_refused. Restored.
+3. Keep revoked serials out of the feed (the revoked query's `revoked_t IS NOT NULL` became `revoked_t IS NULL AND revoked_t IS NOT NULL`, `ctlproxy/feed.go`). Command: `... -run 'TestFeedSignedAndListsOnlyLive|TestStopRevokesSerials|TestRenewOncePerSerial|TestRenewNeedsCurrentEpoch' -count=1`. Observed: FAIL, `feed_test.go:57: feed revoked = [], want the stopped launch's c4168e6f... only, not the live 6e95b59c...`, `feed_test.go:87: feed before any stop = revoked [], 3 launches; want af83f0fc... (renewed) and 3`, `ca_test.go:212: feed revoked = [], want fe01a46f... and not a6cc54e1...`, `ca_test.go:267: feed revoked = [] after the resume, want ff6601e7...`. Restored.
+4. Build outgoing services from current config (dispatch, after `decodeSpec`, rewrote the bootstrap's services from `c.cfg.Manifest.For(j.purpose)`, `launch.go`). Command: `... -run 'TestReplaySendsSnapshotServices' -count=1`. Observed: FAIL, `feed_test.go:262: launches sent for att-1 = 2, bootstraps equal false; want 2, byte for byte`. Restored.
+5. (extra) No code window end (`case false && now.T-... > CodeWindow`). Command: `... -run 'TestRedeemExpires' -count=1`. Observed: FAIL, `ca_test.go:142: redemption 2 min 1 s after the VM was first seen running = 200 {"cert":...`. Restored.
+6. (extra) Code reusable (`case false && redeemed.Valid`, and the redeem UPDATE lost `AND redeemed_t IS NULL`). Command: `... -run 'TestRedeemSingleUse' -count=1`. Observed: FAIL, `ca_test.go:96: second redemption = 200 {"cert":...`. Restored.
+7. (extra) No deadline cap (`now.Wall.Add(CertLifetime)`). Command: `... -run 'TestCertCappedAtDeadline' -count=1`. Observed: FAIL, `ca_test.go:172: short job's certificate NotAfter = 2026-11-30 12:16:00 +0000 UTC, want its deadline 2026-11-30 12:11:00 +0000 UTC`. Restored.
+8. (extra) Renewal ignores the epoch (`case false && l.Epoch != old.Epoch`). Command: `... -run 'TestRenewNeedsCurrentEpoch' -count=1`. Observed: FAIL, `ca_test.go:234: renewal after the epoch moved = 200 {"cert":...`. Restored.
+9. (extra) A stop request revokes nothing (`requestStop` revoked attempt "none", `stop.go`). Command: `... -run 'TestStopRevokesSerials' -count=1`. Observed: FAIL, `feed_test.go:95: feed revoked = [2cdce38a...] after the stop, want 2cdce38a... and 5cc7d371...`. Restored.
+10. (extra) Stop proof revokes nothing (`writeProof` revoked attempt "none"). Same command. Observed: FAIL, `feed_test.go:112: feed revoked = [c36f12cc... e9f174c0...] after att-2 ended, want b4288422...`. Restored.
+11. (extra) A resume revokes nothing (`commitResume` revoked attempt "none", `resume.go`). Command: `... -run 'TestRenewNeedsCurrentEpoch' -count=1`. Observed: FAIL, `ca_test.go:267: feed revoked = [] after the resume, want ff6601e7...`. Restored.
+12. (extra) The silence alert repeats (`if alerted || ...` became `if now-from < SilentAfter`, `feed.go`). Command: `... -run 'TestProxySilentAlertOnce' -count=1`. Observed: FAIL, `feed_test.go:202: proxy_silent alerts = [{Kind:proxy_silent Detail:proxy proxy-1 has not asked for the launch feed for 3m0s or more At:180000000000}], want one each for []`. Restored.
+13. (extra) A later sighting moves the window (`SeenRunning` lost `AND running_t IS NULL`). Command: `... -run 'TestRedeemExpires' -count=1`. Observed: FAIL, `ca_test.go:142: redemption 2 min 1 s after the VM was first seen running = 200 {"cert":...`. Restored.
+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.
diff --git a/internal/hostedclient/client.go b/internal/hostedclient/client.go
index 4c49cd95..5c37aff5 100644
--- a/internal/hostedclient/client.go
+++ b/internal/hostedclient/client.go
@@ -97,6 +97,7 @@ var refusals = map[string]struct {
"not_certified": {http.StatusBadRequest, ErrNotCertified},
"launch_expired": {http.StatusConflict, ErrLaunchExpired},
"forbidden": {http.StatusForbidden, ErrForbidden},
+ "proxy_refused": {http.StatusForbidden, ErrForbidden}, // proxy routes only; an instance key never gets it
"not_found": {http.StatusNotFound, ErrNotFound},
"too_large": {http.StatusRequestEntityTooLarge, ErrTooLarge},
"stop_pending": {http.StatusAccepted, ErrStopPending},
diff --git a/internal/hostedclient/client_test.go b/internal/hostedclient/client_test.go
index 76e34db4..0d04e5cd 100644
--- a/internal/hostedclient/client_test.go
+++ b/internal/hostedclient/client_test.go
@@ -23,6 +23,7 @@ import (
"amadan.net/oficina/equipo/internal/hostedctl"
"amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
"amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
@@ -78,6 +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(),
ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
Manifest: m},
hostedctl.Deps{Store: store, Runner: fake, Auditor: fake, Alerter: nopAlerter{}})
@@ -144,7 +146,7 @@ var testEgress = ctlegress.Manifest{
func launchReq(attempt string) hostedwire.LaunchRequest {
return hostedwire.LaunchRequest{AttemptID: attempt, TaskID: "task-1", Account: "acct-1", Image: imgA,
- Size: isolatedjob.SizeSmall, MaxLifetimeMS: (2 * time.Hour).Milliseconds(), InstanceCode: "code-test-1",
+ Size: isolatedjob.SizeSmall, MaxLifetimeMS: (2 * time.Hour).Milliseconds(), InstanceCode: "aW5zdGFuY2UtY29kZS10ZXN0LTEtMDAwMDAwMC0wMDM",
Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: 1796083200000}
}
diff --git a/internal/hostedclient/driver_test.go b/internal/hostedclient/driver_test.go
index 3082d00d..f1a26115 100644
--- a/internal/hostedclient/driver_test.go
+++ b/internal/hostedclient/driver_test.go
@@ -9,6 +9,8 @@ import (
"bytes"
"context"
"crypto/ed25519"
+ "crypto/sha256"
+ "encoding/base64"
"errors"
"fmt"
"io"
@@ -43,10 +45,17 @@ type liveDriver struct {
func (d *liveDriver) launchRequest(attempt string) hostedwire.LaunchRequest {
return hostedwire.LaunchRequest{AttemptID: attempt, TaskID: "task17-live", Account: "task17-live",
Image: d.image, Size: isolatedjob.SizeSmall, MaxLifetimeMS: d.lifetime.Milliseconds(),
- InstanceCode: "task17-code-" + attempt, Purpose: hostedwire.PurposeChecks, Person: "task17-live",
+ InstanceCode: liveCode(attempt), Purpose: hostedwire.PurposeChecks, Person: "task17-live",
LaunchByUnixMS: 1796083200000}
}
+// liveCode is attempt's instance code: 32 bytes (the SHA-256 of a name for
+// it) in base64url, the form hostedwire.BootstrapV2 needs.
+func liveCode(attempt string) string {
+ sum := sha256.Sum256([]byte("task17-code-" + attempt))
+ return base64.RawURLEncoding.EncodeToString(sum[:])
+}
+
// vmGuard stops an attempt's VM when the step that registered it ends
// without releasing it.
type vmGuard struct{ released bool }
diff --git a/internal/hostedctl/controller.go b/internal/hostedctl/controller.go
index 8364c684..4c3ef66f 100644
--- a/internal/hostedctl/controller.go
+++ b/internal/hostedctl/controller.go
@@ -7,9 +7,12 @@ import (
"net/netip"
"reflect"
"slices"
+ "sync/atomic"
"amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
"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"
)
@@ -45,6 +48,9 @@ type Config struct {
// Manifest is the egress manifest. Launch snapshots Manifest.For(purpose)
// into each new intent; an unset name refuses the launch.
Manifest ctlegress.Manifest
+ // ProxyCA is the egress proxies' client CA: it signs each VM's
+ // certificate when the VM redeems its proxy code (ctlproxy).
+ ProxyCA *ctlproxy.CA
}
// ErrProviderMismatch: the database belongs to another provider namespace
@@ -76,6 +82,10 @@ type Controller struct {
attempts attemptLocks // per-attempt locks (attemptlock.go)
reap reapState // the reaper's in-memory state (reaper.go)
ownership ownershipLock // dispatches against the orphan reaper's final check (reaper.go)
+
+ // proxies are the proxy keys Handler was given, which the reaper
+ // watches for silence (proxy.go).
+ proxies atomic.Pointer[[]hostedwire.KeyID]
// beforeMark, when set, runs in dispatch after its gates pass and just
// before the dispatch marker is recorded. Tests use it to hold the store
// there; production leaves it nil.
@@ -106,6 +116,8 @@ func New(cfg Config, d Deps) (*Controller, error) {
return nil, errors.New("hostedctl: controller needs a provider namespace and fingerprint")
case cfg.Certs == nil:
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")
}
if err := d.Store.bindProvider(context.Background(), cfg.ProviderNamespace); err != nil {
return nil, err
diff --git a/internal/hostedctl/ctlproxy/ca.go b/internal/hostedctl/ctlproxy/ca.go
new file mode 100644
index 00000000..6ac89623
--- /dev/null
+++ b/internal/hostedctl/ctlproxy/ca.go
@@ -0,0 +1,466 @@
+// Package ctlproxy makes the controller the egress proxies' client CA
+// (spec §6, plan decision S2-8) and writes their signed launch feed.
+//
+// A VM's bootstrap carries a single-use proxy code. The VM sends it, with
+// a certificate request for a fresh ECDSA P-256 key, through a proxy's
+// bootstrap listener to POST /v1/proxy/redeem; the controller answers with
+// a client certificate bound to the launch, the VM and the epoch, which the
+// VM renews once per serial (POST /v1/proxy/renew) for as long as the job
+// lives. The proxies trust that CA, and poll GET /v1/proxy/feed for which
+// launches are live and which serials are revoked.
+//
+// The package keeps its own tables (schema version 4, 0004_proxy.sql in
+// hostedctl) and reads the jobs table, never writing it, inside the
+// controller's transactions: every function takes the transaction and the
+// controller time hostedctl hands it.
+package ctlproxy
+
+import (
+ "context"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "database/sql"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "math/big"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+const (
+ // CertLifetime is the longest a client certificate lives. It also
+ // ends at the job's deadline, whichever is earlier.
+ CertLifetime = 15 * time.Minute
+ // CodeWindow is how long a proxy code may be redeemed, from the moment
+ // the controller first sees the VM running.
+ CodeWindow = 2 * time.Minute
+ // certBackdate puts a certificate's NotBefore this far before its
+ // issue, so a proxy whose wall clock is a little behind the
+ // controller's still accepts a fresh certificate.
+ certBackdate = time.Minute
+ // URIScheme is the scheme of a certificate's one URI SAN.
+ URIScheme = "equipo-launch"
+ // CodePlaceholder is a well-formed proxy code (32 zero bytes) of the
+ // real length, for sizing a bootstrap before the code is drawn.
+ CodePlaceholder = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+)
+
+// Audit actions this package writes through the caller's Audit.
+const (
+ ActionIssued = "proxy_cert_issued"
+ ActionRenewed = "proxy_cert_renewed"
+ ActionRefused = "proxy_refused"
+)
+
+var (
+ // ErrRefused is a redemption or renewal the controller will not
+ // grant. Every reason below wraps it; the API answers them alike, so a
+ // refusal tells the caller nothing about another VM's launch.
+ ErrRefused = errors.New("ctlproxy: refused")
+
+ ErrNotLive = fmt.Errorf("%w: the launch is not live", ErrRefused)
+ ErrWrongVM = fmt.Errorf("%w: the VM is not the launch's VM", ErrRefused)
+ ErrWrongCode = fmt.Errorf("%w: wrong proxy code for the launch", ErrRefused)
+ ErrCodeUsed = fmt.Errorf("%w: the proxy code was already used", ErrRefused)
+ ErrNotRunning = fmt.Errorf("%w: the VM was not seen running yet; the code's window has not opened", ErrRefused)
+ ErrCodeExpired = fmt.Errorf("%w: the proxy code expired", ErrRefused)
+ ErrUnknownSerial = fmt.Errorf("%w: unknown serial", ErrRefused)
+ ErrAlreadyRenewed = fmt.Errorf("%w: the serial was already renewed", ErrRefused)
+ ErrRevoked = fmt.Errorf("%w: the serial is revoked", ErrRefused)
+ ErrCertExpired = fmt.Errorf("%w: the certificate expired", ErrRefused)
+ ErrWrongEpoch = fmt.Errorf("%w: the certificate is for another epoch", ErrRefused)
+
+ // ErrRequest is a redemption or renewal that is malformed: it wraps
+ // isolatedjob.ErrInvalid, so the API answers 400.
+ ErrRequest = fmt.Errorf("%w: proxy request", isolatedjob.ErrInvalid)
+)
+
+// Now is the moment a call is judged at: controller time (T, nanoseconds
+// since the controller's epoch) and the wall clock, read together. Every
+// check uses T; the wall clock only dates the certificate.
+type Now struct {
+ T time.Duration
+ Wall time.Time
+}
+
+// Audit writes one audit row in the caller's transaction, by the key that
+// asked.
+type Audit func(attempt, action, reason string) error
+
+// CA is the controller's client CA: an ECDSA P-256 key and its CA
+// certificate.
+type CA struct {
+ cert *x509.Certificate
+ key *ecdsa.PrivateKey
+}
+
+// NewCA reads the CA certificate (one PEM certificate) and its private key
+// (PEM). It refuses a pair that does not match, a key that is not ECDSA
+// P-256, and a certificate that is not a CA allowed to sign certificates.
+func NewCA(certPEM, keyPEM []byte) (*CA, error) {
+ pair, err := tls.X509KeyPair(certPEM, keyPEM)
+ if err != nil {
+ return nil, fmt.Errorf("ctlproxy: client CA: %w", err)
+ }
+ if len(pair.Certificate) != 1 {
+ return nil, fmt.Errorf("ctlproxy: client CA file holds %d certificates, want 1", len(pair.Certificate))
+ }
+ c, err := x509.ParseCertificate(pair.Certificate[0])
+ if err != nil {
+ return nil, fmt.Errorf("ctlproxy: client CA: %w", err)
+ }
+ key, ok := pair.PrivateKey.(*ecdsa.PrivateKey)
+ switch {
+ case !ok || key.Curve != elliptic.P256():
+ return nil, errors.New("ctlproxy: client CA key must be ECDSA P-256")
+ case !c.BasicConstraintsValid || !c.IsCA || c.KeyUsage&x509.KeyUsageCertSign == 0:
+ return nil, errors.New("ctlproxy: client CA certificate is not a CA that may sign certificates")
+ }
+ return &CA{cert: c, key: key}, nil
+}
+
+// Pool is a pool holding only the CA's certificate: what a proxy trusts.
+func (ca *CA) Pool() *x509.CertPool {
+ p := x509.NewCertPool()
+ p.AddCert(ca.cert)
+ return p
+}
+
+// LaunchIdentity is what a client certificate is bound to.
+type LaunchIdentity struct {
+ LaunchID, AttemptID string
+ VMRef isolatedjob.Ref
+ Epoch int64
+}
+
+// URI is the certificate's one URI SAN:
+// equipo-launch://<launch_id>/<attempt_id>/<vm_ref>/<epoch>, with the
+// attempt and VM path-escaped.
+func (id LaunchIdentity) URI() *url.URL {
+ return &url.URL{Scheme: URIScheme, Host: id.LaunchID,
+ Path: "/" + id.AttemptID + "/" + string(id.VMRef) + "/" + strconv.FormatInt(id.Epoch, 10),
+ RawPath: "/" + url.PathEscape(id.AttemptID) + "/" + url.PathEscape(string(id.VMRef)) + "/" + strconv.FormatInt(id.Epoch, 10)}
+}
+
+// ParseLaunchURI reads a URI that LaunchIdentity.URI wrote. It refuses any
+// other scheme, user, port, query or fragment, an empty part, and an epoch
+// that is not a canonical non-negative decimal.
+func ParseLaunchURI(u *url.URL) (LaunchIdentity, error) {
+ bad := fmt.Errorf("ctlproxy: %q is not a launch URI", u.String())
+ if u.Scheme != URIScheme || u.User != nil || u.Port() != "" || u.Hostname() == "" || u.Opaque != "" ||
+ u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
+ return LaunchIdentity{}, bad
+ }
+ seg := strings.Split(u.EscapedPath(), "/")
+ if len(seg) != 4 || seg[0] != "" {
+ return LaunchIdentity{}, bad
+ }
+ attempt, err1 := url.PathUnescape(seg[1])
+ ref, err2 := url.PathUnescape(seg[2])
+ epoch, err3 := strconv.ParseInt(seg[3], 10, 64)
+ if err1 != nil || err2 != nil || err3 != nil || attempt == "" || ref == "" || epoch < 0 || strconv.FormatInt(epoch, 10) != seg[3] {
+ return LaunchIdentity{}, bad
+ }
+ 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
+}
+
+// CodeHash is the hex SHA-256 of a proxy code's text: all the controller
+// keeps of it, and what the feed lists.
+func CodeHash(code string) string {
+ sum := sha256.Sum256([]byte(code))
+ 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.
+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 {
+ return fmt.Errorf("ctlproxy: save proxy code of %s: %w", attemptID, err)
+ }
+ return 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 {
+ if _, err := tx.ExecContext(ctx, `UPDATE proxy_codes SET running_t = ? WHERE attempt_id = ? AND running_t IS NULL`,
+ int64(now), attempt); err != nil {
+ return fmt.Errorf("ctlproxy: open the code window of %s: %w", attempt, err)
+ }
+ return nil
+}
+
+// Revoke revokes every serial of attempt not already revoked: on a stop
+// request, stop proof, or a new epoch.
+func Revoke(ctx context.Context, tx *sql.Tx, attempt string, now time.Duration) error {
+ if _, err := tx.ExecContext(ctx, `UPDATE proxy_certs SET revoked_t = ? WHERE attempt_id = ? AND revoked_t IS NULL`,
+ int64(now), attempt); err != nil {
+ return fmt.Errorf("ctlproxy: revoke the serials of %s: %w", attempt, err)
+ }
+ return nil
+}
+
+// launch is a jobs row as the CA reads it.
+type launch struct {
+ LaunchIdentity
+ hasRef bool
+ deadline time.Duration
+ ended bool // a stop asked for or proven, or the VM stopping
+}
+
+// live reports whether l's VM may hold a certificate at now.
+func (l launch) live(now time.Duration) bool { return l.hasRef && !l.ended && now < l.deadline }
+
+// loadLaunch reads the job of launchID. found is false when there is none.
+// The state 'stopping' is hostedctl's JobStopping: the provider reports
+// the VM stopping.
+func loadLaunch(ctx context.Context, tx *sql.Tx, launchID string) (launch, bool, error) {
+ var l launch
+ var ref sql.NullString
+ err := tx.QueryRowContext(ctx, `SELECT launch_id, attempt_id, vm_ref, epoch, deadline_t,
+ stop_requested_t IS NOT NULL OR stop_proof_json IS NOT NULL OR state = 'stopping'
+ FROM jobs WHERE launch_id = ?`, launchID).Scan(&l.LaunchID, &l.AttemptID, &ref, &l.Epoch, &l.deadline, &l.ended)
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
+ return launch{}, false, nil
+ case err != nil:
+ return launch{}, false, fmt.Errorf("ctlproxy: read launch: %w", err)
+ }
+ l.VMRef, l.hasRef = isolatedjob.Ref(ref.String), ref.Valid
+ return l, true, nil
+}
+
+// checkRequest reads the VM's public key from csr (DER): a certificate
+// request whose signature verifies, for an ECDSA P-256 key. Nothing else in
+// it is used.
+func checkRequest(csr []byte) (*ecdsa.PublicKey, error) {
+ r, err := x509.ParseCertificateRequest(csr)
+ if err != nil {
+ return nil, fmt.Errorf("%w: the certificate request does not parse", ErrRequest)
+ }
+ if err := r.CheckSignature(); err != nil {
+ return nil, fmt.Errorf("%w: the certificate request's signature does not verify", ErrRequest)
+ }
+ pub, ok := r.PublicKey.(*ecdsa.PublicKey)
+ if !ok || pub.Curve != elliptic.P256() {
+ return nil, fmt.Errorf("%w: the certificate request is not for an ECDSA P-256 key", ErrRequest)
+ }
+ return pub, nil
+}
+
+// Redeem trades a VM's proxy code for its first client certificate, in tx.
+// It refuses (ErrRefused, audited through audit) a launch that is not live
+// (no VM yet, a stop asked for or proven, the deadline reached), a VM
+// reference other than the launch's, a code whose hash is not the
+// launch's, a used code, and a code outside its window: before the
+// controller has seen the VM running, or more than CodeWindow after. A
+// refusal writes nothing but its audit row, so it never uses the code up.
+// A malformed request is ErrRequest, before tx is read.
+func (ca *CA) Redeem(ctx context.Context, tx *sql.Tx, q hostedwire.RedeemRequest, now Now, audit Audit) (hostedwire.RedeemResponse, error) {
+ if !printable(q.LaunchID, hostedwire.MaxLaunchIDLen) || !printable(string(q.VMRef), 256) || len(q.ProxyCode) != len(CodePlaceholder) {
+ return hostedwire.RedeemResponse{}, fmt.Errorf("%w: launch, VM or code out of form", ErrRequest)
+ }
+ pub, err := checkRequest(q.CSR)
+ if err != nil {
+ return hostedwire.RedeemResponse{}, err
+ }
+ l, found, err := loadLaunch(ctx, tx, q.LaunchID)
+ if err != nil {
+ return hostedwire.RedeemResponse{}, err
+ }
+ refuse := func(why error) (hostedwire.RedeemResponse, error) {
+ return hostedwire.RedeemResponse{}, refusal(audit, l.AttemptID, "redeem for launch "+q.LaunchID, why)
+ }
+ switch {
+ case !found || !l.live(now.T):
+ return refuse(ErrNotLive)
+ case l.VMRef != q.VMRef:
+ return refuse(ErrWrongVM)
+ }
+ var hash string
+ var running, redeemed sql.NullInt64
+ err = tx.QueryRowContext(ctx, `SELECT code_sha256, running_t, redeemed_t FROM proxy_codes WHERE launch_id = ?`,
+ q.LaunchID).Scan(&hash, &running, &redeemed)
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
+ return refuse(ErrWrongCode) // an intent from before proxy codes
+ case err != nil:
+ return hostedwire.RedeemResponse{}, fmt.Errorf("ctlproxy: read proxy code: %w", err)
+ case subtle.ConstantTimeCompare([]byte(CodeHash(q.ProxyCode)), []byte(hash)) != 1:
+ return refuse(ErrWrongCode)
+ case redeemed.Valid:
+ return refuse(ErrCodeUsed)
+ case !running.Valid:
+ return refuse(ErrNotRunning)
+ case now.T-time.Duration(running.Int64) > CodeWindow:
+ return refuse(ErrCodeExpired)
+ }
+ res, err := tx.ExecContext(ctx, `UPDATE proxy_codes SET redeemed_t = ? WHERE launch_id = ? AND redeemed_t IS NULL`,
+ int64(now.T), q.LaunchID)
+ if err != nil {
+ return hostedwire.RedeemResponse{}, fmt.Errorf("ctlproxy: use proxy code: %w", err)
+ }
+ if n, err := res.RowsAffected(); err != nil || n != 1 {
+ return refuse(ErrCodeUsed)
+ }
+ out, serial, err := ca.issue(ctx, tx, l, pub, now)
+ if err != nil {
+ return hostedwire.RedeemResponse{}, err
+ }
+ return out, audit(l.AttemptID, ActionIssued, fmt.Sprintf("proxy code redeemed; serial %s for VM %s, epoch %d", serial, l.VMRef, l.Epoch))
+}
+
+// Renew renews the client certificate q.Serial, in tx: once per serial,
+// for the same launch, VM and epoch, before its NotAfter, while the launch
+// is live. It revokes the old serial. Refusals are ErrRefused, audited
+// through audit; a malformed request is ErrRequest.
+func (ca *CA) Renew(ctx context.Context, tx *sql.Tx, q hostedwire.RenewCertRequest, now Now, audit Audit) (hostedwire.RedeemResponse, error) {
+ if !serialText(q.Serial) {
+ return hostedwire.RedeemResponse{}, fmt.Errorf("%w: serial must be 1 to 40 lower-case hex digits", ErrRequest)
+ }
+ pub, err := checkRequest(q.CSR)
+ if err != nil {
+ return hostedwire.RedeemResponse{}, err
+ }
+ var old LaunchIdentity
+ var notAfter int64
+ var renewed bool
+ var revoked sql.NullInt64
+ err = tx.QueryRowContext(ctx, `SELECT launch_id, attempt_id, vm_ref, epoch, not_after_t, renewed, revoked_t
+ FROM proxy_certs WHERE serial = ?`, q.Serial).Scan(&old.LaunchID, &old.AttemptID, &old.VMRef, &old.Epoch, &notAfter, &renewed, &revoked)
+ refuse := func(why error) (hostedwire.RedeemResponse, error) {
+ return hostedwire.RedeemResponse{}, refusal(audit, old.AttemptID, "renew serial "+q.Serial, why)
+ }
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
+ return refuse(ErrUnknownSerial)
+ case err != nil:
+ return hostedwire.RedeemResponse{}, fmt.Errorf("ctlproxy: read serial: %w", err)
+ case renewed:
+ return refuse(ErrAlreadyRenewed)
+ case revoked.Valid:
+ return refuse(ErrRevoked)
+ case now.T >= time.Duration(notAfter):
+ return refuse(ErrCertExpired)
+ }
+ l, found, err := loadLaunch(ctx, tx, old.LaunchID)
+ switch {
+ case err != nil:
+ return hostedwire.RedeemResponse{}, err
+ case !found || !l.live(now.T):
+ return refuse(ErrNotLive)
+ case l.VMRef != old.VMRef:
+ return refuse(ErrWrongVM)
+ case l.Epoch != old.Epoch:
+ return refuse(ErrWrongEpoch)
+ }
+ res, err := tx.ExecContext(ctx, `UPDATE proxy_certs SET renewed = 1, revoked_t = ?
+ WHERE serial = ? AND renewed = 0 AND revoked_t IS NULL`, int64(now.T), q.Serial)
+ if err != nil {
+ return hostedwire.RedeemResponse{}, fmt.Errorf("ctlproxy: mark serial renewed: %w", err)
+ }
+ if n, err := res.RowsAffected(); err != nil || n != 1 {
+ return refuse(ErrAlreadyRenewed)
+ }
+ out, serial, err := ca.issue(ctx, tx, l, pub, now)
+ if err != nil {
+ return hostedwire.RedeemResponse{}, err
+ }
+ return out, audit(l.AttemptID, ActionRenewed, fmt.Sprintf("serial %s renewed and revoked; new serial %s", q.Serial, serial))
+}
+
+// issue signs a client certificate for l's identity and pub, and records
+// its serial. NotAfter is the earlier of CertLifetime and l's deadline,
+// rounded down to the second the certificate can hold.
+func (ca *CA) issue(ctx context.Context, tx *sql.Tx, l launch, pub *ecdsa.PublicKey, now Now) (hostedwire.RedeemResponse, string, error) {
+ notAfter := now.Wall.Add(min(CertLifetime, l.deadline-now.T)).Truncate(time.Second)
+ life := notAfter.Sub(now.Wall)
+ if life <= 0 {
+ return hostedwire.RedeemResponse{}, "", ErrNotLive
+ }
+ n, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
+ if err != nil {
+ return hostedwire.RedeemResponse{}, "", fmt.Errorf("ctlproxy: serial: %w", err)
+ }
+ n.Add(n, big.NewInt(1)) // never zero
+ tmpl := &x509.Certificate{
+ SerialNumber: n, Subject: pkix.Name{CommonName: l.LaunchID},
+ NotBefore: now.Wall.Add(-certBackdate), NotAfter: notAfter,
+ KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
+ BasicConstraintsValid: true, URIs: []*url.URL{l.URI()},
+ }
+ der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.cert, pub, ca.key)
+ if err != nil {
+ return hostedwire.RedeemResponse{}, "", fmt.Errorf("ctlproxy: sign client certificate: %w", err)
+ }
+ serial, until := n.Text(16), now.T+life
+ if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_certs (serial, launch_id, attempt_id, vm_ref, epoch, issued_t, not_after_t)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, serial, l.LaunchID, l.AttemptID, string(l.VMRef), l.Epoch, int64(now.T), int64(until)); err != nil {
+ return hostedwire.RedeemResponse{}, "", fmt.Errorf("ctlproxy: record serial: %w", err)
+ }
+ return hostedwire.RedeemResponse{Cert: der, NotAfterNS: int64(until)}, serial, nil
+}
+
+// refusal audits a refusal of what, for attempt ("" when unknown), and
+// returns it. If the audit row cannot be written, that error is returned
+// instead, so the caller's transaction rolls back.
+func refusal(audit Audit, attempt, what string, why error) error {
+ if err := audit(attempt, ActionRefused, what+": "+why.Error()); err != nil {
+ return err
+ }
+ return fmt.Errorf("%s: %w", what, why)
+}
+
+// printable is 1 to n bytes of printable ASCII.
+func printable(s string, n int) bool {
+ if s == "" || len(s) > n {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ if s[i] < 0x20 || s[i] > 0x7e {
+ return false
+ }
+ }
+ return true
+}
+
+// serialText is a serial as issue writes it: 1 to 40 lower-case hex
+// digits (big.Int.Text(16) of at most 129 bits).
+func serialText(s string) bool {
+ if s == "" || len(s) > 40 {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ if c := s[i]; !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/hostedctl/ctlproxy/ca_test.go b/internal/hostedctl/ctlproxy/ca_test.go
new file mode 100644
index 00000000..dd586411
--- /dev/null
+++ b/internal/hostedctl/ctlproxy/ca_test.go
@@ -0,0 +1,292 @@
+package ctlproxy_test
+
+import (
+ "crypto/ecdsa"
+ "crypto/x509"
+ "database/sql"
+ "errors"
+ "net/http"
+ "testing"
+ "time"
+
+ "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"
+)
+
+func TestNewCARefuses(t *testing.T) {
+ t.Parallel()
+ certPEM, keyPEM := ctlproxytest.PEM()
+ if _, err := ctlproxy.NewCA(certPEM, keyPEM); err != nil {
+ t.Fatalf("NewCA(test CA) = %v", err)
+ }
+ leafCert, leafKey := ctlproxytest.SelfSigned(false)
+ _, otherKey := ctlproxytest.SelfSigned(true)
+ for name, c := range map[string][2][]byte{
+ "not a CA": {leafCert, leafKey},
+ "key of another": {certPEM, otherKey},
+ "no certificate": {nil, keyPEM},
+ "two in the file": {append(append([]byte{}, certPEM...), certPEM...), keyPEM},
+ } {
+ if ca, err := ctlproxy.NewCA(c[0], c[1]); err == nil || ca != nil {
+ t.Errorf("NewCA with %s = (%v, %v), want an error", name, ca, err)
+ }
+ }
+}
+
+// TestLaunchURI: the one URI SAN names launch, attempt, VM and epoch, each
+// escaped, and reads back the same.
+func TestLaunchURI(t *testing.T) {
+ t.Parallel()
+ id := ctlproxy.LaunchIdentity{LaunchID: "0123456789abcdef0123456789abcdef", AttemptID: "att/1 x", VMRef: "vm-0001", Epoch: 3}
+ u := id.URI()
+ if got := u.String(); got != "equipo-launch://0123456789abcdef0123456789abcdef/att%2F1%20x/vm-0001/3" {
+ t.Fatalf("URI = %s", got)
+ }
+ back, err := ctlproxy.ParseLaunchURI(u)
+ if err != nil || back != id {
+ t.Fatalf("ParseLaunchURI(%s) = (%+v, %v), want %+v", u, back, err, id)
+ }
+ for _, bad := range []string{"https://l/a/v/1", "equipo-launch://l/a/v", "equipo-launch://l/a/v/-1", "equipo-launch://l/a/v/01",
+ "equipo-launch://l/a/v/1?x", "equipo-launch://u@l/a/v/1", "equipo-launch://l:1/a/v/1", "equipo-launch://l//v/1"} {
+ u, err := u.Parse(bad)
+ if err != nil {
+ continue
+ }
+ if got, err := ctlproxy.ParseLaunchURI(u); err == nil {
+ t.Errorf("ParseLaunchURI(%s) = %+v, want an error", bad, got)
+ }
+ }
+}
+
+// TestRedeemSingleUse: the VM's proxy code buys one certificate, bound to
+// the launch, and a second redemption of the same code is refused.
+func TestRedeemSingleUse(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ v := e.launch("att-1", 2*time.Hour)
+ e.run()
+ b := e.boot("att-1")
+ key, csr := ctlproxytest.CSR()
+ status, body := e.do(http.MethodPost, "/v1/proxy/redeem",
+ hostedwire.RedeemRequest{LaunchID: v.LaunchID, VMRef: v.VMRef, ProxyCode: b.ProxyCode, CSR: csr}, idProxy, keyProxy)
+ if status != http.StatusOK {
+ t.Fatalf("redeem = %d %s, want 200", status, body)
+ }
+ r := decodeCert(t, status, body)
+ c := cert(t, r)
+ want := ctlproxy.LaunchIdentity{LaunchID: v.LaunchID, AttemptID: "att-1", VMRef: v.VMRef, Epoch: 0}
+ if len(c.URIs) != 1 || c.URIs[0].String() != want.URI().String() {
+ t.Fatalf("certificate URIs = %v, want only %s", c.URIs, want.URI())
+ }
+ if pub, ok := c.PublicKey.(*ecdsa.PublicKey); !ok || !pub.Equal(&key.PublicKey) {
+ t.Fatal("certificate does not carry the VM's key from the request")
+ }
+ if _, err := c.Verify(x509.VerifyOptions{Roots: e.cfg.ProxyCA.Pool(), CurrentTime: e.clk.Wall(),
+ KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}); err != nil {
+ t.Fatalf("certificate does not verify as a client certificate under the CA: %v", err)
+ }
+ if c.IsCA || len(c.DNSNames)+len(c.IPAddresses)+len(c.EmailAddresses) != 0 {
+ t.Fatalf("certificate is a CA or names more than its launch: %+v", c)
+ }
+ e.noCodeStored(b.ProxyCode)
+
+ status, _, body = e.redeem(v.LaunchID, v.VMRef, b.ProxyCode)
+ e.wantRefused("second redemption", status, body, "already used")
+ if n := e.certCount("att-1"); n != 1 {
+ t.Fatalf("certificates issued = %d, want 1", n)
+ }
+}
+
+// TestRedeemBindsVMRef: the right code from another VM, or another launch's
+// code, is refused, and a refusal does not use the code up.
+func TestRedeemBindsVMRef(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ v1, v2 := e.launch("att-1", 2*time.Hour), e.launch("att-2", 2*time.Hour)
+ e.run()
+ code1, code2 := e.boot("att-1").ProxyCode, e.boot("att-2").ProxyCode
+
+ status, _, body := e.redeem(v1.LaunchID, v2.VMRef, code1)
+ e.wantRefused("att-1's code from att-2's VM", status, body, "not the launch's VM")
+ status, _, body = e.redeem(v1.LaunchID, "vm-9999", code1)
+ e.wantRefused("att-1's code from an unknown VM", status, body, "not the launch's VM")
+ status, _, body = e.redeem(v1.LaunchID, v1.VMRef, code2)
+ e.wantRefused("att-2's code for att-1", status, body, "wrong proxy code")
+ status, _, body = e.redeem("ffffffffffffffffffffffffffffffff", v1.VMRef, code1)
+ e.wantRefused("an unknown launch", status, body, "not live")
+
+ if status, r, body := e.redeem(v1.LaunchID, v1.VMRef, code1); status != http.StatusOK {
+ t.Fatalf("att-1's own redemption after the refusals = %d %s, want 200", status, body)
+ } else if id, err := ctlproxy.ParseLaunchURI(cert(t, r).URIs[0]); err != nil || id.VMRef != v1.VMRef || id.AttemptID != "att-1" {
+ t.Fatalf("certificate names %+v (%v), want att-1 on %s", id, err, v1.VMRef)
+ }
+}
+
+// TestRedeemExpires: the code's window opens when the controller first sees
+// the VM running and lasts two minutes; a later sighting does not move it.
+func TestRedeemExpires(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ v := e.launch("att-1", 2*time.Hour)
+ code := e.boot("att-1").ProxyCode
+ status, _, body := e.redeem(v.LaunchID, v.VMRef, code)
+ e.wantRefused("redemption before the VM was seen running", status, body, "not seen running")
+
+ e.run()
+ e.advance(time.Minute)
+ e.run() // a second sighting
+ e.advance(time.Minute + time.Second)
+ status, _, body = e.redeem(v.LaunchID, v.VMRef, code)
+ e.wantRefused("redemption 2 min 1 s after the VM was first seen running", status, body, "expired")
+
+ // The boundary: exactly two minutes is still inside.
+ w := e.launch("att-2", 2*time.Hour)
+ e.run()
+ e.advance(ctlproxy.CodeWindow)
+ if status, _, body := e.redeem(w.LaunchID, w.VMRef, e.boot("att-2").ProxyCode); status != http.StatusOK {
+ t.Fatalf("redemption at exactly %v = %d %s, want 200", ctlproxy.CodeWindow, status, body)
+ }
+}
+
+// TestCertCappedAtDeadline: a certificate ends at the earlier of 15 minutes
+// and the job's deadline, on issue and on renewal.
+func TestCertCappedAtDeadline(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ long := e.launch("att-long", 2*time.Hour)
+ short := e.launch("att-short", 11*time.Minute) // deadline 11 min after launch
+ e.run()
+ e.advance(time.Minute)
+ now := e.clk.Wall()
+
+ _, r, _ := e.redeem(long.LaunchID, long.VMRef, e.boot("att-long").ProxyCode)
+ if got := cert(t, r).NotAfter; !got.Equal(now.Add(ctlproxy.CertLifetime)) {
+ t.Fatalf("long job's certificate NotAfter = %v, want %v", got, now.Add(ctlproxy.CertLifetime))
+ }
+ _, r, body := e.redeem(short.LaunchID, short.VMRef, e.boot("att-short").ProxyCode)
+ c := cert(t, r)
+ deadline := now.Add(10 * time.Minute)
+ if !c.NotAfter.Equal(deadline) {
+ t.Fatalf("short job's certificate NotAfter = %v, want its deadline %v (%s)", c.NotAfter, deadline, body)
+ }
+ if r.NotAfterNS != int64(11*time.Minute) {
+ t.Fatalf("not_after_ns = %d, want the deadline in controller time, %d", r.NotAfterNS, int64(11*time.Minute))
+ }
+
+ e.advance(9*time.Minute + 30*time.Second)
+ status, r, body := e.renew(serial(c))
+ if status != http.StatusOK {
+ t.Fatalf("renew = %d %s, want 200", status, body)
+ }
+ if got := cert(t, r).NotAfter; !got.Equal(deadline) {
+ t.Fatalf("renewed NotAfter = %v, want the deadline %v", got, deadline)
+ }
+ e.advance(30 * time.Second)
+ status, _, body = e.renew(serial(cert(t, r)))
+ e.wantRefused("renewal at the deadline", status, body, "expired")
+}
+
+// TestRenewOncePerSerial: a serial renews once; the old serial is revoked
+// and a replayed renewal of it is refused.
+func TestRenewOncePerSerial(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ v := e.launch("att-1", 2*time.Hour)
+ e.run()
+ _, r, _ := e.redeem(v.LaunchID, v.VMRef, e.boot("att-1").ProxyCode)
+ s1 := serial(cert(t, r))
+
+ status, r2, body := e.renew(s1)
+ if status != http.StatusOK {
+ t.Fatalf("first renewal = %d %s, want 200", status, body)
+ }
+ c2 := cert(t, r2)
+ if serial(c2) == s1 || c2.URIs[0].String() != cert(t, r).URIs[0].String() {
+ t.Fatalf("renewal = serial %s URIs %v, want a new serial for the same launch", serial(c2), c2.URIs)
+ }
+ status, _, body = e.renew(s1)
+ e.wantRefused("second renewal of one serial", status, body, "already renewed")
+ if f := e.feed(); !contains(f.Revoked, s1) || contains(f.Revoked, serial(c2)) {
+ t.Fatalf("feed revoked = %v, want %s and not %s", f.Revoked, s1, serial(c2))
+ }
+ if status, _, body := e.renew(serial(c2)); status != http.StatusOK {
+ t.Fatalf("renewal of the new serial = %d %s, want 200", status, body)
+ }
+ status, _, body = e.renew("abcdef")
+ e.wantRefused("renewal of an unknown serial", status, body, "unknown")
+}
+
+// TestRenewNeedsCurrentEpoch: renewal is for the launch's current epoch;
+// a resume raises the epoch and revokes every serial of the launch.
+func TestRenewNeedsCurrentEpoch(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ v := e.launch("att-1", 2*time.Hour)
+ e.run()
+ _, r, _ := e.redeem(v.LaunchID, v.VMRef, e.boot("att-1").ProxyCode)
+ e.tx(func(tx *sql.Tx) error {
+ _, err := tx.ExecContext(e.ctx, `UPDATE jobs SET epoch = epoch + 1 WHERE attempt_id = 'att-1'`)
+ return err
+ })
+ status, _, body := e.renew(serial(cert(t, r)))
+ e.wantRefused("renewal after the epoch moved", status, body, "epoch")
+
+ // A real resume: drain, suspend, resume.
+ e = newEnv(t)
+ v = e.launch("att-1", 2*time.Hour)
+ e.run()
+ _, r, _ = e.redeem(v.LaunchID, v.VMRef, e.boot("att-1").ProxyCode)
+ s := serial(cert(t, r))
+ inst := hostedwire.VerifyKey{Role: hostedwire.RoleInstance}
+ g, err := e.c.Drain(e.ctx, idInst, inst, "att-1")
+ if err != nil {
+ t.Fatalf("Drain = %v", err)
+ }
+ if err := e.c.Quiescent(e.ctx, idInst, inst, "att-1", g); err != nil {
+ t.Fatalf("Quiescent = %v", err)
+ }
+ if err := e.c.Suspend(e.ctx, idInst, inst, "att-1", g); err != nil {
+ t.Fatalf("Suspend = %v", err)
+ }
+ e.run()
+ if f := e.feed(); contains(f.Revoked, s) {
+ t.Fatalf("feed revoked %v before the resume", f.Revoked)
+ }
+ epoch, err := e.c.Resume(e.ctx, idInst, inst, "att-1", "op-1")
+ for i := 0; errors.Is(err, hostedctl.ErrResumePending) && i < 3; i++ {
+ e.run()
+ epoch, err = e.c.Resume(e.ctx, idInst, inst, "att-1", "op-1")
+ }
+ if err != nil || epoch != 1 {
+ t.Fatalf("Resume = (%d, %v), want epoch 1", epoch, err)
+ }
+ f := e.feed()
+ if !contains(f.Revoked, s) {
+ t.Fatalf("feed revoked = %v after the resume, want %s", f.Revoked, s)
+ }
+ if len(f.Launches) != 1 || f.Launches[0].Epoch != 1 {
+ t.Fatalf("feed launches = %+v, want att-1 at epoch 1", f.Launches)
+ }
+ status, _, body = e.renew(s)
+ e.wantRefused("renewal of a serial the resume revoked", status, body, "revoked")
+}
+
+func contains(list []string, s string) bool {
+ for _, x := range list {
+ if x == s {
+ return true
+ }
+ }
+ return false
+}
+
+func (e *env) certCount(attempt string) int {
+ e.t.Helper()
+ var n int
+ e.tx(func(tx *sql.Tx) error {
+ return tx.QueryRowContext(e.ctx, `SELECT count(*) FROM proxy_certs WHERE attempt_id = ?`, attempt).Scan(&n)
+ })
+ return n
+}
diff --git a/internal/hostedctl/ctlproxy/ctlproxytest/ctlproxytest.go b/internal/hostedctl/ctlproxy/ctlproxytest/ctlproxytest.go
new file mode 100644
index 00000000..af8db1e9
--- /dev/null
+++ b/internal/hostedctl/ctlproxy/ctlproxytest/ctlproxytest.go
@@ -0,0 +1,91 @@
+// Package ctlproxytest holds a test client CA for the controller and
+// certificate requests from fresh VM keys. Nothing outside tests may
+// import it.
+package ctlproxytest
+
+import (
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/pem"
+ "math/big"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
+)
+
+var (
+ once sync.Once
+ certPEM, keyPEM []byte
+)
+
+// PEM returns the test CA's certificate and its PKCS #8 key, made once per
+// process: ECDSA P-256, valid from 2020 to 2040.
+func PEM() (cert, key []byte) {
+ once.Do(func() {
+ k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ panic(err)
+ }
+ certPEM, keyPEM = selfSigned(k, true)
+ })
+ return certPEM, keyPEM
+}
+
+// CA is a ctlproxy.CA over PEM. It panics if they do not load.
+func CA() *ctlproxy.CA {
+ c, k := PEM()
+ ca, err := ctlproxy.NewCA(c, k)
+ if err != nil {
+ panic(err)
+ }
+ return ca
+}
+
+// SelfSigned returns a fresh self-signed P-256 certificate and its key,
+// marked as a CA when ca is true.
+func SelfSigned(ca bool) (cert, key []byte) {
+ k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ panic(err)
+ }
+ return selfSigned(k, ca)
+}
+
+func selfSigned(k *ecdsa.PrivateKey, ca bool) (cert, key []byte) {
+ tmpl := &x509.Certificate{
+ SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "equipo hosted test client CA"},
+ NotBefore: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), NotAfter: time.Date(2040, 1, 1, 0, 0, 0, 0, time.UTC),
+ BasicConstraintsValid: true, IsCA: ca, KeyUsage: x509.KeyUsageDigitalSignature,
+ }
+ if ca {
+ tmpl.KeyUsage |= x509.KeyUsageCertSign
+ }
+ der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &k.PublicKey, k)
+ if err != nil {
+ panic(err)
+ }
+ pk, err := x509.MarshalPKCS8PrivateKey(k)
+ if err != nil {
+ panic(err)
+ }
+ return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}),
+ pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pk})
+}
+
+// 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) {
+ k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ if err != nil {
+ panic(err)
+ }
+ der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{Subject: pkix.Name{CommonName: "vm"}}, k)
+ if err != nil {
+ panic(err)
+ }
+ return k, der
+}
diff --git a/internal/hostedctl/ctlproxy/env_test.go b/internal/hostedctl/ctlproxy/env_test.go
new file mode 100644
index 00000000..40ace291
--- /dev/null
+++ b/internal/hostedctl/ctlproxy/env_test.go
@@ -0,0 +1,357 @@
+package ctlproxy_test
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "crypto/x509"
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedctl"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
+ "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"
+ "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
+)
+
+// The tests drive a real controller (hostedctl) over a fresh store and the
+// fake provider, through its signed HTTP API, as the proxies will.
+
+var (
+ keyInst = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize))
+ keyOp = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{3}, ed25519.SeedSize))
+ keyCtl = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{4}, ed25519.SeedSize))
+ keyProxy = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{5}, ed25519.SeedSize))
+ keyProxy2 = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{6}, ed25519.SeedSize))
+)
+
+const (
+ idInst hostedwire.KeyID = "inst-1"
+ idOp hostedwire.KeyID = "op-1"
+ idProxy hostedwire.KeyID = "proxy-1"
+ idProxy2 hostedwire.KeyID = "proxy-2"
+
+ host = "equipo.example.com"
+ // instCode is every launch's instance code: 32 bytes in base64url.
+ instCode = "aW5zdGFuY2UtY29kZS1TRUNSRVQtNGYyYTljLTAwMDE"
+)
+
+var (
+ img = isolatedjob.ImageDigest("sha256:" + strings.Repeat("a", 64))
+ wall0 = time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC)
+)
+
+func keys() map[hostedwire.KeyID]hostedwire.VerifyKey {
+ return map[hostedwire.KeyID]hostedwire.VerifyKey{
+ idInst: {Public: keyInst.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance},
+ idOp: {Public: keyOp.Public().(ed25519.PublicKey), Role: hostedwire.RoleOperator},
+ idProxy: {Public: keyProxy.Public().(ed25519.PublicKey), Role: hostedwire.RoleProxy},
+ idProxy2: {Public: keyProxy2.Public().(ed25519.PublicKey), Role: hostedwire.RoleProxy},
+ }
+}
+
+func manifest(host, pin string, proxy string) ctlegress.Manifest {
+ return ctlegress.Manifest{
+ Services: map[string]hostedwire.Service{"instance": {Host: host, Port: 443, Class: hostedwire.ServiceInstance}},
+ Proxies: []netip.AddrPort{netip.MustParseAddrPort(proxy + ":8443")},
+ ProxyBoot: []netip.AddrPort{netip.MustParseAddrPort(proxy + ":8444")},
+ ProxyCAPin: strings.Repeat(pin, 32),
+ }
+}
+
+// recorder keeps every spec the controller sends the provider, then passes
+// the call on.
+type recorder struct {
+ isolatedjob.Runner
+ mu sync.Mutex
+ specs []isolatedjob.LaunchSpec
+}
+
+func (r *recorder) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) {
+ r.mu.Lock()
+ r.specs = append(r.specs, s)
+ r.mu.Unlock()
+ return r.Runner.Launch(ctx, s)
+}
+
+func (r *recorder) sent(attempt string) []isolatedjob.LaunchSpec {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ var out []isolatedjob.LaunchSpec
+ for _, s := range r.specs {
+ if s.AttemptID == attempt {
+ out = append(out, s)
+ }
+ }
+ return out
+}
+
+type alertLog struct {
+ mu sync.Mutex
+ got []hostedctl.Alert
+}
+
+func (a *alertLog) Alert(_ context.Context, al hostedctl.Alert) error {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.got = append(a.got, al)
+ return nil
+}
+
+// kinds returns the alerts of kind delivered so far, and forgets them.
+func (a *alertLog) take(kind string) []hostedctl.Alert {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ var out, keep []hostedctl.Alert
+ for _, al := range a.got {
+ if al.Kind == kind {
+ out = append(out, al)
+ } else {
+ keep = append(keep, al)
+ }
+ }
+ a.got = keep
+ return out
+}
+
+type env struct {
+ t *testing.T
+ ctx context.Context
+ clk *isolatedjobtest.FakeClock
+ fake *isolatedjob.Fake
+ rec *recorder
+ cfg hostedctl.Config
+ store *hostedctl.Store
+ c *hostedctl.Controller
+ h http.Handler
+ metrics *hostedctl.Metrics
+ alerts *alertLog
+ nonce int
+}
+
+func newEnv(t *testing.T) *env {
+ t.Helper()
+ clk := isolatedjobtest.NewFakeClock(wall0)
+ fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits())
+ e := &env{t: t, ctx: context.Background(), clk: clk, fake: fake, rec: &recorder{Runner: fake}, alerts: &alertLog{},
+ cfg: hostedctl.Config{Enabled: true, Certs: ctlcerttest.Set(ctlcerttest.Cert(img, host, "one.example.com", "two.example.com")),
+ ProviderNamespace: "test:account-1:region-1",
+ 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)
+ if err != nil {
+ t.Fatalf("Open = %v", err)
+ }
+ t.Cleanup(func() { _ = s.Close() })
+ e.store = s
+ e.build()
+ return e
+}
+
+// build makes a controller over e.store with e.cfg and serves its API.
+func (e *env) build() {
+ e.t.Helper()
+ c, err := hostedctl.New(e.cfg, hostedctl.Deps{Store: e.store, Runner: e.rec, Auditor: e.fake, Alerter: e.alerts})
+ if err != nil {
+ e.t.Fatalf("New = %v", err)
+ }
+ e.c = c
+ e.metrics = hostedctl.NewMetrics()
+ h, err := c.Handler(hostedctl.HandlerConfig{Keys: keys(), Signing: keyCtl, Wall: e.clk.Wall, Metrics: e.metrics})
+ if err != nil {
+ e.t.Fatalf("Handler = %v", err)
+ }
+ e.h = h
+}
+
+// advance moves controller time and the wall clock on by d.
+func (e *env) advance(d time.Duration) {
+ e.clk.AdvanceMono(d)
+ e.clk.SetWall(e.clk.Wall().Add(d))
+}
+
+// launch launches attempt for life and wants it to start.
+func (e *env) launch(attempt string, life time.Duration) hostedctl.JobView {
+ e.t.Helper()
+ if err := e.c.RunAudit(e.ctx); err != nil {
+ e.t.Fatalf("RunAudit = %v", err)
+ }
+ v, err := e.c.Launch(e.ctx, idInst, hostedwire.VerifyKey{Role: hostedwire.RoleInstance}, request(attempt, life))
+ if err != nil || v.State != hostedctl.JobStarting {
+ e.t.Fatalf("Launch %s = (%+v, %v), want starting", attempt, v, err)
+ }
+ return v
+}
+
+func request(attempt string, life time.Duration) hostedctl.LaunchRequest {
+ return hostedctl.LaunchRequest{AttemptID: attempt, TaskID: "task-1", Account: "acct-1", Image: img,
+ Size: isolatedjob.SizeSmall, MaxLifetime: life, InstanceCode: instCode,
+ Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: wall0.Add(24 * time.Hour).UnixMilli()}
+}
+
+// run lets every VM reach running and the controller see it.
+func (e *env) run() {
+ e.t.Helper()
+ e.fake.Tick()
+ if err := e.c.Refresh(e.ctx); err != nil {
+ e.t.Fatalf("Refresh = %v", err)
+ }
+}
+
+// boot is the last bootstrap sent for attempt.
+func (e *env) boot(attempt string) hostedwire.BootstrapV2 {
+ e.t.Helper()
+ sent := e.rec.sent(attempt)
+ if len(sent) == 0 {
+ e.t.Fatalf("no launch sent for %s", attempt)
+ }
+ var b hostedwire.BootstrapV2
+ if err := json.Unmarshal(sent[len(sent)-1].Bootstrap, &b); err != nil {
+ e.t.Fatalf("bootstrap of %s is not JSON: %v", attempt, err)
+ }
+ return b
+}
+
+// do sends a request signed by id and wants a response signed by the
+// controller for it.
+func (e *env) do(method, path string, body any, id hostedwire.KeyID, key ed25519.PrivateKey) (int, []byte) {
+ e.t.Helper()
+ var raw []byte
+ if body != nil {
+ var err error
+ if raw, err = json.Marshal(body); err != nil {
+ e.t.Fatal(err)
+ }
+ }
+ req := httptest.NewRequest(method, "https://controller.example"+path, bytes.NewReader(raw))
+ e.nonce++
+ nonce := fmt.Sprintf("ctlproxy-test-nonce-%08d", e.nonce)
+ if err := hostedwire.SignRequest(req, raw, id, key, e.clk.Wall(), nonce); err != nil {
+ e.t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ e.h.ServeHTTP(w, req)
+ resp := w.Result()
+ got := w.Body.Bytes()
+ if err := hostedwire.VerifyResponse(resp, got, nonce, keyCtl.Public().(ed25519.PublicKey)); err != nil {
+ e.t.Fatalf("%s %s by %s: response %d %s is not signed for its request: %v", method, path, id, resp.StatusCode, got, err)
+ }
+ return resp.StatusCode, got
+}
+
+// redeem trades code for a certificate for launch on vm, with a fresh key.
+func (e *env) redeem(launch string, vm isolatedjob.Ref, code string) (int, hostedwire.RedeemResponse, []byte) {
+ e.t.Helper()
+ _, csr := ctlproxytest.CSR()
+ status, body := e.do(http.MethodPost, "/v1/proxy/redeem",
+ hostedwire.RedeemRequest{LaunchID: launch, VMRef: vm, ProxyCode: code, CSR: csr}, idProxy, keyProxy)
+ return status, decodeCert(e.t, status, body), body
+}
+
+// renew renews serial with a fresh key.
+func (e *env) renew(serial string) (int, hostedwire.RedeemResponse, []byte) {
+ e.t.Helper()
+ _, csr := ctlproxytest.CSR()
+ status, body := e.do(http.MethodPost, "/v1/proxy/renew", hostedwire.RenewCertRequest{Serial: serial, CSR: csr}, idProxy, keyProxy)
+ return status, decodeCert(e.t, status, body), body
+}
+
+func decodeCert(t *testing.T, status int, body []byte) hostedwire.RedeemResponse {
+ t.Helper()
+ var r hostedwire.RedeemResponse
+ if status == http.StatusOK {
+ if err := hostedwire.DecodeStrict(bytes.NewReader(body), &r); err != nil {
+ t.Fatalf("certificate response %s: %v", body, err)
+ }
+ }
+ return r
+}
+
+// feed reads the feed as proxy-1.
+func (e *env) feed() hostedwire.ProxyFeed {
+ e.t.Helper()
+ status, body := e.do(http.MethodGet, "/v1/proxy/feed", nil, idProxy, keyProxy)
+ if status != http.StatusOK {
+ e.t.Fatalf("feed = %d %s, want 200", status, body)
+ }
+ var f hostedwire.ProxyFeed
+ if err := hostedwire.DecodeStrict(bytes.NewReader(body), &f); err != nil {
+ e.t.Fatalf("feed %s: %v", body, err)
+ }
+ return f
+}
+
+// cert parses a certificate the controller issued.
+func cert(t *testing.T, r hostedwire.RedeemResponse) *x509.Certificate {
+ t.Helper()
+ c, err := x509.ParseCertificate(r.Cert)
+ if err != nil {
+ t.Fatalf("issued certificate does not parse: %v", err)
+ }
+ return c
+}
+
+func serial(c *x509.Certificate) string { return c.SerialNumber.Text(16) }
+
+// wantRefused wants a signed 403 proxy_refused, and the last audit row a
+// proxy refusal whose reason holds why.
+func (e *env) wantRefused(what string, status int, body []byte, why string) {
+ e.t.Helper()
+ var er hostedwire.ErrorResponse
+ _ = json.Unmarshal(body, &er)
+ if status != http.StatusForbidden || er.Code != "proxy_refused" {
+ e.t.Fatalf("%s = %d %s, want 403 proxy_refused", what, status, body)
+ }
+ action, reason := e.lastAudit()
+ if action != ctlproxy.ActionRefused || !strings.Contains(reason, why) {
+ e.t.Fatalf("%s: last audit = %s %q, want %s naming %q", what, action, reason, ctlproxy.ActionRefused, why)
+ }
+}
+
+func (e *env) lastAudit() (action, reason string) {
+ e.t.Helper()
+ e.tx(func(tx *sql.Tx) error {
+ return tx.QueryRowContext(e.ctx, `SELECT action, reason FROM audit ORDER BY id DESC LIMIT 1`).Scan(&action, &reason)
+ })
+ return action, reason
+}
+
+func (e *env) tx(fn func(*sql.Tx) error) {
+ e.t.Helper()
+ if err := e.store.Tx(e.ctx, fn); err != nil {
+ e.t.Fatalf("store: %v", err)
+ }
+}
+
+// noCodeStored wants no table but the saved spec to hold code.
+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 {
+ return err
+ }
+ if n != 0 {
+ e.t.Fatalf("%s found the proxy code", q)
+ }
+ }
+ return nil
+ })
+}
diff --git a/internal/hostedctl/ctlproxy/feed.go b/internal/hostedctl/ctlproxy/feed.go
new file mode 100644
index 00000000..3c34110f
--- /dev/null
+++ b/internal/hostedctl/ctlproxy/feed.go
@@ -0,0 +1,151 @@
+package ctlproxy
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "maps"
+ "slices"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+)
+
+const (
+ // FeedVersion is the ProxyFeed layout this package writes.
+ FeedVersion = 1
+ // FeedLifetime is how long a proxy may act on a feed, from receipt,
+ // on its own monotonic clock (plan decision S2-3).
+ FeedLifetime = 5 * time.Minute
+ // SilentAfter is how long a configured proxy may go without asking for
+ // the feed before AlertProxySilent is raised.
+ SilentAfter = 3 * time.Minute
+ // AlertProxySilent is the alert kind for a silent proxy.
+ AlertProxySilent = "proxy_silent"
+)
+
+// Feed records that the proxy key by asked for the feed at now, and
+// returns the next feed: a new serial, every live launch and every revoked
+// serial whose certificate has not yet expired. A launch is live while it
+// has a VM, no stop asked for or proven, the VM is not stopping, and its
+// deadline has not come; only launches with a proxy code are listed. Each
+// lists the services snapshot saved with its intent. The API signs the
+// response with the controller's key, bound to the proxy's request.
+func Feed(ctx context.Context, tx *sql.Tx, by hostedwire.KeyID, now time.Duration) (hostedwire.ProxyFeed, error) {
+ if _, err := tx.ExecContext(ctx, `INSERT INTO proxy_polls (key_id, last_t, silent_alerted) VALUES (?, ?, 0)
+ ON CONFLICT (key_id) DO UPDATE SET last_t = excluded.last_t, silent_alerted = 0`, string(by), int64(now)); err != nil {
+ return hostedwire.ProxyFeed{}, fmt.Errorf("ctlproxy: record feed request: %w", err)
+ }
+ f := hostedwire.ProxyFeed{Version: FeedVersion, IssuedNS: int64(now), TTLMS: FeedLifetime.Milliseconds(),
+ Launches: []hostedwire.FeedLaunch{}, Revoked: []string{}}
+ if err := tx.QueryRowContext(ctx, `INSERT INTO proxy_feed (id, serial) VALUES (1, 1)
+ ON CONFLICT (id) DO UPDATE SET serial = serial + 1 RETURNING serial`).Scan(&f.Serial); err != nil {
+ return hostedwire.ProxyFeed{}, fmt.Errorf("ctlproxy: feed serial: %w", err)
+ }
+ rows, err := tx.QueryContext(ctx, `SELECT j.launch_id, j.attempt_id, j.vm_ref, j.epoch, j.services_json, p.code_sha256, j.deadline_t
+ FROM jobs j JOIN proxy_codes p ON p.launch_id = j.launch_id
+ WHERE j.vm_ref IS NOT NULL AND j.stop_requested_t IS NULL AND j.stop_proof_json IS NULL
+ AND j.state <> 'stopping' AND j.deadline_t > ?
+ ORDER BY j.launch_id`, int64(now))
+ if err != nil {
+ return hostedwire.ProxyFeed{}, fmt.Errorf("ctlproxy: list live launches: %w", err)
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var l hostedwire.FeedLaunch
+ var services string
+ if err := rows.Scan(&l.LaunchID, &l.AttemptID, &l.VMRef, &l.Epoch, &services, &l.ProxyCodeHash, &l.DeadlineNS); err != nil {
+ return hostedwire.ProxyFeed{}, fmt.Errorf("ctlproxy: list live launches: %w", err)
+ }
+ if err := json.Unmarshal([]byte(services), &l.Services); err != nil {
+ return hostedwire.ProxyFeed{}, fmt.Errorf("ctlproxy: services of %s are unreadable: %w", l.AttemptID, err)
+ }
+ f.Launches = append(f.Launches, l)
+ }
+ if err := rows.Err(); err != nil {
+ return hostedwire.ProxyFeed{}, fmt.Errorf("ctlproxy: list live launches: %w", err)
+ }
+ if f.Revoked, err = column(ctx, tx, `SELECT serial FROM proxy_certs WHERE revoked_t IS NOT NULL AND not_after_t > ?
+ ORDER BY serial`, int64(now)); err != nil {
+ return hostedwire.ProxyFeed{}, fmt.Errorf("ctlproxy: list revoked serials: %w", err)
+ }
+ return f, nil
+}
+
+// column reads one text column of a query, never nil.
+func column(ctx context.Context, tx *sql.Tx, q string, args ...any) ([]string, error) {
+ rows, err := tx.QueryContext(ctx, q, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := []string{}
+ for rows.Next() {
+ var s string
+ if err := rows.Scan(&s); err != nil {
+ return nil, err
+ }
+ out = append(out, s)
+ }
+ 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
+ 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)
+ }
+ from := since
+ if last.Valid {
+ from = max(from, time.Duration(last.Int64))
+ }
+ 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)
+ }
+ out = append(out, id)
+ }
+ return out, nil
+}
+
+// ProxyKeys returns the IDs of the proxy keys in keys, sorted.
+func ProxyKeys(keys map[hostedwire.KeyID]hostedwire.VerifyKey) []hostedwire.KeyID {
+ var ids []hostedwire.KeyID
+ for _, id := range slices.Sorted(maps.Keys(keys)) {
+ if keys[id].Role == hostedwire.RoleProxy {
+ ids = append(ids, id)
+ }
+ }
+ return ids
+}
+
+// FeedAges returns, for each of proxies that has asked for the feed, the
+// controller time from its last request to now.
+func FeedAges(ctx context.Context, tx *sql.Tx, proxies []hostedwire.KeyID, now time.Duration) (map[hostedwire.KeyID]time.Duration, error) {
+ out := map[hostedwire.KeyID]time.Duration{}
+ for _, id := range proxies {
+ var last sql.NullInt64
+ err := tx.QueryRowContext(ctx, `SELECT last_t FROM proxy_polls WHERE key_id = ?`, string(id)).Scan(&last)
+ if err != nil && !errors.Is(err, sql.ErrNoRows) {
+ return nil, fmt.Errorf("ctlproxy: read last feed request of %s: %w", id, err)
+ }
+ if last.Valid {
+ out[id] = now - time.Duration(last.Int64)
+ }
+ }
+ return out, nil
+}
diff --git a/internal/hostedctl/ctlproxy/feed_test.go b/internal/hostedctl/ctlproxy/feed_test.go
new file mode 100644
index 00000000..e70aaf78
--- /dev/null
+++ b/internal/hostedctl/ctlproxy/feed_test.go
@@ -0,0 +1,291 @@
+package ctlproxy_test
+
+import (
+ "bytes"
+ "database/sql"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedctl"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+var instance = hostedwire.VerifyKey{Role: hostedwire.RoleInstance}
+
+// TestFeedSignedAndListsOnlyLive: the feed is signed by the controller for
+// the proxy's request, lists each live launch with its saved services and
+// code hash, leaves out stopped and Ref-less ones, and lists every revoked
+// serial until its certificate would have expired anyway.
+func TestFeedSignedAndListsOnlyLive(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ live := e.launch("att-1", 2*time.Hour)
+ stopped := e.launch("att-2", 2*time.Hour)
+ e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
+ if v, err := e.c.Launch(e.ctx, idInst, instance, request("att-3", 2*time.Hour)); err != nil || v.State != hostedctl.JobWaiting {
+ t.Fatalf("throttled Launch = (%+v, %v), want waiting", v, err)
+ }
+ e.run()
+ _, r1, _ := e.redeem(live.LaunchID, live.VMRef, e.boot("att-1").ProxyCode)
+ _, r2, _ := e.redeem(stopped.LaunchID, stopped.VMRef, e.boot("att-2").ProxyCode)
+ if _, err := e.c.Stop(e.ctx, idInst, instance, "att-2", "done"); err != nil && !strings.Contains(err.Error(), "not proven") {
+ t.Fatalf("Stop att-2 = %v", err)
+ }
+
+ f := e.feed() // do checked the controller's signature over it
+ if f.Version != ctlproxy.FeedVersion || f.TTLMS != ctlproxy.FeedLifetime.Milliseconds() || f.IssuedNS != int64(e.clk.Mono()) {
+ t.Fatalf("feed = version %d ttl %d issued %d, want %d, %d, %d", f.Version, f.TTLMS, f.IssuedNS,
+ ctlproxy.FeedVersion, ctlproxy.FeedLifetime.Milliseconds(), int64(e.clk.Mono()))
+ }
+ want := []hostedwire.FeedLaunch{{LaunchID: live.LaunchID, AttemptID: "att-1", VMRef: live.VMRef, Epoch: 0,
+ Services: []hostedwire.Service{{Host: host, Port: 443, Class: hostedwire.ServiceInstance}},
+ ProxyCodeHash: ctlproxy.CodeHash(e.boot("att-1").ProxyCode), DeadlineNS: int64(2 * time.Hour)}}
+ if !reflect.DeepEqual(f.Launches, want) {
+ t.Fatalf("feed launches = %+v, want only the live one %+v", f.Launches, want)
+ }
+ s1, s2 := serial(cert(t, r1)), serial(cert(t, r2))
+ if !reflect.DeepEqual(f.Revoked, []string{s2}) {
+ t.Fatalf("feed revoked = %v, want the stopped launch's %s only, not the live %s", f.Revoked, s2, s1)
+ }
+ if again := e.feed(); again.Serial != f.Serial+1 {
+ t.Fatalf("feed serials %d then %d, want them to rise by one", f.Serial, again.Serial)
+ }
+
+ // Once its certificate has expired, a revoked serial leaves the list.
+ e.advance(ctlproxy.CertLifetime)
+ if f := e.feed(); len(f.Revoked) != 0 {
+ t.Fatalf("feed revoked = %v after the certificates expired, want none", f.Revoked)
+ }
+}
+
+// TestStopRevokesSerials: a stop revokes every serial of the launch, renewed
+// ones included; so does a VM that ends on its own; and a stopped launch
+// redeems nothing.
+func TestStopRevokesSerials(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ v := e.launch("att-1", 2*time.Hour)
+ ended := e.launch("att-2", 2*time.Hour)
+ early := e.launch("att-3", 2*time.Hour)
+ e.run()
+ _, r, _ := e.redeem(v.LaunchID, v.VMRef, e.boot("att-1").ProxyCode)
+ s1 := serial(cert(t, r))
+ _, r, _ = e.renew(s1)
+ s2 := serial(cert(t, r))
+ _, r, _ = e.redeem(ended.LaunchID, ended.VMRef, e.boot("att-2").ProxyCode)
+ s3 := serial(cert(t, r))
+ if f := e.feed(); !reflect.DeepEqual(f.Revoked, []string{s1}) || len(f.Launches) != 3 {
+ t.Fatalf("feed before any stop = revoked %v, %d launches; want %s (renewed) and 3", f.Revoked, len(f.Launches), s1)
+ }
+
+ if _, err := e.c.Stop(e.ctx, idInst, instance, "att-1", "done"); err != nil && !strings.Contains(err.Error(), "not proven") {
+ t.Fatalf("Stop = %v", err)
+ }
+ f := e.feed()
+ if !contains(f.Revoked, s1) || !contains(f.Revoked, s2) {
+ t.Fatalf("feed revoked = %v after the stop, want %s and %s", f.Revoked, s1, s2)
+ }
+ for _, l := range f.Launches {
+ if l.AttemptID == "att-1" {
+ t.Fatalf("feed lists the stopped launch: %+v", l)
+ }
+ }
+ status, _, body := e.renew(s2)
+ e.wantRefused("renewal after the stop", status, body, "revoked")
+
+ // att-2's VM ends without a stop request: its proof revokes too.
+ if err := e.fake.Stop(e.ctx, ended.VMRef, "maximum lifetime"); err != nil {
+ t.Fatal(err)
+ }
+ e.fake.Tick()
+ e.run()
+ if f := e.feed(); !contains(f.Revoked, s3) {
+ t.Fatalf("feed revoked = %v after att-2 ended, want %s", f.Revoked, s3)
+ }
+
+ if _, err := e.c.Stop(e.ctx, idInst, instance, "att-3", "done"); err != nil && !strings.Contains(err.Error(), "not proven") {
+ t.Fatalf("Stop att-3 = %v", err)
+ }
+ status, _, body = e.redeem(early.LaunchID, early.VMRef, e.boot("att-3").ProxyCode)
+ e.wantRefused("redemption after the stop", status, body, "not live")
+}
+
+// TestProxyRoleOnlyOnProxyRoutes: a proxy key may use the proxy routes and
+// nothing else, and no other key may use them.
+func TestProxyRoleOnlyOnProxyRoutes(t *testing.T) {
+ t.Parallel()
+ if err := hostedctl.CheckVerifyKeys(keys()); err != nil {
+ t.Fatalf("CheckVerifyKeys with proxy keys = %v", err)
+ }
+ e := newEnv(t)
+ e.launch("att-1", 2*time.Hour)
+ launch := hostedwire.LaunchRequest{AttemptID: "att-9", TaskID: "t", Account: "a", Image: img, Size: isolatedjob.SizeSmall,
+ MaxLifetimeMS: time.Hour.Milliseconds(), InstanceCode: instCode, Person: "p", Purpose: hostedwire.PurposeChecks,
+ LaunchByUnixMS: wall0.Add(time.Hour).UnixMilli()}
+ redeem := hostedwire.RedeemRequest{LaunchID: "l", VMRef: "vm-0001", ProxyCode: instCode, CSR: []byte{1}}
+ for _, c := range []struct {
+ method, path string
+ body any
+ id hostedwire.KeyID
+ key []byte
+ }{
+ {http.MethodPost, "/v1/jobs", launch, idProxy, keyProxy},
+ {http.MethodGet, "/v1/jobs/att-1", nil, idProxy, keyProxy},
+ {http.MethodGet, "/v1/jobs/att-1/admission", nil, idProxy, keyProxy},
+ {http.MethodPost, "/v1/jobs/att-1/stop", hostedwire.StopRequest{Reason: "x"}, idProxy, keyProxy},
+ {http.MethodGet, "/v1/vms", nil, idProxy, keyProxy},
+ {http.MethodGet, "/v1/proxy/feed", nil, idInst, keyInst},
+ {http.MethodPost, "/v1/proxy/redeem", redeem, idInst, keyInst},
+ {http.MethodPost, "/v1/proxy/renew", hostedwire.RenewCertRequest{Serial: "ab", CSR: []byte{1}}, idInst, keyInst},
+ {http.MethodGet, "/v1/proxy/feed", nil, idOp, keyOp},
+ } {
+ status, body := e.do(c.method, c.path, c.body, c.id, c.key)
+ var er hostedwire.ErrorResponse
+ _ = json.Unmarshal(body, &er)
+ if status != http.StatusForbidden || er.Code != "forbidden" {
+ t.Errorf("%s %s by %s = %d %s, want 403 forbidden", c.method, c.path, c.id, status, body)
+ }
+ if action, _ := e.lastAudit(); action != "api_refused" {
+ t.Errorf("%s %s by %s: last audit %q, want api_refused", c.method, c.path, c.id, action)
+ }
+ }
+ if j, err := e.c.Get(e.ctx, idInst, "att-9"); err == nil {
+ t.Fatalf("a proxy key's launch made a job: %+v", j)
+ }
+ if status, body := e.do(http.MethodGet, "/v1/proxy/feed", nil, idProxy2, keyProxy2); status != http.StatusOK {
+ t.Fatalf("feed by a proxy key = %d %s, want 200", status, body)
+ }
+}
+
+// TestProxySilentAlertOnce: a configured proxy that has not asked for the
+// feed for 3 minutes raises one proxy_silent alert per silence; its last
+// request is a metric.
+func TestProxySilentAlertOnce(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ poll := func(id hostedwire.KeyID, key []byte) {
+ t.Helper()
+ if status, body := e.do(http.MethodGet, "/v1/proxy/feed", nil, id, key); status != http.StatusOK {
+ t.Fatalf("feed by %s = %d %s", id, status, body)
+ }
+ }
+ reap := func(want ...hostedwire.KeyID) {
+ t.Helper()
+ if _, err := e.c.Reap(e.ctx); err != nil {
+ t.Fatalf("Reap = %v", err)
+ }
+ got := e.alerts.take(ctlproxy.AlertProxySilent)
+ if len(got) != len(want) {
+ 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])) {
+ t.Fatalf("alert %+v, want it to name %s", a, want[i])
+ }
+ }
+ }
+ poll(idProxy, keyProxy)
+ e.advance(ctlproxy.SilentAfter - time.Second)
+ poll(idProxy2, keyProxy2)
+ reap()
+ e.advance(time.Second)
+ reap(idProxy)
+ reap()
+ if got := e.metric(`equipo_hosted_proxy_last_feed_seconds{proxy="proxy-1"}`); got != "180" {
+ t.Fatalf("proxy-1 last feed metric = %q, want 180", got)
+ }
+ if got := e.metric(`equipo_hosted_proxy_last_feed_seconds{proxy="proxy-2"}`); got != "1" {
+ t.Fatalf("proxy-2 last feed metric = %q, want 1", got)
+ }
+ e.advance(ctlproxy.SilentAfter)
+ reap(idProxy2)
+ reap()
+
+ // proxy-1 polls again, then falls silent again: one more alert.
+ poll(idProxy, keyProxy)
+ reap()
+ e.advance(ctlproxy.SilentAfter)
+ reap(idProxy)
+ reap()
+}
+
+// metric returns the value of the sample named exactly name, or "".
+func (e *env) metric(name string) string {
+ e.t.Helper()
+ w := httptest.NewRecorder()
+ e.metrics.Handler(e.c).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/metrics", nil))
+ body, _ := io.ReadAll(w.Result().Body)
+ for _, line := range strings.Split(string(body), "\n") {
+ if v, ok := strings.CutPrefix(line, name+" "); ok {
+ return v
+ }
+ }
+ return ""
+}
+
+// TestReplaySendsSnapshotServices: Replay sends the bootstrap saved with the
+// intent, byte for byte: its services and proxies, not the manifest's now.
+func TestReplaySendsSnapshotServices(t *testing.T) {
+ t.Parallel()
+ e := newEnv(t)
+ e.cfg.Manifest = manifest("one.example.com", "ab", "10.42.1.10")
+ e.build()
+ if err := e.c.RunAudit(e.ctx); err != nil {
+ t.Fatal(err)
+ }
+ e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
+ v, err := e.c.Launch(e.ctx, idInst, instance, request("att-1", 2*time.Hour))
+ if err != nil || v.State != hostedctl.JobWaiting {
+ t.Fatalf("throttled Launch = (%+v, %v), want waiting", v, err)
+ }
+
+ e.cfg.Manifest = manifest("two.example.com", "cd", "10.42.2.20")
+ e.build()
+ if err := e.c.RunAudit(e.ctx); err != nil {
+ t.Fatal(err)
+ }
+ e.advance(time.Minute)
+ if err := e.c.Replay(e.ctx); err != nil {
+ t.Fatalf("Replay = %v", err)
+ }
+ sent := e.rec.sent("att-1")
+ if len(sent) != 2 || !bytes.Equal(sent[0].Bootstrap, sent[1].Bootstrap) {
+ t.Fatalf("launches sent for att-1 = %d, bootstraps equal %v; want 2, byte for byte", len(sent), len(sent) == 2 && bytes.Equal(sent[0].Bootstrap, sent[1].Bootstrap))
+ }
+ b := e.boot("att-1")
+ want := hostedwire.BootstrapV2{Version: hostedwire.BootstrapV2Version, Purpose: hostedwire.PurposeChecks,
+ LaunchID: v.LaunchID, AttemptID: "att-1", InstanceCode: instCode, ProxyCode: b.ProxyCode,
+ Proxies: []netip.AddrPort{netip.MustParseAddrPort("10.42.1.10:8443")},
+ ProxyBoot: []netip.AddrPort{netip.MustParseAddrPort("10.42.1.10:8444")},
+ ProxyCAPin: strings.Repeat("ab", 32),
+ Services: []hostedwire.Service{{Host: "one.example.com", Port: 443, Class: hostedwire.ServiceInstance}}}
+ if !reflect.DeepEqual(b, want) {
+ t.Fatalf("replayed bootstrap = %+v, want the saved one %+v", b, want)
+ }
+ if _, err := b.Encode(); err != nil {
+ t.Fatalf("replayed bootstrap does not encode: %v", err)
+ }
+ 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)
+ })
+ if hash != ctlproxy.CodeHash(b.ProxyCode) {
+ t.Fatalf("stored code hash %q, want the SHA-256 of the bootstrap's code", hash)
+ }
+ e.noCodeStored(b.ProxyCode)
+
+ w := e.launch("att-2", 2*time.Hour)
+ if got := e.boot("att-2"); got.Services[0].Host != "two.example.com" || got.ProxyCAPin != strings.Repeat("cd", 32) ||
+ got.ProxyCode == b.ProxyCode || got.LaunchID != w.LaunchID {
+ t.Fatalf("new launch's bootstrap = %+v, want the current manifest and a code of its own", got)
+ }
+}
diff --git a/internal/hostedctl/http.go b/internal/hostedctl/http.go
index 95e7666e..ee0029b7 100644
--- a/internal/hostedctl/http.go
+++ b/internal/hostedctl/http.go
@@ -15,6 +15,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"
)
@@ -79,6 +80,7 @@ var apiErrors = []apiError{
{isolatedjob.ErrBootstrapTooLarge, http.StatusBadRequest, "invalid", "The request has a field out of range."},
{isolatedjob.ErrInvalid, http.StatusBadRequest, "invalid", "The request has a field out of range."},
{ErrNotCertified, http.StatusBadRequest, "not_certified", "No valid certificate covers the image for this deployment."},
+ {ctlproxy.ErrRefused, http.StatusForbidden, "proxy_refused", "The proxy request was refused."},
{ErrForbidden, http.StatusForbidden, "forbidden", "This key may not do that."},
{errNoRoute, http.StatusNotFound, "no_route", "No such route."},
{isolatedjob.ErrNotFound, http.StatusNotFound, "not_found", "Not found."},
@@ -173,6 +175,12 @@ func matchRoute(r *http.Request) (route, string, error) {
rt = routeLaunch
case len(seg) == 3 && seg[0] == "" && seg[1] == "v1" && seg[2] == "vms":
rt = routeVMs
+ case len(seg) == 4 && seg[0] == "" && seg[1] == "v1" && seg[2] == "proxy":
+ p, ok := proxyRoutes[seg[3]]
+ if !ok {
+ return route{}, "", errNoRoute
+ }
+ rt = p
case len(seg) == 4 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs" && seg[3] != "":
rt, attempt = routeGet, seg[3]
case len(seg) == 5 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs" && seg[3] != "":
@@ -201,7 +209,8 @@ func matchRoute(r *http.Request) (route, string, error) {
// Handler returns the controller's HTTP API. It refuses a config with no
// keys, a key of the wrong length or with an unknown role, one public key
-// under two key IDs, or a signing key of the wrong length.
+// under two key IDs, or a signing key of the wrong length. Its proxy keys
+// are the configured proxies the reaper watches for silence (proxy.go).
//
// Each request goes through, in order:
//
@@ -238,6 +247,7 @@ func (c *Controller) Handler(hc HandlerConfig) (http.Handler, error) {
for id, k := range hc.Keys {
keys[id] = hostedwire.VerifyKey{Public: bytes.Clone(k.Public), Role: k.Role}
}
+ c.watchProxies(keys)
return &apiHandler{
c: c,
v: &hostedwire.Verifier{Keys: keys, Nonces: c.store, Now: hc.Wall},
@@ -247,8 +257,8 @@ func (c *Controller) Handler(hc HandlerConfig) (http.Handler, error) {
}
// CheckVerifyKeys refuses an empty key table, a key ID or public key of the
-// wrong form, a role other than instance or operator, and one public key
-// under two key IDs.
+// wrong form, a role other than instance, operator or proxy, and one public
+// key under two key IDs.
func CheckVerifyKeys(keys map[hostedwire.KeyID]hostedwire.VerifyKey) error {
if len(keys) == 0 {
return errors.New("hostedctl: no verify keys")
@@ -261,8 +271,8 @@ func CheckVerifyKeys(keys map[hostedwire.KeyID]hostedwire.VerifyKey) error {
if len(k.Public) != ed25519.PublicKeySize {
return fmt.Errorf("hostedctl: public key of %s has the wrong length", id)
}
- if k.Role != hostedwire.RoleInstance && k.Role != hostedwire.RoleOperator {
- return fmt.Errorf("hostedctl: key %s has role %q; want instance or operator", id, k.Role)
+ if k.Role != hostedwire.RoleInstance && k.Role != hostedwire.RoleOperator && k.Role != hostedwire.RoleProxy {
+ return fmt.Errorf("hostedctl: key %s has role %q; want instance, operator or proxy", id, k.Role)
}
if other, dup := seen[string(k.Public)]; dup {
return fmt.Errorf("hostedctl: %w: %s and %s", hostedwire.ErrSharedKey, other, id)
diff --git a/internal/hostedctl/launch.go b/internal/hostedctl/launch.go
index db067807..43ae7e17 100644
--- a/internal/hostedctl/launch.go
+++ b/internal/hostedctl/launch.go
@@ -16,6 +16,8 @@ import (
"amadan.net/oficina/equipo/internal/hostedcert"
"amadan.net/oficina/equipo/internal/hostedctl/ctlcert"
+ "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"
)
@@ -119,10 +121,13 @@ func Deadlines(launched T, lifetime time.Duration) (deadline, drain, stop T) {
//
// In order it refuses: launches switched off (ErrDisabled); a key without
// RoleInstance, or a certification launch, which is the operator's
-// (ErrForbidden); a malformed request (isolatedjob.ErrInvalid,
-// or ErrBootstrapTooLarge; see checkRequest for the controller's own
-// limits); a wall clock past q.LaunchByUnixMS (ErrLaunchExpired); a purpose
-// whose egress services are not all set (ctlegress.ErrServiceUnset); no
+// (ErrForbidden); a malformed request (isolatedjob.ErrInvalid; see
+// checkRequest for the controller's own limits); a wall clock past
+// q.LaunchByUnixMS (ErrLaunchExpired); a purpose whose egress services are
+// not all set (ctlegress.ErrServiceUnset); a bootstrap that breaks
+// hostedwire.BootstrapV2's rules, the instance code's form among them, or
+// the runner's limits (isolatedjob.ErrInvalid, ErrBootstrapTooLarge; see
+// checkSpec); no
// certificate in Config.Certs for the image, signing the provider image
// version the image launches with at q.Size and covering every instance
// host of those services (ErrNotCertified); no passing network audit begun within
@@ -178,6 +183,9 @@ func (c *Controller) Launch(ctx context.Context, by hostedwire.KeyID, key hosted
if err != nil {
return c.refuse(ctx, by, q, err)
}
+ if err := c.checkSpec(q, services); err != nil {
+ return c.refuse(ctx, by, q, err)
+ }
cert, err := c.cfg.Certs.For(q.Image, q.Size, ctlcert.InstanceHosts(services))
if err != nil {
return c.refuse(ctx, by, q, err)
@@ -217,10 +225,7 @@ func (c *Controller) refuse(ctx context.Context, by hostedwire.KeyID, q LaunchRe
return JobView{}, err
}
-// checkRequest checks q's fields, then validates the spec q would give
-// against the runner's limits. That spec carries a placeholder launch ID of
-// the real length, so the bootstrap size checked is the size sent; the real
-// ID is drawn only in transaction 1, for a new intent.
+// checkRequest checks q's fields; checkSpec checks the bootstrap.
//
// Two limits are controller policy (ruling R16), beyond what the provider
// needs: TaskID and Account must be 1 to maxNameLen printable ASCII
@@ -241,22 +246,35 @@ func (c *Controller) checkRequest(q LaunchRequest) error {
return fmt.Errorf("%w: replaced attempt id must be printable ASCII", isolatedjob.ErrInvalid)
case q.MaxLifetime <= StopBefore:
return fmt.Errorf("%w: lifetime %v must be more than %v", isolatedjob.ErrInvalid, q.MaxLifetime, StopBefore)
- case !printableASCII(q.InstanceCode, math.MaxInt):
- // The text never repeats the code.
- return fmt.Errorf("%w: instance code must be one or more printable ASCII characters", isolatedjob.ErrInvalid)
}
- spec, err := buildSpec(q, strings.Repeat("0", launchIDLen))
+ return nil
+}
+
+// checkSpec validates the spec q would give, with services, against
+// hostedwire.BootstrapV2's rules and the runner's limits. It carries a
+// launch ID and a proxy code of the real lengths, which are drawn only in
+// transaction 1, so the bootstrap size checked is the size sent.
+func (c *Controller) checkSpec(q LaunchRequest, services []hostedwire.Service) error {
+ spec, err := buildSpec(q, strings.Repeat("0", launchIDLen), ctlproxy.CodePlaceholder, c.cfg.Manifest, services)
if err != nil {
return err
}
return spec.Validate(c.runner.Limits())
}
-// buildSpec is the LaunchSpec for q with launchID in its bootstrap.
-func buildSpec(q LaunchRequest, launchID string) (isolatedjob.LaunchSpec, error) {
- boot, err := json.Marshal(hostedwire.Bootstrap{Version: hostedwire.BootstrapVersion, LaunchID: launchID, InstanceCode: q.InstanceCode})
- if err != nil {
- return isolatedjob.LaunchSpec{}, fmt.Errorf("hostedctl: encode bootstrap: %w", err)
+// buildSpec is the LaunchSpec for q. Its bootstrap is a
+// hostedwire.BootstrapV2 with launchID, the proxy code, m's proxies and the
+// services snapshot; one Encode refuses is isolatedjob.ErrInvalid, or
+// isolatedjob.ErrBootstrapTooLarge. The error never holds a code.
+func buildSpec(q LaunchRequest, launchID, proxyCode string, m ctlegress.Manifest, services []hostedwire.Service) (isolatedjob.LaunchSpec, error) {
+ boot, err := hostedwire.BootstrapV2{Version: hostedwire.BootstrapV2Version, Purpose: q.Purpose, LaunchID: launchID,
+ AttemptID: q.AttemptID, InstanceCode: q.InstanceCode, ProxyCode: proxyCode, Proxies: m.Proxies, ProxyBoot: m.ProxyBoot,
+ ProxyCAPin: m.ProxyCAPin, Services: services}.Encode()
+ switch {
+ case errors.Is(err, hostedwire.ErrBootstrapTooLarge):
+ return isolatedjob.LaunchSpec{}, fmt.Errorf("%w: %w", isolatedjob.ErrBootstrapTooLarge, err)
+ case err != nil:
+ return isolatedjob.LaunchSpec{}, fmt.Errorf("%w: %w", isolatedjob.ErrInvalid, err)
}
return isolatedjob.LaunchSpec{AttemptID: q.AttemptID, Image: q.Image, Size: q.Size, MaxLifetime: q.MaxLifetime, Bootstrap: boot}, nil
}
@@ -342,11 +360,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,
-// builds the spec, saves the new intent with its services snapshot,
-// certificate digest and launch-by time, and returns its view (created
-// true). A conflict or a live replaced attempt is audited, committed, and
-// returned as the error.
+// 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
+// snapshot, certificate digest and launch-by time, and the code's hash
+// (ctlproxy.SaveCode), and returns its view (created true). 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)
servicesJSON, err := json.Marshal(services)
@@ -388,7 +407,11 @@ func (c *Controller) saveIntent(ctx context.Context, by hostedwire.KeyID, q Laun
if err != nil {
return err
}
- spec, err := buildSpec(q, launchID)
+ code, codeHash, err := ctlproxy.NewCode()
+ if err != nil {
+ return err
+ }
+ spec, err := buildSpec(q, launchID, code, c.cfg.Manifest, services)
if err != nil {
return err
}
@@ -407,6 +430,9 @@ 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 {
+ return err
+ }
a.Action = actionLaunchIntent
a.Reason = fmt.Sprintf("intent saved: launch %s, image %s, size %s, lifetime %v", launchID, spec.Image, spec.Size, spec.MaxLifetime)
if err := appendAudit(tx, a); err != nil {
diff --git a/internal/hostedctl/launch_test.go b/internal/hostedctl/launch_test.go
index c07f9661..1ec5f273 100644
--- a/internal/hostedctl/launch_test.go
+++ b/internal/hostedctl/launch_test.go
@@ -9,12 +9,14 @@ import (
"fmt"
"log/slog"
"path/filepath"
+ "reflect"
"strings"
"sync"
"testing"
"time"
"amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
@@ -25,9 +27,10 @@ const (
imgB = isolatedjob.ImageDigest("sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
imgOther = isolatedjob.ImageDigest("sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc")
- // testCode is the instance code every test request carries. It must
- // never appear in an audit row, an error or a JobView.
- testCode = "code-SECRET-4f2a9c"
+ // testCode is the instance code every test request carries: 32 bytes
+ // in base64url, as hostedwire.BootstrapV2 needs. It must never appear
+ // in an audit row, an error or a JobView.
+ testCode = "aW5zdGFuY2UtY29kZS1TRUNSRVQtNGYyYTljLTAwMDE"
)
var (
@@ -58,7 +61,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(),
+ cfg: Config{Enabled: true, Certs: testCerts(), ProxyCA: ctlproxytest.CA(),
ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint, Manifest: testManifest("equipo.example.com")},
}
e.store = openStore(t, e.path, e.gc)
@@ -301,12 +304,17 @@ func TestLaunchSavesIntentBeforeProvider(t *testing.T) {
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)
}
- var boot hostedwire.Bootstrap
+ var boot hostedwire.BootstrapV2
if err := json.Unmarshal(seen.spec.Bootstrap, &boot); err != nil {
t.Fatalf("bootstrap is not JSON: %v", err)
}
- if boot != (hostedwire.Bootstrap{Version: 1, LaunchID: v.LaunchID, InstanceCode: testCode}) || len(v.LaunchID) < 26 {
- t.Fatalf("bootstrap = %+v, want version 1, launch ID %q (26+ characters) and the instance code", boot, v.LaunchID)
+ m := e.cfg.Manifest
+ if boot.Version != 2 || boot.Purpose != hostedwire.PurposeChecks || boot.LaunchID != v.LaunchID || len(v.LaunchID) < 26 ||
+ boot.AttemptID != "att-1" || boot.InstanceCode != testCode || len(boot.ProxyCode) != 43 ||
+ !reflect.DeepEqual(boot.Services, svc("equipo.example.com")) || !reflect.DeepEqual(boot.Proxies, m.Proxies) ||
+ !reflect.DeepEqual(boot.ProxyBoot, m.ProxyBoot) || boot.ProxyCAPin != m.ProxyCAPin {
+ t.Fatalf("bootstrap = %+v, want version 2 for checks, launch ID %q (26+ characters), the instance code, a proxy code, "+
+ "and the manifest's proxies and services", boot, v.LaunchID)
}
wantDeadline, wantDrain, wantStop := Deadlines(launchedAt, 2*time.Hour)
if T(r.launchedT) != launchedAt || T(r.deadlineT) != wantDeadline || T(r.drainT) != wantDrain || T(r.stopT) != wantStop {
@@ -379,7 +387,7 @@ func TestLaunchConflictOnChangedRequest(t *testing.T) {
{"image", "inst-1", func(q *LaunchRequest) { q.Image = imgB }},
{"size", "inst-1", func(q *LaunchRequest) { q.Size = isolatedjob.SizeLarge }},
{"lifetime", "inst-1", func(q *LaunchRequest) { q.MaxLifetime = 3 * time.Hour }},
- {"instance code", "inst-1", func(q *LaunchRequest) { q.InstanceCode = "code-other" }},
+ {"instance code", "inst-1", func(q *LaunchRequest) { q.InstanceCode = "aW5zdGFuY2UtY29kZS1PVEhFUi0tMDAwMDAwLTAwMDI" }},
{"person", "inst-1", func(q *LaunchRequest) { q.Person = "person-2" }},
{"launch-by", "inst-1", func(q *LaunchRequest) { q.LaunchByUnixMS++ }},
{"another key", "inst-2", func(*LaunchRequest) {}},
diff --git a/internal/hostedctl/metrics.go b/internal/hostedctl/metrics.go
index ad6442d4..45a6a5b7 100644
--- a/internal/hostedctl/metrics.go
+++ b/internal/hostedctl/metrics.go
@@ -137,6 +137,14 @@ func (m *Metrics) write(ctx context.Context, w io.Writer, c *Controller) {
}
}
+ feeds, err := c.proxyLastFeeds(ctx)
+ p.head("equipo_hosted_proxy_last_feed_seconds", "gauge", "Controller time since each configured proxy last asked for the launch feed. Absent for a proxy that has not asked, or when the store could not be read.")
+ for _, id := range slices.Sorted(maps.Keys(feeds)) {
+ if err == nil {
+ p.sample("equipo_hosted_proxy_last_feed_seconds", []string{"proxy", string(id)}, feeds[id].Seconds())
+ }
+ }
+
m.mu.Lock()
launches, errs, alerts := maps.Clone(m.launches), maps.Clone(m.errs), maps.Clone(m.alerts)
m.mu.Unlock()
diff --git a/internal/hostedctl/proxy.go b/internal/hostedctl/proxy.go
new file mode 100644
index 00000000..1467f282
--- /dev/null
+++ b/internal/hostedctl/proxy.go
@@ -0,0 +1,125 @@
+package hostedctl
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+ "net/http"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+)
+
+// Wiring for the egress proxies' routes (the logic is ctlproxy's). Only a
+// proxy key may use them, and a proxy key nothing else:
+//
+// GET /v1/proxy/feed (empty body) -> hostedwire.ProxyFeed
+// POST /v1/proxy/redeem hostedwire.RedeemRequest -> hostedwire.RedeemResponse
+// POST /v1/proxy/renew hostedwire.RenewCertRequest -> hostedwire.RedeemResponse
+//
+// POST /v1/proxy/cert-report is Task 13's.
+var proxyRoutes = map[string]route{
+ "feed": {"proxy_feed", http.MethodGet, hostedwire.RoleProxy, serveFeed},
+ "redeem": {"proxy_redeem", http.MethodPost, hostedwire.RoleProxy, serveRedeem},
+ "renew": {"proxy_renew", http.MethodPost, hostedwire.RoleProxy, serveRenew},
+}
+
+func serveFeed(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, _ []byte) (any, error) {
+ return c.proxyTx(ctx, by, func(tx *sql.Tx, now ctlproxy.Now, _ ctlproxy.Audit) (any, error) {
+ return ctlproxy.Feed(ctx, tx, by, now.T)
+ })
+}
+
+func serveRedeem(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, body []byte) (any, error) {
+ var q hostedwire.RedeemRequest
+ if err := decode(body, &q); err != nil {
+ return nil, err
+ }
+ return c.proxyTx(ctx, by, func(tx *sql.Tx, now ctlproxy.Now, audit ctlproxy.Audit) (any, error) {
+ return c.cfg.ProxyCA.Redeem(ctx, tx, q, now, audit)
+ })
+}
+
+func serveRenew(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, body []byte) (any, error) {
+ var q hostedwire.RenewCertRequest
+ if err := decode(body, &q); err != nil {
+ return nil, err
+ }
+ return c.proxyTx(ctx, by, func(tx *sql.Tx, now ctlproxy.Now, audit ctlproxy.Audit) (any, error) {
+ return c.cfg.ProxyCA.Renew(ctx, tx, q, now, audit)
+ })
+}
+
+// proxyTx runs fn in one transaction, at the controller time and wall clock
+// read inside it, with audit rows by by. A refusal (ctlproxy.ErrRefused),
+// which fn has audited, is committed and then returned.
+func (c *Controller) proxyTx(ctx context.Context, by hostedwire.KeyID,
+ fn func(*sql.Tx, ctlproxy.Now, ctlproxy.Audit) (any, error)) (any, error) {
+ var out any
+ var refusal error
+ err := c.store.Tx(ctx, func(tx *sql.Tx) error {
+ out, refusal = nil, nil
+ now := ctlproxy.Now{T: time.Duration(c.store.Clock().Now()), Wall: c.store.wall()}
+ v, err := fn(tx, now, func(attempt, action, reason string) error {
+ return appendAudit(tx, Audit{Actor: by, Attempt: attempt, Action: action, Reason: reason, At: T(now.T)})
+ })
+ if errors.Is(err, ctlproxy.ErrRefused) {
+ refusal = err
+ return nil
+ }
+ out = v
+ return err
+ })
+ if err != nil {
+ return nil, err
+ }
+ return out, refusal
+}
+
+// watchProxies keeps the proxy keys of keys as the configured proxies
+// checkProxies watches.
+func (c *Controller) watchProxies(keys map[hostedwire.KeyID]hostedwire.VerifyKey) {
+ ids := ctlproxy.ProxyKeys(keys)
+ 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.
+func (c *Controller) checkProxies(ctx context.Context) error {
+ ids := c.proxies.Load()
+ if ids == nil || len(*ids) == 0 {
+ return nil
+ }
+ var silent []hostedwire.KeyID
+ now := c.store.Clock().Now()
+ 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()))
+ 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)})
+ }
+ return err
+}
+
+// proxyLastFeeds returns, for each configured proxy that has asked for the
+// feed, the controller time since its last request.
+func (c *Controller) proxyLastFeeds(ctx context.Context) (map[hostedwire.KeyID]time.Duration, error) {
+ ids := c.proxies.Load()
+ if ids == nil {
+ return nil, nil
+ }
+ var ages map[hostedwire.KeyID]time.Duration
+ err := c.store.Tx(ctx, func(tx *sql.Tx) error {
+ var err error
+ ages, err = ctlproxy.FeedAges(ctx, tx, *ids, time.Duration(c.store.Clock().Now()))
+ return err
+ })
+ return ages, err
+}
diff --git a/internal/hostedctl/reaper.go b/internal/hostedctl/reaper.go
index 43edd22f..b7872f07 100644
--- a/internal/hostedctl/reaper.go
+++ b/internal/hostedctl/reaper.go
@@ -251,6 +251,7 @@ func (c *Controller) reapPass(ctx context.Context, rep *ReapReport) error {
errs = append(errs, c.reapJobs(ctx, rep))
errs = append(errs, c.reapOrphans(ctx, rep))
errs = append(errs, c.reaperAudit(ctx))
+ errs = append(errs, c.checkProxies(ctx))
errs = append(errs, c.sendAlerts(ctx))
return errors.Join(errs...)
}
diff --git a/internal/hostedctl/resume.go b/internal/hostedctl/resume.go
index 6a637334..59572b00 100644
--- a/internal/hostedctl/resume.go
+++ b/internal/hostedctl/resume.go
@@ -7,6 +7,7 @@ import (
"fmt"
"time"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
)
@@ -178,6 +179,9 @@ func commitResume(ctx context.Context, tx *sql.Tx, j *pauseJob, op resumeOp, act
if n, err := res.RowsAffected(); err != nil || n != 1 {
return fmt.Errorf("hostedctl: commit resume %s of %s: epoch is not %d (%d rows, %v)", op.id, j.attempt, op.prepared-1, n, err)
}
+ if err := ctlproxy.Revoke(ctx, tx, j.attempt, time.Duration(now)); err != nil { // a new epoch revokes every serial
+ return err
+ }
res, err = tx.ExecContext(ctx, `UPDATE resume_ops SET status = ?, result_epoch = ?, completed_t = ?
WHERE attempt_id = ? AND operation_id = ? AND status = ?`, opDone, op.prepared, int64(now), j.attempt, op.id, opPending)
if err != nil {
diff --git a/internal/hostedctl/schema/0004_proxy.sql b/internal/hostedctl/schema/0004_proxy.sql
new file mode 100644
index 00000000..6302d617
--- /dev/null
+++ b/internal/hostedctl/schema/0004_proxy.sql
@@ -0,0 +1,52 @@
+-- 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.
+CREATE TABLE proxy_codes (
+ launch_id TEXT PRIMARY KEY REFERENCES jobs(launch_id),
+ attempt_id TEXT NOT NULL UNIQUE REFERENCES jobs(attempt_id),
+ code_sha256 TEXT NOT NULL CHECK (length(code_sha256) = 64),
+ running_t INTEGER, -- when the controller first saw the VM running: the code's window opens; absent until then
+ redeemed_t INTEGER -- absent until the code is used; it is used once
+);
+
+CREATE TRIGGER proxy_codes_immutable
+BEFORE UPDATE OF launch_id, attempt_id, code_sha256 ON proxy_codes
+WHEN NEW.launch_id IS NOT OLD.launch_id OR NEW.attempt_id IS NOT OLD.attempt_id OR NEW.code_sha256 IS NOT OLD.code_sha256
+BEGIN
+ SELECT RAISE(ABORT, 'proxy code is immutable');
+END;
+
+-- Every client certificate issued. A serial renews once; renewal, a stop,
+-- stop proof and a new epoch revoke it.
+CREATE TABLE proxy_certs (
+ serial TEXT PRIMARY KEY, -- lower-case hex of the certificate's serial number
+ launch_id TEXT NOT NULL REFERENCES jobs(launch_id),
+ attempt_id TEXT NOT NULL,
+ vm_ref TEXT NOT NULL,
+ epoch INTEGER NOT NULL,
+ issued_t INTEGER NOT NULL,
+ not_after_t INTEGER NOT NULL, -- the certificate's NotAfter in controller time
+ renewed INTEGER NOT NULL DEFAULT 0 CHECK (renewed IN (0, 1)),
+ revoked_t INTEGER -- absent until revoked
+);
+
+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).
+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))
+);
+
+-- The last feed serial: one row. Each feed takes the next.
+CREATE TABLE proxy_feed (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ serial INTEGER NOT NULL
+);
diff --git a/internal/hostedctl/sim_model_test.go b/internal/hostedctl/sim_model_test.go
index 9fb22d12..5f3bf256 100644
--- a/internal/hostedctl/sim_model_test.go
+++ b/internal/hostedctl/sim_model_test.go
@@ -358,7 +358,7 @@ func (r *simRunner) ownerLocked(s *simSnap, ref isolatedjob.Ref) string {
}
func bootLaunchID(b []byte) string {
- var boot hostedwire.Bootstrap
+ var boot hostedwire.BootstrapV2
if json.Unmarshal(b, &boot) != nil {
return ""
}
diff --git a/internal/hostedctl/sim_test.go b/internal/hostedctl/sim_test.go
index 67159323..30a196c7 100644
--- a/internal/hostedctl/sim_test.go
+++ b/internal/hostedctl/sim_test.go
@@ -18,6 +18,7 @@ import (
"time"
"amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
@@ -228,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")),
+ cfg: Config{Enabled: true, Certs: ctlcerttest.Set(ctlcerttest.Cert(imgA, "equipo.example.com")), ProxyCA: ctlproxytest.CA(),
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/stop.go b/internal/hostedctl/stop.go
index 57e20f0b..458ff310 100644
--- a/internal/hostedctl/stop.go
+++ b/internal/hostedctl/stop.go
@@ -8,6 +8,7 @@ import (
"fmt"
"time"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
)
@@ -266,6 +267,9 @@ func (c *Controller) requestStop(ctx context.Context, actor hostedwire.KeyID, at
if n, err := res.RowsAffected(); err != nil || n != 1 {
return fmt.Errorf("hostedctl: record stop request for %s: %d rows (%v)", attempt, n, err)
}
+ if err := ctlproxy.Revoke(ctx, tx, attempt, time.Duration(now)); err != nil {
+ return err
+ }
a.Action, a.Reason = actionStopRequested, "stop asked for: "+reason
if state == JobAbandoned && j.state != JobAbandoned {
a.Reason += "; intent abandoned before any VM ref was saved"
@@ -434,6 +438,9 @@ func writeProof(ctx context.Context, tx *sql.Tx, actor hostedwire.KeyID, j jobRo
if ended {
why += "; no stop was asked for, so it ended on its own"
}
+ if err := ctlproxy.Revoke(ctx, tx, j.attempt, time.Duration(p.ObservedAt)); err != nil {
+ return err
+ }
if err := appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: j.attempt,
Action: actionStopProven, Reason: why, At: p.ObservedAt}); err != nil {
return err
@@ -444,7 +451,8 @@ func writeProof(ctx context.Context, tx *sql.Tx, actor hostedwire.KeyID, j jobRo
// mirrorState saves a live VM state the provider reported as the job's
// state, unless the job holds proof. A live VM was seen, so any first
-// not-found held in notfound_since_t no longer counts and is cleared.
+// not-found held in notfound_since_t no longer counts and is cleared. The
+// first time the VM is seen running, its proxy code's window opens.
func (c *Controller) mirrorState(ctx context.Context, attempt string, st isolatedjob.State) error {
return c.store.Tx(ctx, func(tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, notfound_since_t = NULL, revision = revision + 1
@@ -454,6 +462,9 @@ func (c *Controller) mirrorState(ctx context.Context, attempt string, st isolate
if err != nil {
return fmt.Errorf("hostedctl: save state of %s: %w", attempt, err)
}
- return nil
+ if st != isolatedjob.StateRunning {
+ return nil
+ }
+ return ctlproxy.SeenRunning(ctx, tx, attempt, time.Duration(c.store.Clock().Now())) // the proxy code's window opens
})
}
diff --git a/internal/hostedctl/store.go b/internal/hostedctl/store.go
index 08295493..e621d7bd 100644
--- a/internal/hostedctl/store.go
+++ b/internal/hostedctl/store.go
@@ -51,7 +51,7 @@ var schemaFS embed.FS
// migrations are applied in order; version n is migrations[n-1]. Add a file,
// never edit one.
-var migrations = []string{"schema/0001_jobs.sql", "schema/0002_egress.sql", "schema/0003_cert.sql"}
+var migrations = []string{"schema/0001_jobs.sql", "schema/0002_egress.sql", "schema/0003_cert.sql", "schema/0004_proxy.sql"}
// schemaVersion is the newest schema this code knows.
func schemaVersion() int { return len(migrations) }
diff --git a/internal/hostedctl/store_test.go b/internal/hostedctl/store_test.go
index 7f31de36..a5077226 100644
--- a/internal/hostedctl/store_test.go
+++ b/internal/hostedctl/store_test.go
@@ -13,6 +13,7 @@ import (
"testing"
"time"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
@@ -556,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()}
+ return Config{ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint, Certs: testCerts(), ProxyCA: ctlproxytest.CA()}
}
func TestNewRefusesNilDependency(t *testing.T) {
@@ -589,6 +590,11 @@ func TestNewRefusesNilDependency(t *testing.T) {
if got, err := New(noCerts, full); err == nil || got != nil || !strings.Contains(err.Error(), "certificate") {
t.Errorf("New with no certificate set = (%v, %v), want (nil, an error naming the certificates)", got, err)
}
+ noCA := testConfig()
+ noCA.ProxyCA = nil
+ 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)
+ }
}
// TestProviderNamespaceBound: the first controller binds the database to its