Skip to content
quarry Artifact [b5f7fa9c65]
Login

Artifact [b5f7fa9c65]

Artifact b5f7fa9c656b1257e7f86d25c97d05ab07cf4e61cd1949ede0e6a20768f10dd1:


package main

import (
	"context"
	"net/http"
	"net/http/httptest"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"sync"
	"testing"

	"craftdesign.group/quarry/internal/api"
	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/uv"
	"craftdesign.group/quarry/internal/xfer"
	"craftdesign.group/quarry/internal/zitcli"
)

// memUV is a minimal in-memory xfer.Unversioned backed by the real DB's
// capability checks so stock fossil `sync -u` can be verified end-to-end
// against repository keys.
type memUV struct {
	db    *oltp.DB
	mu    sync.Mutex
	files map[string]uv.File
	body  map[string][]byte
}

func newMemUV(db *oltp.DB) *memUV {
	return &memUV{db: db, files: map[string]uv.File{}, body: map[string][]byte{}}
}

func (u *memUV) UVCatalog(_ context.Context, _ string) ([]uv.File, bool, error) {
	u.mu.Lock()
	defer u.mu.Unlock()
	out := make([]uv.File, 0, len(u.files))
	for _, f := range u.files {
		out = append(out, f)
	}
	return out, true, nil
}

func (u *memUV) UVWritable(_ context.Context, _ string) (int64, error) { return 1 << 20, nil }

func (u *memUV) UVContent(_ context.Context, _ string, f uv.File) ([]byte, error) {
	u.mu.Lock()
	defer u.mu.Unlock()
	return append([]byte(nil), u.body[f.Name]...), nil
}

func (u *memUV) UVWrite(_ context.Context, _ string, f uv.File, content []byte) (uv.File, bool, error) {
	u.mu.Lock()
	defer u.mu.Unlock()
	u.files[f.Name] = f
	u.body[f.Name] = append([]byte(nil), content...)
	return f, true, nil
}

func (u *memUV) UVTouch(_ context.Context, _ string, f uv.File) (uv.File, bool, error) {
	u.mu.Lock()
	defer u.mu.Unlock()
	if cur, ok := u.files[f.Name]; ok {
		cur.Mtime = f.Mtime
		u.files[f.Name] = cur
		return cur, true, nil
	}
	return f, false, nil
}

func (u *memUV) MayPublish(repo, user string) bool {
	return u.db.EffectiveCaps(user, repo).HasAny("y")
}

func (u *memUV) has(name string) ([]byte, bool) {
	u.mu.Lock()
	defer u.mu.Unlock()
	b, ok := u.body[name]
	return b, ok
}

func fossilCmd(t *testing.T, dir string, args ...string) (string, error) {
	t.Helper()
	cmd := exec.Command("fossil", args...)
	cmd.Dir = dir
	cmd.Env = append(os.Environ(), "HOME="+dir, "USER=tester")
	out, err := cmd.CombinedOutput()
	return string(out), err
}

func authURL(base, repo, user, pass string) string {
	return strings.Replace(base+repo, "http://", "http://"+user+":"+pass+"@", 1)
}

// End-to-end sync front verification for repository keys using real zit
// and stock fossil:
//   - read clones private repo and refuses push (zit + fossil)
//   - push pushes unprotected branch (zit + fossil), refuses protected trunk,
//     refuses uv push, refuses another private repo
//   - publish pushes uv (fossil sync -u) and unprotected check-ins
//   - revoke refuses immediately (zit + fossil)
func TestRepoKeySyncFrontZitAndFossil(t *testing.T) {
	if _, err := exec.LookPath("fossil"); err != nil {
		if os.Getenv("CI") == "true" {
			t.Fatalf("fossil not on PATH under CI")
		}
		t.Skip("fossil not on PATH")
	}
	r := newFirstPushRig(t, "sandbox", "wardrobe")
	db := r.rg.odb
	r.commit(t, r.dirs["sandbox"])
	r.commit(t, r.dirs["wardrobe"])

	// Protect trunk on sandbox so push/publish keys can only push unprotected branches.
	if err := db.AddAccount("alice", "pw-alice-12345", true); err != nil {
		t.Fatal(err)
	}
	if err := db.SetProtection("sandbox", "trunk", []string{"alice"}); err != nil {
		t.Fatal(err)
	}
	r.front.SetProtect(db.Refused)
	uvStore := newMemUV(db)
	r.front.SetUnversioned(uvStore)

	readLogin, readVal, _, err := db.MintRepoKey(oltp.RepoKeySpec{Repo: "sandbox", Name: "backup-read", Access: "read"})
	if err != nil {
		t.Fatal(err)
	}
	pushLogin, pushVal, pushTok, err := db.MintRepoKey(oltp.RepoKeySpec{Repo: "sandbox", Name: "mac-push", Access: "push"})
	if err != nil {
		t.Fatal(err)
	}
	pubLogin, pubVal, _, err := db.MintRepoKey(oltp.RepoKeySpec{Repo: "sandbox", Name: "deploy-box", Access: "publish"})
	if err != nil {
		t.Fatal(err)
	}

	// 1. Read key: zit clone succeeds, zit push refused; stock fossil clone succeeds, fossil push refused.
	readZitDir := t.TempDir()
	if out, err := r.zit(t, readZitDir, "clone", "--once", "--user", readLogin, "--password", readVal, r.base+"sandbox", "."); err != nil {
		t.Fatalf("read key zit clone failed: %v\n%s", err, out)
	}
	r.mustZit(t, readZitDir, "branch", "new", "read-try")
	r.commit(t, readZitDir)
	if out, err := r.zit(t, readZitDir, "push", "--once", "--user", readLogin, "--password", readVal, r.base+"sandbox"); err == nil {
		t.Errorf("read key zit push unexpectedly succeeded:\n%s", out)
	}

	readFossilDir := t.TempDir()
	readFossilRepo := filepath.Join(readFossilDir, "sandbox.fossil")
	if out, err := fossilCmd(t, readFossilDir, "clone", "-B", readLogin+":"+readVal, authURL(r.base, "sandbox", readLogin, readVal), readFossilRepo); err != nil {
		t.Fatalf("read key fossil clone failed: %v\n%s", err, out)
	}
	readFossilCO := t.TempDir()
	if out, err := fossilCmd(t, readFossilCO, "open", readFossilRepo, "--nosync"); err != nil {
		t.Fatalf("fossil open: %v\n%s", err, out)
	}
	_, _ = fossilCmd(t, readFossilCO, "settings", "autosync", "off")
	if err := os.WriteFile(filepath.Join(readFossilCO, "r.txt"), []byte("read\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	_, _ = fossilCmd(t, readFossilCO, "add", "r.txt")
	if out, err := fossilCmd(t, readFossilCO, "commit", "--branch", "fossil-read-try", "-m", "read-try", "--no-warnings"); err != nil {
		t.Fatalf("fossil commit: %v\n%s", err, out)
	}
	beforeCheckins := r.checkins(t, r.dirs["sandbox"])
	_, _ = fossilCmd(t, readFossilCO, "push", authURL(r.base, "sandbox", readLogin, readVal), "--once")
	if got := r.checkins(t, r.dirs["sandbox"]); got != beforeCheckins {
		t.Errorf("read key fossil push landed check-in: got %d, want %d", got, beforeCheckins)
	}

	// 2. Push key: refuses another private repo (wardrobe).
	if out, err := r.zit(t, t.TempDir(), "clone", "--once", "--user", pushLogin, "--password", pushVal, r.base+"wardrobe", "."); err == nil {
		t.Errorf("push key cloned another repo wardrobe:\n%s", out)
	}

	// Push key: refuses protected trunk, allows unprotected branch via zit.
	pushZitDir := t.TempDir()
	if out, err := r.zit(t, pushZitDir, "clone", "--once", "--user", pushLogin, "--password", pushVal, r.base+"sandbox", "."); err != nil {
		t.Fatalf("push key zit clone failed: %v\n%s", err, out)
	}
	r.commit(t, pushZitDir)
	if out, err := r.zit(t, pushZitDir, "push", "--once", "--user", pushLogin, "--password", pushVal, r.base+"sandbox"); err == nil {
		t.Errorf("push key pushed to protected trunk:\n%s", out)
	}

	pushBranchDir := t.TempDir()
	if out, err := r.zit(t, pushBranchDir, "clone", "--once", "--user", pushLogin, "--password", pushVal, r.base+"sandbox", "."); err != nil {
		t.Fatalf("push key zit clone (branch) failed: %v\n%s", err, out)
	}
	r.mustZit(t, pushBranchDir, "branch", "new", "work")
	r.commit(t, pushBranchDir)
	beforeWork := r.checkins(t, r.dirs["sandbox"])
	if out, err := r.zit(t, pushBranchDir, "push", "--once", "--user", pushLogin, "--password", pushVal, r.base+"sandbox"); err != nil {
		t.Fatalf("push key zit push to unprotected branch failed: %v\n%s", err, out)
	}
	if got := r.checkins(t, r.dirs["sandbox"]); got <= beforeWork {
		t.Errorf("push key zit push did not land on sandbox: %d <= %d", got, beforeWork)
	}

	// Push key: allows unprotected branch via stock fossil, refuses UV push.
	pushFossilDir := t.TempDir()
	pushFossilRepo := filepath.Join(pushFossilDir, "sandbox.fossil")
	if out, err := fossilCmd(t, pushFossilDir, "clone", "-B", pushLogin+":"+pushVal, authURL(r.base, "sandbox", pushLogin, pushVal), pushFossilRepo); err != nil {
		t.Fatalf("push key fossil clone failed: %v\n%s", err, out)
	}
	pushFossilCO := t.TempDir()
	if out, err := fossilCmd(t, pushFossilCO, "open", pushFossilRepo, "--nosync"); err != nil {
		t.Fatalf("fossil open: %v\n%s", err, out)
	}
	_, _ = fossilCmd(t, pushFossilCO, "settings", "autosync", "off")
	if err := os.WriteFile(filepath.Join(pushFossilCO, "f.txt"), []byte("from-fossil\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	_, _ = fossilCmd(t, pushFossilCO, "add", "f.txt")
	if out, err := fossilCmd(t, pushFossilCO, "commit", "--branch", "fossil-work", "-m", "fossil work", "--no-warnings"); err != nil {
		t.Fatalf("fossil commit: %v\n%s", err, out)
	}
	beforeFossil := r.checkins(t, r.dirs["sandbox"])
	if out, err := fossilCmd(t, pushFossilCO, "push", authURL(r.base, "sandbox", pushLogin, pushVal), "--once"); err != nil {
		t.Fatalf("push key fossil push failed: %v\n%s", err, out)
	}
	if got := r.checkins(t, r.dirs["sandbox"]); got <= beforeFossil {
		t.Errorf("push key fossil push did not land on sandbox: %d <= %d", got, beforeFossil)
	}

	uvFile := filepath.Join(pushFossilDir, "artifact.txt")
	if err := os.WriteFile(uvFile, []byte("release-bytes\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	if out, err := fossilCmd(t, pushFossilDir, "uv", "add", uvFile, "--as", "artifact.txt", "-R", pushFossilRepo); err != nil {
		t.Fatalf("fossil uv add: %v\n%s", err, out)
	}
	_, _ = fossilCmd(t, pushFossilDir, "sync", "-u", authURL(r.base, "sandbox", pushLogin, pushVal), "-R", pushFossilRepo)
	if _, ok := uvStore.has("artifact.txt"); ok {
		t.Error("push key (without y) published an unversioned file")
	}

	// 3. Publish key: publishes unversioned file via stock fossil sync -u.
	if out, err := fossilCmd(t, pushFossilDir, "sync", "-u", authURL(r.base, "sandbox", pubLogin, pubVal), "-R", pushFossilRepo); err != nil {
		t.Fatalf("publish key fossil sync -u failed: %v\n%s", err, out)
	}
	if body, ok := uvStore.has("artifact.txt"); !ok || string(body) != "release-bytes\n" {
		t.Fatalf("publish key uv push missing or wrong bytes: ok=%v body=%q", ok, string(body))
	}

	// 4. Revoke refuses immediately for both zit and stock fossil.
	if err := db.RevokeRepoKey("sandbox", pushTok.ID); err != nil {
		t.Fatal(err)
	}
	if out, err := r.zit(t, t.TempDir(), "clone", "--once", "--user", pushLogin, "--password", pushVal, r.base+"sandbox", "."); err == nil {
		t.Errorf("revoked key still cloned with zit:\n%s", out)
	}
	if out, err := fossilCmd(t, t.TempDir(), "clone", "-B", pushLogin+":"+pushVal, authURL(r.base, "sandbox", pushLogin, pushVal), filepath.Join(t.TempDir(), "rev.fossil")); err == nil {
		t.Errorf("revoked key still cloned with fossil:\n%s", out)
	}

	// Verify xfer.Auth contract directly: Secrets returns nil after revoke.
	if creds := xfer.Auth(db).Secrets("sandbox", pushLogin); len(creds) != 0 {
		t.Errorf("revoked key still returned %d sync secrets", len(creds))
	}
}

func TestRepoKeyAPIDoorBasicAndBearer(t *testing.T) {
	g := newDoorRig(t)
	db := g.rg.odb
	db.SyncProjectCode = func(repo string) (string, bool) { return "CODE-" + repo, true }

	apiLogin, apiVal, apiTok, err := db.MintRepoKey(oltp.RepoKeySpec{Repo: "vault", Name: "api-push", Access: "push", API: true})
	if err != nil {
		t.Fatal(err)
	}
	syncOnlyLogin, syncOnlyVal, _, err := db.MintRepoKey(oltp.RepoKeySpec{Repo: "vault", Name: "sync-only", Access: "push", API: false})
	if err != nil {
		t.Fatal(err)
	}
	readLogin, readVal, _, err := db.MintRepoKey(oltp.RepoKeySpec{Repo: "vault", Name: "api-read", Access: "read", API: true})
	if err != nil {
		t.Fatal(err)
	}

	// Basic auth on its own repo succeeds for push+api, 403 for read+api (door-test needs i), refused on other repo.
	if code := g.callAPI("vault", apiLogin, apiVal); code != http.StatusOK {
		t.Errorf("push+api key Basic on vault = %d; want 200", code)
	}
	if code := g.callAPI("vault", readLogin, readVal); code != http.StatusForbidden {
		t.Errorf("read+api key Basic on vault = %d; want 403", code)
	}
	if code := g.callAPI("other", apiLogin, apiVal); code == http.StatusOK {
		t.Errorf("push+api key reached other repo: %d", code)
	}

	// Bearer token auth resolves via TokenAccount and works identically.
	req := httptest.NewRequest(http.MethodPost, "/api/v1/r/vault/door-test", nil)
	req.Header.Set("Authorization", "Bearer "+apiVal)
	w := httptest.NewRecorder()
	g.api.ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Errorf("push+api key Bearer on vault = %d body=%s; want 200", w.Code, w.Body.String())
	}

	// Sync-only key is refused at the API door.
	if code := g.callAPI("vault", syncOnlyLogin, syncOnlyVal); code == http.StatusOK {
		t.Errorf("sync-only key accepted at API door: %d", code)
	}

	// Revoked key is refused immediately.
	if err := db.RevokeRepoKey("vault", apiTok.ID); err != nil {
		t.Fatal(err)
	}
	if code := g.callAPI("vault", apiLogin, apiVal); code != http.StatusUnauthorized {
		t.Errorf("revoked key at API door = %d; want 401", code)
	}
}

// A sync-only (api: false) read repository key on a private repository
// fetches archives through both /api/v1/r/{repo}/archive/{version} and
// /r/{repo}/archive/{version}, while remaining refused on other API
// endpoints and on another private repository's archive.
func TestRepoKeySyncOnlyArchiveDownload(t *testing.T) {
	dir, trunk, _ := archiveStore(t)
	g := newSiteRigWith(t, func(name string, r *api.Repo) {
		if name == "granted" || name == "secret" {
			r.Zit = zitcli.New(dir)
		}
	})
	g.db.SyncProjectCode = func(repo string) (string, bool) { return "CODE-" + repo, true }

	login, val, _, err := g.db.MintRepoKey(oltp.RepoKeySpec{
		Repo: "granted", Name: "archive-reader", Access: "read", API: false,
	})
	if err != nil {
		t.Fatal(err)
	}

	// Sync-only read key succeeds on both API and web archive endpoints (Basic).
	for _, path := range []string{
		"/api/v1/r/granted/archive/" + trunk,
		"/r/granted/archive/" + trunk,
	} {
		if code, body := g.doAs(login, http.MethodGet, path, val, "", nil); code != http.StatusOK {
			t.Errorf("GET %s with Basic repo key = %d; want 200: %.120s", path, code, body)
		}
	}

	// Bearer auth also works on the API archive endpoint.
	req := httptest.NewRequest(http.MethodGet, "/api/v1/r/granted/archive/"+trunk, nil)
	req.Header.Set("Authorization", "Bearer "+val)
	w := httptest.NewRecorder()
	g.h.ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Errorf("GET /api/v1/r/granted/archive/%s with Bearer repo key = %d; want 200: %.120s", trunk, w.Code, w.Body.String())
	}

	// Refused on non-archive API endpoints on the same repository (sync-only).
	if code, body := g.doAs(login, http.MethodGet, "/api/v1/r/granted/tickets", val, "", nil); code != http.StatusUnauthorized || !strings.Contains(body, `"wrong_scope"`) {
		t.Errorf("GET /api/v1/r/granted/tickets with sync-only repo key = %d; want 401 wrong_scope: %.120s", code, body)
	}

	// Refused on another private repository's archive.
	for _, path := range []string{
		"/api/v1/r/secret/archive/" + trunk,
		"/r/secret/archive/" + trunk,
	} {
		if code, _ := g.doAs(login, http.MethodGet, path, val, "", nil); code == http.StatusOK {
			t.Errorf("GET %s with granted's repo key unexpectedly returned 200", path)
		}
	}
}