package install
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"craftdesign.group/quarry/internal/pickupclient"
)
// A runner without an install code (RFC 0030): with no code and no token
// in hand, install asks the forge for a worker token the repository's
// owner approves. It makes a pickup key, keeps it in the install's
// private directory, starts a runner request with the key's code and
// waits; the token is collected with the key, written to a private file
// by the caller, and printed nowhere.
// hostLabel is this machine's name as a runner start may carry it.
func hostLabel(name string) string {
var b strings.Builder
for _, r := range name {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '.', r == '-', r == '_':
b.WriteRune(r)
default:
b.WriteByte('-')
}
}
out := strings.TrimLeft(b.String(), ".-_")
if len(out) > 64 {
out = out[:64]
}
if out == "" {
return "host"
}
return out
}
// request files a runner request for the repository this install is
// for and waits for its approval, returning the worker token and its
// id. keyPath is where the pickup key waits meanwhile; it is removed
// again whatever happens, and a failure leaves nothing of the request
// on this machine.
func (b *builder) request(ctx context.Context, e Env, forge *url.URL, keyPath, owner, group string) (token, id string, err error) {
m := b.m
key, pickup, err := pickupclient.NewKey()
if err != nil {
return "", "", err
}
if err := b.s.WriteFile(keyPath, key, owner, group, 0o600); err != nil {
return "", "", err
}
addOnce(&m.Paths, keyPath)
defer func() {
b.s.Remove(keyPath)
m.Paths = without(m.Paths, keyPath)
}()
host, _ := b.s.Hostname()
host = hostLabel(host)
origin := forge.Scheme + "://" + forge.Host
var started struct {
Code string `json:"code"`
Link string `json:"link"`
}
err = postJSON(ctx, e.client(), origin+"/api/v1/setup/start", "",
map[string]string{"kind": "runner", "repo": m.Repo, "host": host, "pickup": pickup}, &started)
var se *statusError
switch {
case errors.As(err, &se) && se.Code == http.StatusNotFound:
return "", "", fmt.Errorf("the forge has no repository %s that can be seen without signing in; for a private repository, ask an admin for an install code (the repository's Settings, Runners, Add a runner) and pass --code", m.Repo)
case errors.As(err, &se) && se.Code == http.StatusTooManyRequests:
return "", "", errors.New("the forge is holding as many runner requests as it may from this address or for this repository's owner; try again once they lapse (10 minutes), or ask an admin for an install code (the repository's Settings, Runners, Add a runner) and pass --code")
case err != nil:
return "", "", fmt.Errorf("starting the runner request: %w", err)
}
fmt.Fprintf(e.Out, "Asked the owner of %s to approve a runner for %s.\nCode %s: it is on their request too, and approving it is all they do.\nWaiting (the request lapses after 10 minutes)...\n", m.Repo, host, started.Code)
wait := e.Wait
if wait == 0 {
wait = 15 * time.Minute
}
rel, err := pickupclient.CollectRunner(ctx, origin, key, pickupclient.CollectOpts{Client: e.client(), Wait: wait, Poll: e.Poll})
var closed *pickupclient.Closed
switch {
case errors.As(err, &closed) && closed.State == "denied":
return "", "", errors.New("the request was denied; nothing was installed")
case errors.As(err, &closed):
return "", "", fmt.Errorf("the request ended (%s) without a token; nothing was installed, run install again", closed.State)
case errors.Is(err, pickupclient.ErrStillPending):
return "", "", errors.New("nobody approved the request in time; nothing was installed, run install again")
case err != nil:
return "", "", err
}
// The key proves who collects; the answer says what it is for. Another
// client could have bound the code first.
if rel.Repo != m.Repo || !strings.HasPrefix(rel.Agent, "runner at ") {
// Not this install's request: what was released is retired, not kept.
postJSON(ctx, e.client(), origin+"/api/v1/r/"+url.PathEscape(rel.Repo)+"/ci/worker-tokens/retire", "",
map[string]string{"token": rel.Secret, "host": host}, nil)
return "", "", errors.New("the forge released a token for something other than this install's request; it was retired and nothing was installed")
}
return rel.Secret, rel.TokenID, nil
}
func without(list []string, v string) []string {
var out []string
for _, x := range list {
if x != v {
out = append(out, x)
}
}
return out
}