package api
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"time"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
// RepoKeyStore is the optional half of the account seam behind
// repository keys: per-repository machine credentials with no account
// behind them. *oltp.DB satisfies it.
type RepoKeyStore interface {
MintRepoKey(spec oltp.RepoKeySpec) (login, value string, tok oltp.Token, err error)
RepoKeys(repo string) ([]oltp.Token, error)
RevokeRepoKey(repo, id string) error
}
var _ RepoKeyStore = (*oltp.DB)(nil)
func (d Deps) repoKeyStore() (RepoKeyStore, error) {
if d.Accounts == nil {
return nil, errNoAccounts()
}
ks, ok := d.Accounts.(RepoKeyStore)
if !ok {
return nil, fmt.Errorf("this forge's account store has no repository keys: %w", ops.ErrUnavailable)
}
return ks, nil
}
type repoKeyRow struct {
ID string `json:"id"`
Login string `json:"login"`
Label string `json:"label"`
Access string `json:"access"`
Scopes []string `json:"scopes"`
Created string `json:"created"`
Expires string `json:"expires,omitempty"`
Idle bool `json:"idle"`
Lapses string `json:"lapses,omitempty"`
Used string `json:"used,omitempty"`
Revoked string `json:"revoked,omitempty"`
}
func repoKeyRowOf(t oltp.Token) repoKeyRow {
row := repoKeyRow{
ID: t.ID,
Login: "key-" + t.ID,
Label: t.Name,
Access: oltp.RepoKeyAccess(t.Ceiling),
Scopes: orEmpty(t.Scopes),
Created: t.Created,
Expires: t.Expires,
Idle: t.Idle(),
Used: t.LastUsed,
Revoked: t.Revoked,
}
if exp, ok := t.Lapses(); ok {
row.Lapses = exp.UTC().Format(time.RFC3339)
}
return row
}
type repoKeyNewIn struct {
Repo string `json:"repo" validate:"required,max=64"`
Label string `json:"label" validate:"required,max=64"`
Access string `json:"access" validate:"required,oneof=read|push|publish"`
API bool `json:"api,omitempty"`
Days int `json:"days,omitempty" validate:"min=0,max=365"`
}
type repoKeyNewOut struct {
Login string `json:"login"`
Value string `json:"value" secret:"once"`
Key repoKeyRow `json:"key"`
}
type repoKeyListIn struct {
Repo string `json:"repo" validate:"required,max=64"`
}
type repoKeyListOut struct {
Keys []repoKeyRow `json:"keys"`
}
type repoKeyRevokeIn struct {
Repo string `json:"repo" validate:"required,max=64"`
ID string `json:"id" validate:"required,max=64"`
}
func (d Deps) repoKeyList(ks RepoKeyStore, repo string) (repoKeyListOut, error) {
keys, err := ks.RepoKeys(repo)
if err != nil {
return repoKeyListOut{}, err
}
out := repoKeyListOut{Keys: make([]repoKeyRow, 0, len(keys))}
for _, k := range keys {
out.Keys = append(out.Keys, repoKeyRowOf(k))
}
return out, nil
}
func registerRepoKeys(r *ops.Registry, d Deps) error {
if err := ops.Register(r, ops.Op[repoKeyNewIn, repoKeyNewOut]{
Name: "repo.key.new",
Ask: "Mint a repository key for {repo}",
Caps: "a",
Doc: "Mint a repository key for one repository: a scoped machine credential with no account behind it, " +
"whose login is `key-<id>` and whose value is `qkt_<id>_<secret>`. `access` is `read` (`goz`), " +
"`push` (`gozi`, unprotected branches only), or `publish` (`goziy`, adding unversioned files); " +
"repository keys never hold `a` or `s`. Set `api` to also open the API door on this repository. " +
"`days` sets a fixed expiry (1–365); 0 lapses after 90 days unused. The value is returned once and " +
"cannot be read back. An agent does not mint one directly and may ask with `Quarry-Ask` and `Quarry-Pickup`.",
Kind: ops.Command,
Auth: ops.Token,
Route: "POST /api/v1/r/{repo}/keys",
Run: func(ctx context.Context, in repoKeyNewIn) (repoKeyNewOut, error) {
ks, err := d.repoKeyStore()
if err != nil {
return repoKeyNewOut{}, err
}
if who := ops.User(ctx); who != "" {
if op := d.operatorOf(who); op != "" {
return repoKeyNewOut{}, fmt.Errorf("%s is an agent, operated by %s, and an agent does not mint a repository key; ask %s: %w",
who, op, op, ops.ErrForbidden)
}
}
if _, err := d.repoFor(ctx, in.Repo); err != nil {
return repoKeyNewOut{}, err
}
if err := d.refuseWithout(ctx, in.Repo, "a", false); err != nil {
return repoKeyNewOut{}, err
}
spec := oltp.RepoKeySpec{
Repo: in.Repo,
Name: in.Label,
Access: in.Access,
API: in.API,
}
if in.Days > 0 {
spec.Expires = time.Now().Add(time.Duration(in.Days) * 24 * time.Hour)
}
login, value, tok, err := ks.MintRepoKey(spec)
if err != nil {
return repoKeyNewOut{}, refusalAsInvalid(err)
}
d.logRepoKey(in.Repo, ctx, "", fmt.Sprintf("minted %q (%s, %s)", tok.Name, login, in.Access))
return repoKeyNewOut{Login: login, Value: value, Key: repoKeyRowOf(tok)}, nil
},
}); err != nil {
return err
}
if err := ops.Register(r, ops.Op[repoKeyListIn, repoKeyListOut]{
Name: "repo.key.list",
Caps: "a",
Doc: "List this repository's keys: id, login, label, access level, scopes, dates, last used and revocation — never a value.",
Kind: ops.Query,
Auth: ops.Token,
Route: "GET /api/v1/r/{repo}/keys",
Run: func(ctx context.Context, in repoKeyListIn) (repoKeyListOut, error) {
ks, err := d.repoKeyStore()
if err != nil {
return repoKeyListOut{}, err
}
if _, err := d.repoFor(ctx, in.Repo); err != nil {
return repoKeyListOut{}, err
}
if err := d.refuseWithout(ctx, in.Repo, "a", false); err != nil {
return repoKeyListOut{}, err
}
return d.repoKeyList(ks, in.Repo)
},
}); err != nil {
return err
}
return ops.Register(r, ops.Op[repoKeyRevokeIn, repoKeyListOut]{
Name: "repo.key.revoke",
Caps: "a",
Doc: "Revoke one repository key by its id, at once, returning the list that remains. " +
"Only a key belonging to this repository can be revoked here; another repository's id is not found. " +
"Revoking an already-revoked key returns the list without error.",
Kind: ops.Command,
Auth: ops.Token,
Route: "POST /api/v1/r/{repo}/keys/revoke",
Run: func(ctx context.Context, in repoKeyRevokeIn) (repoKeyListOut, error) {
ks, err := d.repoKeyStore()
if err != nil {
return repoKeyListOut{}, err
}
if _, err := d.repoFor(ctx, in.Repo); err != nil {
return repoKeyListOut{}, err
}
if err := d.refuseWithout(ctx, in.Repo, "a", false); err != nil {
return repoKeyListOut{}, err
}
keys, err := ks.RepoKeys(in.Repo)
if err != nil {
return repoKeyListOut{}, err
}
var found *oltp.Token
for i := range keys {
if keys[i].ID == in.ID {
found = &keys[i]
break
}
}
if found == nil {
return repoKeyListOut{}, fmt.Errorf("no repository key %q on %s: %w", in.ID, in.Repo, ops.ErrNotFound)
}
if found.Revoked == "" {
err := ks.RevokeRepoKey(in.Repo, in.ID)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return repoKeyListOut{}, err
}
if err == nil {
d.logRepoKey(in.Repo, ctx, fmt.Sprintf("%q (key-%s)", found.Name, found.ID), "revoked")
}
}
return d.repoKeyList(ks, in.Repo)
},
})
}
func (d Deps) logRepoKey(repo string, ctx context.Context, 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), "repo-key", was, now); err != nil {
log.Printf("settings log: repo key on %s: %v", repo, err)
}
}