Skip to content
quarry Artifact [680b4ccf32]
Login

Artifact [680b4ccf32]

Artifact 680b4ccf32ed96671392f195ef2a2d25d73e59613bbfe420344f4f60e9857294:


package api

import (
	"context"
	"crypto/sha256"
	"encoding/base32"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"regexp"
	"strings"
	"time"

	"craftdesign.group/quarry/internal/oltp"
)

// RFC 0030, A runner without an install code. `quarry-runner install`
// with no code and no token starts a runner request: an anonymous start
// of kind "runner" for one repository the caller can see. It files an
// ordinary sign-off request on the repository's owner, for the op that
// mints a worker token, bound to the start's pickup code; approving it
// is the one act that mints the token as the approver, and the
// installer collects it with its key. Nothing is minted until then.

const (
	// runnerKind is the start kind of a runner request.
	runnerKind = "runner"
	// runnerAskerPrefix begins the asker of a runner request: "runner at
	// ADDRESS", where the start came from. It is not an account name,
	// since it holds a space.
	runnerAskerPrefix = "runner at "
	// runnerStartLife is how long a runner request waits for its owner.
	runnerStartLife = oltp.SetupStartLife
	// runnerStartsPerRepo is how many runner requests may wait on one
	// repository at once.
	runnerStartsPerRepo = 3
)

func runnerAsker(addr string) string { return runnerAskerPrefix + addr }

// isRunnerAsker reports whether agent is the asker of a runner request.
func isRunnerAsker(agent string) bool { return strings.HasPrefix(agent, runnerAskerPrefix) }

// RunnerAddress is the address a runner request's asker names.
func RunnerAddress(agent string) string { return strings.TrimPrefix(agent, runnerAskerPrefix) }

// runnerLapsed reports whether a runner request has waited past its
// ten minutes.
func runnerLapsed(s SignOffRequest, now time.Time) bool {
	return isRunnerAsker(s.Agent) && s.State == "pending" &&
		s.Requested < now.UTC().Add(-runnerStartLife).Format(time.RFC3339)
}

var shortAlphabet = base32.NewEncoding("0123456789ABCDEFGHJKMNPQRSTVWXYZ").WithPadding(base32.NoPadding)

// RunnerShortCode is the code shown to the person installing and on the
// owner's page, XXXX-XXXX, so they can compare the two: derived from the
// start's pickup code, which both sides hold and nothing else shows.
func RunnerShortCode(pickup string) string {
	sum := sha256.Sum256([]byte("runner-start:" + pickup))
	return formatSetupCode(shortAlphabet.EncodeToString(sum[:5]))
}

// runnerHost is what a host name may be: the account-name alphabet, so
// nothing the installer reports can carry markup or a line break.
var runnerHost = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)

// startRunner is the runner kind of POST /api/v1/setup/start, after the
// address budget has been spent.
func (s *SetupStarter) startRunner(w http.ResponseWriter, ip string, now time.Time, in setupStartIn) {
	d := s.d
	if in.Name != "" || !runnerHost.MatchString(in.Host) || in.Repo == "" || len(in.Repo) > 64 {
		pickupJSON(w, http.StatusBadRequest, map[string]string{"error": "a runner start names a repository and a host (letters, digits, '.', '-' or '_') and a pickup code, and nothing else"})
		return
	}
	if !validPickupCode(in.Pickup) {
		pickupJSON(w, http.StatusBadRequest, map[string]string{"error": "a pickup code is the lowercase hex SHA-256 of the 32-byte pickup key"})
		return
	}
	// A repository the caller cannot see, one that does not exist and one
	// nobody answers for are one answer.
	missing := func() {
		pickupJSON(w, http.StatusNotFound, map[string]string{"error": "no such repository"})
	}
	r, err := d.repo(in.Repo)
	if err != nil || !d.listable(context.Background(), in.Repo) || d.companionParent(in.Repo) != "" || d.Owners == nil {
		missing()
		return
	}
	owner, err := d.Owners.OwnerOf(in.Repo)
	if err != nil || owner == "" || d.operatorOf(owner) != "" {
		missing()
		return
	}
	code := RunnerShortCode(in.Pickup)
	label := in.Host + " " + code
	input, err := json.Marshal(workerTokenNewIn{Repo: in.Repo, Label: label})
	if err != nil {
		pickupJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
		return
	}
	s.runnerMu.Lock()
	defer s.runnerMu.Unlock()
	rows, err := d.SignOffs.SignOffsFor(owner, 200)
	if err != nil {
		pickupJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
		return
	}
	open := 0
	for _, row := range rows {
		if row.Repo == in.Repo && isRunnerAsker(row.Agent) && row.State == "pending" && !runnerLapsed(row, now) {
			open++
		}
	}
	if open >= runnerStartsPerRepo {
		w.Header().Set("Retry-After", "60")
		pickupJSON(w, http.StatusTooManyRequests, map[string]string{"error": "this repository has as many runner requests waiting as it may; try again in a few minutes"})
		return
	}
	summary := fmt.Sprintf("Set up a CI runner on %s for %s", in.Host, in.Repo)
	req, err := d.SignOffs.RequestSignOff(SignOffRequest{Agent: runnerAsker(ip), Owner: owner, Op: "ci.worker.token.new", Repo: in.Repo, Code: r.Code,
		Input: string(input), Summary: summary, Reason: runnerReason(in.Host, code), Pickup: in.Pickup})
	switch {
	case errors.Is(err, ErrPickupBound), errors.Is(err, ErrPickupMismatch):
		pickupJSON(w, http.StatusBadRequest, map[string]string{"error": "that pickup code cannot be used; make a new key and start again"})
		return
	case errors.Is(err, ErrTooManySignOffs):
		w.Header().Set("Retry-After", "60")
		pickupJSON(w, http.StatusTooManyRequests, map[string]string{"error": "this address has as many runner requests waiting as it may; try again in a few minutes"})
		return
	case err != nil:
		pickupJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
		return
	}
	d.attend(owner, AttentionEvent{Kind: "signoff", Repo: in.Repo, From: req.Agent, Summary: summary, Link: "/me/requests/" + req.ID})
	d.fireSignOff(owner, in.Repo, req.Agent, summary, req.ID)
	pickupJSON(w, http.StatusOK, setupStartOut{Code: code, Link: d.link("/me/requests"),
		Expires: now.UTC().Add(runnerStartLife).Format(time.RFC3339)})
}

// runnerReason is the line the forge writes on a runner request: the
// installer's own words reach no page but the host name, held to the
// account-name alphabet.
func runnerReason(host, code string) string {
	return fmt.Sprintf("Approve only if you started this install on %s yourself. Its code is %s.", host, code)
}

// IsRunnerAsker is isRunnerAsker for the pages that draw a request.
func IsRunnerAsker(agent string) bool { return isRunnerAsker(agent) }