193 lines
5.9 KiB
Go
193 lines
5.9 KiB
Go
package forgeaccount
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"gitea/internal/forgehttp"
|
|
)
|
|
|
|
type heldKey struct {
|
|
ID int64 `json:"id"`
|
|
Title string `json:"title"`
|
|
Key string `json:"key"`
|
|
}
|
|
|
|
// keyForge is the part of gitea's API the keys use, as the administrator's login reaches it (issue 955 F2).
|
|
type keyForge struct {
|
|
mu sync.Mutex
|
|
keys map[string][]heldKey
|
|
next int64
|
|
calls []string
|
|
posts []map[string]any
|
|
}
|
|
|
|
var keysPath = regexp.MustCompile(`^/api/v1/(?:admin/)?users/([^/]+)/keys(?:/(\d+))?$`)
|
|
|
|
func (f *keyForge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.calls = append(f.calls, r.Method+" "+r.URL.Path)
|
|
m := keysPath.FindStringSubmatch(r.URL.Path)
|
|
if m == nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
user := m[1]
|
|
reply := func(status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
if v != nil {
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|
|
}
|
|
switch {
|
|
case r.Method == http.MethodGet && m[2] == "" && !strings.Contains(r.URL.Path, "/admin/"):
|
|
reply(200, f.keys[user])
|
|
case r.Method == http.MethodPost && m[2] == "" && strings.Contains(r.URL.Path, "/admin/"):
|
|
body, _ := io.ReadAll(r.Body)
|
|
var in map[string]any
|
|
_ = json.Unmarshal(body, &in)
|
|
f.posts = append(f.posts, in)
|
|
key, _ := in["key"].(string)
|
|
for _, k := range f.keys[user] {
|
|
if k.Key == key {
|
|
reply(422, map[string]any{"message": "Key content has been used as non-deploy key"})
|
|
return
|
|
}
|
|
}
|
|
title, _ := in["title"].(string)
|
|
for _, k := range f.keys[user] {
|
|
if k.Title == title {
|
|
reply(422, map[string]any{"message": "Key title has been used"})
|
|
return
|
|
}
|
|
}
|
|
f.next++
|
|
f.keys[user] = append(f.keys[user], heldKey{ID: f.next, Title: title, Key: key})
|
|
reply(201, map[string]any{"id": f.next})
|
|
case r.Method == http.MethodDelete && m[2] != "" && strings.Contains(r.URL.Path, "/admin/"):
|
|
var kept []heldKey
|
|
for _, k := range f.keys[user] {
|
|
if fmt.Sprint(k.ID) != m[2] {
|
|
kept = append(kept, k)
|
|
}
|
|
}
|
|
f.keys[user] = kept
|
|
reply(204, nil)
|
|
default:
|
|
http.Error(w, "unexpected "+r.Method+" "+r.URL.Path, 400)
|
|
}
|
|
}
|
|
|
|
const (
|
|
keyA = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
|
keyB = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
|
|
)
|
|
|
|
func keyAccounts(t *testing.T, f *keyForge) *Accounts {
|
|
t.Helper()
|
|
srv := httptest.NewServer(f)
|
|
t.Cleanup(srv.Close)
|
|
pw := filepath.Join(t.TempDir(), "pw")
|
|
if err := os.WriteFile(pw, []byte("x\n"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return &Accounts{Forge: forgehttp.Client{URL: srv.URL, User: "mesh-admin", PasswordFile: pw}, Log: func(string, ...any) {}}
|
|
}
|
|
|
|
func TestEnsureKeysAddsTheWantedKeyUnderItsTitle(t *testing.T) {
|
|
f := &keyForge{keys: map[string][]heldKey{}}
|
|
a := keyAccounts(t, f)
|
|
if err := a.EnsureKeys(t.Context(), "agent-g14", []WantedKey{{Title: "mesh:g14.nox", Key: keyA + " nox@g14 (mesh)"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(f.posts) != 1 || f.posts[0]["title"] != "mesh:g14.nox" || f.posts[0]["read_only"] != false ||
|
|
f.posts[0]["key"] != keyA+" nox@g14 (mesh)" {
|
|
t.Fatalf("posts = %v", f.posts)
|
|
}
|
|
}
|
|
|
|
func TestEnsureKeysAgainChangesNothing(t *testing.T) {
|
|
f := &keyForge{keys: map[string][]heldKey{}}
|
|
a := keyAccounts(t, f)
|
|
want := []WantedKey{{Title: "mesh:g14.nox", Key: keyA + " nox@g14 (mesh)"}}
|
|
for range 2 {
|
|
if err := a.EnsureKeys(t.Context(), "agent-g14", want); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if len(f.posts) != 1 || len(f.keys["agent-g14"]) != 1 {
|
|
t.Fatalf("posts = %v, held = %v", f.posts, f.keys)
|
|
}
|
|
}
|
|
|
|
func TestEnsureKeysReplacesAChangedMeshKeyOfTheSameTitle(t *testing.T) {
|
|
// The forge refuses a title held twice, so the old key goes first.
|
|
f := &keyForge{keys: map[string][]heldKey{"agent-g14": {{ID: 7, Title: "mesh:g14.nox", Key: keyA}}}, next: 7}
|
|
a := keyAccounts(t, f)
|
|
if err := a.EnsureKeys(t.Context(), "agent-g14", []WantedKey{{Title: "mesh:g14.nox", Key: keyB + " nox@g14 (mesh)"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
held := f.keys["agent-g14"]
|
|
if len(held) != 1 || !strings.HasPrefix(held[0].Key, keyB) {
|
|
t.Fatalf("held = %v", held)
|
|
}
|
|
}
|
|
|
|
func TestEnsureKeysRemovesAMeshKeyOfAnotherTitleAfterTheNewOneIsIn(t *testing.T) {
|
|
f := &keyForge{keys: map[string][]heldKey{"agent-g14": {{ID: 7, Title: "mesh:g14.old", Key: keyA}}}, next: 7}
|
|
a := keyAccounts(t, f)
|
|
if err := a.EnsureKeys(t.Context(), "agent-g14", []WantedKey{{Title: "mesh:g14.nox", Key: keyB}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var post, del int
|
|
for i, c := range f.calls {
|
|
if strings.HasPrefix(c, "POST") {
|
|
post = i
|
|
}
|
|
if strings.HasPrefix(c, "DELETE") {
|
|
del = i
|
|
}
|
|
}
|
|
if post == 0 || del == 0 || post > del || len(f.keys["agent-g14"]) != 1 || f.keys["agent-g14"][0].Title != "mesh:g14.nox" {
|
|
t.Fatalf("calls = %v, held = %v", f.calls, f.keys)
|
|
}
|
|
}
|
|
|
|
func TestEnsureKeysNeverTouchesAKeyTheOperatorAdded(t *testing.T) {
|
|
f := &keyForge{keys: map[string][]heldKey{"agent-g14": {
|
|
{ID: 3, Title: "my laptop", Key: keyB},
|
|
{ID: 7, Title: "mesh:g14.nox", Key: keyA},
|
|
}}, next: 7}
|
|
a := keyAccounts(t, f)
|
|
// Nothing wanted any more: the mesh's key goes, the operator's stays.
|
|
if err := a.EnsureKeys(t.Context(), "agent-g14", nil); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
held := f.keys["agent-g14"]
|
|
if len(held) != 1 || held[0].Title != "my laptop" {
|
|
t.Fatalf("held = %v", held)
|
|
}
|
|
}
|
|
|
|
func TestEnsureKeysLeavesAWantedKeyTheOperatorAlreadyHoldsUnderAnotherTitle(t *testing.T) {
|
|
f := &keyForge{keys: map[string][]heldKey{"agent-g14": {{ID: 3, Title: "by hand", Key: keyA}}}, next: 3}
|
|
a := keyAccounts(t, f)
|
|
if err := a.EnsureKeys(t.Context(), "agent-g14", []WantedKey{{Title: "mesh:g14.nox", Key: keyA + " nox@g14 (mesh)"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(f.posts) != 0 || len(f.keys["agent-g14"]) != 1 || f.keys["agent-g14"][0].Title != "by hand" {
|
|
t.Fatalf("posts = %v, held = %v", f.posts, f.keys)
|
|
}
|
|
}
|