package web
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"strings"
"sync"
"time"
"craftdesign.group/quarry/internal/ops"
)
// repoKeysPanel holds the repository keys shown on /r/{repo}/settings#keys.
type repoKeysPanel struct {
Live []repoKeyView
Revoked []repoKeyView
}
type repoKeyView struct {
ID string
Login string
Label string
Access string
AccessLabel string
ScopeText string
Created string
Used string
Expires string
Idle bool
Lapses string
Revoked string
Expired bool
}
func (k repoKeyView) LifespanNote() string {
if !k.Idle && k.Expires != "" {
return "expires " + rkDay(k.Expires)
}
if k.Lapses != "" {
return "lapses unused " + rkDay(k.Lapses)
}
return "lapses after 90 days unused"
}
func rkDay(ts string) string {
if len(ts) >= 10 {
return ts[:10]
}
return ts
}
// newRepoKeyView is the once-only reveal panel rendered after minting a
// repository key, collected from mintedRepoKeys via ?rk=<nonce>#keys.
type newRepoKeyView struct {
Login string
Value string
Label string
Access string
AccessLabel string
Command string
}
type repoKeyPayload struct {
user string
repo string
login string
value string
label string
access string
at time.Time
}
type repoKeyVault struct {
mu sync.Mutex
m map[string]repoKeyPayload
}
func newRepoKeyVault() *repoKeyVault {
return &repoKeyVault{m: map[string]repoKeyPayload{}}
}
// mintedRepoKeys holds freshly minted repository key secrets between
// the POST that created them and the GET that shows them once, bound
// to the creating user and repository.
var mintedRepoKeys = newRepoKeyVault()
func (v *repoKeyVault) stash(user, repo string, p repoKeyPayload) string {
if p.value == "" {
return ""
}
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return ""
}
nonce := hex.EncodeToString(b)
p.user, p.repo, p.at = user, repo, time.Now()
v.mu.Lock()
defer v.mu.Unlock()
v.sweepLocked()
v.m[nonce] = p
return nonce
}
func (v *repoKeyVault) take(nonce, user, repo string) (repoKeyPayload, bool) {
if nonce == "" {
return repoKeyPayload{}, false
}
v.mu.Lock()
defer v.mu.Unlock()
v.sweepLocked()
e, ok := v.m[nonce]
if !ok || e.user != user || e.repo != repo || time.Since(e.at) > secretTTL {
return repoKeyPayload{}, false
}
delete(v.m, nonce)
return e, true
}
func (v *repoKeyVault) sweepLocked() {
for k, e := range v.m {
if time.Since(e.at) > secretTTL {
delete(v.m, k)
}
}
}
func repoKeyAccessLabel(access string) string {
switch access {
case "read":
return "Read"
case "push":
return "Push"
case "publish":
return "Publish"
default:
return access
}
}
func repoKeyScopeText(scopes []string) string {
if slices.Contains(scopes, "api") {
return "sync + api"
}
return "sync"
}
func repoKeyCommand(req *http.Request, repo, login, access string) string {
u := shellQuote(origin(req) + hooksOf(req.Context()).repoURL(repo))
l := shellQuote(login)
if access == "read" {
return fmt.Sprintf("ZIT_PASSWORD=\"$KEY\" zit clone --user %s --once %s .", l, u)
}
return fmt.Sprintf("ZIT_PASSWORD=\"$KEY\" zit push --user %s --once %s", l, u)
}
func takeRepoKeySecret(req *http.Request, repo string) *newRepoKeyView {
p, ok := mintedRepoKeys.take(req.URL.Query().Get("rk"), ops.User(req.Context()), repo)
if !ok {
return nil
}
return &newRepoKeyView{
Login: p.login,
Value: p.value,
Label: p.label,
Access: p.access,
AccessLabel: repoKeyAccessLabel(p.access),
Command: repoKeyCommand(req, repo, p.login, p.access),
}
}
func repoKeysFor(r *ops.Registry, req *http.Request, repo string) *repoKeysPanel {
if r == nil {
return nil
}
if _, ok := r.Lookup("repo.key.list"); !ok {
return nil
}
out, err := invoke(req.Context(), r, "repo.key.list", url.Values{"repo": {repo}})
if err != nil {
return nil
}
var resp struct {
Keys []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"`
Idle bool `json:"idle"`
Lapses string `json:"lapses"`
Used string `json:"used"`
Revoked string `json:"revoked"`
} `json:"keys"`
}
remarshal(out, &resp)
now := time.Now().UTC()
panel := &repoKeysPanel{}
for _, k := range resp.Keys {
expired := false
if k.Revoked == "" && k.Lapses != "" {
if exp, err := time.Parse(time.RFC3339, k.Lapses); err == nil && !now.Before(exp) {
expired = true
}
}
v := repoKeyView{
ID: k.ID,
Login: k.Login,
Label: k.Label,
Access: k.Access,
AccessLabel: repoKeyAccessLabel(k.Access),
ScopeText: repoKeyScopeText(k.Scopes),
Created: k.Created,
Used: k.Used,
Expires: k.Expires,
Idle: k.Idle,
Lapses: k.Lapses,
Revoked: k.Revoked,
Expired: expired,
}
if k.Revoked != "" || expired {
panel.Revoked = append(panel.Revoked, v)
} else {
panel.Live = append(panel.Live, v)
}
}
return panel
}
func repoKeyLifespanDays(lifespan string) string {
switch strings.TrimSpace(lifespan) {
case "", "idle":
return "0"
case "30", "90", "365":
return strings.TrimSpace(lifespan)
default:
return strings.TrimSpace(lifespan)
}
}
func handleRepoKeyCreate(r *ops.Registry, w http.ResponseWriter, req *http.Request, repo string) {
days := repoKeyLifespanDays(req.FormValue("lifespan"))
apiScope := "false"
if req.FormValue("api") != "" {
apiScope = "true"
}
form := url.Values{
"repo": {repo},
"label": {strings.TrimSpace(req.FormValue("label"))},
"access": {strings.TrimSpace(req.FormValue("access"))},
"api": {apiScope},
"days": {days},
}
out, err := invoke(req.Context(), r, "repo.key.new", form)
if err != nil {
if errors.Is(err, ops.ErrInvalid) {
q := url.Values{"e": {opsSentence(err)}}
http.Redirect(w, req, "/r/"+repo+"/settings?"+q.Encode()+"#keys", http.StatusSeeOther)
return
}
fail(r, w, req, err)
return
}
var minted struct {
Login string `json:"login"`
Value string `json:"value"`
Key struct {
Label string `json:"label"`
Access string `json:"access"`
} `json:"key"`
}
remarshal(out, &minted)
nonce := mintedRepoKeys.stash(ops.User(req.Context()), repo, repoKeyPayload{
login: minted.Login,
value: minted.Value,
label: minted.Key.Label,
access: minted.Key.Access,
})
if nonce == "" {
http.Redirect(w, req, "/r/"+repo+"/settings#keys", http.StatusSeeOther)
return
}
http.Redirect(w, req, "/r/"+repo+"/settings?rk="+nonce+"#keys", http.StatusSeeOther)
}
func handleRepoKeyRevoke(r *ops.Registry, w http.ResponseWriter, req *http.Request, repo string) {
id := strings.TrimSpace(req.FormValue("id"))
if _, err := invoke(req.Context(), r, "repo.key.revoke", url.Values{"repo": {repo}, "id": {id}}); err != nil {
fail(r, w, req, err)
return
}
http.Redirect(w, req, "/r/"+repo+"/settings?saved=1#keys", http.StatusSeeOther)
}