Skip to content
quarry Artifact [60ed64fe40]
Login

Artifact [60ed64fe40]

Artifact 60ed64fe408bf0fb3085e72cff25361761dc0eb1e99e44765952e3172c0f607f:


package api

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"

	"craftdesign.group/quarry/internal/artifact"
	"craftdesign.group/quarry/internal/index"
	"craftdesign.group/quarry/internal/lease"
	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
	"craftdesign.group/quarry/internal/zitcli"
)

type wikiFixture struct {
	dir  string
	repo *Repo
	red  memRedactions
	z0   *zitcli.Client
	r    *ops.Registry
	ix   *index.Index
	z    interface {
		ArtifactRaw(context.Context, string, int) ([]byte, error)
	}
}

func newWikiFixture(t *testing.T) *wikiFixture {
	t.Helper()
	if _, err := exec.LookPath("zit"); err != nil {
		t.Skip("zit not on PATH")
	}
	dir := t.TempDir()
	if err := zitcli.Init(context.Background(), dir); err != nil {
		t.Fatal(err)
	}
	z := zitcli.New(dir)
	ix, err := index.Open(filepath.Join(t.TempDir(), "index.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { ix.Close() })
	db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { db.Close() })
	repo := &Repo{Index: ix, Zit: z, Sync: zitSync(z, ix)}
	red := memRedactions{}
	d := Deps{Version: "v", Repos: NewRepos(map[string]*Repo{"test": repo}),
		Removals: memRemovals{}, Forum: db, Redactions: red}
	r := ops.NewRegistry()
	if err := RegisterAll(r, d); err != nil {
		t.Fatal(err)
	}
	return &wikiFixture{dir: dir, repo: repo, red: red, z0: z, r: r, ix: ix, z: z}
}

func (f *wikiFixture) save(t *testing.T, name, body string) {
	t.Helper()
	if _, err := f.r.Invoke(as("pat", "kfiw"), "wiki.save", wikiSaveIn{Repo: "test", Name: name, Body: body}); err != nil {
		t.Fatalf("wiki.save %s: %v", name, err)
	}
}

func (f *wikiFixture) get(t *testing.T, name string) wikiGetOut {
	t.Helper()
	out, err := f.r.Invoke(as("pat", "j"), "wiki.get", wikiGetIn{Repo: "test", Name: name})
	if err != nil {
		t.Fatalf("wiki.get %s: %v", name, err)
	}
	return out.(wikiGetOut)
}

func (f *wikiFixture) live(t *testing.T) []string {
	t.Helper()
	out, err := f.r.Invoke(as("pat", "j"), "wiki.list", wikiListIn{Repo: "test"})
	if err != nil {
		t.Fatal(err)
	}
	var titles []string
	for _, p := range out.(wikiListOut).Pages {
		titles = append(titles, p.Title)
	}
	return titles
}

// call goes through the router, the one place a letter is checked, as
// an account holding exactly those letters.
func (f *wikiFixture) call(t *testing.T, letters, route string, body any) int {
	t.Helper()
	h, err := RouterWithCaps(f.r, "test", func(_, _ string) CapSet { return oltp.CapSet(letters) }, nil)
	if err != nil {
		t.Fatal(err)
	}
	raw, _ := json.Marshal(body)
	req := httptest.NewRequest("POST", route, bytes.NewReader(raw))
	req.Header.Set("Content-Type", "application/json")
	req = req.WithContext(ops.WithUser(req.Context(), "sam"))
	w := httptest.NewRecorder()
	h.ServeHTTP(w, req)
	return w.Code
}

func (f *wikiFixture) artifact(t *testing.T, hash string) *artifact.Artifact {
	t.Helper()
	raw, err := f.z.ArtifactRaw(context.Background(), hash, 1<<20)
	if err != nil {
		t.Fatal(err)
	}
	a, err := artifact.Parse(raw)
	if err != nil || a == nil {
		t.Fatalf("parse %.12s: %v", hash, err)
	}
	return a
}

func TestWikiDeleteWritesAnEmptyEditAndKeepsHistory(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Notes", "one\n")
	f.save(t, "Other", "two\n")
	out, err := f.r.Invoke(as("pat", "kf"), "wiki.delete", wikiDeleteIn{Repo: "test", Name: "Notes"})
	if err != nil {
		t.Fatal(err)
	}
	a := f.artifact(t, out.(wikiDeleteOut).Hash)
	if a.Type != artifact.Wiki || a.WikiTitle != "Notes" || len(a.Body) != 0 || a.User != "pat" {
		t.Errorf("FAIL: the deletion is %+v, want an empty wiki edit of Notes by pat", a)
	}
	if got := f.live(t); len(got) != 1 || got[0] != "Other" {
		t.Errorf("FAIL: the list holds %v after the delete", got)
	}
	g := f.get(t, "Notes")
	if !g.Deleted || g.User != "pat" || g.Date == "" {
		t.Errorf("FAIL: the page route answers %+v", g)
	}
	h, err := f.r.Invoke(as("pat", "j"), "wiki.history", wikiHistoryIn{Repo: "test", Name: "Notes"})
	if err != nil || h.(wikiHistoryOut).Count != 2 {
		t.Errorf("FAIL: history after the delete: %+v %v", h, err)
	}
	// Editing it again restores it.
	f.save(t, "Notes", "back\n")
	if g := f.get(t, "Notes"); g.Deleted || g.Source != "back\n" {
		t.Errorf("FAIL: after an edit the page is %+v", g)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestWikiDeleteRefusals(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Notes", "one\n")
	del := func(ctx context.Context, name string) error {
		_, err := f.r.Invoke(ctx, "wiki.delete", wikiDeleteIn{Repo: "test", Name: name})
		return err
	}
	if err := del(as("pat", "kf"), "Never"); !errors.Is(err, ops.ErrNotFound) {
		t.Errorf("FAIL: a page that does not exist: %v", err)
	}
	// Writing existing pages is k. Reading, appending, moderating and
	// creating new pages are not.
	for _, letters := range []string{"j", "m", "l", "f", "o", "n"} {
		if code := f.call(t, letters, "/api/v1/r/test/wiki/Notes/delete", map[string]string{}); code != http.StatusForbidden {
			t.Errorf("FAIL: letters %q delete a page: %d", letters, code)
		}
	}
	if code := f.call(t, "k", "/api/v1/r/test/wiki/Notes/delete", map[string]string{}); code != http.StatusOK {
		t.Errorf("FAIL: letter k is refused deleting a page: %d", code)
	}
	f.save(t, "Notes", "one again\n")
	if err := del(as("pat", "kf"), "Notes"); err != nil {
		t.Fatal(err)
	}
	if err := del(as("pat", "kf"), "Notes"); !errors.Is(err, ops.ErrInvalid) {
		t.Errorf("FAIL: a page already deleted: %v", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestWikiRenameMovesThePage(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Old", "the text\n")
	out, err := f.r.Invoke(as("pat", "kf"), "wiki.rename", wikiRenameIn{Repo: "test", Name: "Old", To: "New name"})
	if err != nil {
		t.Fatal(err)
	}
	ro := out.(wikiRenameOut)
	first, ended := f.artifact(t, ro.Hash), f.artifact(t, ro.Ended)
	if first.WikiTitle != "New name" || string(first.Body) != "the text\n" || first.User != "pat" {
		t.Errorf("FAIL: the new page is %+v", first)
	}
	if ended.WikiTitle != "Old" || len(ended.Body) != 0 {
		t.Errorf("FAIL: the old page was ended by %+v", ended)
	}
	if got := f.live(t); len(got) != 1 || got[0] != "New name" {
		t.Errorf("FAIL: the list holds %v", got)
	}
	if g := f.get(t, "New name"); g.Deleted || g.Source != "the text\n" || g.Mimetype != "text/x-markdown" {
		t.Errorf("FAIL: the new page reads %+v", g)
	}
	if g := f.get(t, "Old"); !g.Deleted {
		t.Errorf("FAIL: the old title answers %+v, want deleted", g)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestWikiRenameRefusals(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Old", "the text\n")
	f.save(t, "Taken", "mine\n")
	f.save(t, "branch/work", "design\n")
	f.save(t, "Pics", "pictures\n")
	f.save(t, "Ended", "x\n")
	if _, err := f.r.Invoke(as("pat", "kf"), "wiki.delete", wikiDeleteIn{Repo: "test", Name: "Ended"}); err != nil {
		t.Fatal(err)
	}
	if err := f.ix.FoldNow([]index.Parsed{{Hash: "att1", Art: &artifact.Artifact{
		Type: artifact.Attachment, Date: "2030-01-01T00:00:00", User: "pat", Mimetype: "image/png",
		Attachment: &artifact.Attach{Name: "shot.png", Target: "Pics", Source: "blob1"}}}}); err != nil {
		t.Fatal(err)
	}
	rename := func(ctx context.Context, from, to string) error {
		_, err := f.r.Invoke(ctx, "wiki.rename", wikiRenameIn{Repo: "test", Name: from, To: to})
		return err
	}
	kf := as("pat", "kf")
	for _, c := range []struct {
		why, from, to string
		want          error
	}{
		{"onto a live page", "Old", "Taken", ops.ErrInvalid},
		{"onto itself", "Old", "Old", ops.ErrInvalid},
		{"to a title with a leading space", "Old", " Old", ops.ErrInvalid},
		{"to a title with a run of spaces", "Old", "a  b", ops.ErrInvalid},
		{"to a title with a control character", "Old", "a\tb", ops.ErrInvalid},
		{"to a title over a hundred bytes", "Old", strings.Repeat("x", 101), ops.ErrInvalid},
		{"a page that does not exist", "Never", "Anything", ops.ErrNotFound},
		{"a page already deleted", "Ended", "Anything", ops.ErrInvalid},
		{"a branch page", "branch/work", "Elsewhere", ops.ErrInvalid},
		{"onto a branch page's title", "Old", "branch/other", ops.ErrInvalid},
		{"onto a checkin page's title", "Old", "checkin/abc", ops.ErrInvalid},
		{"a page with attached files", "Pics", "Pictures", ops.ErrInvalid},
	} {
		if err := rename(kf, c.from, c.to); !errors.Is(err, c.want) {
			t.Errorf("FAIL: %s: %v, want %v", c.why, err, c.want)
		}
	}
	for _, letters := range []string{"j", "m", "l", "f", "o", "n"} {
		if code := f.call(t, letters, "/api/v1/r/test/wiki/Old/rename", map[string]string{"to": "Mine"}); code != http.StatusForbidden {
			t.Errorf("FAIL: letters %q rename a page: %d", letters, code)
		}
	}
	// Onto a title whose page was deleted is a re-creation, and allowed.
	if err := rename(kf, "Old", "Ended"); err != nil {
		t.Errorf("FAIL: renaming onto a deleted title: %v", err)
	}
	if g := f.get(t, "Ended"); g.Deleted || g.Source != "the text\n" {
		t.Errorf("FAIL: the re-created page reads %+v", g)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestWikiDeleteAndRenameLeaveSearch(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Old", "quokkas\n")
	f.save(t, "Gone", "quokkas also\n")
	kf := as("pat", "kf")
	if _, err := f.r.Invoke(kf, "wiki.rename", wikiRenameIn{Repo: "test", Name: "Old", To: "New"}); err != nil {
		t.Fatal(err)
	}
	if _, err := f.r.Invoke(kf, "wiki.delete", wikiDeleteIn{Repo: "test", Name: "Gone"}); err != nil {
		t.Fatal(err)
	}
	rs, err := f.ix.Search("quokkas", "wiki", 10)
	if err != nil {
		t.Fatal(err)
	}
	if len(rs) != 1 || rs[0].Ref != "New" {
		t.Errorf("FAIL: the search holds %+v, want only New", rs)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A rename ends the old page with a C card naming the new title, in the
// one form the old title's address reads back; a plain delete writes no
// C card, and a page ended before this existed (an empty edit with no
// card) is just deleted: nothing is guessed from the text.
func TestWikiRenameRecordsWhereThePageWent(t *testing.T) {
	f := newWikiFixture(t)
	f.save(t, "Old", "the text\n")
	f.save(t, "Gone", "bye\n")
	f.save(t, "Early", "early\n")
	out, err := f.r.Invoke(as("pat", "kf"), "wiki.rename", wikiRenameIn{Repo: "test", Name: "Old", To: "New name"})
	if err != nil {
		t.Fatal(err)
	}
	ended := f.artifact(t, out.(wikiRenameOut).Ended)
	if ended.Comment != "moved to New name" {
		t.Errorf("FAIL: the ending edit's C card is %q", ended.Comment)
	}
	if g := f.get(t, "Old"); !g.Deleted || g.MovedTo != "New name" {
		t.Errorf("FAIL: the old title reads %+v, want deleted and moved to the new title", g)
	}
	if g := f.get(t, "New name"); g.MovedTo != "" {
		t.Errorf("FAIL: the live page claims it moved: %+v", g)
	}

	del, err := f.r.Invoke(as("pat", "kf"), "wiki.delete", wikiDeleteIn{Repo: "test", Name: "Gone"})
	if err != nil {
		t.Fatal(err)
	}
	if c := f.artifact(t, del.(wikiDeleteOut).Hash).Comment; c != "" {
		t.Errorf("FAIL: a delete wrote the C card %q", c)
	}
	if g := f.get(t, "Gone"); !g.Deleted || g.MovedTo != "" {
		t.Errorf("FAIL: a deleted page reads %+v", g)
	}

	// A rename from before the card: the new page, then a bare ending.
	tok := lease.Unguarded("test: a rename as it was written before the card")
	f.commit(t, tok, "Earlier new", "early\n")
	f.commit(t, tok, "Early", "")
	if _, err := f.repo.Sync(); err != nil {
		t.Fatal(err)
	}
	if g := f.get(t, "Early"); !g.Deleted || g.MovedTo != "" {
		t.Errorf("FAIL: a pre-change rename reads %+v, want plain deleted", g)
	}

	// The notice follows the new page: once that is gone too, the old
	// title has nowhere to point.
	if _, err := f.r.Invoke(as("pat", "kf"), "wiki.delete", wikiDeleteIn{Repo: "test", Name: "New name"}); err != nil {
		t.Fatal(err)
	}
	if g := f.get(t, "Old"); !g.Deleted || g.MovedTo != "" {
		t.Errorf("FAIL: with the new page deleted, the old title reads %+v", g)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}