// 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" "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") // ErrTransport: sending the request or reading the answer failed. Its // text never holds anything the server sent; errors.Is still matches // context.Canceled and context.DeadlineExceeded when those caused it. ErrTransport = errors.New("hostedclient: the exchange with the controller failed") // 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 carries the deployment's TLS settings (in its Transport) and // timeout; New refuses nil rather than guess them. The client sends // through HTTP.Transport (http.DefaultTransport when nil) itself, not // through HTTP.Do, so no redirect is ever followed or even parsed before // the response is verified; Jar and CheckRedirect are not used. Timeout, // when set, bounds each whole call, reading the body included. The // transport must honour request contexts; one that stops only through // Request.Cancel or CancelRequest is not supported. 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 rt http.RoundTripper timeout time.Duration } // 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") } rt := cfg.HTTP.Transport if rt == nil { rt = http.DefaultTransport } return &Client{ origin: "https://" + u.Host, keyID: cfg.KeyID, key: bytes.Clone(cfg.Key), ctl: bytes.Clone(cfg.ControllerKey), rt: rt, timeout: cfg.HTTP.Timeout, }, 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 with one RoundTrip, so a 3xx is never followed or parsed, and // read at most hostedwire.MaxBody+1 bytes of the answer. The context, // with the HTTP client's Timeout when set, bounds both. // 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 { if c.timeout > 0 { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, c.timeout) defer cancel() } 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) } // A followed redirect would resend the signed request elsewhere, and // http.Client parses Location before any redirect policy runs, so the // client never goes through http.Client.Do. resp, err := c.rt.RoundTrip(req) if err != nil { return transportError(op, "sending", err) } defer resp.Body.Close() got, err := io.ReadAll(io.LimitReader(resp.Body, hostedwire.MaxBody+1)) if err != nil { return transportError(op, "reading the body", err) } if err := hostedwire.VerifyResponse(resp, got, nonce, c.ctl); err != nil { return fmt.Errorf("%w: %s: %w", ErrUnverified, op, 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) } // transportError replaces an error from sending or reading with a fixed // one: its text may quote bytes the server sent (a malformed status line, // header or trailer), and nothing of an unverified answer may reach the // caller. Cancellation and deadlines stay recognisable with errors.Is; a // network timeout keeps that one fixed word; anything else is ErrTransport // alone. func transportError(op, step string, err error) error { var ne net.Error switch { case errors.Is(err, context.Canceled): return fmt.Errorf("%w: %s: %s: %w", ErrTransport, op, step, context.Canceled) case errors.Is(err, context.DeadlineExceeded): return fmt.Errorf("%w: %s: %s: %w", ErrTransport, op, step, context.DeadlineExceeded) case errors.As(err, &ne) && ne.Timeout(): return fmt.Errorf("%w: %s: %s: network timeout", ErrTransport, op, step) } return fmt.Errorf("%w: %s: %s", ErrTransport, op, step) } // 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 }