oficina / equipo Public

hostedctl: exact-host egress manifest, snapshotted per launch

Slice 2 Task 2: ctlegress.Manifest (Load, For, ErrServiceUnset) with
exact lower-case FQDNs on port 443 only: no wildcard or leading dot, IP
literal, trailing dot, upper case or amadan.net. The controller config
names the manifest file (egress_manifest_file). Launch runs
LaunchRequest.Validate (400 invalid), refuses an unset service, and
copies Manifest.For(purpose) into the new jobs.services_json column
(0002_egress.sql), immutable under its own trigger; Replay never reads
the current manifest. Raises the internal/hostedctl budget record.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 1fc906c90bf1b5aadebd3582e8c3ccc23b9d99ff parent 9d35ff5
19 files changed, +771 −39
  • .rastrillo/budgets.txt +1 −1
  • cmd/equipo-hosted-controller/config.go +23 −1
  • cmd/equipo-hosted-controller/config_test.go +79 −3
  • cmd/equipo-hosted-controller/crashpoint_test.go +4 −2
  • cmd/equipo-hosted-controller/main_test.go +6 −3
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +19 −0
  • internal/hostedclient/client_test.go +14 −2
  • internal/hostedclient/driver_test.go +2 −1
  • internal/hostedctl/controller.go +5 −0
  • internal/hostedctl/ctlegress/manifest.go +197 −0
  • internal/hostedctl/ctlegress/manifest_test.go +166 −0
  • internal/hostedctl/egress_test.go +183 −0
  • internal/hostedctl/http.go +2 −1
  • internal/hostedctl/http_test.go +2 −1
  • internal/hostedctl/launch.go +39 −19
  • internal/hostedctl/launch_test.go +11 −2
  • internal/hostedctl/schema/0002_egress.sql +14 −0
  • internal/hostedctl/sim_test.go +3 −2
  • internal/hostedctl/store.go +1 −1
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 2436ecfa..8dc3d595 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 5313 8516 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).
+size internal/hostedctl 5339 8710 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), measured 5339/8710.
diff --git a/cmd/equipo-hosted-controller/config.go b/cmd/equipo-hosted-controller/config.go
index 819d6342..6aea26fd 100644
--- a/cmd/equipo-hosted-controller/config.go
+++ b/cmd/equipo-hosted-controller/config.go
@@ -12,6 +12,7 @@ import (
"strings"
"amadan.net/oficina/equipo/internal/hostedctl"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/oficina/equipo/internal/isolatedjob/awsjob"
@@ -54,6 +55,10 @@ type fileConfig struct {
// the VM security group has no outbound rules (ruling R30).
Egress []string `json:"egress"`
SNSTopicARN string `json:"sns_topic_arn"`
+ // EgressManifestFile is the egress manifest (ctlegress.Load): the exact
+ // service hosts VMs may reach through the proxies, and the proxies. A
+ // service named but unset loads, and blocks launches until it is set.
+ EgressManifestFile string `json:"egress_manifest_file"`
}
// keyEntry is one verify key: its ID, role (instance or operator) and
@@ -120,7 +125,8 @@ func (fc fileConfig) check() (config, error) {
return config{}, errors.New("listen and metrics_listen must differ")
}
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} {
+ "database": fc.Database, "signing_key_file": fc.SigningKeyFile, "sns_topic_arn": fc.SNSTopicARN,
+ "egress_manifest_file": fc.EgressManifestFile} {
if v == "" {
return config{}, fmt.Errorf("%s is required", name)
}
@@ -140,9 +146,25 @@ func (fc fileConfig) check() (config, error) {
}
c.ctl.Egress = c.aws.Egress
c.ctl.ProviderFingerprint = c.aws.Fingerprint
+ if c.ctl.Manifest, err = readManifest(fc.EgressManifestFile); err != nil {
+ return config{}, err
+ }
return c, nil
}
+// readManifest reads and checks the egress manifest at path.
+func readManifest(path string) (ctlegress.Manifest, error) {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return ctlegress.Manifest{}, fmt.Errorf("egress manifest: %w", err)
+ }
+ m, err := ctlegress.Load(raw)
+ if err != nil {
+ return ctlegress.Manifest{}, fmt.Errorf("egress manifest %s: %w", path, err)
+ }
+ return m, nil
+}
+
// checkListen accepts only "IP:port" with a specific IP: a wildcard
// (0.0.0.0, ::) or an empty host (":port") would listen on every interface,
// and a host name could resolve to anything.
diff --git a/cmd/equipo-hosted-controller/config_test.go b/cmd/equipo-hosted-controller/config_test.go
index e1e7512a..8f55d163 100644
--- a/cmd/equipo-hosted-controller/config_test.go
+++ b/cmd/equipo-hosted-controller/config_test.go
@@ -5,11 +5,14 @@ import (
"crypto/ed25519"
"encoding/base64"
"encoding/json"
+ "errors"
"os"
"path/filepath"
+ "reflect"
"strings"
"testing"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/rastrillo/rastrillo/budget"
)
@@ -31,6 +34,10 @@ func validConfig(t *testing.T, dir string) fileConfig {
if err := os.WriteFile(keyPath, []byte(seed+"\n"), 0o600); err != nil {
t.Fatal(err)
}
+ manifestPath := filepath.Join(dir, "egress.json")
+ if err := os.WriteFile(manifestPath, manifestBody("equipo.example.com"), 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",
@@ -42,9 +49,78 @@ func validConfig(t *testing.T, dir string) fileConfig {
Images: []imageEntry{{Digest: testDigest, ARN: "arn:aws:lambda:eu-west-1:123456789012:microvm-image:img",
Versions: map[string]string{"small": "1", "large": "2"}}},
Region: "eu-west-1", VPCID: "vpc-1", VMSubnetID: "subnet-1", VMSecurityGroupID: "sg-1",
- ConnectorARN: "arn:aws:lambda:eu-west-1:123456789012:network-connector:egress:3",
- Egress: []string{},
- SNSTopicARN: "arn:aws:sns:eu-west-1:123456789012:equipo-hosted",
+ ConnectorARN: "arn:aws:lambda:eu-west-1:123456789012:network-connector:egress:3",
+ Egress: []string{},
+ SNSTopicARN: "arn:aws:sns:eu-west-1:123456789012:equipo-hosted",
+ EgressManifestFile: manifestPath,
+ }
+}
+
+// testEgress is the manifest of manifestBody("equipo.example.com"), for
+// tests that build a controller directly.
+var testEgress = func() ctlegress.Manifest {
+ m, err := ctlegress.Load(manifestBody("equipo.example.com"))
+ if err != nil {
+ panic(err)
+ }
+ return m
+}()
+
+const testPin = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+
+// manifestBody is an egress manifest whose instance service is host.
+func manifestBody(host string) []byte {
+ return []byte(`{"services":{"instance":{"host":"` + host + `","port":443,"class":"instance"}},` +
+ `"proxies":["10.42.1.10:8443"],"proxy_boot":["10.42.1.10:8444"],"proxy_ca_pin":"` + testPin + `"}`)
+}
+
+// TestManifestFromConfig: the controller reads its egress manifest from the
+// file the config names, with ctlegress.Load's rules. An unset name loads
+// (it blocks launch, not start); a wildcard, an IP literal or the forge does
+// not.
+func TestManifestFromConfig(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ c, err := loadFC(t, dir, validConfig(t, dir))
+ if err != nil {
+ t.Fatalf("valid config: %v", err)
+ }
+ want := []hostedwire.Service{{Host: "equipo.example.com", Port: 443, Class: hostedwire.ServiceInstance}}
+ if got, err := c.ctl.Manifest.For(hostedwire.PurposeChecks); err != nil || !reflect.DeepEqual(got, want) ||
+ c.ctl.Manifest.ProxyCAPin != testPin || len(c.ctl.Manifest.Proxies) != 1 {
+ t.Fatalf("manifest loaded as %+v (For: %+v, %v), want the file's", c.ctl.Manifest, got, err)
+ }
+
+ unset := filepath.Join(dir, "unset.json")
+ if err := os.WriteFile(unset, manifestBody(""), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ fc := validConfig(t, dir)
+ fc.EgressManifestFile = unset
+ if c, err := loadFC(t, dir, fc); err != nil {
+ t.Fatalf("manifest with the name unset: %v, want it to load", err)
+ } else if _, err := c.ctl.Manifest.For(hostedwire.PurposeChecks); !errors.Is(err, ctlegress.ErrServiceUnset) {
+ t.Fatalf("unset manifest: For = %v, want ErrServiceUnset", err)
+ }
+
+ for _, host := range []string{"*.example.com", ".example.com", "1.2.3.4", "[::1]", "amadan.net", "forge.amadan.net",
+ "equipo.example.com.", "Equipo.example.com"} {
+ path := filepath.Join(t.TempDir(), "egress.json")
+ if err := os.WriteFile(path, manifestBody(host), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ fc := validConfig(t, dir)
+ fc.EgressManifestFile = path
+ if _, err := loadFC(t, dir, fc); !errors.Is(err, ctlegress.ErrManifest) {
+ t.Errorf("manifest host %q: %v, want ErrManifest", host, err)
+ }
+ }
+ for name, path := range map[string]string{"no manifest file": "", "missing manifest file": filepath.Join(dir, "absent.json")} {
+ fc := validConfig(t, dir)
+ fc.EgressManifestFile = path
+ if _, err := loadFC(t, dir, fc); err == nil {
+ t.Errorf("%s: config loaded, want a refusal", name)
+ }
}
}
diff --git a/cmd/equipo-hosted-controller/crashpoint_test.go b/cmd/equipo-hosted-controller/crashpoint_test.go
index 76cc273a..7c7a2bba 100644
--- a/cmd/equipo-hosted-controller/crashpoint_test.go
+++ b/cmd/equipo-hosted-controller/crashpoint_test.go
@@ -29,7 +29,8 @@ func crashCtl(t *testing.T, path string, clk *isolatedjobtest.FakeClock, run iso
}
t.Cleanup(func() { _ = store.Close() }) // a second Close does nothing
c, err := hostedctl.New(hostedctl.Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{testDigest: true},
- ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" }},
+ ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
+ Manifest: testEgress},
hostedctl.Deps{Store: store, Runner: run, Auditor: fake, Alerter: nopAlerter{}})
if err != nil {
t.Fatal(err)
@@ -59,7 +60,8 @@ 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: "code-1",
+ Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: 1796083200000}
t.Setenv(crashAfterLaunchEnv, "1")
if runnerHook == nil {
diff --git a/cmd/equipo-hosted-controller/main_test.go b/cmd/equipo-hosted-controller/main_test.go
index e7426349..164762a4 100644
--- a/cmd/equipo-hosted-controller/main_test.go
+++ b/cmd/equipo-hosted-controller/main_test.go
@@ -63,7 +63,8 @@ func newTestCtl(t *testing.T, wrap func(*isolatedjob.Fake) isolatedjob.Runner) *
}
t.Cleanup(func() { _ = store.Close() })
c, err := hostedctl.New(hostedctl.Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{testDigest: true},
- ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" }},
+ ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
+ Manifest: testEgress},
hostedctl.Deps{Store: store, Runner: run, Auditor: fake, Alerter: nopAlerter{}})
if err != nil {
t.Fatal(err)
@@ -234,7 +235,8 @@ 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"}); err != nil {
+ Size: isolatedjob.SizeSmall, MaxLifetime: 2 * time.Hour, InstanceCode: "code-1",
+ Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: 1796083200000}); err != nil {
t.Fatal(err)
}
gb.armed.Store(true)
@@ -320,7 +322,8 @@ 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: "code-1",
+ 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 {
t.Fatal(err)
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 1992b7fa..4064d013 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -16,3 +16,22 @@ Mutation checks (each restored, then the GREEN command passed again):
4. (extra) Drop the person rule for checks in `LaunchRequest.Validate` (`internal/hostedwire/api.go`). `go test ./internal/hostedwire -run TestLaunchRequestV2Strict -count=1`: FAIL, `api_test.go:163: empty person for checks: decode and Validate = <nil>, want hostedwire: launch request is not valid`. Restored.
Also run: `go test ./internal/wire/... ./internal/hostedwire ./internal/hostedctl/... ./internal/hostedclient -count=1` ok (after moving the existing tests' current-protocol pins from 38 to 39); `go test ./internal/runner/thin ./internal/equipo/chat ./internal/thintest -run 'Protocol|Hello|Welcome|Spoken|Downgrade|Mixed|Older' -count=1` ok; `make budget` ok after raising the `internal/wire` record to 9848; `make build vet` ok.
+
+## Task 2
+
+Egress manifest (`internal/hostedctl/ctlegress`) and the per-launch services snapshot. The controller config names the manifest file (`egress_manifest_file`, required); `hostedctl.Config.Manifest` holds it. `Launch` now runs `hostedwire.LaunchRequest.Validate` (refused as `isolatedjob.ErrInvalid`, 400) and snapshots `Manifest.For(purpose)` into the new `jobs.services_json` (migration `0002_egress.sql`, with its own immutability trigger `jobs_services_immutable`); an unset name refuses the launch (`ctlegress.ErrServiceUnset`, audited). `jobs.purpose` now holds the request's purpose. The request hash covers purpose, person and launch-by. The VM bootstrap is unchanged (v1): the snapshot is the launch record's, for the proxy feed and certificates of later tasks.
+
+RED: `go test ./internal/hostedctl/ctlegress -run TestManifest -count=1` failed to build (`undefined: Load`, `undefined: Manifest`, `undefined: ErrManifest`, `undefined: ErrServiceUnset`). `go test ./internal/hostedctl/... ./cmd/equipo-hosted-controller -run 'TestManifest|TestUnsetService|TestLaunchSnapshots|TestSnapshotImmutable' -count=1` failed to build (`e.cfg.Manifest undefined`, `unknown field Purpose in struct literal of type LaunchRequest`); `go vet ./cmd/equipo-hosted-controller` failed (`unknown field EgressManifestFile in struct literal of type fileConfig`).
+
+GREEN: the same command: `ok internal/hostedctl`, `ok internal/hostedctl/ctlegress`, `ok cmd/equipo-hosted-controller` (TestManifestRefusesWildcardsAndLiterals, TestManifestRefusesBadShape, TestManifestForBothPurposes, TestManifestUnsetServiceBlocksLaunch, TestUnsetServiceBlocksLaunch, TestLaunchSnapshotsServices, TestSnapshotImmutable, TestManifestFromConfig).
+
+Mutation checks (each restored, then the GREEN command passed again):
+
+1. Suffix match in `Load`: `ExactHost` began with `h = strings.TrimPrefix(strings.TrimPrefix(h, "*"), ".")`. `go test ./internal/hostedctl/ctlegress -run TestManifestRefusesWildcardsAndLiterals -count=1`: FAIL, `manifest_test.go:70: host "*.example.com" port 443: Load = ({...}, <nil>), want ErrManifest` (and `".example.com"`). Restored.
+2. Replay from current config, as a gate: `dispatch` refused when `c.cfg.Manifest.For(...)` failed. `go test ./internal/hostedctl -run TestLaunchSnapshotsServices -count=1`: FAIL, `egress_test.go:134: Replay provider calls = 0, want 1: the snapshot, not the current manifest, governs a saved intent`. Restored.
+3. Replay from current config, as a re-snapshot: `dispatch` wrote `services_json` from the current manifest. Same command: FAIL, `egress_test.go:113: throttled Replay under a new manifest = constraint failed: services are immutable (1811)`. With the trigger also removed from `0002_egress.sql`: `egress_test.go:120: services after a manifest change = [{Host:two.example.com Port:443 Class:instance}], want the snapshot` and `egress_test.go:175: UPDATE jobs SET services_json = '[]' ... = <nil>, want the immutability trigger to refuse it` (TestSnapshotImmutable). Restored.
+4. (extra) Forge matched exactly only (`if h == forge`). `go test ./internal/hostedctl/ctlegress -run TestManifestRefusesWildcardsAndLiterals -count=1`: FAIL, `host "forge.amadan.net" port 443: Load = ({...}, <nil>), want ErrManifest`. Restored.
+5. (extra) `Validate` result ignored in `checkRequest`. `go test ./internal/hostedctl -run TestLaunchRefusals -count=1`: FAIL, `TestLaunchRefusals/checks_without_a_person: launch_test.go:843: Launch = ({... State:starting ...}, <nil>), want (zero view, isolatedjob: invalid request)`. Restored.
+6. (extra) `For` error ignored in `Launch`. `go test ./internal/hostedctl -run TestUnsetServiceBlocksLaunch -count=1`: FAIL, `egress_test.go:65: no manifest, checks: Launch = ({... State:starting ...}, <nil>), want ErrServiceUnset`. Restored.
+
+Also run: `go test ./internal/hostedctl/... ./cmd/equipo-hosted-controller -count=1` ok (TestLifecycleSimulation and the 1a launch, HTTP and main tests with fixtures given a manifest and the slice 2 request fields); `go test ./internal/hostedclient -count=1` ok (its fixtures likewise); `go vet -tags hostedlive` on the three packages ok; `make budget` ok after raising the `internal/hostedctl` record to 5339/8710; `make build vet` ok.
diff --git a/internal/hostedclient/client_test.go b/internal/hostedclient/client_test.go
index 93c5ca02..389c5ef9 100644
--- a/internal/hostedclient/client_test.go
+++ b/internal/hostedclient/client_test.go
@@ -10,6 +10,7 @@ import (
"net"
"net/http"
"net/http/httptest"
+ "net/netip"
"os"
"os/exec"
"path/filepath"
@@ -19,6 +20,7 @@ import (
"time"
"amadan.net/oficina/equipo/internal/hostedctl"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
"amadan.net/oficina/equipo/internal/hostedwire"
"amadan.net/oficina/equipo/internal/isolatedjob"
"amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
@@ -68,7 +70,8 @@ func newCtlEnv(t *testing.T) *ctlEnv {
t.Cleanup(func() { _ = store.Close() })
fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits())
c, err := hostedctl.New(hostedctl.Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true},
- ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" }},
+ ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" },
+ Manifest: testEgress},
hostedctl.Deps{Store: store, Runner: fake, Auditor: fake, Alerter: nopAlerter{}})
if err != nil {
t.Fatalf("New = %v", err)
@@ -123,9 +126,18 @@ func newClient(t *testing.T, srv *httptest.Server, key ed25519.PrivateKey, ctl e
return cl
}
+// testEgress is an egress manifest whose one instance service is set.
+var testEgress = ctlegress.Manifest{
+ Services: map[string]hostedwire.Service{"instance": {Host: "equipo.example.com", Port: 443, Class: hostedwire.ServiceInstance}},
+ 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),
+}
+
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: "code-test-1",
+ Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: 1796083200000}
}
func TestClientAgainstController(t *testing.T) {
diff --git a/internal/hostedclient/driver_test.go b/internal/hostedclient/driver_test.go
index 34ae6c74..3082d00d 100644
--- a/internal/hostedclient/driver_test.go
+++ b/internal/hostedclient/driver_test.go
@@ -43,7 +43,8 @@ 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}
+ InstanceCode: "task17-code-" + attempt, Purpose: hostedwire.PurposeChecks, Person: "task17-live",
+ LaunchByUnixMS: 1796083200000}
}
// vmGuard stops an attempt's VM when the step that registered it ends
diff --git a/internal/hostedctl/controller.go b/internal/hostedctl/controller.go
index 90ba58a9..6427696b 100644
--- a/internal/hostedctl/controller.go
+++ b/internal/hostedctl/controller.go
@@ -9,6 +9,7 @@ import (
"reflect"
"slices"
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
"amadan.net/oficina/equipo/internal/isolatedjob"
)
@@ -39,6 +40,9 @@ type Config struct {
// a dispatch under a different one abandons the intent (ruling R29), as
// re-sending it would not repeat the request a lost reply answered.
ProviderFingerprint func(isolatedjob.ImageDigest, isolatedjob.Size) string
+ // Manifest is the egress manifest. Launch snapshots Manifest.For(purpose)
+ // into each new intent; an unset name refuses the launch.
+ Manifest ctlegress.Manifest
}
// ErrProviderMismatch: the database belongs to another provider namespace
@@ -107,6 +111,7 @@ func New(cfg Config, d Deps) (*Controller, error) {
}
cfg.Images = maps.Clone(cfg.Images)
cfg.Egress = slices.Clone(cfg.Egress)
+ cfg.Manifest = cfg.Manifest.Clone()
log := d.Log
if log == nil {
log = slog.New(slog.DiscardHandler)
diff --git a/internal/hostedctl/ctlegress/manifest.go b/internal/hostedctl/ctlegress/manifest.go
new file mode 100644
index 00000000..0d12cac0
--- /dev/null
+++ b/internal/hostedctl/ctlegress/manifest.go
@@ -0,0 +1,197 @@
+// Package ctlegress reads the controller's egress manifest: the exact
+// service hosts a hosted VM may reach through the egress proxies, and the
+// proxies themselves.
+//
+// Every service is one exact, lower-case, fully qualified host name on port
+// 443 (spec §6). There is no wildcard or suffix match, no IP literal, and
+// never amadan.net or a name under it. The controller copies a launch's
+// services into its launch record when the intent is saved; later manifest
+// changes never reach a saved intent.
+package ctlegress
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "maps"
+ "net/netip"
+ "slices"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+)
+
+// ServicePort is the only port a service may use.
+const ServicePort = 443
+
+// forge is the forge's host name. Workers never reach it, or any name under
+// it, while the personal primary supplies source and publishes candidates.
+const forge = "amadan.net"
+
+// maxProxies: one egress proxy, or two in two availability zones.
+const maxProxies = 2
+
+var (
+ // ErrManifest is a manifest Load refuses.
+ ErrManifest = errors.New("ctlegress: egress manifest is not valid")
+ // ErrServiceUnset is a purpose whose services are not all set: an unset
+ // name blocks launch.
+ ErrServiceUnset = errors.New("ctlegress: an egress service for this purpose is not set")
+ // ErrPurpose is a purpose the manifest does not know.
+ ErrPurpose = errors.New("ctlegress: unknown launch purpose")
+)
+
+// Manifest is the egress manifest. Services are keyed by name; a service
+// with an empty Host is named but unset, and blocks launch until the
+// operator sets it. Proxies are the egress listeners and ProxyBoot the
+// bootstrap listeners, on the same hosts in the same order. ProxyCAPin is
+// the hex SHA-256 of the intercept CA's SPKI.
+type Manifest struct {
+ Services map[string]hostedwire.Service `json:"services"`
+ Proxies []netip.AddrPort `json:"proxies"`
+ ProxyBoot []netip.AddrPort `json:"proxy_boot"`
+ ProxyCAPin string `json:"proxy_ca_pin"`
+}
+
+// Load reads raw with hostedwire.DecodeStrict and checks every rule above.
+// An unset service loads; For refuses it.
+func Load(raw []byte) (Manifest, error) {
+ var m Manifest
+ if err := hostedwire.DecodeStrict(bytes.NewReader(raw), &m); err != nil {
+ return Manifest{}, fmt.Errorf("%w: %v", ErrManifest, err)
+ }
+ if err := m.check(); err != nil {
+ return Manifest{}, fmt.Errorf("%w: %v", ErrManifest, err)
+ }
+ return m, nil
+}
+
+func (m Manifest) check() error {
+ for name, s := range m.Services {
+ switch {
+ case s.Class != hostedwire.ServiceInstance:
+ return fmt.Errorf("service %q: class %q is not %q", name, s.Class, hostedwire.ServiceInstance)
+ case s.Port != ServicePort:
+ return fmt.Errorf("service %q: port %d is not %d", name, s.Port, ServicePort)
+ case s.Host != "":
+ if err := ExactHost(s.Host); err != nil {
+ return fmt.Errorf("service %q: %w", name, err)
+ }
+ }
+ }
+ if len(m.Proxies) == 0 || len(m.Proxies) > maxProxies || len(m.ProxyBoot) != len(m.Proxies) {
+ return fmt.Errorf("%d proxies and %d bootstrap listeners; want 1 or 2 of each", len(m.Proxies), len(m.ProxyBoot))
+ }
+ for i, p := range m.Proxies {
+ boot := m.ProxyBoot[i]
+ if !listener(p) || !listener(boot) || boot.Addr() != p.Addr() || boot.Port() == p.Port() {
+ return fmt.Errorf("proxy %d: %s and bootstrap %s must be one specific address on two ports", i, p, boot)
+ }
+ }
+ if !sha256Hex(m.ProxyCAPin) {
+ return errors.New("proxy_ca_pin is not 64 lower-case hex digits")
+ }
+ return nil
+}
+
+// ExactHost returns nil if h is an exact, lower-case, fully qualified DNS
+// name with at least two labels and no trailing dot: no wildcard or leading
+// dot, no IP literal (bracketed or not, nor a numeric last label, which
+// some resolvers read as an address), and not amadan.net or a name under it.
+func ExactHost(h string) error {
+ if h == "" || len(h) > hostedwire.MaxHostLen {
+ return fmt.Errorf("host %q must be 1 to %d characters", h, hostedwire.MaxHostLen)
+ }
+ if _, err := netip.ParseAddr(strings.Trim(h, "[]")); err == nil {
+ return fmt.Errorf("host %q is an IP literal", h)
+ }
+ labels := strings.Split(h, ".")
+ if len(labels) < 2 {
+ return fmt.Errorf("host %q is not fully qualified", h)
+ }
+ for _, l := range labels {
+ if !dnsLabel(l) {
+ return fmt.Errorf("host %q: label %q is not 1 to 63 of a-z, 0-9 and inner hyphens", h, l)
+ }
+ }
+ if allDigits(labels[len(labels)-1]) {
+ return fmt.Errorf("host %q has a numeric last label", h)
+ }
+ if h == forge || strings.HasSuffix(h, "."+forge) {
+ return fmt.Errorf("host %q is the forge or under it", h)
+ }
+ return nil
+}
+
+// dnsLabel is 1 to 63 of a-z, 0-9 and hyphen, not starting or ending with a
+// hyphen. A "*" or an empty label (a leading, trailing or doubled dot) fails.
+func dnsLabel(l string) bool {
+ if l == "" || len(l) > 63 || l[0] == '-' || l[len(l)-1] == '-' {
+ return false
+ }
+ for i := 0; i < len(l); i++ {
+ if c := l[i]; !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
+ return false
+ }
+ }
+ return true
+}
+
+func allDigits(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if s[i] < '0' || s[i] > '9' {
+ return false
+ }
+ }
+ return s != ""
+}
+
+// listener is one specific address and a port, without a zone.
+func listener(p netip.AddrPort) bool {
+ return p.IsValid() && p.Port() != 0 && p.Addr().Zone() == "" && !p.Addr().Unmap().IsUnspecified()
+}
+
+// sha256Hex is 64 lower-case hex digits.
+func sha256Hex(s string) bool {
+ if len(s) != 64 {
+ 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
+}
+
+// For returns the services a VM launched for purpose may reach, sorted by
+// name, as a new slice. Both purposes get the instance class: a checks VM
+// talks to its instance, and a certification VM uses it as its positive
+// control (its report goes through the proxy bootstrap listener, not as
+// egress). ErrServiceUnset: no instance service, or one with no host.
+func (m Manifest) For(purpose string) ([]hostedwire.Service, error) {
+ if purpose != hostedwire.PurposeChecks && purpose != hostedwire.PurposeCertification {
+ return nil, fmt.Errorf("%w %q", ErrPurpose, purpose)
+ }
+ var out []hostedwire.Service
+ for _, name := range slices.Sorted(maps.Keys(m.Services)) {
+ s := m.Services[name]
+ if s.Class != hostedwire.ServiceInstance {
+ continue
+ }
+ if s.Host == "" {
+ return nil, fmt.Errorf("%w: %q has no host", ErrServiceUnset, name)
+ }
+ out = append(out, s)
+ }
+ if len(out) == 0 {
+ return nil, fmt.Errorf("%w: no %s service", ErrServiceUnset, hostedwire.ServiceInstance)
+ }
+ return out, nil
+}
+
+// Clone returns a deep copy of m.
+func (m Manifest) Clone() Manifest {
+ return Manifest{Services: maps.Clone(m.Services), Proxies: slices.Clone(m.Proxies),
+ ProxyBoot: slices.Clone(m.ProxyBoot), ProxyCAPin: m.ProxyCAPin}
+}
diff --git a/internal/hostedctl/ctlegress/manifest_test.go b/internal/hostedctl/ctlegress/manifest_test.go
new file mode 100644
index 00000000..4fba550b
--- /dev/null
+++ b/internal/hostedctl/ctlegress/manifest_test.go
@@ -0,0 +1,166 @@
+package ctlegress
+
+import (
+ "encoding/json"
+ "errors"
+ "net/netip"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/rastrillo/rastrillo/budget"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+
+const testPin = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+
+// manifestJSON is a valid manifest whose instance service has host and port.
+func manifestJSON(host string, port int) []byte {
+ m := map[string]any{
+ "services": map[string]any{"instance": map[string]any{"host": host, "port": port, "class": "instance"}},
+ "proxies": []string{"10.42.1.10:8443", "10.42.2.10:8443"},
+ "proxy_boot": []string{"10.42.1.10:8444", "10.42.2.10:8444"},
+ "proxy_ca_pin": testPin,
+ }
+ b, err := json.Marshal(m)
+ if err != nil {
+ panic(err)
+ }
+ return b
+}
+
+func TestManifestRefusesWildcardsAndLiterals(t *testing.T) {
+ t.Parallel()
+ m, err := Load(manifestJSON("equipo.example.com", 443))
+ if err != nil {
+ t.Fatalf("valid manifest: Load = %v", err)
+ }
+ want := Manifest{
+ Services: map[string]hostedwire.Service{"instance": {Host: "equipo.example.com", Port: 443, Class: hostedwire.ServiceInstance}},
+ Proxies: []netip.AddrPort{netip.MustParseAddrPort("10.42.1.10:8443"), netip.MustParseAddrPort("10.42.2.10:8443")},
+ ProxyBoot: []netip.AddrPort{netip.MustParseAddrPort("10.42.1.10:8444"), netip.MustParseAddrPort("10.42.2.10:8444")},
+ ProxyCAPin: testPin,
+ }
+ if !reflect.DeepEqual(m, want) {
+ t.Fatalf("Load = %+v, want %+v", m, want)
+ }
+ for _, ok := range []string{"a.b", "x-1.example.co.uk", "equipo-7.tail5fd3ba.ts.net", "amadan.network", "notamadan.net"} {
+ if _, err := Load(manifestJSON(ok, 443)); err != nil {
+ t.Errorf("host %q: Load = %v, want it accepted", ok, err)
+ }
+ }
+ bad := []struct {
+ host string
+ port int
+ }{
+ {"*.x", 443}, {"*.example.com", 443}, {".x", 443}, {".example.com", 443},
+ {"1.2.3.4", 443}, {"[::1]", 443}, {"::1", 443}, {"[2001:db8::1]", 443}, {"127.1", 443}, {"10.0.0.1.", 443},
+ {"amadan.net", 443}, {"forge.amadan.net", 443}, {"a.b.amadan.net", 443},
+ {"equipo.example.com.", 443}, {"Equipo.example.com", 443}, {"EQUIPO.EXAMPLE.COM", 443},
+ {"equipo.example.com", 8443}, {"equipo.example.com", 80}, {"equipo.example.com", 0},
+ {"localhost", 443}, {"a..b", 443}, {"-a.example.com", 443}, {"a-.example.com", 443},
+ {"a_b.example.com", 443}, {"equipo.example.com:443", 443}, {"équipo.example.com", 443},
+ {"a." + strings.Repeat("b", 64) + ".com", 443}, {strings.Repeat("abcdefgh.", 32) + "com", 443},
+ }
+ for _, c := range bad {
+ if m, err := Load(manifestJSON(c.host, c.port)); !errors.Is(err, ErrManifest) {
+ t.Errorf("host %q port %d: Load = (%+v, %v), want ErrManifest", c.host, c.port, m, err)
+ }
+ }
+}
+
+func TestManifestRefusesBadShape(t *testing.T) {
+ t.Parallel()
+ edit := func(f func(m map[string]any)) []byte {
+ var m map[string]any
+ if err := json.Unmarshal(manifestJSON("equipo.example.com", 443), &m); err != nil {
+ t.Fatal(err)
+ }
+ f(m)
+ b, err := json.Marshal(m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+ }
+ svc := func(class string) map[string]any {
+ return map[string]any{"instance": map[string]any{"host": "equipo.example.com", "port": 443, "class": class}}
+ }
+ cases := map[string][]byte{
+ "unknown field": edit(func(m map[string]any) { m["extra"] = 1 }),
+ "no proxies": edit(func(m map[string]any) { m["proxies"], m["proxy_boot"] = []string{}, []string{} }),
+ "three proxies": edit(func(m map[string]any) { m["proxies"] = []string{"10.0.0.1:1", "10.0.0.2:1", "10.0.0.3:1"} }),
+ "boot count differs": edit(func(m map[string]any) { m["proxy_boot"] = []string{"10.42.1.10:8444"} }),
+ "boot on other host": edit(func(m map[string]any) { m["proxy_boot"] = []string{"10.42.1.11:8444", "10.42.2.10:8444"} }),
+ "boot on egress port": edit(func(m map[string]any) {
+ m["proxy_boot"] = []string{"10.42.1.10:8443", "10.42.2.10:8444"}
+ }),
+ "wildcard proxy": edit(func(m map[string]any) { m["proxies"] = []string{"0.0.0.0:8443", "10.42.2.10:8443"} }),
+ "bad pin": edit(func(m map[string]any) { m["proxy_ca_pin"] = strings.ToUpper(testPin) }),
+ "unknown class": edit(func(m map[string]any) { m["services"] = svc("gateway") }),
+ "empty class": edit(func(m map[string]any) { m["services"] = svc("") }),
+ "upper-case name": []byte(strings.Replace(string(manifestJSON("equipo.example.com", 443)), `"instance":{`, `"Instance":{`, 1)),
+ "not JSON": []byte("{"),
+ "trailing content": append(manifestJSON("equipo.example.com", 443), []byte(" {}")...),
+ }
+ for name, raw := range cases {
+ if m, err := Load(raw); err == nil {
+ t.Errorf("%s: Load = %+v, want an error", name, m)
+ }
+ }
+}
+
+func TestManifestForBothPurposes(t *testing.T) {
+ t.Parallel()
+ m, err := Load(manifestJSON("equipo.example.com", 443))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []hostedwire.Service{{Host: "equipo.example.com", Port: 443, Class: hostedwire.ServiceInstance}}
+ for _, p := range []string{hostedwire.PurposeChecks, hostedwire.PurposeCertification} {
+ got, err := m.For(p)
+ if err != nil || !reflect.DeepEqual(got, want) {
+ t.Fatalf("For(%q) = (%+v, %v), want %+v", p, got, err, want)
+ }
+ got[0].Host = "changed.example.com"
+ if again, _ := m.For(p); !reflect.DeepEqual(again, want) {
+ t.Fatalf("changing For's result changed the manifest: %+v", again)
+ }
+ }
+ for _, p := range []string{"", "task", "Checks", "gateway"} {
+ if got, err := m.For(p); err == nil || errors.Is(err, ErrServiceUnset) {
+ t.Fatalf("For(%q) = (%+v, %v), want an unknown purpose error", p, got, err)
+ }
+ }
+ c := m.Clone()
+ c.Services["instance"] = hostedwire.Service{Host: "other.example.com", Port: 443, Class: hostedwire.ServiceInstance}
+ c.Proxies[0] = netip.MustParseAddrPort("10.9.9.9:1")
+ if got, _ := m.For(hostedwire.PurposeChecks); !reflect.DeepEqual(got, want) || m.Proxies[0].Addr().String() != "10.42.1.10" {
+ t.Fatalf("changing a Clone changed the manifest: %+v", m)
+ }
+}
+
+func TestManifestUnsetServiceBlocksLaunch(t *testing.T) {
+ t.Parallel()
+ unset, err := Load(manifestJSON("", 443))
+ if err != nil {
+ t.Fatalf("an unset name must load (it blocks launch, not start): %v", err)
+ }
+ none, err := Load([]byte(`{"services":{},"proxies":["10.42.1.10:8443"],"proxy_boot":["10.42.1.10:8444"],"proxy_ca_pin":"` + testPin + `"}`))
+ if err != nil {
+ t.Fatalf("a manifest with no services must load: %v", err)
+ }
+ for name, m := range map[string]Manifest{"unset host": unset, "no services": none, "zero manifest": {}} {
+ for _, p := range []string{hostedwire.PurposeChecks, hostedwire.PurposeCertification} {
+ if got, err := m.For(p); !errors.Is(err, ErrServiceUnset) || got != nil {
+ t.Errorf("%s: For(%q) = (%+v, %v), want ErrServiceUnset and no services", name, p, got, err)
+ }
+ }
+ }
+ if _, err := Load(manifestJSON("", 8443)); !errors.Is(err, ErrManifest) {
+ t.Fatalf("unset host on port 8443: Load = %v, want ErrManifest", err)
+ }
+}
diff --git a/internal/hostedctl/egress_test.go b/internal/hostedctl/egress_test.go
new file mode 100644
index 00000000..6cedc6f5
--- /dev/null
+++ b/internal/hostedctl/egress_test.go
@@ -0,0 +1,183 @@
+package hostedctl
+
+import (
+ "bytes"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "net/netip"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlegress"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// testManifest is an egress manifest whose one instance service is host on
+// port 443; an empty host is a named but unset service.
+func testManifest(host string) ctlegress.Manifest {
+ return ctlegress.Manifest{
+ Services: map[string]hostedwire.Service{"instance": {Host: host, Port: 443, Class: hostedwire.ServiceInstance}},
+ 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 reads attempt's saved services snapshot.
+func (e *launchEnv) services(attempt string) []hostedwire.Service {
+ e.t.Helper()
+ var raw string
+ if err := e.store.Tx(e.ctx, func(tx *sql.Tx) error {
+ return tx.QueryRowContext(e.ctx, `SELECT services_json FROM jobs WHERE attempt_id = ?`, attempt).Scan(&raw)
+ }); err != nil {
+ e.t.Fatalf("read services of %s = %v", attempt, err)
+ }
+ var s []hostedwire.Service
+ if err := json.Unmarshal([]byte(raw), &s); err != nil {
+ e.t.Fatalf("services of %s = %q, not JSON: %v", attempt, raw, err)
+ }
+ return s
+}
+
+func svc(host string) []hostedwire.Service {
+ return []hostedwire.Service{{Host: host, Port: 443, Class: hostedwire.ServiceInstance}}
+}
+
+func TestUnsetServiceBlocksLaunch(t *testing.T) {
+ t.Parallel()
+ for _, purpose := range []string{hostedwire.PurposeChecks, hostedwire.PurposeCertification} {
+ for name, m := range map[string]ctlegress.Manifest{"unset host": testManifest(""), "no manifest": {}} {
+ e := newLaunchEnv(t)
+ e.cfg.Manifest = m
+ e.newController()
+ e.audit()
+ q := request("att-1")
+ q.Purpose = purpose
+ if purpose == hostedwire.PurposeCertification {
+ q.Person = ""
+ }
+ v, err := e.c.Launch(e.ctx, "inst-1", instKey, q)
+ if !errors.Is(err, ctlegress.ErrServiceUnset) || v != (JobView{}) {
+ t.Fatalf("%s, %s: Launch = (%+v, %v), want ErrServiceUnset", name, purpose, v, err)
+ }
+ if n := e.fake.Calls(isolatedjob.OpLaunch); n != 0 || e.jobCount() != 0 {
+ t.Fatalf("%s, %s: %d provider launches and %d jobs, want none", name, purpose, n, e.jobCount())
+ }
+ if a := e.lastAudit(); a.Action != actionLaunchRefused || !strings.Contains(a.Reason, "not set") {
+ t.Fatalf("%s, %s: last audit = %+v, want a refusal naming the unset service", name, purpose, a)
+ }
+ e.noCodeInAudit()
+ }
+ }
+}
+
+// TestLaunchSnapshotsServices: the intent keeps the manifest's services as
+// they were at launch. A restart under another manifest, even one with the
+// name unset, neither changes the saved snapshot nor stops Replay sending
+// the saved spec; a new launch takes the new manifest's services.
+func TestLaunchSnapshotsServices(t *testing.T) {
+ t.Parallel()
+ e := newLaunchEnv(t)
+ e.cfg.Manifest = testManifest("one.example.com")
+ e.newController()
+ e.audit()
+ e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
+ v, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
+ if err != nil || v.State != JobWaiting {
+ t.Fatalf("throttled Launch = (%+v, %v), want a waiting intent", v, err)
+ }
+ if got := e.services("att-1"); !reflect.DeepEqual(got, svc("one.example.com")) {
+ t.Fatalf("saved services = %+v, want the manifest's at launch", got)
+ }
+ saved, _ := e.job("att-1")
+
+ for _, m := range []ctlegress.Manifest{testManifest("two.example.com"), testManifest("")} {
+ e.cfg.Manifest = m
+ e.reopen()
+ e.audit()
+ // A repeat passes the same gates as a new launch: under the unset
+ // manifest it is refused, and either way the saved job stays.
+ again, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1"))
+ if unset := m.Services["instance"].Host == ""; unset && !errors.Is(err, ctlegress.ErrServiceUnset) ||
+ !unset && (err != nil || again.LaunchID != v.LaunchID) {
+ t.Fatalf("repeated Launch under %+v = (%+v, %v), want the saved job, or ErrServiceUnset if unset", m.Services, again, err)
+ }
+ if unset := m.Services["instance"].Host == ""; !unset {
+ // A dispatch under the new manifest, throttled again.
+ e.fake.Inject(isolatedjob.OpLaunch, isolatedjob.FaultThrottle)
+ if err := e.c.Replay(e.ctx); err != nil {
+ t.Fatalf("throttled Replay under a new manifest = %v", err)
+ }
+ if j, _ := e.job("att-1"); j.state != JobWaiting {
+ t.Fatalf("att-1 after a throttled Replay = %q, want waiting", j.state)
+ }
+ }
+ if got := e.services("att-1"); !reflect.DeepEqual(got, svc("one.example.com")) {
+ t.Fatalf("services after a manifest change = %+v, want the snapshot", got)
+ }
+ }
+
+ probe := &intentProbe{Fake: e.fake, store: e.store}
+ e.run = probe
+ e.newController()
+ e.audit()
+ e.clk.AdvanceMono(time.Minute)
+ if err := e.c.Replay(e.ctx); err != nil {
+ t.Fatalf("Replay under a manifest with the name unset = %v", err)
+ }
+ seen := probe.join(t)
+ if len(seen) != 1 {
+ t.Fatalf("Replay provider calls = %d, want 1: the snapshot, not the current manifest, governs a saved intent", len(seen))
+ }
+ sent, err := decodeSpec(saved.specJSON, "att-1")
+ if err != nil || !bytes.Equal(sent.Bootstrap, seen[0].spec.Bootstrap) || !reflect.DeepEqual(e.services("att-1"), svc("one.example.com")) {
+ t.Fatalf("Replay sent %+v (decode %v), saved %+v, services %+v; want the saved spec and snapshot", seen[0].spec, err, sent, e.services("att-1"))
+ }
+ if j, _ := e.job("att-1"); j.state != JobStarting {
+ t.Fatalf("att-1 after Replay = %q, want starting", j.state)
+ }
+
+ e.cfg.Manifest = testManifest("two.example.com")
+ e.newController()
+ e.audit()
+ if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-2")); err != nil {
+ t.Fatalf("Launch att-2 = %v", err)
+ }
+ if got := e.services("att-2"); !reflect.DeepEqual(got, svc("two.example.com")) {
+ t.Fatalf("att-2 services = %+v, want the manifest's at its launch", got)
+ }
+ if got := e.services("att-1"); !reflect.DeepEqual(got, svc("one.example.com")) {
+ t.Fatalf("att-1 services = %+v after att-2, want its own snapshot", got)
+ }
+}
+
+func TestSnapshotImmutable(t *testing.T) {
+ t.Parallel()
+ e := newLaunchEnv(t)
+ if _, err := e.c.Launch(e.ctx, "inst-1", instKey, request("att-1")); err != nil {
+ t.Fatalf("Launch = %v", err)
+ }
+ before := e.services("att-1")
+ for _, q := range []string{
+ `UPDATE jobs SET services_json = '[]' WHERE attempt_id = 'att-1'`,
+ `UPDATE jobs SET services_json = '[{"host":"evil.example.com","port":443,"class":"instance"}]' WHERE attempt_id = 'att-1'`,
+ `UPDATE jobs SET services_json = NULL WHERE attempt_id = 'att-1'`,
+ } {
+ err := e.store.Tx(e.ctx, func(tx *sql.Tx) error {
+ _, err := tx.ExecContext(e.ctx, q)
+ return err
+ })
+ if err == nil || !strings.Contains(err.Error(), "immutable") {
+ t.Fatalf("%s = %v, want the immutability trigger to refuse it", q, err)
+ }
+ }
+ // A write that leaves the snapshot as it is still goes through.
+ e.exec(`UPDATE jobs SET services_json = services_json, revision = revision + 1 WHERE attempt_id = 'att-1'`)
+ if got := e.services("att-1"); !reflect.DeepEqual(got, before) || !reflect.DeepEqual(got, svc("equipo.example.com")) {
+ t.Fatalf("services = %+v, want %+v unchanged", got, before)
+ }
+}
diff --git a/internal/hostedctl/http.go b/internal/hostedctl/http.go
index 9e0790bb..72368d43 100644
--- a/internal/hostedctl/http.go
+++ b/internal/hostedctl/http.go
@@ -424,7 +424,8 @@ func serveLaunch(ctx context.Context, c *Controller, by hostedwire.KeyID, key ho
return nil, err
}
v, err := c.Launch(ctx, by, key, LaunchRequest{AttemptID: q.AttemptID, TaskID: q.TaskID, Account: q.Account,
- Replaces: q.Replaces, Image: q.Image, Size: q.Size, MaxLifetime: life, InstanceCode: q.InstanceCode})
+ Replaces: q.Replaces, Image: q.Image, Size: q.Size, MaxLifetime: life, InstanceCode: q.InstanceCode,
+ Person: q.Person, Purpose: q.Purpose, LaunchByUnixMS: q.LaunchByUnixMS})
if err != nil {
return nil, err
}
diff --git a/internal/hostedctl/http_test.go b/internal/hostedctl/http_test.go
index 333b55c9..2f83e0a1 100644
--- a/internal/hostedctl/http_test.go
+++ b/internal/hostedctl/http_test.go
@@ -164,7 +164,8 @@ func (e *apiEnv) call(method, path string, body any, id hostedwire.KeyID, key ed
func wireLaunch(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: testCode}
+ Size: isolatedjob.SizeSmall, MaxLifetimeMS: (2 * time.Hour).Milliseconds(), InstanceCode: testCode,
+ Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: testLaunchBy}
}
// launch launches attempt as instance A and wants a 200.
diff --git a/internal/hostedctl/launch.go b/internal/hostedctl/launch.go
index 83a64bee..8d750928 100644
--- a/internal/hostedctl/launch.go
+++ b/internal/hostedctl/launch.go
@@ -50,9 +50,6 @@ const maxNameLen = 128
// launchIDLen is the length of a launch ID: 128 random bits in hex.
const launchIDLen = 32
-// purposeTask is jobs.purpose for a launch that runs a task attempt.
-const purposeTask = "task"
-
// Audit actions written by Launch and Replay.
const (
actionLaunchRefused = "launch_refused"
@@ -79,13 +76,15 @@ const AlertConfigChanged = "config_changed"
// LaunchRequest asks for one VM for one task attempt. InstanceCode is a
// secret: it goes into the VM's bootstrap and the saved spec, and nowhere
-// else.
+// else. Person, Purpose and LaunchByUnixMS are hostedwire.LaunchRequest's.
type LaunchRequest struct {
AttemptID, TaskID, Account, Replaces string
Image isolatedjob.ImageDigest
Size isolatedjob.Size
MaxLifetime time.Duration
InstanceCode string
+ Person, Purpose string
+ LaunchByUnixMS int64
}
// JobView is the controller's view of one attempt. The *In fields count down
@@ -118,9 +117,14 @@ func Deadlines(launched T, lifetime time.Duration) (deadline, drain, stop T) {
// In order it refuses: launches switched off (ErrDisabled); a key without
// RoleInstance (ErrForbidden); a malformed request (isolatedjob.ErrInvalid,
// or ErrBootstrapTooLarge; see checkRequest for the controller's own
-// limits); an image outside Config.Images (ErrImageNotAllowed); no passing
-// network audit begun within AuditMaxAge (ErrNetworkAudit). Each refusal is
-// audited and creates nothing.
+// limits); an image outside Config.Images (ErrImageNotAllowed); a purpose
+// whose egress services are not all set (ctlegress.ErrServiceUnset); no
+// passing network audit begun within AuditMaxAge (ErrNetworkAudit). Each
+// refusal is audited and creates nothing.
+//
+// The services of Config.Manifest for q.Purpose are copied into the new
+// intent (jobs.services_json) and never change; a later manifest never
+// reaches a saved intent, and Replay never reads it.
//
// Transaction 1 then looks up q.AttemptID. A job saved for the same request
// by the same key is returned as it stands, with no provider call; a
@@ -158,11 +162,15 @@ func (c *Controller) Launch(ctx context.Context, by hostedwire.KeyID, key hosted
if !c.cfg.Images[q.Image] {
return c.refuse(ctx, by, q, fmt.Errorf("%w: %s", ErrImageNotAllowed, q.Image))
}
+ services, err := c.cfg.Manifest.For(q.Purpose)
+ if err != nil {
+ return c.refuse(ctx, by, q, err)
+ }
if err := c.audit.check(c.store.Clock().Now()); err != nil {
return c.refuse(ctx, by, q, err)
}
- view, created, err := c.saveIntent(ctx, by, q)
+ view, created, err := c.saveIntent(ctx, by, q, services)
if err != nil || !created {
return view, err
}
@@ -204,6 +212,10 @@ func (c *Controller) refuse(ctx context.Context, by hostedwire.KeyID, q LaunchRe
// be more than StopBefore, since a shorter one has its stop time at launch
// and the reaper would stop it, or Replay abandon it, at once.
func (c *Controller) checkRequest(q LaunchRequest) error {
+ v2 := hostedwire.LaunchRequest{Person: q.Person, Purpose: q.Purpose, LaunchByUnixMS: q.LaunchByUnixMS}
+ if err := v2.Validate(); err != nil {
+ return fmt.Errorf("%w: %w", isolatedjob.ErrInvalid, err)
+ }
switch {
case !printableASCII(q.TaskID, maxNameLen):
return fmt.Errorf("%w: task id must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen)
@@ -265,7 +277,7 @@ func requestHash(by hostedwire.KeyID, q LaunchRequest) string {
_, _ = h.Write(binary.AppendUvarint(nil, uint64(len(s))))
_, _ = h.Write([]byte(s))
}
- field("hostedctl launch request v1")
+ field("hostedctl launch request v2")
field(string(by))
field(q.AttemptID)
field(q.TaskID)
@@ -275,6 +287,9 @@ func requestHash(by hostedwire.KeyID, q LaunchRequest) string {
field(string(q.Size))
field(fmt.Sprint(int64(q.MaxLifetime)))
field(q.InstanceCode)
+ field(q.Purpose)
+ field(q.Person)
+ field(fmt.Sprint(q.LaunchByUnixMS))
return hex.EncodeToString(h.Sum(nil))
}
@@ -312,15 +327,19 @@ 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 and returns its view (created
-// true). A conflict or a live replaced attempt is audited, committed, and
+// builds the spec, saves the new intent with its services snapshot 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) (JobView, bool, error) {
+func (c *Controller) saveIntent(ctx context.Context, by hostedwire.KeyID, q LaunchRequest, services []hostedwire.Service) (JobView, bool, error) {
hash := requestHash(by, q)
+ servicesJSON, err := json.Marshal(services)
+ if err != nil {
+ return JobView{}, false, fmt.Errorf("hostedctl: encode services: %w", err)
+ }
var view JobView
var created bool
var refusal error
- err := c.store.Tx(ctx, func(tx *sql.Tx) error {
+ err = c.store.Tx(ctx, func(tx *sql.Tx) error {
view, created, refusal = JobView{}, false, nil
now := c.store.Clock().Now()
a := Audit{Actor: by, Account: q.Account, Task: q.TaskID, Attempt: q.AttemptID, At: now}
@@ -363,10 +382,10 @@ func (c *Controller) saveIntent(ctx context.Context, by hostedwire.KeyID, q Laun
deadline, drain, stop := Deadlines(now, spec.MaxLifetime)
replaces := sql.NullString{String: q.Replaces, Valid: q.Replaces != ""}
if _, err := tx.ExecContext(ctx, `INSERT INTO jobs (attempt_id, launch_id, task_id, account_id, actor_key,
- purpose, replaces_attempt, spec_json, spec_sha256, provider_fingerprint, state, launched_t, deadline_t, drain_t, stop_t)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- q.AttemptID, launchID, q.TaskID, q.Account, string(by), purposeTask, replaces, specJSON, hash,
- c.cfg.ProviderFingerprint(spec.Image, spec.Size), JobWaiting, int64(now), int64(deadline), int64(drain), int64(stop)); err != nil {
+ purpose, replaces_attempt, spec_json, spec_sha256, provider_fingerprint, services_json, state, launched_t, deadline_t, drain_t, stop_t)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ q.AttemptID, launchID, q.TaskID, q.Account, string(by), q.Purpose, replaces, specJSON, hash,
+ c.cfg.ProviderFingerprint(spec.Image, spec.Size), string(servicesJSON), JobWaiting, int64(now), int64(deadline), int64(drain), int64(stop)); err != nil {
return fmt.Errorf("hostedctl: save launch intent: %w", err)
}
a.Action = actionLaunchIntent
@@ -617,8 +636,9 @@ func (c *Controller) saveRef(ctx context.Context, actor hostedwire.KeyID, attemp
}
// Replay launches every intent that has no Ref yet, in launch order, each
-// with its saved spec, through dispatch. Before each provider call the
-// gates are re-checked:
+// with its saved spec and services snapshot, through dispatch; the current
+// egress manifest is never read. Before each provider call the gates are
+// re-checked:
//
// - a stop asked for, the intent's stop time reached, or provider
// settings changed since it was saved (config_changed, alerted): the
diff --git a/internal/hostedctl/launch_test.go b/internal/hostedctl/launch_test.go
index 151e0e13..b169e440 100644
--- a/internal/hostedctl/launch_test.go
+++ b/internal/hostedctl/launch_test.go
@@ -58,7 +58,7 @@ func newLaunchEnv(t *testing.T) *launchEnv {
t: t, ctx: context.Background(), path: filepath.Join(t.TempDir(), "hosted.db"),
clk: clk, gc: &gateClock{FakeClock: clk}, fake: fake, run: fake,
cfg: Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true, imgB: true},
- ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint},
+ ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint, Manifest: testManifest("equipo.example.com")},
}
e.store = openStore(t, e.path, e.gc)
e.newController()
@@ -187,10 +187,13 @@ func request(attempt string) LaunchRequest {
return LaunchRequest{
AttemptID: attempt, TaskID: "task-1", Account: "acct-1",
Image: imgA, Size: isolatedjob.SizeSmall, MaxLifetime: 2 * time.Hour,
- InstanceCode: testCode,
+ InstanceCode: testCode, Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: testLaunchBy,
}
}
+// testLaunchBy is every test request's launch-by time (Unix milliseconds).
+const testLaunchBy = 1796083200000
+
// intentProbe wraps the fake provider. At each Launch it reads the job row
// for the attempt from the store in a helper goroutine, as the provider is
// called. If the read has not finished after 2 s, something holds the store
@@ -368,6 +371,9 @@ func TestLaunchConflictOnChangedRequest(t *testing.T) {
{"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" }},
+ {"purpose", "inst-1", func(q *LaunchRequest) { q.Purpose, q.Person = hostedwire.PurposeCertification, "" }},
+ {"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) {}},
}
for _, tc := range cases {
@@ -797,6 +803,9 @@ func TestLaunchRefusals(t *testing.T) {
{name: "non-ASCII instance code", edit: func(q *LaunchRequest) { q.InstanceCode = testCode + "é" }, want: isolatedjob.ErrInvalid},
{name: "empty task", edit: func(q *LaunchRequest) { q.TaskID = "" }, want: isolatedjob.ErrInvalid},
{name: "lifetime within the stop margin", edit: func(q *LaunchRequest) { q.MaxLifetime = StopBefore }, want: isolatedjob.ErrInvalid},
+ {name: "unknown purpose", edit: func(q *LaunchRequest) { q.Purpose = "task" }, want: isolatedjob.ErrInvalid},
+ {name: "checks without a person", edit: func(q *LaunchRequest) { q.Person = "" }, want: isolatedjob.ErrInvalid},
+ {name: "no launch-by time", edit: func(q *LaunchRequest) { q.LaunchByUnixMS = 0 }, want: isolatedjob.ErrInvalid},
{name: "live replaced attempt", setup: func(e *launchEnv) { launchOld(e, "inst-1") }, edit: replacing, want: ErrReplacementLive},
{name: "replaced attempt unknown", edit: replacing, want: ErrReplacementLive},
{name: "replaced attempt of another key", setup: func(e *launchEnv) { launchOld(e, "inst-2"); proveStopped(e) }, edit: replacing, want: ErrReplacementLive},
diff --git a/internal/hostedctl/schema/0002_egress.sql b/internal/hostedctl/schema/0002_egress.sql
new file mode 100644
index 00000000..d6b60fb0
--- /dev/null
+++ b/internal/hostedctl/schema/0002_egress.sql
@@ -0,0 +1,14 @@
+-- Schema version 2: each launch intent keeps the egress services it was
+-- launched with (ctlegress.Manifest.For at the moment the intent was saved),
+-- as a JSON array of hostedwire.Service. Replay and every later reader use
+-- this snapshot, never the current manifest. Intents saved before this
+-- version had no egress and keep an empty array.
+ALTER TABLE jobs ADD COLUMN services_json TEXT NOT NULL DEFAULT '[]';
+
+-- Like the spec (jobs_spec_immutable), the snapshot never changes.
+CREATE TRIGGER jobs_services_immutable
+BEFORE UPDATE OF services_json ON jobs
+WHEN NEW.services_json IS NOT OLD.services_json
+BEGIN
+ SELECT RAISE(ABORT, 'services are immutable');
+END;
diff --git a/internal/hostedctl/sim_test.go b/internal/hostedctl/sim_test.go
index 3517d247..c6087145 100644
--- a/internal/hostedctl/sim_test.go
+++ b/internal/hostedctl/sim_test.go
@@ -223,7 +223,7 @@ func newSimWorld(dir string, seed int64) *simWorld {
seed: seed, rng: rand.New(rand.NewSource(seed)), ctx: context.Background(),
path: filepath.Join(dir, fmt.Sprintf("sim-%d.db", seed)), clk: clk, fake: fake,
cfg: Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true},
- ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint},
+ 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{}},
}
@@ -542,7 +542,8 @@ func (w *simWorld) newRequest(replaces string) LaunchRequest {
}
}
q := LaunchRequest{AttemptID: id, TaskID: "task-" + id, Account: "acct-1", Replaces: replaces,
- Image: imgA, Size: isolatedjob.SizeSmall, MaxLifetime: life, InstanceCode: testCode}
+ Image: imgA, Size: isolatedjob.SizeSmall, MaxLifetime: life, InstanceCode: testCode,
+ Purpose: hostedwire.PurposeChecks, Person: "person-1", LaunchByUnixMS: testLaunchBy}
w.m.req[id] = q
return q
}
diff --git a/internal/hostedctl/store.go b/internal/hostedctl/store.go
index b47d3f2c..f4c4c163 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"}
+var migrations = []string{"schema/0001_jobs.sql", "schema/0002_egress.sql"}
// schemaVersion is the newest schema this code knows.
func schemaVersion() int { return len(migrations) }