oficina / alta Public

Clone
git clone https://amadan.net/oficina/alta

Plain git — no account needed to clone.

Download

Download this file

1package homeop
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/base64"
8 stdjson "encoding/json"
9 "errors"
10 "fmt"
11 "io"
12 "net/http"
13 "slices"
14 "time"
15
16 family "amadan.net/rastrillo/rastrillo/crypto"
17)
18
19func manifestDigest(consumers map[string]string) string {
20 ids := make([]string, 0, len(consumers))
21 for id := range consumers {
22 ids = append(ids, id)
23 }
24 slices.Sort(ids)
25 entries := make([][2]string, 0, len(ids))
26 for _, id := range ids {
27 entries = append(entries, [2]string{id, consumers[id]})
28 }
29 b, err := stdjson.Marshal([]any{ManifestContext, entries})
30 if err != nil {
31 return ""
32 }
33 sum := sha256.Sum256(b)
34 return base64.RawURLEncoding.EncodeToString(sum[:])
35}
36
37// Outcome is what one call to Home's endpoint came to. Home answers a
38// refusal and an outage with fixed codes and nothing else (§6), so this
39// is all Alta can know, and all it may log.
40type Outcome int
41
42const (
43 // OK: 200, body is the result.
44 OK Outcome = iota
45 // Refused: Home said no (403 refused, 401 prefilter, 404, 405, 415).
46 Refused
47 // Busy: 409, a plan is already pending or a window open on the role.
48 Busy
49 // Unavailable: 503, or anything else Home answered.
50 Unavailable
51 // Lost: no answer. Nothing may be inferred from it (§6): the request
52 // may or may not have committed, and only an exact replay says.
53 Lost
54)
55
56func (o Outcome) String() string {
57 return [...]string{"ok", "refused", "busy", "unavailable", "lost"}[o]
58}
59
60// Role is one Home role's endpoint as Alta reaches it: its origin, the
61// pins Home holds for Alta, and the prefilter bearer.
62type Role struct {
63 Name string
64 Origin string
65 // URL is where the role is reached, when that is not Origin (a test
66 // server); the pins still name Origin.
67 URL string
68 Installation string
69 Registry string
70 Device string
71}
72
73// Client talks to both roles' /operator/v1. It sends nothing a browser
74// would (no cookie, no Origin, no Sec-Fetch-*), as Home refuses those.
75type Client struct {
76 HTTP *http.Client
77 Key *family.Keypair
78 Prefilter string
79 Roles map[string]Role
80 Now func() time.Time
81}
82
83func (c *Client) now() time.Time {
84 if c.Now != nil {
85 return c.Now()
86 }
87 return time.Now()
88}
89
90func (c *Client) role(name string) (Role, error) {
91 r, ok := c.Roles[name]
92 if !ok {
93 return Role{}, fmt.Errorf("homeop: no role %q", name)
94 }
95 return r, nil
96}
97
98// Post sends body to one of the role's two routes.
99func (c *Client) Post(ctx context.Context, role, path string, body []byte) (Outcome, []byte) {
100 r, err := c.role(role)
101 if err != nil {
102 return Refused, nil
103 }
104 base := r.Origin
105 if r.URL != "" {
106 base = r.URL
107 }
108 req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+path, bytes.NewReader(body))
109 if err != nil {
110 return Refused, nil
111 }
112 req.Header.Set("Content-Type", "application/json")
113 req.Header.Set("Authorization", "Bearer "+c.Prefilter)
114 client := c.HTTP
115 if client == nil {
116 client = http.DefaultClient
117 }
118 // No redirect is followed: Home's operator routes never redirect, and
119 // a redirect would carry the prefilter bearer somewhere else.
120 cc := *client
121 cc.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
122 resp, err := cc.Do(req)
123 if err != nil {
124 return Lost, nil
125 }
126 defer resp.Body.Close()
127 out, err := io.ReadAll(io.LimitReader(resp.Body, BodyLimit+1))
128 if err != nil || len(out) > BodyLimit {
129 if resp.StatusCode == http.StatusOK {
130 return Lost, nil
131 }
132 return Unavailable, nil
133 }
134 switch resp.StatusCode {
135 case http.StatusOK:
136 return OK, out
137 case http.StatusConflict:
138 return Busy, nil
139 case http.StatusForbidden, http.StatusUnauthorized, http.StatusNotFound, http.StatusMethodNotAllowed, http.StatusUnsupportedMediaType, http.StatusRequestEntityTooLarge:
140 return Refused, nil
141 default:
142 return Unavailable, nil
143 }
144}
145
146// Inspect signs a fresh challenge for role and returns Home's answer,
147// checked to answer this challenge.
148func (c *Client) Inspect(ctx context.Context, role string) (Inspection, Outcome, error) {
149 r, err := c.role(role)
150 if err != nil {
151 return Inspection{}, Refused, err
152 }
153 now := c.now().Unix() - Skew
154 ch := InspectChallenge{Role: role, Origin: r.Origin, Installation: r.Installation, Registry: r.Registry, Device: r.Device, Challenge: Token(), Issued: now, Expires: now + RequestLifetime}
155 raw, err := SignInspect(c.Key, ch)
156 if err != nil {
157 return Inspection{}, Refused, err
158 }
159 o, body := c.Post(ctx, role, "/operator/v1", raw)
160 if o != OK {
161 return Inspection{}, o, nil
162 }
163 var in Inspection
164 if Decode(body, &in) != nil || in.Version != 1 || in.Role != role || in.Challenge != ch.Challenge || in.Sequence < 0 {
165 return Inspection{}, Unavailable, errors.New("homeop: inspection does not answer the challenge")
166 }
167 return in, OK, nil
168}
169
170// SubmitPlan posts a signed plan to role.
171func (c *Client) SubmitPlan(ctx context.Context, role string, signed []byte) Outcome {
172 o, _ := c.Post(ctx, role, "/operator/v1/plan", signed)
173 return o
174}
175
176// Execute posts a signed operation and decodes the result.
177func (c *Client) Execute(ctx context.Context, role string, req []byte) (Result, []byte, Outcome) {
178 o, body := c.Post(ctx, role, "/operator/v1", req)
179 if o != OK {
180 return Result{}, nil, o
181 }
182 var res Result
183 if Decode(body, &res) != nil || res.Version != 1 || res.Outcome != "committed" {
184 return Result{}, nil, Unavailable
185 }
186 return res, body, OK
187}
188
189// NewPlan fills a plan's pins for role.
190func (c *Client) NewPlan(role, planID, kind string, apps []string, issued time.Time) (Plan, error) {
191 r, err := c.role(role)
192 if err != nil {
193 return Plan{}, err
194 }
195 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
196}
197
198// NewAuthorization fills an authorization's pins for role.
199func (c *Client) NewAuthorization(role string) (Authorization, error) {
200 r, err := c.role(role)
201 if err != nil {
202 return Authorization{}, err
203 }
204 return Authorization{Role: role, Origin: r.Origin, Installation: r.Installation, Registry: r.Registry, Device: r.Device}, nil
205}
206