package api
import (
"context"
"fmt"
"strings"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
// reissueInOf reads an asked input, a value or a pointer, as the replacement's.
func reissueInOf(in any) agentReissueIn {
switch v := in.(type) {
case agentReissueIn:
return v
case *agentReissueIn:
return *v
}
return agentReissueIn{}
}
// planReissue fixes, when a replacement is asked for, what approval will
// do: the token copied, its limits and the tokens that end, each as of
// now. The page shows this and approval carries out exactly it. The
// agent must be the asker's person's own (checked by the preflight);
// asking about oneself needs a pickup code, since approving revokes the
// very token the answer would be read with; and a token asks only for
// what it holds itself.
func (d Deps) planReissue(ctx context.Context, person, pickup string, in any) (agentReissueIn, error) {
ri := reissueInOf(in)
as, err := d.agents()
if err != nil {
return ri, err
}
caller := ops.User(ctx)
if ri.Name == caller && pickup == "" {
return ri, fmt.Errorf("replacing your own token revokes the one you are asking with, and you could not collect the new one: add Quarry-Pickup (the hex SHA-256 of a key you keep) and collect it with POST /api/v1/pickups/collect: %w", ops.ErrInvalid)
}
plan, ok, err := as.PlanReissue(ri.Name)
if err != nil {
return ri, err
}
if !ok {
return ri, fmt.Errorf("%s holds no live token to copy; ask for a new token (agent.token.new) instead: %w", ri.Name, ops.ErrInvalid)
}
if tok, byToken := ops.TokenOf(ctx); byToken {
toks, err := as.Tokens(caller)
if err != nil {
return ri, err
}
found := false
for _, t := range toks {
if t.ID == tok.ID {
found = true
if err := withinToken(t, plan); err != nil {
return ri, err
}
}
}
if !found && tok.Limited {
return ri, fmt.Errorf("a token limited to repositories asks only within its own limits, and this one cannot be read: %w", ops.ErrForbidden)
}
}
ri.Plan = &plan
return ri, nil
}
// withinToken is nil when what a replacement would mint is no wider than
// the asking token: scopes, repositories and ceiling letters all inside.
func withinToken(asker oltp.Token, plan oltp.ReissuePlan) error {
wider := fmt.Errorf("the replacement would hold more than the token you ask with (scopes, repositories or ceiling); ask with a token that holds at least that: %w", ops.ErrForbidden)
for _, sc := range plan.Scopes {
if !asker.Has(sc) {
return wider
}
}
if len(asker.Repos) > 0 {
if len(plan.Repos) == 0 {
return wider
}
for _, r := range plan.Repos {
ok := false
for _, a := range asker.Repos {
ok = ok || a == r
}
if !ok {
return wider
}
}
}
if asker.Ceiling != "" {
if plan.Ceiling == "" {
return wider
}
for _, c := range plan.Ceiling {
if !strings.ContainsRune(asker.Ceiling, c) {
return wider
}
}
}
return nil
}