Skip to content
quarry Artifact [40e8cef8c6]
Login

Artifact [40e8cef8c6]

Artifact 40e8cef8c64ebd3924b9cd2377bf108c42e726c6db33d729ee7f8a6b0f684e1d:


package api

import (
	"errors"
	"strings"
	"testing"

	"craftdesign.group/quarry/internal/lease"
	"craftdesign.group/quarry/internal/ops"
)

// before makes the next lease-guarded write start only after fn has
// run, which is how a writer that got in between a caller's look and its
// write is put there deterministically.
func (f *wikiFixture) before(fn func(lease.Token)) {
	f.repo.Guard = func(run func(lease.Token) error) error {
		f.repo.Guard = nil
		tok := lease.Unguarded("test: a writer that got in first")
		fn(tok)
		return run(tok)
	}
}

func (f *wikiFixture) commit(t *testing.T, tok lease.Token, title, body string) {
	t.Helper()
	if _, err := f.z0.WikiCommit(tok, title, "sam", "text/x-markdown", []byte(body)); err != nil {
		t.Fatal(err)
	}
}

func (f *wikiFixture) history(t *testing.T, name string) int {
	t.Helper()
	h, err := f.r.Invoke(as("pat", "j"), "wiki.history", wikiHistoryIn{Repo: "test", Name: name})
	if err != nil {
		return 0
	}
	return h.(wikiHistoryOut).Count
}

// Fossil's rule for writing a page: an existing page takes k, a new
// title f, and a checkin/, branch/, tag/ or ticket/ page one letter
// more. A rename creates a title, so it takes both unless the title
// belongs to a deleted page, which fossil treats as an edit.
func TestWikiWritesTakeFossilsCapabilities(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Exists", "x\n")
	f.save(t, "Gone", "y\n")
	if _, err := f.r.Invoke(as("pat", "kf"), "wiki.delete", wikiDeleteIn{Repo: "test", Name: "Gone"}); err != nil {
		t.Fatal(err)
	}
	save := func(letters, name string) error {
		_, err := f.r.Invoke(as("sam", letters), "wiki.save", wikiSaveIn{Repo: "test", Name: name, Body: "text " + letters + "\n"})
		return err
	}
	del := func(letters, name string) error {
		_, err := f.r.Invoke(as("sam", letters), "wiki.delete", wikiDeleteIn{Repo: "test", Name: name})
		return err
	}
	rename := func(letters, from, to string) error {
		_, err := f.r.Invoke(as("sam", letters), "wiki.rename", wikiRenameIn{Repo: "test", Name: from, To: to})
		return err
	}
	for _, c := range []struct {
		what string
		err  error
		deny bool
	}{
		{"edit an existing page with only f", save("f", "Exists"), true},
		{"edit an existing page with k", save("k", "Exists"), false},
		{"create a page with only k", save("k", "Fresh"), true},
		{"create a page with f", save("f", "Fresh"), false},
		{"recreate a deleted page with only k", save("k", "Gone"), false},
		{"create branch/x without i", save("kf", "branch/x"), true},
		{"create branch/x with i", save("kfi", "branch/x"), false},
		{"create tag/x without i", save("kf", "tag/x"), true},
		{"create checkin/x without i", save("kf", "checkin/x"), true},
		{"create ticket/x with i but not w", save("kfi", "ticket/x"), true},
		{"create ticket/x with w", save("kfw", "ticket/x"), false},
		{"delete branch/x without i", del("k", "branch/x"), true},
		{"delete branch/x with i", del("ki", "branch/x"), false},
		{"delete ticket/x with only i", del("ki", "ticket/x"), true},
		{"delete with only f", del("f", "Exists"), true},
		{"rename onto a new title with only k", rename("k", "Exists", "Moved"), true},
		{"rename with only f", rename("f", "Exists", "Moved"), true},
		{"rename onto a new title with k and f", rename("kf", "Exists", "Moved"), false},
	} {
		if denied := errors.Is(c.err, ops.ErrForbidden); denied != c.deny || (!c.deny && c.err != nil) {
			t.Errorf("FAIL: %s: %v", c.what, c.err)
		}
	}
	// A title that belongs to a deleted page is an edit: k alone.
	f.save(t, "Moving", "z\n")
	if err := rename("k", "Moving", "Gone"); err == nil {
		t.Errorf("FAIL: renamed onto the live recreated page")
	}
	if _, err := f.r.Invoke(as("pat", "kf"), "wiki.delete", wikiDeleteIn{Repo: "test", Name: "Gone"}); err != nil {
		t.Fatal(err)
	}
	if err := rename("k", "Moving", "Gone"); err != nil {
		t.Errorf("FAIL: k alone renaming onto a deleted title: %v", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestWikiRenameBuildsOnTheHeadItFindsUnderTheLease(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Old", "first\n")
	old := f.get(t, "Old").Hash
	// An edit lands after the caller looked, before the write begins.
	f.before(func(tok lease.Token) { f.commit(t, tok, "Old", "edited meanwhile\n") })
	if _, err := f.r.Invoke(as("pat", "kf"), "wiki.rename", wikiRenameIn{Repo: "test", Name: "Old", To: "New", Expect: old}); !errors.Is(err, ops.ErrInvalid) {
		t.Errorf("FAIL: a rename of a version that is no longer the newest: %v", err)
	}
	for _, title := range f.live(t) {
		if title == "New" {
			t.Errorf("FAIL: a refused rename still wrote the new page")
		}
	}
	if g := f.get(t, "Old"); g.Deleted || g.Source != "edited meanwhile\n" {
		t.Errorf("FAIL: the old page after the refusal: %+v", g)
	}
	// Without a named version the rename carries the text as it is then,
	// so the concurrent edit is not lost.
	f.before(func(tok lease.Token) { f.commit(t, tok, "Old", "edited again\n") })
	if _, err := f.r.Invoke(as("pat", "kf"), "wiki.rename", wikiRenameIn{Repo: "test", Name: "Old", To: "New"}); err != nil {
		t.Fatal(err)
	}
	if g := f.get(t, "New"); g.Source != "edited again\n" {
		t.Errorf("FAIL: the new page carries %q, the edit made meanwhile is lost", g.Source)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestWikiRenameDoesNotOverwriteADestinationCreatedMeanwhile(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Old", "mine\n")
	f.before(func(tok lease.Token) { f.commit(t, tok, "Taken", "theirs\n") })
	if _, err := f.r.Invoke(as("pat", "kf"), "wiki.rename", wikiRenameIn{Repo: "test", Name: "Old", To: "Taken"}); !errors.Is(err, ops.ErrInvalid) {
		t.Errorf("FAIL: renaming onto a page created meanwhile: %v", err)
	}
	if g := f.get(t, "Taken"); g.Source != "theirs\n" || f.history(t, "Taken") != 1 {
		t.Errorf("FAIL: the destination was overwritten: %+v", g)
	}
	if g := f.get(t, "Old"); g.Deleted {
		t.Errorf("FAIL: the old page was ended though nothing moved")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestTwoRenamesOfOnePageLeaveOneLiveCopy(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Old", "text\n")
	// The other rename wins the lease first: new page, then the end.
	f.before(func(tok lease.Token) {
		f.commit(t, tok, "First", "text\n")
		f.commit(t, tok, "Old", "")
	})
	if _, err := f.r.Invoke(as("pat", "kf"), "wiki.rename", wikiRenameIn{Repo: "test", Name: "Old", To: "Second"}); !errors.Is(err, ops.ErrInvalid) {
		t.Errorf("FAIL: the second rename of an ended page: %v", err)
	}
	live := f.live(t)
	if len(live) != 1 || live[0] != "First" {
		t.Errorf("FAIL: live pages are %v, want exactly First", live)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A rename that died between its two writes leaves both titles live with
// the same text; asking again finishes it instead of refusing.
func TestAnInterruptedRenameIsFinishedByAskingAgain(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Old", "text\n")
	tok := lease.Unguarded("test: the first write of a rename that then died")
	if _, err := f.z0.WikiCommit(tok, "New", "pat", "text/x-markdown", []byte("text\n")); err != nil {
		t.Fatal(err)
	}
	if err := f.repo.synced(); err != nil {
		t.Fatal(err)
	}
	out, err := f.r.Invoke(as("pat", "kf"), "wiki.rename", wikiRenameIn{Repo: "test", Name: "Old", To: "New"})
	if err != nil {
		t.Fatalf("FAIL: the retry: %v", err)
	}
	live := f.live(t)
	if len(live) != 1 || live[0] != "New" || f.history(t, "New") != 1 {
		t.Errorf("FAIL: after the retry live=%v, New has %d versions", live, f.history(t, "New"))
	}
	if out.(wikiRenameOut).Hash != f.get(t, "New").Hash {
		t.Errorf("FAIL: the retry reports a different first page than the one that is there")
	}
	// A destination with other text is a clash, not an interrupted rename.
	f.save(t, "Old2", "one\n")
	f.save(t, "Clash", "other\n")
	if _, err := f.r.Invoke(as("pat", "kf"), "wiki.rename", wikiRenameIn{Repo: "test", Name: "Old2", To: "Clash"}); !errors.Is(err, ops.ErrInvalid) {
		t.Errorf("FAIL: renaming onto a page with other text: %v", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestWikiDeleteDoesNotDeleteAnEditItNeverSaw(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Notes", "first\n")
	seen := f.get(t, "Notes").Hash
	f.before(func(tok lease.Token) { f.commit(t, tok, "Notes", "edited meanwhile\n") })
	_, err := f.r.Invoke(as("pat", "kf"), "wiki.delete", wikiDeleteIn{Repo: "test", Name: "Notes", Expect: seen})
	if !errors.Is(err, ops.ErrInvalid) {
		t.Fatalf("FAIL: deleting a version that is no longer the newest: %v", err)
	}
	head := f.get(t, "Notes")
	if head.Deleted || !strings.Contains(err.Error(), head.Hash[:12]) {
		t.Errorf("FAIL: deleted=%v, refusal %q does not carry the new head %.12s", head.Deleted, err, head.Hash)
	}
	// Two deletes racing: the loser is told the page is already gone.
	f.before(func(tok lease.Token) { f.commit(t, tok, "Notes", "") })
	if _, err := f.r.Invoke(as("pat", "kf"), "wiki.delete", wikiDeleteIn{Repo: "test", Name: "Notes"}); !errors.Is(err, ops.ErrInvalid) {
		t.Errorf("FAIL: the second of two deletes: %v", err)
	}
	if f.history(t, "Notes") != 3 {
		t.Errorf("FAIL: history holds %d versions, want 3", f.history(t, "Notes"))
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A redacted head is refused for everyone, a moderator (5) included: the
// new page is a fresh artifact and would publish the withheld text.
func TestAPageWhoseTextIsRedactedCannotBeRenamed(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Secret", "withheld\n")
	f.red[f.get(t, "Secret").Hash] = "legal"
	for _, letters := range []string{"kf", "kf5", "kfa"} {
		if _, err := f.r.Invoke(as("mod", letters), "wiki.rename", wikiRenameIn{Repo: "test", Name: "Secret", To: "Public"}); !errors.Is(err, ops.ErrInvalid) {
			t.Errorf("FAIL: letters %q renamed a redacted page: %v", letters, err)
		}
	}
	if got := f.live(t); len(got) != 1 || got[0] != "Secret" {
		t.Errorf("FAIL: live pages %v after refusals", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}