Skip to content
quarry Artifact [359ea92879]
Login

Artifact [359ea92879]

Artifact 359ea9287987501e5658560b33083ce5613f11698a57891bc1d655c3467d97a9:


package api

import (
	"context"
	"errors"
	"fmt"
	"strings"

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

// WikiSpecialName reports whether a wiki title is one fossil ties to a
// subject: checkin/HASH, branch/NAME, tag/NAME and ticket/ID pages are
// what a check-in, branch, tag or ticket shows as its own.
func WikiSpecialName(name string) bool {
	for _, p := range []string{"checkin/", "branch/", "tag/", "ticket/"} {
		if strings.HasPrefix(name, p) {
			return true
		}
	}
	return false
}

// WikiExtraLetter is the capability fossil asks of a writer on top of
// the wiki's own for this title (wiki_special_permission): check-in
// write for checkin/, branch/ and tag/ pages, ticket write for ticket/
// pages, and nothing for an ordinary page.
func WikiExtraLetter(name string) string {
	switch {
	case strings.HasPrefix(name, "ticket/"):
		return "w"
	case WikiSpecialName(name):
		return "i"
	}
	return ""
}

// wikiMay applies fossil's rule for writing one wiki page: an existing
// page (a deleted one is still a page) takes WrWiki k, a new title takes
// NewWiki f, and a special title takes its extra letter as well. A call
// carrying no capabilities at all is a forge with no capability plane,
// where every caller is the operator.
func wikiMay(ctx context.Context, name string, exists bool) error {
	if !ops.HasCaps(ctx) {
		return nil
	}
	c := ops.CapsOf(ctx)
	need, what := "f", "create a wiki page (New-Wiki, f)"
	if exists {
		need, what = "k", "change a wiki page that exists (Write-Wiki, k)"
	}
	if !c.HasAny(need) {
		return fmt.Errorf("you need the capability to %s: %w", what, ops.ErrForbidden)
	}
	if extra := WikiExtraLetter(name); extra != "" && !c.HasAny(extra) {
		return fmt.Errorf("%q is tied to a check-in, branch, tag or ticket, so writing it also takes capability %s: %w", name, extra, ops.ErrForbidden)
	}
	return nil
}

// wikiFold brings the index up to the store under the lease, so what is
// read next is the head a write would build on. A stalled ingest is a
// refusal, not a guess from a stale index.
func wikiFold(repo *Repo) error {
	if repo.Sync == nil {
		return nil
	}
	if _, err := repo.Sync(); err != nil {
		if errors.Is(err, ingest.ErrStalled) {
			return fmt.Errorf("the index has not caught up with the store; try again once ingest recovers: %w", ops.ErrUnavailable)
		}
		return err
	}
	return nil
}

// liveHead is a page's newest edit, read under the lease. A page never
// written is not found; one already ended cannot be ended twice; and a
// caller who named the version they were looking at is told when it is
// no longer the newest.
func liveHead(repo *Repo, name, expect string) (index.WikiEdit, error) {
	cur, ok, err := repo.Index.WikiPage(name)
	if err != nil {
		return index.WikiEdit{}, err
	}
	if !ok {
		return index.WikiEdit{}, fmt.Errorf("no wiki page %q: %w", name, ops.ErrNotFound)
	}
	if artifact.WikiDeleted(cur.Body) {
		return index.WikiEdit{}, fmt.Errorf("wiki page %q is already deleted: %w", name, ops.ErrInvalid)
	}
	if expect != "" && !strings.HasPrefix(cur.Hash, expect) {
		return index.WikiEdit{}, fmt.Errorf("the page changed while you were looking at it; its newest version is %.12s, look again: %w", cur.Hash, ops.ErrInvalid)
	}
	return cur, nil
}

func (d Deps) wikiDelete(ctx context.Context, in wikiDeleteIn) (wikiDeleteOut, error) {
	if err := d.refuseUnlessWritable(in.Repo); err != nil {
		return wikiDeleteOut{}, err
	}
	repo, err := d.repoFor(ctx, in.Repo)
	if err != nil {
		return wikiDeleteOut{}, err
	}
	// Existence for the capability rule is read under the lease too.
	var hash string
	werr := repo.write(func(tok lease.Token) error {
		if err := wikiFold(repo); err != nil {
			return err
		}
		cur, err := liveHead(repo, in.Name, in.Expect)
		if err != nil {
			return err
		}
		if err := wikiMay(ctx, in.Name, true); err != nil {
			return err
		}
		hash, err = repo.Zit.WikiCommit(tok, in.Name, author(ctx), cur.Mimetype, nil, "")
		return err
	})
	if serr := repo.synced(); werr == nil {
		werr = serr
	}
	if werr != nil {
		return wikiDeleteOut{}, werr
	}
	d.fireNotify(NotifyEvent{
		Workflow: "quarry-activity", To: "repo:" + in.Repo,
		Payload: map[string]any{"repo": in.Repo, "actor": author(ctx), "via": ops.Via(ctx),
			"summary": "deleted wiki page " + in.Name,
			"link":    d.link("/r/" + in.Repo + "/wiki/" + in.Name)},
		TxnID: "activity:wiki:" + hash,
	})
	return wikiDeleteOut{Hash: hash}, nil
}

func (d Deps) wikiRename(ctx context.Context, in wikiRenameIn) (wikiRenameOut, error) {
	if err := d.refuseUnlessWritable(in.Repo); err != nil {
		return wikiRenameOut{}, err
	}
	if !artifact.ValidWikiName(in.To) {
		return wikiRenameOut{}, fmt.Errorf("%q is not a title fossil accepts for a wiki page: it must be 1 to 100 characters, with no leading or trailing space, no control characters and no run of spaces: %w", in.To, ops.ErrInvalid)
	}
	if in.To == in.Name {
		return wikiRenameOut{}, fmt.Errorf("the page is already called %q: %w", in.Name, ops.ErrInvalid)
	}
	for _, n := range []string{in.Name, in.To} {
		if WikiSpecialName(n) {
			return wikiRenameOut{}, fmt.Errorf("%q is tied to its check-in, branch, tag or ticket by its title, so it cannot be renamed or renamed onto: %w", n, ops.ErrInvalid)
		}
	}
	repo, err := d.repoFor(ctx, in.Repo)
	if err != nil {
		return wikiRenameOut{}, err
	}
	var first, ended string
	werr := repo.write(func(tok lease.Token) error {
		// Everything below is read and written under one lease, against
		// the heads as they are now: a concurrent edit, create or rename
		// either happened before this read or waits for it.
		if err := wikiFold(repo); err != nil {
			return err
		}
		cur, err := liveHead(repo, in.Name, in.Expect)
		if err != nil {
			return err
		}
		if err := wikiMay(ctx, in.Name, true); err != nil {
			return err
		}
		// Fossil judges the new title by whether a page of that name
		// exists at all: a deleted one is an edit (k), a new one a
		// creation (f).
		dest, destExists, err := repo.Index.WikiPage(in.To)
		if err != nil {
			return err
		}
		if err := wikiMay(ctx, in.To, destExists); err != nil {
			return err
		}
		// Whoever the text was redacted for, the new page is a fresh
		// artifact that would publish it: refused for everyone, moderators
		// included. Unredact first.
		if reason, _ := d.withheld(ctx, in.Repo, cur.Hash); reason != "" {
			return fmt.Errorf("the page's text is redacted; unredact it before moving it: %w", ops.ErrInvalid)
		}
		if att, err := repo.Index.AttachmentsFor(in.Name); err != nil {
			return err
		} else if len(att) > 0 {
			return fmt.Errorf("the page has %d attached files, which belong to its title and would be left behind: %w", len(att), ops.ErrInvalid)
		}
		switch {
		case destExists && !artifact.WikiDeleted(dest.Body):
			// An interrupted rename: the new page is there with exactly
			// this text. Finishing it is the retry's job.
			if string(dest.Body) != string(cur.Body) || dest.Mimetype != cur.Mimetype {
				return fmt.Errorf("a page called %q already exists: %w", in.To, ops.ErrInvalid)
			}
			first = dest.Hash
		default:
			if first, err = repo.Zit.WikiCommit(tok, in.To, author(ctx), cur.Mimetype, cur.Body, ""); err != nil {
				return err
			}
		}
		ended, err = repo.Zit.WikiCommit(tok, in.Name, author(ctx), cur.Mimetype, nil, artifact.MovedToComment(in.To))
		return err
	})
	// Folded on the way out even when a write failed: a half-done rename
	// must be visible to the retry that finishes it.
	if serr := repo.synced(); werr == nil {
		werr = serr
	}
	if werr != nil {
		return wikiRenameOut{}, werr
	}
	d.fireNotify(NotifyEvent{
		Workflow: "quarry-activity", To: "repo:" + in.Repo,
		Payload: map[string]any{"repo": in.Repo, "actor": author(ctx), "via": ops.Via(ctx),
			"summary": "renamed wiki page " + in.Name + " to " + in.To,
			"link":    d.link("/r/" + in.Repo + "/wiki/" + in.To)},
		TxnID: "activity:wiki:" + first,
	})
	return wikiRenameOut{From: in.Name, To: in.To, Hash: first, Ended: ended}, nil
}