Skip to content
quarry Artifact [a77505c76d]
Login

Artifact [a77505c76d]

Artifact a77505c76d5d48999d02cccb13227fb999238844bd2b737af1b9e464cb154e37:


package api

import (
	"context"
	"errors"
	"fmt"
	"log"
	"strings"
	"time"
	"unicode/utf8"

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

// RunnerCodeStore holds install codes (RFC 0030, Install codes) and the
// proof a worker token retires itself by. *oltp.DB is one.
type RunnerCodeStore interface {
	NewRunnerCode(repo, maker string, max int, now time.Time) (string, error)
	SpendRunnerCode(repo, code string, now time.Time) (maker string, ok bool, err error)
	RunnerCodeFailures(repo string, now time.Time) (int, error)
	NoteRunnerCodeFailure(repo string, now time.Time) error
	NoteWorkerTokenProof(bearer, id, repo string) error
	WorkerTokenByProof(bearer string) (id, repo string, ok bool, err error)
}

const (
	// runnerCodesLive is how many live codes one repository may hold.
	runnerCodesLive = 5
	// runnerCodeFailures is how many failed redemptions close a
	// repository's redemption for the rest of the window.
	runnerCodeFailures = 5
)

// noSuchInstallCode is the one answer for a wrong, spent or expired
// code, a repository the caller cannot see and a closed window.
func noSuchInstallCode() error {
	return fmt.Errorf("no such install code, or it has expired or been used: %w", ops.ErrNotFound)
}

func (d Deps) now() time.Time {
	if d.Now != nil {
		return d.Now()
	}
	return time.Now()
}

type runnerCodeNewIn struct {
	Repo string `json:"repo" validate:"required,max=64"`
}

type runnerCodeNewOut struct {
	// Code is the install code, in the clear here and nowhere else.
	Code string `json:"code" secret:"once"`
	// Expires is when the code lapses.
	Expires string `json:"expires"`
	// Group is the worker group a runner installed with it attaches to.
	Group string `json:"group"`
}

type runnerCodeRedeemIn struct {
	Repo  string `json:"repo" validate:"required,max=64"`
	Code  string `json:"code" validate:"required,max=200"`
	Host  string `json:"host" validate:"required,max=100"`
	Label string `json:"label" validate:"max=100"`
}

type runnerCodeRedeemOut struct {
	// Value is the worker token, in the clear here and nowhere else.
	Value string         `json:"value" secret:"once"`
	Token workerTokenRow `json:"token"`
	// Group is the worker group the token is scoped to.
	Group string `json:"group"`
}

type workerTokenRetireIn struct {
	Repo string `json:"repo" validate:"required,max=64"`
	// Token is the worker token's value: the credential that retires
	// itself.
	Token string `json:"token" validate:"required,max=400"`
	Host  string `json:"host" validate:"max=100"`
}

func registerRunnerCodes(r *ops.Registry, d Deps) error {
	noEngine := fmt.Errorf("no CI engine is configured here: %w", ops.ErrNotFound)
	if err := ops.Register(r, ops.Op[runnerCodeNewIn, runnerCodeNewOut]{
		Name: "ci.runner.code.new",
		Ask:  "Make an install code for a runner on {repo}",
		Caps: "a",
		Doc: "Make an install code for one repository: what its admin hands to the person installing a runner, who redeems it once, " +
			"with no account, for a worker token scoped to the repository's worker group and nothing wider. It lives 15 minutes, " +
			"is spent by its first redemption, and a repository holds at most five live ones. The code is returned once; only its hash is kept. " +
			"An agent is refused, as for `ci.worker.token.new`, and may ask the person who answers for it with `Quarry-Ask`. " +
			"Recorded in the settings log, by whom, and never the code.",
		Kind:  ops.Command,
		Auth:  ops.Token,
		Route: "POST /api/v1/r/{repo}/ci/runner-codes",
		Run: func(ctx context.Context, in runnerCodeNewIn) (runnerCodeNewOut, error) {
			if d.WorkerTokens == nil || d.RunnerCodes == nil {
				return runnerCodeNewOut{}, noEngine
			}
			if who := ops.User(ctx); who != "" {
				if op := d.operatorOf(who); op != "" {
					return runnerCodeNewOut{}, fmt.Errorf("%s is an agent, operated by %s, and an agent does not make an install code, which becomes a worker token that never expires; ask %s: %w",
						who, op, op, ops.ErrForbidden)
				}
			}
			if _, err := d.repoFor(ctx, in.Repo); err != nil {
				return runnerCodeNewOut{}, err
			}
			if err := d.refuseWithout(ctx, in.Repo, "a", false); err != nil {
				return runnerCodeNewOut{}, err
			}
			now := d.now()
			code, err := d.RunnerCodes.NewRunnerCode(in.Repo, ops.User(ctx), runnerCodesLive, now)
			if err == oltp.ErrRunnerCodesFull {
				return runnerCodeNewOut{}, fmt.Errorf("%s already has %d live install codes; use one, or wait for one to lapse (they last 15 minutes): %w",
					in.Repo, runnerCodesLive, ops.ErrRateLimited)
			}
			if err != nil {
				return runnerCodeNewOut{}, err
			}
			d.logRunnerCode(ctx, in.Repo, "", "install code made")
			return runnerCodeNewOut{Code: code, Expires: now.UTC().Add(oltp.RunnerCodeLife).Format(time.RFC3339), Group: ci.GroupFor(in.Repo)}, nil
		},
	}); err != nil {
		return err
	}
	if err := ops.Register(r, ops.Op[runnerCodeRedeemIn, runnerCodeRedeemOut]{
		Name: "ci.runner.code.redeem",
		Doc: "Redeem an install code for one worker token on its repository, with no account. The code's maker must still hold `a` on the repository; " +
			"the token is minted as the maker, by the same path as `ci.worker.token.new`, and its value is returned in this one response. " +
			"A wrong, spent or expired code, a closed window and a repository the caller cannot see all answer the one not-found sentence. " +
			"Five failures against one repository in 15 minutes close redemption there for the rest of the window.",
		Kind:  ops.Command,
		Auth:  ops.Anonymous,
		Route: "POST /api/v1/r/{repo}/ci/runner-codes/redeem",
		Run: func(ctx context.Context, in runnerCodeRedeemIn) (runnerCodeRedeemOut, error) {
			if d.WorkerTokens == nil || d.RunnerCodes == nil {
				return runnerCodeRedeemOut{}, noEngine
			}
			if _, err := d.repo(in.Repo); err != nil {
				return runnerCodeRedeemOut{}, noSuchInstallCode()
			}
			now := d.now()
			failed, err := d.RunnerCodes.RunnerCodeFailures(in.Repo, now)
			if err != nil {
				return runnerCodeRedeemOut{}, err
			}
			if failed >= runnerCodeFailures {
				return runnerCodeRedeemOut{}, noSuchInstallCode()
			}
			maker, ok, err := d.RunnerCodes.SpendRunnerCode(in.Repo, strings.TrimSpace(in.Code), now)
			if err != nil {
				return runnerCodeRedeemOut{}, err
			}
			if !ok {
				if err := d.RunnerCodes.NoteRunnerCodeFailure(in.Repo, now); err != nil {
					log.Printf("install code failure on %s: %v", in.Repo, err)
				}
				return runnerCodeRedeemOut{}, noSuchInstallCode()
			}
			label := in.Host
			if in.Label != "" {
				label = in.Host + " " + in.Label
			}
			how := fmt.Sprintf(" by install code, made by %s, redeemed from %s", maker, ops.AddrOf(ctx))
			out, err := d.mintWorkerToken(ops.WithUser(ctx, maker), in.Repo, clip(label, 100), how)
			if err != nil {
				// A maker who has lost the letter, or become an agent, is
				// a dead code; the caller is told no more than any other.
				if errors.Is(err, ops.ErrForbidden) || errors.Is(err, ops.ErrNotFound) {
					return runnerCodeRedeemOut{}, noSuchInstallCode()
				}
				return runnerCodeRedeemOut{}, err
			}
			return runnerCodeRedeemOut{Value: out.Value, Token: out.Token, Group: ci.GroupFor(in.Repo)}, nil
		},
	}); err != nil {
		return err
	}
	return ops.Register(r, ops.Op[workerTokenRetireIn, workerTokenListOut]{
		Name: "ci.worker.token.retire",
		Doc: "A worker token retires itself: revokes the token it presents in `token`, and no other, with no account. " +
			"Only a token this forge minted for this repository; anything else is not found. Answers an empty list.",
		Kind:  ops.Command,
		Auth:  ops.Anonymous,
		Route: "POST /api/v1/r/{repo}/ci/worker-tokens/retire",
		Run: func(ctx context.Context, in workerTokenRetireIn) (workerTokenListOut, error) {
			if d.WorkerTokens == nil || d.RunnerCodes == nil {
				return workerTokenListOut{}, noEngine
			}
			notFound := fmt.Errorf("no such worker token on %s: %w", in.Repo, ops.ErrNotFound)
			if _, err := d.repo(in.Repo); err != nil {
				return workerTokenListOut{}, notFound
			}
			id, repo, ok, err := d.RunnerCodes.WorkerTokenByProof(in.Token)
			if err != nil {
				return workerTokenListOut{}, err
			}
			if !ok || repo != in.Repo {
				return workerTokenListOut{}, notFound
			}
			own, err := d.ownWorkerTokens(in.Repo)
			if err != nil {
				return workerTokenListOut{}, err
			}
			for _, t := range own {
				if t.ID != id {
					continue
				}
				if t.RevokedAt == "" {
					if err := d.WorkerTokens.RevokeWorkerToken(id); err != nil {
						return workerTokenListOut{}, err
					}
					now := "revoked by its holder"
					if in.Host != "" {
						now += fmt.Sprintf(" (uninstall on %s)", in.Host)
					}
					d.logWorkerToken(in.Repo, ctx, tokenWords(t, ""), now)
				}
				return workerTokenListOut{Tokens: []workerTokenRow{}}, nil
			}
			return workerTokenListOut{}, notFound
		},
	})
}

// logRunnerCode records an install code's making in the settings log.
func (d Deps) logRunnerCode(ctx context.Context, repo, was, now string) {
	if d.SettingLog == nil {
		return
	}
	if ask, ok := signOffAskOf(ctx); ok {
		now = fmt.Sprintf("%s (asked by %s, request %s)", now, ask.agent, ask.id)
	}
	if err := d.SettingLog.LogSetting(repo, ops.User(ctx), ops.Via(ctx), "runner-code", was, now); err != nil {
		log.Printf("settings log: install code on %s: %v", repo, err)
	}
}

// clip cuts s to at most n bytes on a rune boundary.
func clip(s string, n int) string {
	if len(s) <= n {
		return s
	}
	for n > 0 && !utf8.RuneStart(s[n]) {
		n--
	}
	return s[:n]
}