package runner import ( "bytes" "context" "crypto/ed25519" "crypto/rand" "encoding/base64" "encoding/json" "errors" "io" "net/http" "net/url" "os" "path/filepath" "strconv" "strings" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/wire" ) func outboundClient() *http.Client { return &http.Client{Timeout: 35 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} } func Enrol(ctx context.Context, c Config, output io.Writer) (resultErr error) { variable := "EQUIPO_RUNNER_STATE_DIR" defer func() { resultErr = diagnosticAt(resultErr, variable) }() if err := c.validateEnrolment(); err != nil { return err } if c.WorkerOnly { // A worker enrolled with an older instance would be its newest // runner, which that instance takes for the primary. Ask first. variable = "EQUIPO_ORIGIN" if err := retryTransient(ctx, c, func() error { return workerProtocol(ctx, c.Origin) }); err != nil { return err } variable = "EQUIPO_RUNNER_STATE_DIR" } lock, err := lockState(c.StateDir) if err != nil { return err } defer lock.Close() credentialPath := filepath.Join(c.StateDir, "credentials.json") if _, err := os.Lstat(credentialPath); err == nil { old, err := readCredentials(credentialPath) if err != nil { return err } if time.Now().Before(old.Bearer.ExpiresAt) { if _, other := otherEnrolment(c.StateDir, c.Origin, c.InstanceID); other { return provider.ErrIdentity } c.notify(EnrolNotice{Kept: true}) return nil } journalPath := filepath.Join(c.StateDir, "journal.db") if _, err = os.Stat(journalPath); err == nil { j, err := OpenJournal(ctx, journalPath) if err != nil { return err } var attempts []attemptState err = j.readStates(ctx, "attempt", &attempts) closeErr := j.Close() if err != nil { return err } if closeErr != nil { return closeErr } for _, a := range attempts { if a.Phase != "contained" { return provider.ErrUncertain } } } else if !os.IsNotExist(err) { return err } } else if !os.IsNotExist(err) { return err } keyPath := filepath.Join(c.StateDir, "machine-key.json") var encoded string if err = privateJSON(keyPath, &encoded); os.IsNotExist(err) { _, key, e := ed25519.GenerateKey(rand.Reader) if e != nil { return e } encoded = base64.RawURLEncoding.EncodeToString(key) err = runnerproto.JournalCredentials(keyPath, encoded) } if err != nil { return err } key, err := base64.RawURLEncoding.DecodeString(encoded) if err != nil || len(key) != ed25519.PrivateKeySize { return provider.ErrIdentity } variable = "EQUIPO_ORIGIN" client := outboundClient() post := func(path string, in, out any) (int, error) { raw, err := runnerproto.Marshal(in) if err != nil { return 0, err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.Origin+path, bytes.NewReader(raw)) if err != nil { return 0, err } req.Header.Set("Content-Type", "application/json") resp, err := client.Do(req) if err != nil { return 0, &enrolNetworkError{err} } defer resp.Body.Close() if resp.StatusCode != 200 && resp.StatusCode != 201 { return resp.StatusCode, answerError(resp) } return resp.StatusCode, runnerproto.DecodeLimit(resp.Body, out, 64<<10) } label := c.MachineLabel if label == "" { label, err = os.Hostname() if err != nil { return err } } if len(label) > 128 || strings.TrimSpace(label) == "" || strings.ContainsAny(label, "\r\n\x00") { return provider.ErrContract } pendingPath := filepath.Join(c.StateDir, "enrolment.json") var pending pendingEnrolment err = privateJSON(pendingPath, &pending) if err != nil && !os.IsNotExist(err) { // Malformed JSON is unusable retry state; permission and I/O errors still deny. if !errors.Is(err, runnerproto.ErrInvalid) { return err } } if err != nil || !pending.usable(c.Origin, c.InstanceID) { var code runnerproto.DeviceCode err = retryTransient(ctx, c, func() error { _, err := post("/api/enrolments", runnerproto.BeginEnrolmentRequest{Version: 1, MachinePublicKey: base64.RawURLEncoding.EncodeToString(ed25519.PrivateKey(key).Public().(ed25519.PublicKey)), Label: label, WorkerOnly: c.WorkerOnly}, &code) return err }) if err != nil { return err } pending = pendingEnrolment{Origin: c.Origin, Label: label, Code: code} pending.Proof = runnerproto.ExchangeProof{EnrolmentID: code.EnrolmentID, Challenge: code.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(randomBytes(32))} pending.Proof.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(ed25519.PrivateKey(key), runnerproto.EnrolmentProofMessage(code.InstanceID, pending.Proof))) if err = runnerproto.JournalCredentials(pendingPath, pending); err != nil { return err } } code, proof := pending.Code, pending.Proof if !pending.usable(c.Origin, c.InstanceID) { return provider.ErrIdentity } // The link carries the code, so opening it shows this machine with one // button to add it; the code stays on its own line for typing. link := code.VerificationURI + "?code=" + url.QueryEscape(code.UserCode) c.notify(EnrolNotice{Link: true}) if _, err = io.WriteString(output, "["+link+"]("+link+")\n"+code.UserCode+"\n"); err != nil { return err } c.notify(EnrolNotice{Waiting: true}) // Polled until approved: "not yet" (409) and anything transient (no // answer, a server error, too soon) are waited out, backing off, until // the code expires. Turned down or expired, the saved code is dropped // so the next run starts with a new one. interval := time.Duration(code.PollIntervalSeconds) * enrolPollUnit wait, failures := interval, 0 var last error for time.Now().Before(code.ExpiresAt) { timer := time.NewTimer(min(wait, max(time.Until(code.ExpiresAt), 0)+enrolPollUnit)) select { case <-ctx.Done(): timer.Stop() return ctx.Err() case <-timer.C: } var cred runnerproto.RunnerCredential status, err := post("/api/enrolments/token", runnerproto.ExchangeEnrolmentRequest{Version: 1, DeviceSecret: code.DeviceSecret, Proof: proof}, &cred) if status == 409 { wait, failures, last = interval, 0, nil continue } if transient(err) { last = err failures++ wait = backoff(interval, failures) c.notify(EnrolNotice{Retry: err}) continue } if status == http.StatusForbidden { // The instance answers 403 for a code turned down (revoked) // and for one that has expired by its clock. _ = os.Remove(pendingPath) if time.Until(code.ExpiresAt) < time.Minute { return ErrEnrolmentExpired } return ErrEnrolmentRefused } if err != nil { return err } if cred.Version != 1 || cred.Token == "" || cred.RunnerID == "" || !time.Now().Before(cred.ExpiresAt) { return provider.ErrIdentity } if c.WorkerOnly && cred.Role != wire.RoleWorker { // The instance enrolled this machine as a primary: a Mac only // ever runs as a worker, so it keeps nothing and says why. return ErrEnrolledAsPrimary } // The role is kept before the runner ever connects (a worker never // serves as a primary), beside the credential so an older runner // binary still reads that. No role is a primary's credential, or an // older instance's, which has only primaries. It is written before // the credential, which is the last write: an enrolment that fails // leaves no new credential (only an expired or absent one reaches // here), so an installer can put its earlier configuration back. role := wire.RolePrimary if cred.Role == wire.RoleWorker { role = wire.RoleWorker } if err := WriteRole(c.StateDir, role); err != nil { return err } return runnerproto.JournalCredentials(credentialPath, runnerproto.CredentialRotation{Bearer: cred}) } if last != nil { // Still failing when the code ran out: that, not the expiry, is // what to fix. return last } _ = os.Remove(pendingPath) return ErrEnrolmentExpired } // ErrEnrolmentExpired: nobody approved the link before its code expired. var ErrEnrolmentExpired = errors.New("the enrolment link expired before it was approved") // ErrEnrolmentRefused: the instance turned the enrolment down (removed // or no longer valid) before it expired. var ErrEnrolmentRefused = errors.New("the instance turned the enrolment down") // EnrolNotice is what Enrol reports while it works: Kept when a valid // enrolment is kept and no link is printed, Link just before the link is // printed, Waiting once it is, Retry for each transient failure it waits // out. type EnrolNotice struct { Kept bool Link bool Waiting bool Retry error } func (c Config) notify(n EnrolNotice) { if c.EnrolNotify != nil { c.EnrolNotify(n) } } // enrolPollUnit is a second: the poll interval's unit (tests shorten it). var enrolPollUnit = time.Second // enrolAttempts bounds the tries of a request made once (the protocol // question, starting the enrolment) when it fails transiently. const enrolAttempts = 4 // enrolNetworkError: the instance could not be reached or did not answer. type enrolNetworkError struct{ err error } func (e *enrolNetworkError) Error() string { return "no answer from Equipo: " + e.err.Error() } func (e *enrolNetworkError) Unwrap() error { return provider.ErrUncertain } // EnrolAnswerError is an answer from the instance that is not success: // its HTTP status and the error key it gave, nothing more. type EnrolAnswerError struct { Status int Key string } func (e *EnrolAnswerError) Error() string { if e.Key == "" { return "Equipo answered HTTP " + strconv.Itoa(e.Status) } return "Equipo answered HTTP " + strconv.Itoa(e.Status) + " (" + e.Key + ")" } func (e *EnrolAnswerError) Unwrap() error { if e.Status >= 500 { return provider.ErrUncertain } return provider.ErrIdentity } func answerError(resp *http.Response) error { var body runnerproto.ErrorResponse key := "" if json.Unmarshal(mustRead(resp.Body), &body) == nil && len(body.Error) <= 64 && strings.Trim(body.Error, "abcdefghijklmnopqrstuvwxyz0123456789._-") == "" { key = body.Error } return &EnrolAnswerError{Status: resp.StatusCode, Key: key} } // transient: worth asking again (no answer, a server error, too soon). func transient(err error) bool { var answer *EnrolAnswerError var network *enrolNetworkError return errors.As(err, &network) || errors.As(err, &answer) && (answer.Status >= 500 || answer.Status == http.StatusTooManyRequests) } // backoff doubles the wait after each failure in a row, up to a minute. func backoff(interval time.Duration, failures int) time.Duration { return min(interval< 300 { detail = detail[:300] } return detail } // RoleFile keeps the role a runner was enrolled with, in its state // directory. const RoleFile = "role" // WriteRole records the enrolled role. func WriteRole(stateDir, role string) error { return runnerproto.JournalCredentials(filepath.Join(stateDir, RoleFile), role) } // ReadRole is the enrolled role, "" when the runner was enrolled before // roles. func ReadRole(stateDir string) string { var role string if privateJSON(filepath.Join(stateDir, RoleFile), &role) != nil || role != wire.RolePrimary && role != wire.RoleWorker { return "" } return role } // ErrEnrolledAsPrimary: a runner that can only be a worker was given the // primary role (the person had no primary). Nothing is kept. var ErrEnrolledAsPrimary = errors.New("a worker-only runner was enrolled as a primary") // ErrInstanceOlder refuses to enrol a runner that can only be a worker // with an instance that does not speak protocol 2. var ErrInstanceOlder = errors.New("the instance is older than this worker") // workerProtocol asks the instance which runner protocol it speaks; one // that does not answer speaks protocol 1, which has no workers. func workerProtocol(ctx context.Context, origin string) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, origin+wire.RunnerProtocolPath, nil) if err != nil { return err } resp, err := outboundClient().Do(req) if err != nil { return &enrolNetworkError{err} } defer resp.Body.Close() if resp.StatusCode >= 500 || resp.StatusCode == http.StatusTooManyRequests { return &EnrolAnswerError{Status: resp.StatusCode} } var v wire.RunnerProtocol if resp.StatusCode != http.StatusOK || wire.Strict(mustRead(resp.Body), &v) != nil || v.Protocol < wire.Protocol2 { return ErrInstanceOlder } return nil } func mustRead(r io.Reader) []byte { raw, _ := io.ReadAll(io.LimitReader(r, 4<<10)) return raw } func randomBytes(n int) []byte { b := make([]byte, n) if _, err := rand.Read(b); err != nil { panic(err) } return b } type pendingEnrolment struct { Origin string `json:"origin"` Label string `json:"label"` Code runnerproto.DeviceCode `json:"code"` Proof runnerproto.ExchangeProof `json:"proof"` } func (c Config) validateEnrolment() error { if !validOrigin(c.Origin) || c.InstanceID == "" { return provider.ErrContract } if !filepath.IsAbs(c.StateDir) || filepath.Clean(c.StateDir) != c.StateDir || c.StateDir == "/" { return provider.ErrPolicy } return nil } func (p pendingEnrolment) usable(origin, instance string) bool { u, e := url.Parse(p.Code.VerificationURI) base, _ := url.Parse(origin) return e == nil && p.Origin == origin && p.Code.InstanceID == instance && u.Scheme == base.Scheme && u.Host == base.Host && u.User == nil && u.Path == "/runners/enrol" && u.RawQuery == "" && u.Fragment == "" && p.Code.Version == 1 && p.Code.EnrolmentID != "" && p.Code.DeviceSecret != "" && p.Code.UserCode != "" && p.Code.Challenge != "" && p.Proof.EnrolmentID == p.Code.EnrolmentID && p.Proof.Challenge == p.Code.Challenge && p.Proof.Signature != "" && p.Proof.ExchangeNonce != "" && p.Label != "" && len(p.Label) <= 128 && !strings.ContainsAny(p.Label, "\r\n\x00") && p.Code.PollIntervalSeconds >= 5 && p.Code.PollIntervalSeconds <= 60 && time.Now().Before(p.Code.ExpiresAt) } func DefaultMachineLabel(stateDir, origin, instance string) (string, error) { var saved pendingEnrolment if privateJSON(filepath.Join(stateDir, "enrolment.json"), &saved) == nil && saved.usable(origin, instance) { return saved.Label, nil } return os.Hostname() } // ReadMachineKey is the runner's enrolment key (machine-key.json): the // owner approved its public half, and the seal key is derived from it. func ReadMachineKey(stateDir string) (ed25519.PrivateKey, error) { var encoded string if err := privateJSON(filepath.Join(stateDir, "machine-key.json"), &encoded); err != nil { return nil, err } key, err := base64.RawURLEncoding.DecodeString(encoded) if err != nil || len(key) != ed25519.PrivateKeySize { return nil, provider.ErrIdentity } return ed25519.PrivateKey(key), nil }