Skip to content
quarry Artifact [5da882683c]
Login

Artifact [5da882683c]

Artifact 5da882683cc2c9374c3bd3ab71c531f9d0cbb38d75ee8512e3d5dbae0fdc4cd0:


package api

import (
	"encoding/json"
	"time"

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

// MintView is the limits of a token a request will mint, or did: the
// same facts a setup request's page draws for its credential, so a plan
// step or a replacement is read as closely as a setup is.
type MintView struct {
	Agent  string   `json:"agent"`
	Scopes []string `json:"scopes"`
	// Repos is where the token reaches; empty is every repository the
	// agent reaches.
	Repos []string `json:"repos"`
	// Ceiling is the letters the token is cut to; empty is the agent's own.
	Ceiling string `json:"ceiling"`
	// Days is the fixed life in days, 0 for none.
	Days int `json:"days"`
	// Replaces are the live tokens approving ends, told to the person
	// asked only.
	Replaces []MintRevoked `json:"replaces,omitempty"`
}

// MintRevoked names a token a replacement ends, never its value.
type MintRevoked struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

// mintViewOf is what an op that mints a token will mint, nil for any
// other op. answer is what the approved call answered, nil while it
// waits; who is the reader.
func (d Deps) mintViewOf(op string, input, answer json.RawMessage, owner, who string) *MintView {
	switch op {
	case "agent.token.new":
		var in agentTokenNewIn
		if json.Unmarshal(input, &in) != nil {
			return nil
		}
		return &MintView{Agent: in.Agent, Scopes: orEmpty(splitList(in.Scopes)), Repos: orEmpty(splitList(in.Repos)),
			Ceiling: in.Ceiling, Days: in.Days}
	case "agent.token.reissue":
		var in agentNameIn
		if json.Unmarshal(input, &in) != nil {
			return nil
		}
		if len(answer) > 0 {
			var out agentTokenReissueOut
			if json.Unmarshal(answer, &out) != nil || out.Token == nil {
				return nil
			}
			return &MintView{Agent: in.Name, Scopes: orEmpty(out.Token.Scopes), Repos: orEmpty(out.Token.Repos), Ceiling: out.Token.Ceiling}
		}
		as, err := d.agents()
		if err != nil {
			return nil
		}
		toks, err := as.Tokens(in.Name)
		if err != nil {
			return nil
		}
		// The replacement is cut like the most recently used live token
		// (oltp.ReissueTokens); every live one is ended.
		now := time.Now()
		var like *oltp.Token
		var ends []MintRevoked
		for i, t := range toks {
			if !t.Live(now) {
				continue
			}
			if who == owner {
				ends = append(ends, MintRevoked{ID: t.ID, Name: t.Name})
			}
			if like == nil || t.LastUsed > like.LastUsed || (t.LastUsed == like.LastUsed && t.Created > like.Created) {
				like = &toks[i]
			}
		}
		if like == nil {
			return nil
		}
		return &MintView{Agent: in.Name, Scopes: orEmpty(like.Scopes), Repos: orEmpty(like.Repos), Ceiling: like.Ceiling, Replaces: ends}
	}
	return nil
}