Skip to content
quarry Artifact [0e9cb79b5c]
Login

Artifact [0e9cb79b5c]

Artifact 0e9cb79b5ccd7d380da4dfa1f4353e83c066b7abdea005899436e178b9b253d3:


package api

import (
	"encoding/json"
	"fmt"
	"time"

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

// Credential is what an answer that minted a token says about it, the
// same way for every op that mints one, so a collector can check what it
// got without knowing each op's shape. Never a value.
type Credential struct {
	// Step is the plan step that minted it, 1-based; 0 outside a plan.
	Step    int      `json:"step,omitempty"`
	Agent   string   `json:"agent"`
	Repos   []string `json:"repos"`
	Scopes  []string `json:"scopes"`
	Ceiling string   `json:"ceiling"`
	TokenID string   `json:"token_id"`
	Expires string   `json:"expires"`
	// IdleLapseDays is the days of disuse after which a token with no
	// expiry ends, 0 for one with a fixed expiry; Idle says which, and
	// Lapses is the day it ends if nothing changes.
	IdleLapseDays int    `json:"idle_lapse_days"`
	Idle          bool   `json:"idle"`
	Lapses        string `json:"lapses,omitempty"`
	// Note says in a sentence when the token ends.
	Note string `json:"note,omitempty"`
}

// secretKeys is, per op that holds a once-only value, the key it sits
// under in the secret half. The ops with a Credential are those whose
// answer carries a token record (see credentialOf).
var secretKeys = map[string]string{
	setupOp:               "value",
	"agent.token.new":     "value",
	"agent.token.reissue": "value",
	"ci.worker.token.new": "value",
	"ci.token.new":        "token",
	"ci.runner.code.new":  "code",
}

func credentialOf(op, repo string, input, answer json.RawMessage) (Credential, bool) {
	var c Credential
	switch op {
	case setupOp:
		var out agentSetupOut
		if json.Unmarshal(answer, &out) != nil || out.Token.ID == "" {
			return c, false
		}
		c = credentialFromRow(out.Agent, out.Token)
	case "agent.token.new":
		var out agentTokenNewOut
		var in struct {
			Agent string `json:"agent"`
		}
		if json.Unmarshal(answer, &out) != nil || json.Unmarshal(input, &in) != nil || out.Token.ID == "" {
			return c, false
		}
		c = credentialFromRow(in.Agent, out.Token)
	case "ci.worker.token.new":
		var out workerTokenNewOut
		if json.Unmarshal(answer, &out) != nil || out.Token.ID == "" {
			return c, false
		}
		c = Credential{Repos: []string{}, Scopes: []string{}, TokenID: out.Token.ID}
		if repo != "" {
			c.Repos = []string{repo}
		}
	default:
		return c, false
	}
	return c, true
}

func credentialFromRow(agent string, t meTokenRow) Credential {
	c := Credential{Agent: agent, Repos: orEmpty(t.Repos), Scopes: orEmpty(t.Scopes), Ceiling: t.Ceiling,
		TokenID: t.ID, Expires: t.Expires, Idle: t.Idle, Lapses: t.Lapses}
	switch {
	case t.Idle:
		c.IdleLapseDays = int(oltp.TokenIdleLife / (24 * time.Hour))
		c.Note = fmt.Sprintf("This token ends if it goes unused for %d days; unused from now, it ends on %s.", c.IdleLapseDays, day(t.Lapses))
	case t.Expires != "":
		c.Note = fmt.Sprintf("This token ends on %s whether or not it is used.", day(t.Expires))
	}
	return c
}

func orEmpty(s []string) []string {
	if s == nil {
		return []string{}
	}
	return s
}

// day is the date of an RFC 3339 time, or the text itself when it is not.
func day(rfc string) string {
	if len(rfc) >= 10 {
		return rfc[:10]
	}
	return rfc
}

// credentialsOf is the credentials an approved request's answer minted,
// in step order for a plan. The one place they are built: signoff.get and
// the pickup route both read it, beside the secret split off by
// splitSecret. A request that minted none gives nil.
func credentialsOf(s SignOffRequest) []Credential {
	if s.Result == "" {
		return nil
	}
	if s.Op != planOp {
		if c, ok := credentialOf(s.Op, s.Repo, json.RawMessage(s.Input), json.RawMessage(s.Result)); ok {
			return []Credential{c}
		}
		return nil
	}
	var steps []planStep
	var results []planStepResult
	if json.Unmarshal([]byte(s.Input), &steps) != nil || json.Unmarshal([]byte(s.Result), &results) != nil {
		return nil
	}
	var out []Credential
	for i, r := range results {
		if i >= len(steps) || r.State != "done" {
			continue
		}
		if c, ok := credentialOf(steps[i].Op, steps[i].Repo, steps[i].Input, r.Answer); ok {
			c.Step = i + 1
			out = append(out, c)
		}
	}
	return out
}

// pendingShape is the answer a request will give, values blanked, for a
// client to be tested before the one real delivery. It is built from the
// op alone (a plan's from its steps' ops), so it says nothing the caller
// did not send; nil when the op mints nothing known.
func pendingShape(s SignOffRequest) map[string]any {
	blank := func(op string) (map[string]any, bool) {
		key, ok := secretKeys[op]
		if !ok {
			return nil, false
		}
		sh := map[string]any{"secret": map[string]string{key: ""}}
		if hasCredential(op) {
			sh["credentials"] = []Credential{{Repos: []string{}, Scopes: []string{}}}
		}
		return sh, true
	}
	if s.Op != planOp {
		sh, ok := blank(s.Op)
		if !ok {
			return nil
		}
		return sh
	}
	var steps []planStep
	if json.Unmarshal([]byte(s.Input), &steps) != nil {
		return nil
	}
	var creds []Credential
	secrets := map[string]map[string]string{}
	for i, st := range steps {
		sh, ok := blank(st.Op)
		if !ok {
			continue
		}
		secrets[fmt.Sprint(i+1)] = sh["secret"].(map[string]string)
		if _, has := sh["credentials"]; has {
			creds = append(creds, Credential{Step: i + 1, Repos: []string{}, Scopes: []string{}})
		}
	}
	if len(secrets) == 0 {
		return nil
	}
	sh := map[string]any{"secret": secrets}
	if len(creds) > 0 {
		sh["credentials"] = creds
	}
	return sh
}

// hasCredential is whether an op's answer carries a token record.
func hasCredential(op string) bool {
	switch op {
	case setupOp, "agent.token.new", "ci.worker.token.new":
		return true
	}
	return false
}

// revokedCredentials is the summaries of a request whose uncollected
// secret lapsed: the tokens were revoked, so the idle and expiry words
// give way to one saying so.
func revokedCredentials(cs []Credential) []Credential {
	for i := range cs {
		cs[i].Idle, cs[i].IdleLapseDays, cs[i].Lapses = false, 0, ""
		cs[i].Note = "This token was revoked because it was not collected in time."
	}
	return cs
}