oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package runner
2
3import (
4 "bytes"
5 "context"
6 "crypto/ed25519"
7 "crypto/rand"
8 "encoding/base64"
9 "encoding/json"
10 "errors"
11 "io"
12 "net/http"
13 "net/url"
14 "os"
15 "path/filepath"
16 "strconv"
17 "strings"
18 "time"
19
20 "amadan.net/oficina/equipo/internal/runner/provider"
21 "amadan.net/oficina/equipo/internal/runnerproto"
22 "amadan.net/oficina/equipo/internal/wire"
23)
24
25func outboundClient() *http.Client {
26 return &http.Client{Timeout: 35 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
27}
28func Enrol(ctx context.Context, c Config, output io.Writer) (resultErr error) {
29 variable := "EQUIPO_RUNNER_STATE_DIR"
30 defer func() { resultErr = diagnosticAt(resultErr, variable) }()
31 if err := c.validateEnrolment(); err != nil {
32 return err
33 }
34 if c.WorkerOnly {
35 // A worker enrolled with an older instance would be its newest
36 // runner, which that instance takes for the primary. Ask first.
37 variable = "EQUIPO_ORIGIN"
38 if err := retryTransient(ctx, c, func() error { return workerProtocol(ctx, c.Origin) }); err != nil {
39 return err
40 }
41 variable = "EQUIPO_RUNNER_STATE_DIR"
42 }
43 lock, err := lockState(c.StateDir)
44 if err != nil {
45 return err
46 }
47 defer lock.Close()
48 credentialPath := filepath.Join(c.StateDir, "credentials.json")
49 if _, err := os.Lstat(credentialPath); err == nil {
50 old, err := readCredentials(credentialPath)
51 if err != nil {
52 return err
53 }
54 if time.Now().Before(old.Bearer.ExpiresAt) {
55 if _, other := otherEnrolment(c.StateDir, c.Origin, c.InstanceID); other {
56 return provider.ErrIdentity
57 }
58 c.notify(EnrolNotice{Kept: true})
59 return nil
60 }
61 journalPath := filepath.Join(c.StateDir, "journal.db")
62 if _, err = os.Stat(journalPath); err == nil {
63 j, err := OpenJournal(ctx, journalPath)
64 if err != nil {
65 return err
66 }
67 var attempts []attemptState
68 err = j.readStates(ctx, "attempt", &attempts)
69 closeErr := j.Close()
70 if err != nil {
71 return err
72 }
73 if closeErr != nil {
74 return closeErr
75 }
76 for _, a := range attempts {
77 if a.Phase != "contained" {
78 return provider.ErrUncertain
79 }
80 }
81 } else if !os.IsNotExist(err) {
82 return err
83 }
84 } else if !os.IsNotExist(err) {
85 return err
86 }
87 keyPath := filepath.Join(c.StateDir, "machine-key.json")
88 var encoded string
89 if err = privateJSON(keyPath, &encoded); os.IsNotExist(err) {
90 _, key, e := ed25519.GenerateKey(rand.Reader)
91 if e != nil {
92 return e
93 }
94 encoded = base64.RawURLEncoding.EncodeToString(key)
95 err = runnerproto.JournalCredentials(keyPath, encoded)
96 }
97 if err != nil {
98 return err
99 }
100 key, err := base64.RawURLEncoding.DecodeString(encoded)
101 if err != nil || len(key) != ed25519.PrivateKeySize {
102 return provider.ErrIdentity
103 }
104 variable = "EQUIPO_ORIGIN"
105 client := outboundClient()
106 post := func(path string, in, out any) (int, error) {
107 raw, err := runnerproto.Marshal(in)
108 if err != nil {
109 return 0, err
110 }
111 req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.Origin+path, bytes.NewReader(raw))
112 if err != nil {
113 return 0, err
114 }
115 req.Header.Set("Content-Type", "application/json")
116 resp, err := client.Do(req)
117 if err != nil {
118 return 0, &enrolNetworkError{err}
119 }
120 defer resp.Body.Close()
121 if resp.StatusCode != 200 && resp.StatusCode != 201 {
122 return resp.StatusCode, answerError(resp)
123 }
124 return resp.StatusCode, runnerproto.DecodeLimit(resp.Body, out, 64<<10)
125 }
126 label := c.MachineLabel
127 if label == "" {
128 label, err = os.Hostname()
129 if err != nil {
130 return err
131 }
132 }
133 if len(label) > 128 || strings.TrimSpace(label) == "" || strings.ContainsAny(label, "\r\n\x00") {
134 return provider.ErrContract
135 }
136 pendingPath := filepath.Join(c.StateDir, "enrolment.json")
137 var pending pendingEnrolment
138 err = privateJSON(pendingPath, &pending)
139 if err != nil && !os.IsNotExist(err) {
140 // Malformed JSON is unusable retry state; permission and I/O errors still deny.
141 if !errors.Is(err, runnerproto.ErrInvalid) {
142 return err
143 }
144 }
145 if err != nil || !pending.usable(c.Origin, c.InstanceID) {
146 var code runnerproto.DeviceCode
147 err = retryTransient(ctx, c, func() error {
148 _, err := post("/api/enrolments", runnerproto.BeginEnrolmentRequest{Version: 1, MachinePublicKey: base64.RawURLEncoding.EncodeToString(ed25519.PrivateKey(key).Public().(ed25519.PublicKey)), Label: label, WorkerOnly: c.WorkerOnly}, &code)
149 return err
150 })
151 if err != nil {
152 return err
153 }
154 pending = pendingEnrolment{Origin: c.Origin, Label: label, Code: code}
155 pending.Proof = runnerproto.ExchangeProof{EnrolmentID: code.EnrolmentID, Challenge: code.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(randomBytes(32))}
156 pending.Proof.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(ed25519.PrivateKey(key), runnerproto.EnrolmentProofMessage(code.InstanceID, pending.Proof)))
157 if err = runnerproto.JournalCredentials(pendingPath, pending); err != nil {
158 return err
159 }
160 }
161 code, proof := pending.Code, pending.Proof
162 if !pending.usable(c.Origin, c.InstanceID) {
163 return provider.ErrIdentity
164 }
165 // The link carries the code, so opening it shows this machine with one
166 // button to add it; the code stays on its own line for typing.
167 link := code.VerificationURI + "?code=" + url.QueryEscape(code.UserCode)
168 c.notify(EnrolNotice{Link: true})
169 if _, err = io.WriteString(output, "["+link+"]("+link+")\n"+code.UserCode+"\n"); err != nil {
170 return err
171 }
172 c.notify(EnrolNotice{Waiting: true})
173 // Polled until approved: "not yet" (409) and anything transient (no
174 // answer, a server error, too soon) are waited out, backing off, until
175 // the code expires. Turned down or expired, the saved code is dropped
176 // so the next run starts with a new one.
177 interval := time.Duration(code.PollIntervalSeconds) * enrolPollUnit
178 wait, failures := interval, 0
179 var last error
180 for time.Now().Before(code.ExpiresAt) {
181 timer := time.NewTimer(min(wait, max(time.Until(code.ExpiresAt), 0)+enrolPollUnit))
182 select {
183 case <-ctx.Done():
184 timer.Stop()
185 return ctx.Err()
186 case <-timer.C:
187 }
188 var cred runnerproto.RunnerCredential
189 status, err := post("/api/enrolments/token", runnerproto.ExchangeEnrolmentRequest{Version: 1, DeviceSecret: code.DeviceSecret, Proof: proof}, &cred)
190 if status == 409 {
191 wait, failures, last = interval, 0, nil
192 continue
193 }
194 if transient(err) {
195 last = err
196 failures++
197 wait = backoff(interval, failures)
198 c.notify(EnrolNotice{Retry: err})
199 continue
200 }
201 if status == http.StatusForbidden {
202 // The instance answers 403 for a code turned down (revoked)
203 // and for one that has expired by its clock.
204 _ = os.Remove(pendingPath)
205 if time.Until(code.ExpiresAt) < time.Minute {
206 return ErrEnrolmentExpired
207 }
208 return ErrEnrolmentRefused
209 }
210 if err != nil {
211 return err
212 }
213 if cred.Version != 1 || cred.Token == "" || cred.RunnerID == "" || !time.Now().Before(cred.ExpiresAt) {
214 return provider.ErrIdentity
215 }
216 if c.WorkerOnly && cred.Role != wire.RoleWorker {
217 // The instance enrolled this machine as a primary: a Mac only
218 // ever runs as a worker, so it keeps nothing and says why.
219 return ErrEnrolledAsPrimary
220 }
221 // The role is kept before the runner ever connects (a worker never
222 // serves as a primary), beside the credential so an older runner
223 // binary still reads that. No role is a primary's credential, or an
224 // older instance's, which has only primaries. It is written before
225 // the credential, which is the last write: an enrolment that fails
226 // leaves no new credential (only an expired or absent one reaches
227 // here), so an installer can put its earlier configuration back.
228 role := wire.RolePrimary
229 if cred.Role == wire.RoleWorker {
230 role = wire.RoleWorker
231 }
232 if err := WriteRole(c.StateDir, role); err != nil {
233 return err
234 }
235 return runnerproto.JournalCredentials(credentialPath, runnerproto.CredentialRotation{Bearer: cred})
236 }
237 if last != nil {
238 // Still failing when the code ran out: that, not the expiry, is
239 // what to fix.
240 return last
241 }
242 _ = os.Remove(pendingPath)
243 return ErrEnrolmentExpired
244}
245
246// ErrEnrolmentExpired: nobody approved the link before its code expired.
247var ErrEnrolmentExpired = errors.New("the enrolment link expired before it was approved")
248
249// ErrEnrolmentRefused: the instance turned the enrolment down (removed
250// or no longer valid) before it expired.
251var ErrEnrolmentRefused = errors.New("the instance turned the enrolment down")
252
253// EnrolNotice is what Enrol reports while it works: Kept when a valid
254// enrolment is kept and no link is printed, Link just before the link is
255// printed, Waiting once it is, Retry for each transient failure it waits
256// out.
257type EnrolNotice struct {
258 Kept bool
259 Link bool
260 Waiting bool
261 Retry error
262}
263
264func (c Config) notify(n EnrolNotice) {
265 if c.EnrolNotify != nil {
266 c.EnrolNotify(n)
267 }
268}
269
270// enrolPollUnit is a second: the poll interval's unit (tests shorten it).
271var enrolPollUnit = time.Second
272
273// enrolAttempts bounds the tries of a request made once (the protocol
274// question, starting the enrolment) when it fails transiently.
275const enrolAttempts = 4
276
277// enrolNetworkError: the instance could not be reached or did not answer.
278type enrolNetworkError struct{ err error }
279
280func (e *enrolNetworkError) Error() string { return "no answer from Equipo: " + e.err.Error() }
281func (e *enrolNetworkError) Unwrap() error { return provider.ErrUncertain }
282
283// EnrolAnswerError is an answer from the instance that is not success:
284// its HTTP status and the error key it gave, nothing more.
285type EnrolAnswerError struct {
286 Status int
287 Key string
288}
289
290func (e *EnrolAnswerError) Error() string {
291 if e.Key == "" {
292 return "Equipo answered HTTP " + strconv.Itoa(e.Status)
293 }
294 return "Equipo answered HTTP " + strconv.Itoa(e.Status) + " (" + e.Key + ")"
295}
296func (e *EnrolAnswerError) Unwrap() error {
297 if e.Status >= 500 {
298 return provider.ErrUncertain
299 }
300 return provider.ErrIdentity
301}
302
303func answerError(resp *http.Response) error {
304 var body runnerproto.ErrorResponse
305 key := ""
306 if json.Unmarshal(mustRead(resp.Body), &body) == nil && len(body.Error) <= 64 && strings.Trim(body.Error, "abcdefghijklmnopqrstuvwxyz0123456789._-") == "" {
307 key = body.Error
308 }
309 return &EnrolAnswerError{Status: resp.StatusCode, Key: key}
310}
311
312// transient: worth asking again (no answer, a server error, too soon).
313func transient(err error) bool {
314 var answer *EnrolAnswerError
315 var network *enrolNetworkError
316 return errors.As(err, &network) || errors.As(err, &answer) && (answer.Status >= 500 || answer.Status == http.StatusTooManyRequests)
317}
318
319// backoff doubles the wait after each failure in a row, up to a minute.
320func backoff(interval time.Duration, failures int) time.Duration {
321 return min(interval<<min(failures, 4), 60*enrolPollUnit)
322}
323
324// retryTransient runs once-only requests up to enrolAttempts times while
325// they fail transiently.
326func retryTransient(ctx context.Context, c Config, f func() error) error {
327 interval := runnerproto.PollIntervalSeconds * enrolPollUnit
328 for n := 1; ; n++ {
329 err := f()
330 if !transient(err) || n == enrolAttempts {
331 return err
332 }
333 c.notify(EnrolNotice{Retry: err})
334 t := time.NewTimer(backoff(interval, n-1))
335 select {
336 case <-ctx.Done():
337 t.Stop()
338 return ctx.Err()
339 case <-t.C:
340 }
341 }
342}
343
344// EnrolledElsewhere reports whether the runner state in stateDir holds a
345// live enrolment with another Equipo than origin and instanceID: the one
346// Enrol refuses with provider.ErrIdentity. It takes no lock and changes
347// nothing, so an installer asks it before it stops a running runner or
348// rewrites its configuration. other is that Equipo's origin, "" when the
349// state does not say which (Enrol refuses that too).
350func EnrolledElsewhere(stateDir, origin, instanceID string) (other string, elsewhere bool, err error) {
351 path := filepath.Join(stateDir, "credentials.json")
352 if _, err := os.Lstat(path); os.IsNotExist(err) {
353 return "", false, nil
354 } else if err != nil {
355 return "", false, err
356 }
357 old, err := readCredentials(path)
358 if err != nil {
359 return "", false, err
360 }
361 if !time.Now().Before(old.Bearer.ExpiresAt) {
362 return "", false, nil
363 }
364 other, elsewhere = otherEnrolment(stateDir, origin, instanceID)
365 return other, elsewhere, nil
366}
367
368// EnrolledWith reports whether stateDir holds a live credential from an
369// enrolment with origin and instanceID. An Enrol that answers an error
370// after it published the credential (the directory sync after the rename
371// failed) leaves this; an installer asks it before it puts back its
372// earlier configuration, which would not go with that credential.
373// err is a credential that cannot be read: whether it is such a one is
374// not known.
375func EnrolledWith(stateDir, origin, instanceID string) (bool, error) {
376 cred, err := readCredentials(filepath.Join(stateDir, "credentials.json"))
377 if os.IsNotExist(err) {
378 return false, nil
379 }
380 if err != nil {
381 return false, err
382 }
383 if !time.Now().Before(cred.Bearer.ExpiresAt) {
384 return false, nil
385 }
386 _, other := otherEnrolment(stateDir, origin, instanceID)
387 return !other, nil
388}
389
390// otherEnrolment: whether the enrolment saved beside live credentials is
391// not for origin and instanceID (or cannot be read), and its origin.
392func otherEnrolment(stateDir, origin, instanceID string) (string, bool) {
393 var saved pendingEnrolment
394 if privateJSON(filepath.Join(stateDir, "enrolment.json"), &saved) != nil {
395 return "", true
396 }
397 if saved.Origin != origin || saved.Code.InstanceID != instanceID {
398 return saved.Origin, true
399 }
400 return "", false
401}
402
403// EnrolDetail is what went wrong, in words, for the person and the
404// install log: the cause under the diagnostic code, which carries no
405// secrets (the device secret and tokens are only ever in request and
406// response bodies, never in errors).
407func EnrolDetail(err error) string {
408 var known *diagnosticError
409 if errors.As(err, &known) && known.cause != nil {
410 err = known.cause
411 }
412 if err == nil {
413 return ""
414 }
415 detail := strings.Map(func(r rune) rune {
416 if r < 0x20 || r == 0x7f {
417 return ' '
418 }
419 return r
420 }, err.Error())
421 if len(detail) > 300 {
422 detail = detail[:300]
423 }
424 return detail
425}
426
427// RoleFile keeps the role a runner was enrolled with, in its state
428// directory.
429const RoleFile = "role"
430
431// WriteRole records the enrolled role.
432func WriteRole(stateDir, role string) error {
433 return runnerproto.JournalCredentials(filepath.Join(stateDir, RoleFile), role)
434}
435
436// ReadRole is the enrolled role, "" when the runner was enrolled before
437// roles.
438func ReadRole(stateDir string) string {
439 var role string
440 if privateJSON(filepath.Join(stateDir, RoleFile), &role) != nil || role != wire.RolePrimary && role != wire.RoleWorker {
441 return ""
442 }
443 return role
444}
445
446// ErrEnrolledAsPrimary: a runner that can only be a worker was given the
447// primary role (the person had no primary). Nothing is kept.
448var ErrEnrolledAsPrimary = errors.New("a worker-only runner was enrolled as a primary")
449
450// ErrInstanceOlder refuses to enrol a runner that can only be a worker
451// with an instance that does not speak protocol 2.
452var ErrInstanceOlder = errors.New("the instance is older than this worker")
453
454// workerProtocol asks the instance which runner protocol it speaks; one
455// that does not answer speaks protocol 1, which has no workers.
456func workerProtocol(ctx context.Context, origin string) error {
457 req, err := http.NewRequestWithContext(ctx, http.MethodGet, origin+wire.RunnerProtocolPath, nil)
458 if err != nil {
459 return err
460 }
461 resp, err := outboundClient().Do(req)
462 if err != nil {
463 return &enrolNetworkError{err}
464 }
465 defer resp.Body.Close()
466 if resp.StatusCode >= 500 || resp.StatusCode == http.StatusTooManyRequests {
467 return &EnrolAnswerError{Status: resp.StatusCode}
468 }
469 var v wire.RunnerProtocol
470 if resp.StatusCode != http.StatusOK || wire.Strict(mustRead(resp.Body), &v) != nil || v.Protocol < wire.Protocol2 {
471 return ErrInstanceOlder
472 }
473 return nil
474}
475
476func mustRead(r io.Reader) []byte {
477 raw, _ := io.ReadAll(io.LimitReader(r, 4<<10))
478 return raw
479}
480
481func randomBytes(n int) []byte {
482 b := make([]byte, n)
483 if _, err := rand.Read(b); err != nil {
484 panic(err)
485 }
486 return b
487}
488
489type pendingEnrolment struct {
490 Origin string `json:"origin"`
491 Label string `json:"label"`
492 Code runnerproto.DeviceCode `json:"code"`
493 Proof runnerproto.ExchangeProof `json:"proof"`
494}
495
496func (c Config) validateEnrolment() error {
497 if !validOrigin(c.Origin) || c.InstanceID == "" {
498 return provider.ErrContract
499 }
500 if !filepath.IsAbs(c.StateDir) || filepath.Clean(c.StateDir) != c.StateDir || c.StateDir == "/" {
501 return provider.ErrPolicy
502 }
503 return nil
504}
505
506func (p pendingEnrolment) usable(origin, instance string) bool {
507 u, e := url.Parse(p.Code.VerificationURI)
508 base, _ := url.Parse(origin)
509 return e == nil && p.Origin == origin && p.Code.InstanceID == instance &&
510 u.Scheme == base.Scheme && u.Host == base.Host && u.User == nil && u.Path == "/runners/enrol" && u.RawQuery == "" && u.Fragment == "" &&
511 p.Code.Version == 1 && p.Code.EnrolmentID != "" && p.Code.DeviceSecret != "" && p.Code.UserCode != "" && p.Code.Challenge != "" &&
512 p.Proof.EnrolmentID == p.Code.EnrolmentID && p.Proof.Challenge == p.Code.Challenge && p.Proof.Signature != "" && p.Proof.ExchangeNonce != "" &&
513 p.Label != "" && len(p.Label) <= 128 && !strings.ContainsAny(p.Label, "\r\n\x00") &&
514 p.Code.PollIntervalSeconds >= 5 && p.Code.PollIntervalSeconds <= 60 && time.Now().Before(p.Code.ExpiresAt)
515}
516
517func DefaultMachineLabel(stateDir, origin, instance string) (string, error) {
518 var saved pendingEnrolment
519 if privateJSON(filepath.Join(stateDir, "enrolment.json"), &saved) == nil && saved.usable(origin, instance) {
520 return saved.Label, nil
521 }
522 return os.Hostname()
523}
524
525// ReadMachineKey is the runner's enrolment key (machine-key.json): the
526// owner approved its public half, and the seal key is derived from it.
527func ReadMachineKey(stateDir string) (ed25519.PrivateKey, error) {
528 var encoded string
529 if err := privateJSON(filepath.Join(stateDir, "machine-key.json"), &encoded); err != nil {
530 return nil, err
531 }
532 key, err := base64.RawURLEncoding.DecodeString(encoded)
533 if err != nil || len(key) != ed25519.PrivateKeySize {
534 return nil, provider.ErrIdentity
535 }
536 return ed25519.PrivateKey(key), nil
537}
538