package hostedctl import ( "bytes" "context" "crypto/ed25519" "database/sql" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strings" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" ) // HandlerConfig is what the controller's HTTP API needs besides the // controller. Every field but Metrics is required. type HandlerConfig struct { // Keys are the verify keys and their roles. Each controller has keys of // its own and keeps each key under one key ID for good: the key ID is not // signed, so it must never move to another key or another controller. Keys map[hostedwire.KeyID]hostedwire.VerifyKey // Signing is the controller's key; every verified request's response is // signed with it. Signing ed25519.PrivateKey // Wall is the wall clock a request's timestamp is checked against. Wall func() time.Time // Metrics, when set, counts launches and refusals. Metrics *Metrics } // Audit action the handler writes when a key's role may not use a route. The // controller's methods audit their own refusals. const actionAPIRefused = "api_refused" // Errors of the handler itself, before any controller method runs. var ( errNoRoute = errors.New("hostedctl: no such route") errMethod = errors.New("hostedctl: method not allowed on this route") errQuery = errors.New("hostedctl: routes take no query") errRead = errors.New("hostedctl: reading the request body failed") ) // apiError is how one kind of error is answered: its status, a fixed code // and a fixed message. The error's own text is never sent. type apiError struct { err error status int code string msg string } // apiErrors maps errors to responses, first match wins. ErrStoreLost comes // first, so a refusal whose audit row could not be written reports the lost // store. ErrProviderLaunch is 502 rather than 500: the controller is well and // the intent is saved, so the client may read the job again later. var apiErrors = []apiError{ {ErrStoreLost, http.StatusServiceUnavailable, "store_lost", "The controller lost its database. Try again later."}, {hostedwire.ErrTooLarge, http.StatusRequestEntityTooLarge, "too_large", "The request body is too large."}, {hostedwire.ErrNonceStore, http.StatusServiceUnavailable, "unavailable", "The request could not be checked. Try again later."}, {hostedwire.ErrNotConfigured, http.StatusInternalServerError, "internal", "The controller failed. Try again later."}, {hostedwire.ErrSharedKey, http.StatusInternalServerError, "internal", "The controller failed. Try again later."}, {hostedwire.ErrUnsigned, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, {hostedwire.ErrMalformed, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, {hostedwire.ErrUnknownKey, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, {hostedwire.ErrSkew, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, {hostedwire.ErrBadSignature, http.StatusUnauthorized, "unauthorized", "The request is not signed by a known key."}, {hostedwire.ErrReplay, http.StatusUnauthorized, "replay", "This request was already used. Sign a new one."}, {errRead, http.StatusBadRequest, "unreadable", "The request body could not be read."}, {errQuery, http.StatusBadRequest, "query", "Routes take no query string."}, {hostedwire.ErrBadJSON, http.StatusBadRequest, "bad_json", "The body is not the JSON object this route takes."}, {hostedwire.ErrDuration, http.StatusBadRequest, "invalid", "The request has a field out of range."}, {isolatedjob.ErrBootstrapTooLarge, http.StatusBadRequest, "invalid", "The request has a field out of range."}, {isolatedjob.ErrInvalid, http.StatusBadRequest, "invalid", "The request has a field out of range."}, {ErrImageNotAllowed, http.StatusBadRequest, "image_not_allowed", "The image is not in the allowlist."}, {ErrForbidden, http.StatusForbidden, "forbidden", "This key may not do that."}, {errNoRoute, http.StatusNotFound, "no_route", "No such route."}, {isolatedjob.ErrNotFound, http.StatusNotFound, "not_found", "Not found."}, {errMethod, http.StatusMethodNotAllowed, "method", "This route does not take that method."}, {ErrStopPending, http.StatusAccepted, "stop_pending", "Stop accepted. The VM is not proven stopped yet; ask again."}, {ErrGenerationCancelled, http.StatusConflict, "generation_cancelled", "That pause generation is cancelled or not the current one."}, {ErrNotQuiescent, http.StatusConflict, "not_quiescent", "No quiescent acknowledgement for this pause generation."}, {ErrResumePending, http.StatusConflict, "resume_pending", "A resume is pending. Retry with its operation ID."}, {ErrReplacementLive, http.StatusConflict, "replacement_live", "The replaced attempt is not proven stopped."}, {ErrStateUnknown, http.StatusConflict, "state_unknown", "The provider reports an unknown VM state."}, {isolatedjob.ErrConflict, http.StatusConflict, "conflict", "The job's state does not allow that."}, {ErrPastDeadline, http.StatusGone, "past_deadline", "The job's stop time has passed."}, {isolatedjob.ErrThrottled, http.StatusTooManyRequests, "throttled", "The provider is busy. Try again later."}, {ErrDisabled, http.StatusServiceUnavailable, "disabled", "Hosted launches are switched off."}, {ErrNetworkAudit, http.StatusServiceUnavailable, "network_audit", "No network audit has passed recently. Try again later."}, {ErrProviderLaunch, http.StatusBadGateway, "provider", "The provider call failed. Read the job again later."}, {isolatedjob.ErrIncomplete, http.StatusBadGateway, "provider", "The provider call failed. Read the job again later."}, } // errInternal answers every error apiErrors does not name. var errInternal = apiError{status: http.StatusInternalServerError, code: "internal", msg: "The controller failed. Try again later."} // ErrorCode is one status and code pair the API may answer a refusal with. type ErrorCode struct { Status int Code string } // ErrorCodes lists every status and code pair of apiErrors and // errInternal, each once, in table order. It returns a new slice, so // clients can test their own mapping against the handler's. func ErrorCodes() []ErrorCode { var out []ErrorCode seen := map[ErrorCode]bool{} for _, a := range append(apiErrors[:len(apiErrors):len(apiErrors)], errInternal) { ec := ErrorCode{Status: a.status, Code: a.code} if !seen[ec] { seen[ec] = true out = append(out, ec) } } return out } // lookupError returns how err is answered. func lookupError(err error) apiError { for _, a := range apiErrors { if errors.Is(err, a.err) { return a } } return errInternal } // route is one API route. serve decodes body (already verified) and calls // the controller; it returns the status and value of a success. type route struct { name string // for metrics and audit rows method string role hostedwire.Role serve func(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) } // jobActions are the POST routes under /v1/jobs/{attempt}/. var jobActions = map[string]route{ "stop": {"stop", http.MethodPost, hostedwire.RoleInstance, serveStop}, "drain": {"drain", http.MethodPost, hostedwire.RoleInstance, serveDrain}, "quiescent": {"quiescent", http.MethodPost, hostedwire.RoleInstance, serveQuiescent}, "suspend": {"suspend", http.MethodPost, hostedwire.RoleInstance, serveSuspend}, "reopen": {"reopen", http.MethodPost, hostedwire.RoleInstance, serveReopen}, "resume": {"resume", http.MethodPost, hostedwire.RoleInstance, serveResume}, } var ( routeLaunch = route{"launch", http.MethodPost, hostedwire.RoleInstance, serveLaunch} routeGet = route{"get", http.MethodGet, hostedwire.RoleInstance, serveGet} routeVMs = route{"vms", http.MethodGet, hostedwire.RoleOperator, serveVMs} ) // matchRoute finds r's route and the attempt its path names. Path segments // are unescaped one by one, so an attempt ID may hold any character. func matchRoute(r *http.Request) (route, string, error) { seg := strings.Split(r.URL.EscapedPath(), "/") var rt route var attempt string switch { case len(seg) == 3 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs": rt = routeLaunch case len(seg) == 3 && seg[0] == "" && seg[1] == "v1" && seg[2] == "vms": rt = routeVMs case len(seg) == 4 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs" && seg[3] != "": rt, attempt = routeGet, seg[3] case len(seg) == 5 && seg[0] == "" && seg[1] == "v1" && seg[2] == "jobs" && seg[3] != "": a, ok := jobActions[seg[4]] if !ok { return route{}, "", errNoRoute } rt, attempt = a, seg[3] default: return route{}, "", errNoRoute } if attempt != "" { var err error if attempt, err = url.PathUnescape(attempt); err != nil { return route{}, "", errNoRoute } } if r.Method != rt.method { return rt, attempt, errMethod } if r.URL.RawQuery != "" || r.URL.ForceQuery { return rt, attempt, errQuery } return rt, attempt, nil } // Handler returns the controller's HTTP API. It refuses a config with no // keys, a key of the wrong length or with an unknown role, one public key // under two key IDs, or a signing key of the wrong length. // // Each request goes through, in order: // // 1. Read the body, at most hostedwire.MaxBody+1 bytes; more is 413. // 2. Verify the signature over exactly those bytes, which also records the // nonce in the store (Store.Remember) so a replay is refused. // 3. Match the route: an unknown path is 404, another method 405, a query // 400. // 4. Check the key's role against the route's; a mismatch is 403 with an // api_refused audit row. // 5. Decode the same bytes with hostedwire.DecodeStrict (a GET takes an // empty body), then call the controller, which checks that the key // created the attempt and audits its own refusals. // // A request with no valid signature (step 1, or a step 2 failure before the // signature verified: missing or malformed headers, unknown key, skew, bad // signature) is answered unsigned with a fixed body. Every other response, // refusals included, is signed with hostedwire.SignResponse bound to the // request's nonce; that covers a replay and a nonce-store failure, which // come after the signature verified (ruling R25). For HEAD the signature // covers the empty body actually sent. Every error is answered from apiErrors with a // fixed code and message, never the error's own text. func (c *Controller) Handler(hc HandlerConfig) (http.Handler, error) { if err := CheckVerifyKeys(hc.Keys); err != nil { return nil, err } if len(hc.Signing) != ed25519.PrivateKeySize { return nil, errors.New("hostedctl: the signing key has the wrong length") } if hc.Wall == nil { return nil, errors.New("hostedctl: the API needs a wall clock") } keys := make(map[hostedwire.KeyID]hostedwire.VerifyKey, len(hc.Keys)) for id, k := range hc.Keys { keys[id] = hostedwire.VerifyKey{Public: bytes.Clone(k.Public), Role: k.Role} } return &apiHandler{ c: c, v: &hostedwire.Verifier{Keys: keys, Nonces: c.store, Now: hc.Wall}, sign: bytes.Clone(hc.Signing), m: hc.Metrics, }, nil } // CheckVerifyKeys refuses an empty key table, a key ID or public key of the // wrong form, a role other than instance or operator, and one public key // under two key IDs. func CheckVerifyKeys(keys map[hostedwire.KeyID]hostedwire.VerifyKey) error { if len(keys) == 0 { return errors.New("hostedctl: no verify keys") } seen := map[string]hostedwire.KeyID{} for id, k := range keys { if !validKeyID(string(id)) { return fmt.Errorf("hostedctl: key ID %q must be 1 to 64 characters of A-Z, a-z, 0-9, '.', '_' or '-'", id) } if len(k.Public) != ed25519.PublicKeySize { return fmt.Errorf("hostedctl: public key of %s has the wrong length", id) } if k.Role != hostedwire.RoleInstance && k.Role != hostedwire.RoleOperator { return fmt.Errorf("hostedctl: key %s has role %q; want instance or operator", id, k.Role) } if other, dup := seen[string(k.Public)]; dup { return fmt.Errorf("hostedctl: %w: %s and %s", hostedwire.ErrSharedKey, other, id) } seen[string(k.Public)] = id } return nil } // validKeyID matches hostedwire's key ID rule: 1 to 64 characters of // [A-Za-z0-9._-]. func validKeyID(s string) bool { if len(s) < 1 || len(s) > 64 { return false } for i := 0; i < len(s); i++ { c := s[i] if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-') { return false } } return true } type apiHandler struct { c *Controller v *hostedwire.Verifier sign ed25519.PrivateKey m *Metrics } func (h *apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(io.LimitReader(r.Body, hostedwire.MaxBody+1)) switch { case err != nil: err = errRead case len(body) > hostedwire.MaxBody: err = hostedwire.ErrTooLarge } var by hostedwire.KeyID var key hostedwire.VerifyKey if err == nil { by, key, err = h.v.Verify(r, body) } if err != nil { a := lookupError(err) h.m.apiError("unverified", a.code) h.write(w, r, a.status, errorBody(a), signedNonce(r, err)) return } nonce := headerValue(r.Header, hostedwire.HeaderNonce) ctx := r.Context() rt, attempt, err := matchRoute(r) switch { case err != nil: case key.Role != rt.role: err = h.refuseRole(ctx, by, key.Role, rt, attempt) case rt.method == http.MethodGet && len(body) != 0: err = fmt.Errorf("%w: a GET takes no body", hostedwire.ErrBadJSON) } var out any if err == nil { out, err = rt.serve(ctx, h.c, by, key, attempt, body) } name := rt.name if name == "" { name = "none" } if err != nil { a := lookupError(err) h.m.apiError(name, a.code) if rt.name == routeLaunch.name { h.m.launch(a.code) } h.write(w, r, a.status, errorBody(a), nonce) return } resp, err := json.Marshal(out) if err != nil { h.m.apiError(name, errInternal.code) h.write(w, r, errInternal.status, errorBody(errInternal), nonce) return } if v, ok := out.(hostedwire.JobView); ok && rt.name == routeLaunch.name { h.m.launch(v.State) } h.write(w, r, http.StatusOK, resp, nonce) } // signedNonce returns the nonce to sign a verification failure for, or "" // to leave it unsigned. Verify checks the signature before it records the // nonce, so a replay or a nonce-store failure comes from a request whose // signature verified (ruling R25): its refusal is signed, bound to its // nonce. Every other failure has no valid signature and goes unsigned. func signedNonce(r *http.Request, err error) string { if errors.Is(err, hostedwire.ErrReplay) || errors.Is(err, hostedwire.ErrNonceStore) { return headerValue(r.Header, hostedwire.HeaderNonce) } return "" } // write sends body with status, signed for nonce unless nonce is empty. A // HEAD response carries no body (HTTP forbids one, and Go drops it), so for // HEAD the signature covers the empty body the client receives, with the // status unchanged. func (h *apiHandler) write(w http.ResponseWriter, r *http.Request, status int, body []byte, nonce string) { if r.Method == http.MethodHead { body = nil } hdr := w.Header() hdr.Set("Content-Type", "application/json") hdr.Set("Cache-Control", "no-store") if nonce != "" { hostedwire.SignResponse(hdr, status, nonce, body, h.sign) } w.WriteHeader(status) _, _ = w.Write(body) } func errorBody(a apiError) []byte { b, _ := json.Marshal(hostedwire.ErrorResponse{Code: a.code, Message: a.msg}) return b } // headerValue returns the one value of name; Verify has already checked // there is exactly one, under any spelling of the name. func headerValue(h http.Header, name string) string { for k, v := range h { if strings.EqualFold(k, name) && len(v) == 1 { return v[0] } } return "" } // refuseRole audits a key whose role may not use rt and returns ErrForbidden // (joined with the audit's error, if any). func (h *apiHandler) refuseRole(ctx context.Context, by hostedwire.KeyID, role hostedwire.Role, rt route, attempt string) error { err := fmt.Errorf("%w: route %s needs the %s role", ErrForbidden, rt.name, rt.role) if !printableASCII(attempt, maxNameLen) { attempt = "" } aerr := h.c.store.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, Audit{Actor: by, Attempt: attempt, Action: actionAPIRefused, Reason: fmt.Sprintf("route %s needs the %s role; the key has %s", rt.name, rt.role, role), At: h.c.store.Clock().Now()}) }) return errors.Join(err, aerr) } // decode reads body into v with hostedwire.DecodeStrict: the same bytes the // signature covers. func decode(body []byte, v any) error { return hostedwire.DecodeStrict(bytes.NewReader(body), v) } func serveLaunch(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, _ string, body []byte) (any, error) { var q hostedwire.LaunchRequest if err := decode(body, &q); err != nil { return nil, err } life, err := q.MaxLifetime() if err != nil { 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}) if err != nil { return nil, err } return wireView(v), nil } // serveGet: Get takes no key, so the route's role check above is the only // one; Get itself checks that by created the attempt. func serveGet(ctx context.Context, c *Controller, by hostedwire.KeyID, _ hostedwire.VerifyKey, attempt string, _ []byte) (any, error) { v, err := c.Get(ctx, by, attempt) if err != nil { return nil, err } return wireView(v), nil } func wireView(v JobView) hostedwire.JobView { return hostedwire.JobView{AttemptID: v.AttemptID, LaunchID: v.LaunchID, State: v.State, VMRef: v.VMRef, Epoch: v.Epoch, DeadlineInMS: v.DeadlineIn.Milliseconds(), DrainInMS: v.DrainIn.Milliseconds(), StopInMS: v.StopIn.Milliseconds()} } func serveStop(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { var q hostedwire.StopRequest if err := decode(body, &q); err != nil { return nil, err } p, err := c.Stop(ctx, by, key, attempt, q.Reason) if err != nil { return nil, err } return p.wire(), nil } func serveDrain(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { var q hostedwire.DrainRequest if err := decode(body, &q); err != nil { return nil, err } g, err := c.Drain(ctx, by, key, attempt) if err != nil { return nil, err } return hostedwire.DrainResponse{Generation: g}, nil } func serveQuiescent(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { var q hostedwire.QuiescentRequest if err := decode(body, &q); err != nil { return nil, err } if err := c.Quiescent(ctx, by, key, attempt, q.Generation); err != nil { return nil, err } return hostedwire.QuiescentResponse(q), nil } func serveSuspend(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { var q hostedwire.SuspendRequest if err := decode(body, &q); err != nil { return nil, err } if err := c.Suspend(ctx, by, key, attempt, q.Generation); err != nil { return nil, err } return hostedwire.SuspendResponse(q), nil } func serveReopen(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { var q hostedwire.ReopenRequest if err := decode(body, &q); err != nil { return nil, err } if err := c.Reopen(ctx, by, key, attempt, q.Generation); err != nil { return nil, err } return hostedwire.ReopenResponse(q), nil } func serveResume(ctx context.Context, c *Controller, by hostedwire.KeyID, key hostedwire.VerifyKey, attempt string, body []byte) (any, error) { var q hostedwire.ResumeRequest if err := decode(body, &q); err != nil { return nil, err } epoch, err := c.Resume(ctx, by, key, attempt, q.OperationID) if err != nil { return nil, err } return hostedwire.ResumeResponse{Epoch: epoch}, nil } func serveVMs(ctx context.Context, c *Controller, _ hostedwire.KeyID, _ hostedwire.VerifyKey, _ string, _ []byte) (any, error) { vms, err := c.ListVMs(ctx) if err != nil { return nil, err } return hostedwire.VMListResponse{VMs: vms}, nil } // ListVMs returns every VM the provider lists, each with the attempt whose // saved Ref it is, or "" when it is no job's. A VM a launch intent may own // but has no Ref saved yet shows "". It makes one provider List and changes // nothing. func (c *Controller) ListVMs(ctx context.Context) ([]hostedwire.VMView, error) { vms, err := c.runner.List(ctx) if err != nil { return nil, err } owners := map[isolatedjob.Ref]string{} err = c.store.Tx(ctx, func(tx *sql.Tx) error { rows, err := tx.QueryContext(ctx, `SELECT vm_ref, attempt_id FROM jobs WHERE vm_ref IS NOT NULL`) if err != nil { return fmt.Errorf("hostedctl: read job refs: %w", err) } defer rows.Close() for rows.Next() { var ref, attempt string if err := rows.Scan(&ref, &attempt); err != nil { return fmt.Errorf("hostedctl: read job refs: %w", err) } owners[isolatedjob.Ref(ref)] = attempt } return rows.Err() }) if err != nil { return nil, err } out := make([]hostedwire.VMView, 0, len(vms)) for _, vm := range vms { v := hostedwire.VMView{VMRef: vm.Ref, State: vm.State, AttemptID: owners[vm.Ref], AgeKnown: vm.AgeKnown} if vm.AgeKnown { v.AgeMS = vm.ProviderAge.Milliseconds() } out = append(out, v) } return out, nil }