oficina / equipo Public

hostedclient: signed controller client behind a flag

The instance's client for the controller's instance routes: launch,
get, stop, drain, quiescent, suspend, reopen and resume. Each request
is signed with a fresh nonce; each response must carry the controller's
signature for that nonce before its status or body is used. Signed
refusals map to exported kinds; redirects are not followed. New refuses
unless EQUIPO_HOSTED_RUNNERS=1, and cmd/equipo does not import it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 1812c05197be2776dd192a38aa3d867ee6eafe57 parent bf8d744
3 files changed, +868 −0
  • docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md +30 −0
  • internal/hostedclient/client.go +387 −0
  • internal/hostedclient/client_test.go +451 −0
diff --git a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
index 5c9f1042..ea8cd25a 100644
--- a/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md
@@ -758,3 +758,33 @@ saved copy; the test passes again after each.
| Lax decode (`json.Unmarshal` for `DecodeStrict`) | `go test ./internal/hostedctl -run '^TestUnknownFieldsRefused$' -count=1` | `http_test.go:311: launch with unknown field = 200 {...}, want 400 {"code":"bad_json",...}` | yes, passes |
| Error text in responses (message from `err.Error()`) | `go test ./internal/hostedctl -run '^TestRoutesEnforceRoles$' -count=1` | `http_test.go:232: operator GET /v1/jobs/a1 = 403 {"code":"forbidden","message":"hostedctl: this key may not do that: route get needs the instance role"}, want 403 {"code":"forbidden","message":"This key may not do that."}` | yes, passes |
| Enabled from any non-empty env value (`!= ""` for `== "1"`) | `go test ./cmd/equipo-hosted-controller -run '^TestConfigEnabledOnlyFromEnv$' -count=1` | `config_test.go:181: EQUIPO_HOSTED_ENABLED="true": Enabled true, want false` | yes, passes |
+
+## Task 16
+
+Instance-side client `internal/hostedclient` (`client.go`, `client_test.go`). New refuses unless
+`EQUIPO_HOSTED_RUNNERS=1`, refuses a non-https or non-bare BaseURL, an empty key ID, keys of the wrong
+length and a nil HTTP client (no default client: the deployment supplies TLS and timeout). One method
+per instance route. Each response is verified against its own request nonce and the controller key
+before its status or body is read; unsigned answers (including the controller's unsigned 401s) are
+`ErrUnverified`. Signed refusals map by code and status to exported kinds (`ErrStopPending`,
+`ErrConflict`, ..., plus `ErrReplay` for ruling R25's signed `replay` code); redirects are not
+followed. No edit to hostedctl; the test builds the handler from hostedctl's public API.
+
+- RED: `go test ./internal/hostedclient -count=1` failed to build (`undefined: Client`, `undefined:
+ FlagEnv`, `undefined: New`, `undefined: Config`, `undefined: ErrGenerationCancelled`, ...). First
+ green run: `TestClientAgainstController` expected a relaunch of a1 to conflict; the controller
+ treats an identical relaunch as a repeat, so the test now relaunches with a different task.
+- GREEN: `go test ./internal/hostedclient -count=1` ok, 0.42 to 0.68 s (go list -deps step 0.05 to
+ 0.08 s, warm cache). gofmt, go vet, staticcheck v0.7.0 clean; `scripts/ci-test.py check` ok;
+ dead-reference scan 0 failures. Also passes against the in-progress R25 handler change.
+
+| Mutation | Command | Observed failure | Restored |
+| --- | --- | --- | --- |
+| Skip response verification (`VerifyResponse` call replaced by nil) | `go test ./internal/hostedclient -run '^TestClientRefusesUnsignedResponse$' -count=1` | `client_test.go:273: unsigned: Get = {AttemptID:a1 ... VMRef:vm-1 ...}, <nil>; want nothing and ErrUnverified` | yes, passes |
+| Nonce binding: verify against the response's own `Equipo-Nonce` header | same | `client_test.go:273: signed for another nonce: Get = {AttemptID:a1 ... VMRef:vm-1 ...}, <nil>; want nothing and ErrUnverified` | yes, passes |
+| Flag from any non-empty value (`!= "1"` to `== ""`) | `go test ./internal/hostedclient -run '^TestClientRefusesWithoutFlag$' -count=1` | `client_test.go:370: New with EQUIPO_HOSTED_RUNNERS="0" = (client true, <nil>); want ErrRunnersOff` | yes, passes |
+| https-only off (scheme check removed) | `go test ./internal/hostedclient -run '^TestNewRefusesBadConfig$' -count=1` | `client_test.go:410: New with plain http = (client true, <nil>); want a refusal` | yes, passes |
+| Follow redirects (`CheckRedirect` line removed) | `go test ./internal/hostedclient -run '^TestClientRefusesUnsignedResponse$' -count=1` | `client_test.go:309: launch answered by a redirect = ... with 1 hits elsewhere, want ErrUnverified and none` | yes, passes |
+| Map by code alone (status check dropped) | `go test ./internal/hostedclient -run '^TestSignedAnswersMapToKinds$' -count=1` | `client_test.go:345: code and status disagree: ... controller answered 409 "disabled"; want ... unexpected answer` | yes, passes |
+| Stop proof check off | same | `client_test.go:359: Stop answered with proof {AttemptID:a9 ...} = {AttemptID:a9 ...}, <nil>; want nothing and ErrBadResponse` | yes, passes |
+| cmd/equipo imports hostedclient (temporary `cmd/equipo/zz_mut.go`) | `go test ./internal/hostedclient -run '^TestInstanceDoesNotCallHostedClient$' -count=1` | `client_test.go:444: amadan.net/oficina/equipo/cmd/equipo depends on internal/hostedclient; ...` | yes, file deleted, passes |
diff --git a/internal/hostedclient/client.go b/internal/hostedclient/client.go
new file mode 100644
index 00000000..2c3287c3
--- /dev/null
+++ b/internal/hostedclient/client.go
@@ -0,0 +1,387 @@
+// Package hostedclient is the Equipo instance's client for the hosted
+// controller's instance routes. Every request is signed with the instance's
+// key and a fresh nonce, and every response must carry the controller's
+// signature bound to that nonce before its status or body is read.
+//
+// New refuses to build a client unless EQUIPO_HOSTED_RUNNERS=1. In slice 1a
+// nothing in the instance calls this package; TestInstanceDoesNotCallHostedClient
+// holds that until slice 2.
+package hostedclient
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedwire"
+)
+
+// FlagEnv must be exactly "1" for New to build a client.
+const FlagEnv = "EQUIPO_HOSTED_RUNNERS"
+
+// Errors of the client itself.
+var (
+ // ErrRunnersOff: New was called without EQUIPO_HOSTED_RUNNERS=1.
+ ErrRunnersOff = errors.New("hostedclient: hosted runners are off; " + FlagEnv + "=1 turns them on")
+ // ErrUnverified: the response does not carry a valid controller
+ // signature for this request. Its status and body are not trusted, and
+ // the controller's own unsigned refusals (a request it could not verify)
+ // land here too.
+ ErrUnverified = errors.New("hostedclient: the response could not be verified")
+ // ErrBadResponse: a signed success whose body is not the route's strict
+ // JSON or does not answer the request (another attempt, generation, or a
+ // stop proof that does not prove a stop).
+ ErrBadResponse = errors.New("hostedclient: the controller's answer does not fit the request")
+ // ErrUnexpected: a signed refusal whose status and code this client does
+ // not know as a pair.
+ ErrUnexpected = errors.New("hostedclient: the controller gave an unexpected answer")
+)
+
+// Kinds of signed refusal, one per controller error code (see hostedctl's
+// apiErrors). An APIError wraps one of them.
+var (
+ ErrUnauthorized = errors.New("hostedclient: the controller refused the request's signature")
+ ErrReplay = errors.New("hostedclient: the controller has already seen this request's nonce")
+ ErrBadRequest = errors.New("hostedclient: the controller could not take the request as sent")
+ ErrInvalid = errors.New("hostedclient: a request field is out of range")
+ ErrImageNotAllowed = errors.New("hostedclient: the image is not in the controller's allowlist")
+ ErrForbidden = errors.New("hostedclient: this key may not do that")
+ ErrNotFound = errors.New("hostedclient: not found")
+ ErrTooLarge = errors.New("hostedclient: the request body is too large")
+ ErrStopPending = errors.New("hostedclient: stop accepted, the VM is not proven stopped yet")
+ ErrGenerationCancelled = errors.New("hostedclient: the pause generation is cancelled or not the current one")
+ ErrNotQuiescent = errors.New("hostedclient: no quiescent acknowledgement for the pause generation")
+ ErrResumePending = errors.New("hostedclient: a resume is pending")
+ ErrReplacementLive = errors.New("hostedclient: the replaced attempt is not proven stopped")
+ ErrStateUnknown = errors.New("hostedclient: the provider reports an unknown VM state")
+ ErrConflict = errors.New("hostedclient: the job's state does not allow that")
+ ErrPastDeadline = errors.New("hostedclient: the job's stop time has passed")
+ ErrThrottled = errors.New("hostedclient: the provider is busy")
+ ErrDisabled = errors.New("hostedclient: the controller has hosted launches switched off")
+ ErrNetworkAudit = errors.New("hostedclient: no network audit has passed recently")
+ ErrProvider = errors.New("hostedclient: the provider call failed")
+ ErrStoreLost = errors.New("hostedclient: the controller lost its database")
+ ErrUnavailable = errors.New("hostedclient: the controller could not check the request")
+ ErrInternal = errors.New("hostedclient: the controller failed")
+)
+
+// refusals maps a signed refusal's code to the status the controller sends
+// with it and its kind. A code with any other status is ErrUnexpected.
+var refusals = map[string]struct {
+ status int
+ kind error
+}{
+ "unauthorized": {http.StatusUnauthorized, ErrUnauthorized},
+ "replay": {http.StatusUnauthorized, ErrReplay},
+ "unreadable": {http.StatusBadRequest, ErrBadRequest},
+ "query": {http.StatusBadRequest, ErrBadRequest},
+ "bad_json": {http.StatusBadRequest, ErrBadRequest},
+ "no_route": {http.StatusNotFound, ErrBadRequest},
+ "method": {http.StatusMethodNotAllowed, ErrBadRequest},
+ "invalid": {http.StatusBadRequest, ErrInvalid},
+ "image_not_allowed": {http.StatusBadRequest, ErrImageNotAllowed},
+ "forbidden": {http.StatusForbidden, ErrForbidden},
+ "not_found": {http.StatusNotFound, ErrNotFound},
+ "too_large": {http.StatusRequestEntityTooLarge, ErrTooLarge},
+ "stop_pending": {http.StatusAccepted, ErrStopPending},
+ "generation_cancelled": {http.StatusConflict, ErrGenerationCancelled},
+ "not_quiescent": {http.StatusConflict, ErrNotQuiescent},
+ "resume_pending": {http.StatusConflict, ErrResumePending},
+ "replacement_live": {http.StatusConflict, ErrReplacementLive},
+ "state_unknown": {http.StatusConflict, ErrStateUnknown},
+ "conflict": {http.StatusConflict, ErrConflict},
+ "past_deadline": {http.StatusGone, ErrPastDeadline},
+ "throttled": {http.StatusTooManyRequests, ErrThrottled},
+ "disabled": {http.StatusServiceUnavailable, ErrDisabled},
+ "network_audit": {http.StatusServiceUnavailable, ErrNetworkAudit},
+ "provider": {http.StatusBadGateway, ErrProvider},
+ "store_lost": {http.StatusServiceUnavailable, ErrStoreLost},
+ "unavailable": {http.StatusServiceUnavailable, ErrUnavailable},
+ "internal": {http.StatusInternalServerError, ErrInternal},
+}
+
+// APIError is a signed refusal from the controller. Kind is one of the
+// kinds above, or ErrUnexpected; errors.Is matches it.
+type APIError struct {
+ Op string // the route: launch, get, stop, drain, quiescent, suspend, reopen, resume
+ Status int
+ Code string // the controller's code, or "" when the body was not a strict ErrorResponse
+ Kind error
+}
+
+func (e *APIError) Error() string {
+ return fmt.Sprintf("%v (%s: controller answered %d %q)", e.Kind, e.Op, e.Status, e.Code)
+}
+
+func (e *APIError) Unwrap() error { return e.Kind }
+
+// Config is what a client needs. Every field is required.
+type Config struct {
+ // BaseURL is the controller's https origin, such as
+ // https://controller.example:8443, with no path, query or user info.
+ BaseURL string
+ // KeyID and Key are the instance's entry in the controller's key table.
+ KeyID hostedwire.KeyID
+ Key ed25519.PrivateKey
+ // ControllerKey is the controller's public key; responses must be
+ // signed by it.
+ ControllerKey ed25519.PublicKey
+ // HTTP sends the requests. It carries the TLS settings and timeout for
+ // the deployment; New refuses nil rather than guess them. The client
+ // uses a copy that never follows redirects.
+ HTTP *http.Client
+}
+
+// Client calls the controller's instance routes. It is safe for concurrent
+// use.
+type Client struct {
+ origin string
+ keyID hostedwire.KeyID
+ key ed25519.PrivateKey
+ ctl ed25519.PublicKey
+ http *http.Client
+}
+
+// String names the controller and nothing else, so a client printed in a
+// log never shows its key.
+func (c *Client) String() string { return "hostedclient.Client(" + c.origin + ")" }
+
+// New builds a client. It refuses unless EQUIPO_HOSTED_RUNNERS is exactly
+// "1", and refuses a BaseURL that is not a bare https origin, an empty key
+// ID, keys of the wrong length, and a nil HTTP client.
+func New(cfg Config) (*Client, error) {
+ if os.Getenv(FlagEnv) != "1" {
+ return nil, ErrRunnersOff
+ }
+ u, err := url.Parse(cfg.BaseURL)
+ if err != nil {
+ return nil, errors.New("hostedclient: BaseURL does not parse")
+ }
+ if u.Scheme != "https" || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") ||
+ u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" {
+ return nil, errors.New("hostedclient: BaseURL must be an https origin with no path, query or user info")
+ }
+ switch {
+ case cfg.KeyID == "":
+ return nil, errors.New("hostedclient: no key ID")
+ case len(cfg.Key) != ed25519.PrivateKeySize:
+ return nil, errors.New("hostedclient: the signing key is missing or the wrong length")
+ case len(cfg.ControllerKey) != ed25519.PublicKeySize:
+ return nil, errors.New("hostedclient: the controller key is missing or the wrong length")
+ case cfg.HTTP == nil:
+ return nil, errors.New("hostedclient: no HTTP client")
+ }
+ hc := *cfg.HTTP
+ // A followed redirect would resend the signed request somewhere else.
+ // The 3xx comes back instead, unsigned, and is refused as unverified.
+ hc.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ return &Client{
+ origin: "https://" + u.Host,
+ keyID: cfg.KeyID,
+ key: bytes.Clone(cfg.Key),
+ ctl: bytes.Clone(cfg.ControllerKey),
+ http: &hc,
+ }, nil
+}
+
+// Launch asks for one VM for q's attempt: POST /v1/jobs.
+func (c *Client) Launch(ctx context.Context, q hostedwire.LaunchRequest) (hostedwire.JobView, error) {
+ var v hostedwire.JobView
+ if err := c.call(ctx, "launch", http.MethodPost, "/v1/jobs", q, &v); err != nil {
+ return hostedwire.JobView{}, err
+ }
+ if v.AttemptID != q.AttemptID {
+ return hostedwire.JobView{}, fmt.Errorf("%w: launch: the view is for another attempt", ErrBadResponse)
+ }
+ return v, nil
+}
+
+// Get reads attempt's job: GET /v1/jobs/{attempt}.
+func (c *Client) Get(ctx context.Context, attempt string) (hostedwire.JobView, error) {
+ p, err := jobPath(attempt, "")
+ if err != nil {
+ return hostedwire.JobView{}, err
+ }
+ var v hostedwire.JobView
+ if err := c.call(ctx, "get", http.MethodGet, p, nil, &v); err != nil {
+ return hostedwire.JobView{}, err
+ }
+ if v.AttemptID != attempt {
+ return hostedwire.JobView{}, fmt.Errorf("%w: get: the view is for another attempt", ErrBadResponse)
+ }
+ return v, nil
+}
+
+// Stop stops attempt's VM: POST /v1/jobs/{attempt}/stop. Until the provider
+// proves the VM stopped it returns ErrStopPending; ask again.
+func (c *Client) Stop(ctx context.Context, attempt, reason string) (hostedwire.StopProof, error) {
+ p, err := jobPath(attempt, "stop")
+ if err != nil {
+ return hostedwire.StopProof{}, err
+ }
+ var proof hostedwire.StopProof
+ if err := c.call(ctx, "stop", http.MethodPost, p, hostedwire.StopRequest{Reason: reason}, &proof); err != nil {
+ return hostedwire.StopProof{}, err
+ }
+ if proof.AttemptID != attempt || !proof.State.Terminal() {
+ return hostedwire.StopProof{}, fmt.Errorf("%w: stop: the proof is for another attempt or not terminal", ErrBadResponse)
+ }
+ return proof, nil
+}
+
+// Drain opens a new pause generation and returns it:
+// POST /v1/jobs/{attempt}/drain.
+func (c *Client) Drain(ctx context.Context, attempt string) (int64, error) {
+ p, err := jobPath(attempt, "drain")
+ if err != nil {
+ return 0, err
+ }
+ var r hostedwire.DrainResponse
+ if err := c.call(ctx, "drain", http.MethodPost, p, hostedwire.DrainRequest{}, &r); err != nil {
+ return 0, err
+ }
+ if r.Generation < 1 {
+ return 0, fmt.Errorf("%w: drain: generation %d", ErrBadResponse, r.Generation)
+ }
+ return r.Generation, nil
+}
+
+// Quiescent acknowledges that the runner takes no more work for generation:
+// POST /v1/jobs/{attempt}/quiescent.
+func (c *Client) Quiescent(ctx context.Context, attempt string, generation int64) error {
+ var r hostedwire.QuiescentResponse
+ return c.generationCall(ctx, "quiescent", attempt, hostedwire.QuiescentRequest{Generation: generation}, &r, &r.Generation, generation)
+}
+
+// Suspend suspends the VM for generation: POST /v1/jobs/{attempt}/suspend.
+func (c *Client) Suspend(ctx context.Context, attempt string, generation int64) error {
+ var r hostedwire.SuspendResponse
+ return c.generationCall(ctx, "suspend", attempt, hostedwire.SuspendRequest{Generation: generation}, &r, &r.Generation, generation)
+}
+
+// Reopen takes work again after an abandoned or cancelled pause of
+// generation: POST /v1/jobs/{attempt}/reopen.
+func (c *Client) Reopen(ctx context.Context, attempt string, generation int64) error {
+ var r hostedwire.ReopenResponse
+ return c.generationCall(ctx, "reopen", attempt, hostedwire.ReopenRequest{Generation: generation}, &r, &r.Generation, generation)
+}
+
+// Resume resumes the suspended VM under operationID and returns the job's
+// new epoch: POST /v1/jobs/{attempt}/resume. ErrResumePending means retry
+// with the same operation ID.
+func (c *Client) Resume(ctx context.Context, attempt, operationID string) (int64, error) {
+ p, err := jobPath(attempt, "resume")
+ if err != nil {
+ return 0, err
+ }
+ var r hostedwire.ResumeResponse
+ if err := c.call(ctx, "resume", http.MethodPost, p, hostedwire.ResumeRequest{OperationID: operationID}, &r); err != nil {
+ return 0, err
+ }
+ if r.Epoch < 1 {
+ return 0, fmt.Errorf("%w: resume: epoch %d", ErrBadResponse, r.Epoch)
+ }
+ return r.Epoch, nil
+}
+
+// generationCall is quiescent, suspend and reopen: each answers with the
+// generation it was asked about.
+func (c *Client) generationCall(ctx context.Context, op, attempt string, req, out any, got *int64, want int64) error {
+ p, err := jobPath(attempt, op)
+ if err != nil {
+ return err
+ }
+ if err := c.call(ctx, op, http.MethodPost, p, req, out); err != nil {
+ return err
+ }
+ if *got != want {
+ return fmt.Errorf("%w: %s: answered for generation %d, asked %d", ErrBadResponse, op, *got, want)
+ }
+ return nil
+}
+
+// jobPath is the escaped path of an attempt route. An attempt that would
+// name another route, or a path step, is refused before anything is sent.
+func jobPath(attempt, action string) (string, error) {
+ if attempt == "" || attempt == "." || attempt == ".." {
+ return "", errors.New("hostedclient: attempt ID must not be empty, \".\" or \"..\"")
+ }
+ p := "/v1/jobs/" + url.PathEscape(attempt)
+ if action != "" {
+ p += "/" + action
+ }
+ return p, nil
+}
+
+// call sends one signed request and reads its answer into out. In order:
+//
+// 1. Marshal body (nil sends an empty body), sign it with a fresh nonce.
+// 2. Send, and read at most hostedwire.MaxBody+1 bytes of the answer.
+// 3. Verify the answer against this request's nonce and the controller
+// key. Nothing about an answer that fails, status included, is used.
+// 4. A 200 is decoded into out with hostedwire.DecodeStrict; anything else
+// must be a strict ErrorResponse and becomes an *APIError.
+func (c *Client) call(ctx context.Context, op, method, path string, body, out any) error {
+ var raw []byte
+ if body != nil {
+ var err error
+ if raw, err = json.Marshal(body); err != nil {
+ return fmt.Errorf("hostedclient: %s: encode request: %w", op, err)
+ }
+ }
+ req, err := http.NewRequestWithContext(ctx, method, c.origin+path, bytes.NewReader(raw))
+ if err != nil {
+ return fmt.Errorf("hostedclient: %s: build request: %w", op, err)
+ }
+ if raw != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ nonce, err := hostedwire.NewNonce()
+ if err != nil {
+ return fmt.Errorf("hostedclient: %s: %w", op, err)
+ }
+ if err := hostedwire.SignRequest(req, raw, c.keyID, c.key, time.Now(), nonce); err != nil {
+ return fmt.Errorf("hostedclient: %s: sign request: %w", op, err)
+ }
+ resp, err := c.http.Do(req)
+ if err != nil {
+ return fmt.Errorf("hostedclient: %s: %w", op, err)
+ }
+ defer resp.Body.Close()
+ got, err := io.ReadAll(io.LimitReader(resp.Body, hostedwire.MaxBody+1))
+ if err != nil {
+ return fmt.Errorf("%w: %s: reading the body: %w", ErrUnverified, op, err)
+ }
+ if err := hostedwire.VerifyResponse(resp, got, nonce, c.ctl); err != nil {
+ return fmt.Errorf("%w: %s (unverified status %d): %w", ErrUnverified, op, resp.StatusCode, err)
+ }
+ if resp.StatusCode == http.StatusOK {
+ if err := hostedwire.DecodeStrict(bytes.NewReader(got), out); err != nil {
+ return fmt.Errorf("%w: %s: %w", ErrBadResponse, op, err)
+ }
+ return nil
+ }
+ return refusal(op, resp.StatusCode, got)
+}
+
+// refusal turns a verified non-200 answer into an *APIError.
+func refusal(op string, status int, body []byte) error {
+ e := &APIError{Op: op, Status: status, Kind: ErrUnexpected}
+ var er hostedwire.ErrorResponse
+ if hostedwire.DecodeStrict(bytes.NewReader(body), &er) != nil {
+ return e
+ }
+ e.Code = er.Code
+ if r, ok := refusals[er.Code]; ok && r.status == status {
+ e.Kind = r.kind
+ }
+ return e
+}
diff --git a/internal/hostedclient/client_test.go b/internal/hostedclient/client_test.go
new file mode 100644
index 00000000..bbb695df
--- /dev/null
+++ b/internal/hostedclient/client_test.go
@@ -0,0 +1,451 @@
+package hostedclient
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedctl"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
+ "amadan.net/rastrillo/rastrillo/budget"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+
+// Keys of these tests: the instance's signing key, a key the controller does
+// not know, and the controller's signing key.
+var (
+ keyInst = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize))
+ keyOther = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2}, ed25519.SeedSize))
+ keyCtl = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{4}, ed25519.SeedSize))
+)
+
+const (
+ idInst hostedwire.KeyID = "inst-a"
+ imgA = isolatedjob.ImageDigest("sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
+)
+
+func ctlPublic() ed25519.PublicKey { return keyCtl.Public().(ed25519.PublicKey) }
+
+// nopAlerter drops alerts; a fresh store raises none.
+type nopAlerter struct{}
+
+func (nopAlerter) Alert(context.Context, hostedctl.Alert) error { return nil }
+
+// ctlEnv is a real controller over a fresh store and the fake provider,
+// served over TLS on 127.0.0.1, built only from hostedctl's public API.
+type ctlEnv struct {
+ ctx context.Context
+ fake *isolatedjob.Fake
+ c *hostedctl.Controller
+ srv *httptest.Server
+}
+
+func newCtlEnv(t *testing.T) *ctlEnv {
+ t.Helper()
+ ctx := context.Background()
+ clk := isolatedjobtest.NewFakeClock(time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC))
+ store, err := hostedctl.Open(ctx, filepath.Join(t.TempDir(), "hosted.db"), clk)
+ if err != nil {
+ t.Fatalf("Open = %v", err)
+ }
+ 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}},
+ hostedctl.Deps{Store: store, Runner: fake, Auditor: fake, Alerter: nopAlerter{}})
+ if err != nil {
+ t.Fatalf("New = %v", err)
+ }
+ if err := c.RunAudit(ctx); err != nil {
+ t.Fatalf("RunAudit = %v", err)
+ }
+ // The client signs with the real wall clock, so the handler checks
+ // timestamps against it; controller time stays on the fake clock.
+ h, err := c.Handler(hostedctl.HandlerConfig{
+ Keys: map[hostedwire.KeyID]hostedwire.VerifyKey{idInst: {Public: keyInst.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}},
+ Signing: keyCtl,
+ Wall: time.Now,
+ })
+ if err != nil {
+ t.Fatalf("Handler = %v", err)
+ }
+ return &ctlEnv{ctx: ctx, fake: fake, c: c, srv: serveTLS(t, h)}
+}
+
+// serveTLS serves h over TLS on 127.0.0.1 only.
+func serveTLS(t *testing.T, h http.Handler) *httptest.Server {
+ t.Helper()
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := httptest.NewUnstartedServer(h)
+ srv.Listener = ln
+ srv.StartTLS()
+ t.Cleanup(srv.Close)
+ return srv
+}
+
+// settle moves every fake VM one step and lets the controller read it.
+func (e *ctlEnv) settle(t *testing.T) {
+ t.Helper()
+ e.fake.Tick()
+ if err := e.c.Refresh(e.ctx); err != nil {
+ t.Fatalf("Refresh = %v", err)
+ }
+}
+
+// newClient builds a client for srv with the flag on.
+func newClient(t *testing.T, srv *httptest.Server, key ed25519.PrivateKey, ctl ed25519.PublicKey) *Client {
+ t.Helper()
+ t.Setenv(FlagEnv, "1")
+ cl, err := New(Config{BaseURL: srv.URL, KeyID: idInst, Key: key, ControllerKey: ctl, HTTP: srv.Client()})
+ if err != nil {
+ t.Fatalf("New = %v", err)
+ }
+ return cl
+}
+
+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"}
+}
+
+func TestClientAgainstController(t *testing.T) {
+ e := newCtlEnv(t)
+ cl := newClient(t, e.srv, keyInst, ctlPublic())
+ ctx := e.ctx
+
+ view, err := cl.Launch(ctx, launchReq("a1"))
+ if err != nil || view.AttemptID != "a1" || view.State != "starting" || view.VMRef == "" {
+ t.Fatalf("Launch = %+v, %v; want a1 starting with a VM", view, err)
+ }
+ got, err := cl.Get(ctx, "a1")
+ if err != nil || got.VMRef != view.VMRef || got.LaunchID != view.LaunchID {
+ t.Fatalf("Get = %+v, %v; want the launched job %+v", got, err, view)
+ }
+ e.settle(t)
+ if got, err = cl.Get(ctx, "a1"); err != nil || got.State != "running" {
+ t.Fatalf("Get after a refresh = %+v, %v; want running", got, err)
+ }
+
+ // Pause: drain, acknowledge, suspend.
+ gen, err := cl.Drain(ctx, "a1")
+ if err != nil || gen != 1 {
+ t.Fatalf("Drain = %d, %v; want generation 1", gen, err)
+ }
+ if err := cl.Quiescent(ctx, "a1", gen+1); !errors.Is(err, ErrGenerationCancelled) {
+ t.Fatalf("Quiescent for a generation not open = %v, want ErrGenerationCancelled", err)
+ }
+ if err := cl.Quiescent(ctx, "a1", gen); err != nil {
+ t.Fatalf("Quiescent = %v", err)
+ }
+ if err := cl.Suspend(ctx, "a1", gen); err != nil {
+ t.Fatalf("Suspend = %v", err)
+ }
+ e.settle(t)
+ if got, err = cl.Get(ctx, "a1"); err != nil || got.State != "suspended" {
+ t.Fatalf("Get after suspend = %+v, %v; want suspended", got, err)
+ }
+
+ // Resume: pending while the VM still reports suspended, then the epoch.
+ if ep, err := cl.Resume(ctx, "a1", "op-1"); !errors.Is(err, ErrResumePending) || ep != 0 {
+ t.Fatalf("first Resume = %d, %v; want 0 and ErrResumePending", ep, err)
+ }
+ e.fake.Tick()
+ if ep, err := cl.Resume(ctx, "a1", "op-1"); err != nil || ep != 1 {
+ t.Fatalf("Resume retry = %d, %v; want epoch 1", ep, err)
+ }
+
+ // An abandoned pause reopens.
+ if gen, err = cl.Drain(ctx, "a1"); err != nil || gen != 2 {
+ t.Fatalf("second Drain = %d, %v; want generation 2", gen, err)
+ }
+ if err := cl.Reopen(ctx, "a1", gen); err != nil {
+ t.Fatalf("Reopen = %v", err)
+ }
+ if got, err = cl.Get(ctx, "a1"); err != nil || got.State != "running" || got.Epoch != 1 {
+ t.Fatalf("Get after reopen = %+v, %v; want running at epoch 1", got, err)
+ }
+
+ // Stop: pending first, then proof.
+ if _, err := cl.Stop(ctx, "a1", "done"); !errors.Is(err, ErrStopPending) {
+ t.Fatalf("first Stop = %v, want ErrStopPending", err)
+ }
+ var api *APIError
+ if _, err := cl.Stop(ctx, "a1", "done"); !errors.As(err, &api) || api.Status != http.StatusAccepted || api.Code != "stop_pending" {
+ t.Fatalf("second Stop before the VM stops = %v, want an APIError 202 stop_pending", err)
+ }
+ e.fake.Tick()
+ proof, err := cl.Stop(ctx, "a1", "done")
+ if err != nil || proof.AttemptID != "a1" || proof.VMRef != view.VMRef || !proof.State.Terminal() {
+ t.Fatalf("Stop = %+v, %v; want proof for a1's VM %s", proof, err, view.VMRef)
+ }
+
+ // Refusals come back as the controller's kinds.
+ if _, err := cl.Get(ctx, "nope"); !errors.Is(err, ErrForbidden) {
+ t.Fatalf("Get of an unknown attempt = %v, want ErrForbidden", err)
+ }
+ changed := launchReq("a1")
+ changed.TaskID = "task-2"
+ if _, err := cl.Launch(ctx, changed); !errors.Is(err, ErrConflict) {
+ t.Fatalf("launch of a1 with a different request = %v, want ErrConflict", err)
+ }
+ bad := launchReq("a2")
+ bad.Image = "sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
+ if _, err := cl.Launch(ctx, bad); !errors.Is(err, ErrImageNotAllowed) {
+ t.Fatalf("launch with an image off the allowlist = %v, want ErrImageNotAllowed", err)
+ }
+}
+
+// fakeCtl answers every request with whatever answer returns, given the
+// request's nonce.
+func fakeCtl(t *testing.T, answer func(w http.ResponseWriter, nonce string)) *httptest.Server {
+ t.Helper()
+ return serveTLS(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ answer(w, r.Header.Get(hostedwire.HeaderNonce))
+ }))
+}
+
+// signedAnswer writes status and body signed by key for nonce.
+func signedAnswer(w http.ResponseWriter, status int, body []byte, nonce string, key ed25519.PrivateKey) {
+ hostedwire.SignResponse(w.Header(), status, nonce, body, key)
+ w.WriteHeader(status)
+ _, _ = w.Write(body)
+}
+
+func TestClientRefusesUnsignedResponse(t *testing.T) {
+ good, err := json.Marshal(hostedwire.JobView{AttemptID: "a1", LaunchID: "launch-1", State: "running", VMRef: "vm-1"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ const replayed = "captured-nonce-000000000"
+ cases := []struct {
+ name string
+ answer func(w http.ResponseWriter, nonce string)
+ }{
+ {"unsigned", func(w http.ResponseWriter, _ string) {
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(good)
+ }},
+ {"signed by another key", func(w http.ResponseWriter, nonce string) {
+ signedAnswer(w, http.StatusOK, good, nonce, keyOther)
+ }},
+ {"signed for another nonce", func(w http.ResponseWriter, _ string) {
+ // A captured response replayed, naming its own nonce.
+ w.Header().Set(hostedwire.HeaderNonce, replayed)
+ signedAnswer(w, http.StatusOK, good, replayed, keyCtl)
+ }},
+ {"signed for another status", func(w http.ResponseWriter, nonce string) {
+ hostedwire.SignResponse(w.Header(), http.StatusNotFound, nonce, good, keyCtl)
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(good)
+ }},
+ {"body changed after signing", func(w http.ResponseWriter, nonce string) {
+ hostedwire.SignResponse(w.Header(), http.StatusOK, nonce, good, keyCtl)
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(bytes.Replace(good, []byte("vm-1"), []byte("vm-2"), 1))
+ }},
+ {"too large", func(w http.ResponseWriter, nonce string) {
+ big := append(bytes.Repeat([]byte(" "), hostedwire.MaxBody), good...)
+ signedAnswer(w, http.StatusOK, big, nonce, keyCtl)
+ }},
+ }
+ for _, c := range cases {
+ cl := newClient(t, fakeCtl(t, c.answer), keyInst, ctlPublic())
+ v, err := cl.Get(context.Background(), "a1")
+ if !errors.Is(err, ErrUnverified) || v != (hostedwire.JobView{}) {
+ t.Fatalf("%s: Get = %+v, %v; want nothing and ErrUnverified", c.name, v, err)
+ }
+ }
+
+ // The same server signing properly is accepted, so the refusals above
+ // are for the signature and nothing else.
+ cl := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) {
+ signedAnswer(w, http.StatusOK, good, nonce, keyCtl)
+ }), keyInst, ctlPublic())
+ if v, err := cl.Get(context.Background(), "a1"); err != nil || v.VMRef != "vm-1" {
+ t.Fatalf("properly signed Get = %+v, %v; want vm-1", v, err)
+ }
+
+ // The real controller's unsigned 401, for a key it does not know, is
+ // unverified too, not a typed refusal.
+ e := newCtlEnv(t)
+ stranger := newClient(t, e.srv, keyOther, ctlPublic())
+ _, err = stranger.Launch(e.ctx, launchReq("a1"))
+ var api *APIError
+ if !errors.Is(err, ErrUnverified) || errors.As(err, &api) {
+ t.Fatalf("launch by an unknown key = %v, want ErrUnverified and no APIError", err)
+ }
+ // A client holding the wrong controller key trusts nothing it hears.
+ wrongCtl := newClient(t, e.srv, keyInst, keyOther.Public().(ed25519.PublicKey))
+ if _, err := wrongCtl.Launch(e.ctx, launchReq("a1")); !errors.Is(err, ErrUnverified) {
+ t.Fatalf("launch with the wrong controller key = %v, want ErrUnverified", err)
+ }
+
+ // A redirect is not followed: the signed request never goes elsewhere.
+ var hits atomic.Int32
+ elsewhere := serveTLS(t, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { hits.Add(1) }))
+ redirect := newClient(t, fakeCtl(t, func(w http.ResponseWriter, _ string) {
+ w.Header().Set("Location", elsewhere.URL+"/v1/jobs")
+ w.WriteHeader(http.StatusTemporaryRedirect)
+ }), keyInst, ctlPublic())
+ if _, err := redirect.Launch(context.Background(), launchReq("a1")); !errors.Is(err, ErrUnverified) || hits.Load() != 0 {
+ t.Fatalf("launch answered by a redirect = %v with %d hits elsewhere, want ErrUnverified and none", err, hits.Load())
+ }
+}
+
+// TestSignedAnswersMapToKinds: a signed refusal is the controller's word and
+// maps to its kind by status and code; a signed answer that does not fit is
+// an error too.
+func TestSignedAnswersMapToKinds(t *testing.T) {
+ refusal := func(code string) []byte {
+ b, _ := json.Marshal(hostedwire.ErrorResponse{Code: code, Message: "fixed text"})
+ return b
+ }
+ other, _ := json.Marshal(hostedwire.JobView{AttemptID: "a9", State: "running", VMRef: "vm-9"})
+ for _, c := range []struct {
+ name string
+ status int
+ body []byte
+ want error
+ }{
+ {"signed signature refusal", http.StatusUnauthorized, refusal("unauthorized"), ErrUnauthorized},
+ {"replay refused", http.StatusUnauthorized, refusal("replay"), ErrReplay},
+ {"nonce store down", http.StatusServiceUnavailable, refusal("unavailable"), ErrUnavailable},
+ {"store lost", http.StatusServiceUnavailable, refusal("store_lost"), ErrStoreLost},
+ {"throttled", http.StatusTooManyRequests, refusal("throttled"), ErrThrottled},
+ {"past deadline", http.StatusGone, refusal("past_deadline"), ErrPastDeadline},
+ {"code and status disagree", http.StatusConflict, refusal("disabled"), ErrUnexpected},
+ {"unknown code", http.StatusTeapot, refusal("teapot"), ErrUnexpected},
+ {"refusal body not strict", http.StatusConflict, []byte(`{"code":"conflict","message":"x","extra":1}`), ErrUnexpected},
+ {"success body not strict", http.StatusOK, []byte(`{"attempt_id":"a1","bogus":true}`), ErrBadResponse},
+ {"success for another attempt", http.StatusOK, other, ErrBadResponse},
+ } {
+ cl := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) {
+ signedAnswer(w, c.status, c.body, nonce, keyCtl)
+ }), keyInst, ctlPublic())
+ v, err := cl.Get(context.Background(), "a1")
+ if !errors.Is(err, c.want) || errors.Is(err, ErrUnverified) || v != (hostedwire.JobView{}) {
+ t.Fatalf("%s: Get = %+v, %v; want nothing and %v", c.name, v, err, c.want)
+ }
+ }
+
+ // A signed stop proof must be for the attempt asked about and terminal.
+ for _, p := range []hostedwire.StopProof{
+ {AttemptID: "a9", VMRef: "vm-1", State: isolatedjob.StateStopped},
+ {AttemptID: "a1", VMRef: "vm-1", State: isolatedjob.StateRunning},
+ } {
+ body, _ := json.Marshal(p)
+ cl := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) {
+ signedAnswer(w, http.StatusOK, body, nonce, keyCtl)
+ }), keyInst, ctlPublic())
+ if got, err := cl.Stop(context.Background(), "a1", "done"); !errors.Is(err, ErrBadResponse) || got != (hostedwire.StopProof{}) {
+ t.Fatalf("Stop answered with proof %+v = %+v, %v; want nothing and ErrBadResponse", p, got, err)
+ }
+ }
+}
+
+func TestClientRefusesWithoutFlag(t *testing.T) {
+ srv := fakeCtl(t, func(http.ResponseWriter, string) {})
+ cfg := Config{BaseURL: srv.URL, KeyID: idInst, Key: keyInst, ControllerKey: ctlPublic(), HTTP: srv.Client()}
+ for _, v := range []string{"", "0", "true", "yes", " 1", "1 ", "01"} {
+ t.Setenv(FlagEnv, v)
+ if cl, err := New(cfg); !errors.Is(err, ErrRunnersOff) || cl != nil {
+ t.Fatalf("New with %s=%q = (client %v, %v); want ErrRunnersOff", FlagEnv, v, cl != nil, err)
+ }
+ }
+ os.Unsetenv(FlagEnv)
+ if _, err := New(cfg); !errors.Is(err, ErrRunnersOff) {
+ t.Fatalf("New with %s unset = %v, want ErrRunnersOff", FlagEnv, err)
+ }
+ t.Setenv(FlagEnv, "1")
+ if _, err := New(cfg); err != nil {
+ t.Fatalf("New with %s=1 = %v", FlagEnv, err)
+ }
+}
+
+func TestNewRefusesBadConfig(t *testing.T) {
+ t.Setenv(FlagEnv, "1")
+ good := Config{BaseURL: "https://127.0.0.1:8443", KeyID: idInst, Key: keyInst, ControllerKey: ctlPublic(), HTTP: &http.Client{}}
+ cl, err := New(good)
+ if err != nil {
+ t.Fatalf("New(good) = %v", err)
+ }
+ if s, want := fmt.Sprintf("%v %+v", cl, cl), "hostedclient.Client(https://127.0.0.1:8443)"; s != want+" "+want {
+ t.Fatalf("a printed client = %q, want only %q twice", s, want)
+ }
+ for name, change := range map[string]func(*Config){
+ "plain http": func(c *Config) { c.BaseURL = "http://127.0.0.1:8443" },
+ "no scheme": func(c *Config) { c.BaseURL = "127.0.0.1:8443" },
+ "no host": func(c *Config) { c.BaseURL = "https://" },
+ "a path": func(c *Config) { c.BaseURL = "https://127.0.0.1:8443/api" },
+ "a query": func(c *Config) { c.BaseURL = "https://127.0.0.1:8443?x=1" },
+ "user info": func(c *Config) { c.BaseURL = "https://u:p@127.0.0.1:8443" },
+ "no key ID": func(c *Config) { c.KeyID = "" },
+ "no key": func(c *Config) { c.Key = nil },
+ "short key": func(c *Config) { c.Key = c.Key[:ed25519.SeedSize] },
+ "no controller key": func(c *Config) { c.ControllerKey = nil },
+ "short controller key": func(c *Config) { c.ControllerKey = c.ControllerKey[:16] },
+ "no HTTP client": func(c *Config) { c.HTTP = nil },
+ } {
+ cfg := good
+ change(&cfg)
+ if cl, err := New(cfg); err == nil || cl != nil {
+ t.Errorf("New with %s = (client %v, %v); want a refusal", name, cl != nil, err)
+ }
+ }
+}
+
+func TestEmptyAttemptRefused(t *testing.T) {
+ var hits atomic.Int32
+ cl := newClient(t, fakeCtl(t, func(http.ResponseWriter, string) { hits.Add(1) }), keyInst, ctlPublic())
+ for _, a := range []string{"", ".", ".."} {
+ if _, err := cl.Get(context.Background(), a); err == nil {
+ t.Fatalf("Get(%q) = nil error, want a refusal", a)
+ }
+ }
+ if hits.Load() != 0 {
+ t.Fatalf("%d requests sent for refused attempts, want none", hits.Load())
+ }
+}
+
+// TestInstanceDoesNotCallHostedClient holds slice 1a's promise that the
+// instance never calls the hosted controller. Slice 2 deletes it.
+func TestInstanceDoesNotCallHostedClient(t *testing.T) {
+ gobin, err := exec.LookPath("go")
+ if err != nil {
+ t.Fatalf("go not on PATH: %v", err)
+ }
+ const instance = "amadan.net/oficina/equipo/cmd/equipo"
+ out, err := exec.Command(gobin, "list", "-deps", instance).Output()
+ if err != nil {
+ t.Fatalf("go list -deps %s: %v", instance, err)
+ }
+ deps := strings.Fields(string(out))
+ var self bool
+ for _, d := range deps {
+ if d == "amadan.net/oficina/equipo/internal/hostedclient" {
+ t.Fatalf("%s depends on internal/hostedclient; slice 1a keeps the instance off the hosted controller", instance)
+ }
+ self = self || d == instance
+ }
+ if !self {
+ t.Fatalf("go list -deps %s did not list the package itself; got %d lines", instance, len(deps))
+ }
+}