| 1 | // Package hostedclient is the Equipo instance's client for the hosted |
| 2 | // controller's instance routes. Every request is signed with the instance's |
| 3 | // key and a fresh nonce, and every response must carry the controller's |
| 4 | // signature bound to that nonce before its status or body is read. |
| 5 | // |
| 6 | // New refuses to build a client unless EQUIPO_HOSTED_RUNNERS=1. In slice 1a |
| 7 | // nothing in the instance calls this package; TestInstanceDoesNotCallHostedClient |
| 8 | // holds that until slice 2. |
| 9 | package hostedclient |
| 10 | |
| 11 | import ( |
| 12 | "bytes" |
| 13 | "context" |
| 14 | "crypto/ed25519" |
| 15 | "encoding/json" |
| 16 | "errors" |
| 17 | "fmt" |
| 18 | "io" |
| 19 | "net" |
| 20 | "net/http" |
| 21 | "net/url" |
| 22 | "os" |
| 23 | "time" |
| 24 | |
| 25 | "amadan.net/oficina/equipo/internal/hostedwire" |
| 26 | ) |
| 27 | |
| 28 | // FlagEnv must be exactly "1" for New to build a client. |
| 29 | const FlagEnv = "EQUIPO_HOSTED_RUNNERS" |
| 30 | |
| 31 | // Errors of the client itself. |
| 32 | var ( |
| 33 | // ErrRunnersOff: New was called without EQUIPO_HOSTED_RUNNERS=1. |
| 34 | ErrRunnersOff = errors.New("hostedclient: hosted runners are off; " + FlagEnv + "=1 turns them on") |
| 35 | // ErrUnverified: the response does not carry a valid controller |
| 36 | // signature for this request. Its status and body are not trusted, and |
| 37 | // the controller's own unsigned refusals (a request it could not verify) |
| 38 | // land here too. |
| 39 | ErrUnverified = errors.New("hostedclient: the response could not be verified") |
| 40 | // ErrTransport: sending the request or reading the answer failed. Its |
| 41 | // text never holds anything the server sent; errors.Is still matches |
| 42 | // context.Canceled and context.DeadlineExceeded when those caused it. |
| 43 | ErrTransport = errors.New("hostedclient: the exchange with the controller failed") |
| 44 | // ErrBadResponse: a signed success whose body is not the route's strict |
| 45 | // JSON or does not answer the request (another attempt, generation, or a |
| 46 | // stop proof that does not prove a stop). |
| 47 | ErrBadResponse = errors.New("hostedclient: the controller's answer does not fit the request") |
| 48 | // ErrUnexpected: a signed refusal whose status and code this client does |
| 49 | // not know as a pair. |
| 50 | ErrUnexpected = errors.New("hostedclient: the controller gave an unexpected answer") |
| 51 | ) |
| 52 | |
| 53 | // Kinds of signed refusal, one per controller error code (see hostedctl's |
| 54 | // apiErrors). An APIError wraps one of them. |
| 55 | var ( |
| 56 | ErrUnauthorized = errors.New("hostedclient: the controller refused the request's signature") |
| 57 | ErrReplay = errors.New("hostedclient: the controller has already seen this request's nonce") |
| 58 | ErrBadRequest = errors.New("hostedclient: the controller could not take the request as sent") |
| 59 | ErrInvalid = errors.New("hostedclient: a request field is out of range") |
| 60 | ErrImageNotAllowed = errors.New("hostedclient: the image is not in the controller's allowlist") |
| 61 | ErrForbidden = errors.New("hostedclient: this key may not do that") |
| 62 | ErrNotFound = errors.New("hostedclient: not found") |
| 63 | ErrTooLarge = errors.New("hostedclient: the request body is too large") |
| 64 | ErrStopPending = errors.New("hostedclient: stop accepted, the VM is not proven stopped yet") |
| 65 | ErrGenerationCancelled = errors.New("hostedclient: the pause generation is cancelled or not the current one") |
| 66 | ErrNotQuiescent = errors.New("hostedclient: no quiescent acknowledgement for the pause generation") |
| 67 | ErrResumePending = errors.New("hostedclient: a resume is pending") |
| 68 | ErrReplacementLive = errors.New("hostedclient: the replaced attempt is not proven stopped") |
| 69 | ErrStateUnknown = errors.New("hostedclient: the provider reports an unknown VM state") |
| 70 | ErrConflict = errors.New("hostedclient: the job's state does not allow that") |
| 71 | ErrPastDeadline = errors.New("hostedclient: the job's stop time has passed") |
| 72 | ErrThrottled = errors.New("hostedclient: the provider is busy") |
| 73 | ErrDisabled = errors.New("hostedclient: the controller has hosted launches switched off") |
| 74 | ErrNetworkAudit = errors.New("hostedclient: no network audit has passed recently") |
| 75 | ErrProvider = errors.New("hostedclient: the provider call failed") |
| 76 | ErrStoreLost = errors.New("hostedclient: the controller lost its database") |
| 77 | ErrUnavailable = errors.New("hostedclient: the controller could not check the request") |
| 78 | ErrInternal = errors.New("hostedclient: the controller failed") |
| 79 | ) |
| 80 | |
| 81 | // refusals maps a signed refusal's code to the status the controller sends |
| 82 | // with it and its kind. A code with any other status is ErrUnexpected. |
| 83 | var refusals = map[string]struct { |
| 84 | status int |
| 85 | kind error |
| 86 | }{ |
| 87 | "unauthorized": {http.StatusUnauthorized, ErrUnauthorized}, |
| 88 | "replay": {http.StatusUnauthorized, ErrReplay}, |
| 89 | "unreadable": {http.StatusBadRequest, ErrBadRequest}, |
| 90 | "query": {http.StatusBadRequest, ErrBadRequest}, |
| 91 | "bad_json": {http.StatusBadRequest, ErrBadRequest}, |
| 92 | "no_route": {http.StatusNotFound, ErrBadRequest}, |
| 93 | "method": {http.StatusMethodNotAllowed, ErrBadRequest}, |
| 94 | "invalid": {http.StatusBadRequest, ErrInvalid}, |
| 95 | "image_not_allowed": {http.StatusBadRequest, ErrImageNotAllowed}, |
| 96 | "forbidden": {http.StatusForbidden, ErrForbidden}, |
| 97 | "not_found": {http.StatusNotFound, ErrNotFound}, |
| 98 | "too_large": {http.StatusRequestEntityTooLarge, ErrTooLarge}, |
| 99 | "stop_pending": {http.StatusAccepted, ErrStopPending}, |
| 100 | "generation_cancelled": {http.StatusConflict, ErrGenerationCancelled}, |
| 101 | "not_quiescent": {http.StatusConflict, ErrNotQuiescent}, |
| 102 | "resume_pending": {http.StatusConflict, ErrResumePending}, |
| 103 | "replacement_live": {http.StatusConflict, ErrReplacementLive}, |
| 104 | "state_unknown": {http.StatusConflict, ErrStateUnknown}, |
| 105 | "conflict": {http.StatusConflict, ErrConflict}, |
| 106 | "past_deadline": {http.StatusGone, ErrPastDeadline}, |
| 107 | "throttled": {http.StatusTooManyRequests, ErrThrottled}, |
| 108 | "disabled": {http.StatusServiceUnavailable, ErrDisabled}, |
| 109 | "network_audit": {http.StatusServiceUnavailable, ErrNetworkAudit}, |
| 110 | "provider": {http.StatusBadGateway, ErrProvider}, |
| 111 | "store_lost": {http.StatusServiceUnavailable, ErrStoreLost}, |
| 112 | "unavailable": {http.StatusServiceUnavailable, ErrUnavailable}, |
| 113 | "internal": {http.StatusInternalServerError, ErrInternal}, |
| 114 | } |
| 115 | |
| 116 | // APIError is a signed refusal from the controller. Kind is one of the |
| 117 | // kinds above, or ErrUnexpected; errors.Is matches it. |
| 118 | type APIError struct { |
| 119 | Op string // the route: launch, get, stop, drain, quiescent, suspend, reopen, resume |
| 120 | Status int |
| 121 | Code string // the controller's code, or "" when the body was not a strict ErrorResponse |
| 122 | Kind error |
| 123 | } |
| 124 | |
| 125 | func (e *APIError) Error() string { |
| 126 | return fmt.Sprintf("%v (%s: controller answered %d %q)", e.Kind, e.Op, e.Status, e.Code) |
| 127 | } |
| 128 | |
| 129 | func (e *APIError) Unwrap() error { return e.Kind } |
| 130 | |
| 131 | // Config is what a client needs. Every field is required. |
| 132 | type Config struct { |
| 133 | // BaseURL is the controller's https origin, such as |
| 134 | // https://controller.example:8443, with no path, query or user info. |
| 135 | BaseURL string |
| 136 | // KeyID and Key are the instance's entry in the controller's key table. |
| 137 | KeyID hostedwire.KeyID |
| 138 | Key ed25519.PrivateKey |
| 139 | // ControllerKey is the controller's public key; responses must be |
| 140 | // signed by it. |
| 141 | ControllerKey ed25519.PublicKey |
| 142 | // HTTP carries the deployment's TLS settings (in its Transport) and |
| 143 | // timeout; New refuses nil rather than guess them. The client sends |
| 144 | // through HTTP.Transport (http.DefaultTransport when nil) itself, not |
| 145 | // through HTTP.Do, so no redirect is ever followed or even parsed before |
| 146 | // the response is verified; Jar and CheckRedirect are not used. Timeout, |
| 147 | // when set, bounds each whole call, reading the body included. The |
| 148 | // transport must honour request contexts; one that stops only through |
| 149 | // Request.Cancel or CancelRequest is not supported. |
| 150 | HTTP *http.Client |
| 151 | } |
| 152 | |
| 153 | // Client calls the controller's instance routes. It is safe for concurrent |
| 154 | // use. |
| 155 | type Client struct { |
| 156 | origin string |
| 157 | keyID hostedwire.KeyID |
| 158 | key ed25519.PrivateKey |
| 159 | ctl ed25519.PublicKey |
| 160 | rt http.RoundTripper |
| 161 | timeout time.Duration |
| 162 | } |
| 163 | |
| 164 | // String names the controller and nothing else, so a client printed in a |
| 165 | // log never shows its key. |
| 166 | func (c *Client) String() string { return "hostedclient.Client(" + c.origin + ")" } |
| 167 | |
| 168 | // New builds a client. It refuses unless EQUIPO_HOSTED_RUNNERS is exactly |
| 169 | // "1", and refuses a BaseURL that is not a bare https origin, an empty key |
| 170 | // ID, keys of the wrong length, and a nil HTTP client. |
| 171 | func New(cfg Config) (*Client, error) { |
| 172 | if os.Getenv(FlagEnv) != "1" { |
| 173 | return nil, ErrRunnersOff |
| 174 | } |
| 175 | u, err := url.Parse(cfg.BaseURL) |
| 176 | if err != nil { |
| 177 | return nil, errors.New("hostedclient: BaseURL does not parse") |
| 178 | } |
| 179 | if u.Scheme != "https" || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || |
| 180 | u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" { |
| 181 | return nil, errors.New("hostedclient: BaseURL must be an https origin with no path, query or user info") |
| 182 | } |
| 183 | switch { |
| 184 | case cfg.KeyID == "": |
| 185 | return nil, errors.New("hostedclient: no key ID") |
| 186 | case len(cfg.Key) != ed25519.PrivateKeySize: |
| 187 | return nil, errors.New("hostedclient: the signing key is missing or the wrong length") |
| 188 | case len(cfg.ControllerKey) != ed25519.PublicKeySize: |
| 189 | return nil, errors.New("hostedclient: the controller key is missing or the wrong length") |
| 190 | case cfg.HTTP == nil: |
| 191 | return nil, errors.New("hostedclient: no HTTP client") |
| 192 | } |
| 193 | rt := cfg.HTTP.Transport |
| 194 | if rt == nil { |
| 195 | rt = http.DefaultTransport |
| 196 | } |
| 197 | return &Client{ |
| 198 | origin: "https://" + u.Host, |
| 199 | keyID: cfg.KeyID, |
| 200 | key: bytes.Clone(cfg.Key), |
| 201 | ctl: bytes.Clone(cfg.ControllerKey), |
| 202 | rt: rt, |
| 203 | timeout: cfg.HTTP.Timeout, |
| 204 | }, nil |
| 205 | } |
| 206 | |
| 207 | // Launch asks for one VM for q's attempt: POST /v1/jobs. |
| 208 | func (c *Client) Launch(ctx context.Context, q hostedwire.LaunchRequest) (hostedwire.JobView, error) { |
| 209 | var v hostedwire.JobView |
| 210 | if err := c.call(ctx, "launch", http.MethodPost, "/v1/jobs", q, &v); err != nil { |
| 211 | return hostedwire.JobView{}, err |
| 212 | } |
| 213 | if v.AttemptID != q.AttemptID { |
| 214 | return hostedwire.JobView{}, fmt.Errorf("%w: launch: the view is for another attempt", ErrBadResponse) |
| 215 | } |
| 216 | return v, nil |
| 217 | } |
| 218 | |
| 219 | // Get reads attempt's job: GET /v1/jobs/{attempt}. |
| 220 | func (c *Client) Get(ctx context.Context, attempt string) (hostedwire.JobView, error) { |
| 221 | p, err := jobPath(attempt, "") |
| 222 | if err != nil { |
| 223 | return hostedwire.JobView{}, err |
| 224 | } |
| 225 | var v hostedwire.JobView |
| 226 | if err := c.call(ctx, "get", http.MethodGet, p, nil, &v); err != nil { |
| 227 | return hostedwire.JobView{}, err |
| 228 | } |
| 229 | if v.AttemptID != attempt { |
| 230 | return hostedwire.JobView{}, fmt.Errorf("%w: get: the view is for another attempt", ErrBadResponse) |
| 231 | } |
| 232 | return v, nil |
| 233 | } |
| 234 | |
| 235 | // Stop stops attempt's VM: POST /v1/jobs/{attempt}/stop. Until the provider |
| 236 | // proves the VM stopped it returns ErrStopPending; ask again. |
| 237 | func (c *Client) Stop(ctx context.Context, attempt, reason string) (hostedwire.StopProof, error) { |
| 238 | p, err := jobPath(attempt, "stop") |
| 239 | if err != nil { |
| 240 | return hostedwire.StopProof{}, err |
| 241 | } |
| 242 | var proof hostedwire.StopProof |
| 243 | if err := c.call(ctx, "stop", http.MethodPost, p, hostedwire.StopRequest{Reason: reason}, &proof); err != nil { |
| 244 | return hostedwire.StopProof{}, err |
| 245 | } |
| 246 | if proof.AttemptID != attempt || !proof.State.Terminal() { |
| 247 | return hostedwire.StopProof{}, fmt.Errorf("%w: stop: the proof is for another attempt or not terminal", ErrBadResponse) |
| 248 | } |
| 249 | return proof, nil |
| 250 | } |
| 251 | |
| 252 | // Drain opens a new pause generation and returns it: |
| 253 | // POST /v1/jobs/{attempt}/drain. |
| 254 | func (c *Client) Drain(ctx context.Context, attempt string) (int64, error) { |
| 255 | p, err := jobPath(attempt, "drain") |
| 256 | if err != nil { |
| 257 | return 0, err |
| 258 | } |
| 259 | var r hostedwire.DrainResponse |
| 260 | if err := c.call(ctx, "drain", http.MethodPost, p, hostedwire.DrainRequest{}, &r); err != nil { |
| 261 | return 0, err |
| 262 | } |
| 263 | if r.Generation < 1 { |
| 264 | return 0, fmt.Errorf("%w: drain: generation %d", ErrBadResponse, r.Generation) |
| 265 | } |
| 266 | return r.Generation, nil |
| 267 | } |
| 268 | |
| 269 | // Quiescent acknowledges that the runner takes no more work for generation: |
| 270 | // POST /v1/jobs/{attempt}/quiescent. |
| 271 | func (c *Client) Quiescent(ctx context.Context, attempt string, generation int64) error { |
| 272 | var r hostedwire.QuiescentResponse |
| 273 | return c.generationCall(ctx, "quiescent", attempt, hostedwire.QuiescentRequest{Generation: generation}, &r, &r.Generation, generation) |
| 274 | } |
| 275 | |
| 276 | // Suspend suspends the VM for generation: POST /v1/jobs/{attempt}/suspend. |
| 277 | func (c *Client) Suspend(ctx context.Context, attempt string, generation int64) error { |
| 278 | var r hostedwire.SuspendResponse |
| 279 | return c.generationCall(ctx, "suspend", attempt, hostedwire.SuspendRequest{Generation: generation}, &r, &r.Generation, generation) |
| 280 | } |
| 281 | |
| 282 | // Reopen takes work again after an abandoned or cancelled pause of |
| 283 | // generation: POST /v1/jobs/{attempt}/reopen. |
| 284 | func (c *Client) Reopen(ctx context.Context, attempt string, generation int64) error { |
| 285 | var r hostedwire.ReopenResponse |
| 286 | return c.generationCall(ctx, "reopen", attempt, hostedwire.ReopenRequest{Generation: generation}, &r, &r.Generation, generation) |
| 287 | } |
| 288 | |
| 289 | // Resume resumes the suspended VM under operationID and returns the job's |
| 290 | // new epoch: POST /v1/jobs/{attempt}/resume. ErrResumePending means retry |
| 291 | // with the same operation ID. |
| 292 | func (c *Client) Resume(ctx context.Context, attempt, operationID string) (int64, error) { |
| 293 | p, err := jobPath(attempt, "resume") |
| 294 | if err != nil { |
| 295 | return 0, err |
| 296 | } |
| 297 | var r hostedwire.ResumeResponse |
| 298 | if err := c.call(ctx, "resume", http.MethodPost, p, hostedwire.ResumeRequest{OperationID: operationID}, &r); err != nil { |
| 299 | return 0, err |
| 300 | } |
| 301 | if r.Epoch < 1 { |
| 302 | return 0, fmt.Errorf("%w: resume: epoch %d", ErrBadResponse, r.Epoch) |
| 303 | } |
| 304 | return r.Epoch, nil |
| 305 | } |
| 306 | |
| 307 | // generationCall is quiescent, suspend and reopen: each answers with the |
| 308 | // generation it was asked about. |
| 309 | func (c *Client) generationCall(ctx context.Context, op, attempt string, req, out any, got *int64, want int64) error { |
| 310 | p, err := jobPath(attempt, op) |
| 311 | if err != nil { |
| 312 | return err |
| 313 | } |
| 314 | if err := c.call(ctx, op, http.MethodPost, p, req, out); err != nil { |
| 315 | return err |
| 316 | } |
| 317 | if *got != want { |
| 318 | return fmt.Errorf("%w: %s: answered for generation %d, asked %d", ErrBadResponse, op, *got, want) |
| 319 | } |
| 320 | return nil |
| 321 | } |
| 322 | |
| 323 | // jobPath is the escaped path of an attempt route. An attempt that would |
| 324 | // name another route, or a path step, is refused before anything is sent. |
| 325 | func jobPath(attempt, action string) (string, error) { |
| 326 | if attempt == "" || attempt == "." || attempt == ".." { |
| 327 | return "", errors.New("hostedclient: attempt ID must not be empty, \".\" or \"..\"") |
| 328 | } |
| 329 | p := "/v1/jobs/" + url.PathEscape(attempt) |
| 330 | if action != "" { |
| 331 | p += "/" + action |
| 332 | } |
| 333 | return p, nil |
| 334 | } |
| 335 | |
| 336 | // call sends one signed request and reads its answer into out. In order: |
| 337 | // |
| 338 | // 1. Marshal body (nil sends an empty body), sign it with a fresh nonce. |
| 339 | // 2. Send with one RoundTrip, so a 3xx is never followed or parsed, and |
| 340 | // read at most hostedwire.MaxBody+1 bytes of the answer. The context, |
| 341 | // with the HTTP client's Timeout when set, bounds both. |
| 342 | // 3. Verify the answer against this request's nonce and the controller |
| 343 | // key. Nothing about an answer that fails, status included, is used. |
| 344 | // 4. A 200 is decoded into out with hostedwire.DecodeStrict; anything else |
| 345 | // must be a strict ErrorResponse and becomes an *APIError. |
| 346 | func (c *Client) call(ctx context.Context, op, method, path string, body, out any) error { |
| 347 | if c.timeout > 0 { |
| 348 | var cancel context.CancelFunc |
| 349 | ctx, cancel = context.WithTimeout(ctx, c.timeout) |
| 350 | defer cancel() |
| 351 | } |
| 352 | var raw []byte |
| 353 | if body != nil { |
| 354 | var err error |
| 355 | if raw, err = json.Marshal(body); err != nil { |
| 356 | return fmt.Errorf("hostedclient: %s: encode request: %w", op, err) |
| 357 | } |
| 358 | } |
| 359 | req, err := http.NewRequestWithContext(ctx, method, c.origin+path, bytes.NewReader(raw)) |
| 360 | if err != nil { |
| 361 | return fmt.Errorf("hostedclient: %s: build request: %w", op, err) |
| 362 | } |
| 363 | if raw != nil { |
| 364 | req.Header.Set("Content-Type", "application/json") |
| 365 | } |
| 366 | nonce, err := hostedwire.NewNonce() |
| 367 | if err != nil { |
| 368 | return fmt.Errorf("hostedclient: %s: %w", op, err) |
| 369 | } |
| 370 | if err := hostedwire.SignRequest(req, raw, c.keyID, c.key, time.Now(), nonce); err != nil { |
| 371 | return fmt.Errorf("hostedclient: %s: sign request: %w", op, err) |
| 372 | } |
| 373 | // A followed redirect would resend the signed request elsewhere, and |
| 374 | // http.Client parses Location before any redirect policy runs, so the |
| 375 | // client never goes through http.Client.Do. |
| 376 | resp, err := c.rt.RoundTrip(req) |
| 377 | if err != nil { |
| 378 | return transportError(op, "sending", err) |
| 379 | } |
| 380 | defer resp.Body.Close() |
| 381 | got, err := io.ReadAll(io.LimitReader(resp.Body, hostedwire.MaxBody+1)) |
| 382 | if err != nil { |
| 383 | return transportError(op, "reading the body", err) |
| 384 | } |
| 385 | if err := hostedwire.VerifyResponse(resp, got, nonce, c.ctl); err != nil { |
| 386 | return fmt.Errorf("%w: %s: %w", ErrUnverified, op, err) |
| 387 | } |
| 388 | if resp.StatusCode == http.StatusOK { |
| 389 | if err := hostedwire.DecodeStrict(bytes.NewReader(got), out); err != nil { |
| 390 | return fmt.Errorf("%w: %s: %w", ErrBadResponse, op, err) |
| 391 | } |
| 392 | return nil |
| 393 | } |
| 394 | return refusal(op, resp.StatusCode, got) |
| 395 | } |
| 396 | |
| 397 | // transportError replaces an error from sending or reading with a fixed |
| 398 | // one: its text may quote bytes the server sent (a malformed status line, |
| 399 | // header or trailer), and nothing of an unverified answer may reach the |
| 400 | // caller. Cancellation and deadlines stay recognisable with errors.Is; a |
| 401 | // network timeout keeps that one fixed word; anything else is ErrTransport |
| 402 | // alone. |
| 403 | func transportError(op, step string, err error) error { |
| 404 | var ne net.Error |
| 405 | switch { |
| 406 | case errors.Is(err, context.Canceled): |
| 407 | return fmt.Errorf("%w: %s: %s: %w", ErrTransport, op, step, context.Canceled) |
| 408 | case errors.Is(err, context.DeadlineExceeded): |
| 409 | return fmt.Errorf("%w: %s: %s: %w", ErrTransport, op, step, context.DeadlineExceeded) |
| 410 | case errors.As(err, &ne) && ne.Timeout(): |
| 411 | return fmt.Errorf("%w: %s: %s: network timeout", ErrTransport, op, step) |
| 412 | } |
| 413 | return fmt.Errorf("%w: %s: %s", ErrTransport, op, step) |
| 414 | } |
| 415 | |
| 416 | // refusal turns a verified non-200 answer into an *APIError. |
| 417 | func refusal(op string, status int, body []byte) error { |
| 418 | e := &APIError{Op: op, Status: status, Kind: ErrUnexpected} |
| 419 | var er hostedwire.ErrorResponse |
| 420 | if hostedwire.DecodeStrict(bytes.NewReader(body), &er) != nil { |
| 421 | return e |
| 422 | } |
| 423 | e.Code = er.Code |
| 424 | if r, ok := refusals[er.Code]; ok && r.status == status { |
| 425 | e.Kind = r.kind |
| 426 | } |
| 427 | return e |
| 428 | } |
| 429 | |