package homeop import ( "bytes" "context" "crypto/sha256" "encoding/base64" stdjson "encoding/json" "errors" "fmt" "io" "net/http" "slices" "time" family "amadan.net/rastrillo/rastrillo/crypto" ) func manifestDigest(consumers map[string]string) string { ids := make([]string, 0, len(consumers)) for id := range consumers { ids = append(ids, id) } slices.Sort(ids) entries := make([][2]string, 0, len(ids)) for _, id := range ids { entries = append(entries, [2]string{id, consumers[id]}) } b, err := stdjson.Marshal([]any{ManifestContext, entries}) if err != nil { return "" } sum := sha256.Sum256(b) return base64.RawURLEncoding.EncodeToString(sum[:]) } // Outcome is what one call to Home's endpoint came to. Home answers a // refusal and an outage with fixed codes and nothing else (§6), so this // is all Alta can know, and all it may log. type Outcome int const ( // OK: 200, body is the result. OK Outcome = iota // Refused: Home said no (403 refused, 401 prefilter, 404, 405, 415). Refused // Busy: 409, a plan is already pending or a window open on the role. Busy // Unavailable: 503, or anything else Home answered. Unavailable // Lost: no answer. Nothing may be inferred from it (§6): the request // may or may not have committed, and only an exact replay says. Lost ) func (o Outcome) String() string { return [...]string{"ok", "refused", "busy", "unavailable", "lost"}[o] } // Role is one Home role's endpoint as Alta reaches it: its origin, the // pins Home holds for Alta, and the prefilter bearer. type Role struct { Name string Origin string // URL is where the role is reached, when that is not Origin (a test // server); the pins still name Origin. URL string Installation string Registry string Device string } // Client talks to both roles' /operator/v1. It sends nothing a browser // would (no cookie, no Origin, no Sec-Fetch-*), as Home refuses those. type Client struct { HTTP *http.Client Key *family.Keypair Prefilter string Roles map[string]Role Now func() time.Time } func (c *Client) now() time.Time { if c.Now != nil { return c.Now() } return time.Now() } func (c *Client) role(name string) (Role, error) { r, ok := c.Roles[name] if !ok { return Role{}, fmt.Errorf("homeop: no role %q", name) } return r, nil } // Post sends body to one of the role's two routes. func (c *Client) Post(ctx context.Context, role, path string, body []byte) (Outcome, []byte) { r, err := c.role(role) if err != nil { return Refused, nil } base := r.Origin if r.URL != "" { base = r.URL } req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+path, bytes.NewReader(body)) if err != nil { return Refused, nil } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+c.Prefilter) client := c.HTTP if client == nil { client = http.DefaultClient } // No redirect is followed: Home's operator routes never redirect, and // a redirect would carry the prefilter bearer somewhere else. cc := *client cc.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } resp, err := cc.Do(req) if err != nil { return Lost, nil } defer resp.Body.Close() out, err := io.ReadAll(io.LimitReader(resp.Body, BodyLimit+1)) if err != nil || len(out) > BodyLimit { if resp.StatusCode == http.StatusOK { return Lost, nil } return Unavailable, nil } switch resp.StatusCode { case http.StatusOK: return OK, out case http.StatusConflict: return Busy, nil case http.StatusForbidden, http.StatusUnauthorized, http.StatusNotFound, http.StatusMethodNotAllowed, http.StatusUnsupportedMediaType, http.StatusRequestEntityTooLarge: return Refused, nil default: return Unavailable, nil } } // Inspect signs a fresh challenge for role and returns Home's answer, // checked to answer this challenge. func (c *Client) Inspect(ctx context.Context, role string) (Inspection, Outcome, error) { r, err := c.role(role) if err != nil { return Inspection{}, Refused, err } now := c.now().Unix() - Skew ch := InspectChallenge{Role: role, Origin: r.Origin, Installation: r.Installation, Registry: r.Registry, Device: r.Device, Challenge: Token(), Issued: now, Expires: now + RequestLifetime} raw, err := SignInspect(c.Key, ch) if err != nil { return Inspection{}, Refused, err } o, body := c.Post(ctx, role, "/operator/v1", raw) if o != OK { return Inspection{}, o, nil } var in Inspection if Decode(body, &in) != nil || in.Version != 1 || in.Role != role || in.Challenge != ch.Challenge || in.Sequence < 0 { return Inspection{}, Unavailable, errors.New("homeop: inspection does not answer the challenge") } return in, OK, nil } // SubmitPlan posts a signed plan to role. func (c *Client) SubmitPlan(ctx context.Context, role string, signed []byte) Outcome { o, _ := c.Post(ctx, role, "/operator/v1/plan", signed) return o } // Execute posts a signed operation and decodes the result. func (c *Client) Execute(ctx context.Context, role string, req []byte) (Result, []byte, Outcome) { o, body := c.Post(ctx, role, "/operator/v1", req) if o != OK { return Result{}, nil, o } var res Result if Decode(body, &res) != nil || res.Version != 1 || res.Outcome != "committed" { return Result{}, nil, Unavailable } return res, body, OK } // NewPlan fills a plan's pins for role. func (c *Client) NewPlan(role, planID, kind string, apps []string, issued time.Time) (Plan, error) { r, err := c.role(role) if err != nil { return Plan{}, err } return Plan{Role: role, Origin: r.Origin, Installation: r.Installation, Registry: r.Registry, Device: r.Device, PlanID: planID, Kind: kind, Apps: append([]string{}, apps...), Issued: issued.Unix(), Expires: issued.Unix() + PlanLifetime}, nil } // NewAuthorization fills an authorization's pins for role. func (c *Client) NewAuthorization(role string) (Authorization, error) { r, err := c.role(role) if err != nil { return Authorization{}, err } return Authorization{Role: role, Origin: r.Origin, Installation: r.Installation, Registry: r.Registry, Device: r.Device}, nil }