Skip to content
quarry Artifact [39a8ed2533]
Login

Artifact [39a8ed2533]

Artifact 39a8ed2533c065c0b2a4dcf56ae67d78eb87d02f55258f0c9647c29b5b1c91e1:


package api

import (
	"encoding/json"
	"errors"
	"path/filepath"
	"strings"
	"testing"

	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
	"craftdesign.group/quarry/internal/webhook"
)

// urlHooks puts the real webhook store behind the op, so the secret,
// the history and the repository scoping under test are the store's.
type urlHooks struct{ db *oltp.DB }

func (urlHooks) Deliveries(string, int64, int) ([]HookDelivery, error) { return nil, nil }
func (urlHooks) Redeliver(string, int64) (webhook.Outcome, error)      { return webhook.Outcome{}, nil }
func (urlHooks) Ping(string, int64) (webhook.Outcome, error)           { return webhook.Outcome{}, nil }
func (h urlHooks) SetURL(repo string, id int64, to string) (string, error) {
	return h.db.SetWebhookURL(repo, id, to)
}

func hookURLRegistry(t *testing.T) (*ops.Registry, *oltp.DB, *settingRecorder) {
	t.Helper()
	db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { db.Close() })
	rec := &settingRecorder{}
	caps := func(account, repo string) CapSet {
		if account == "dan" {
			return oltp.CapSet("a")
		}
		return oltp.CapSet("3")
	}
	r := ops.NewRegistry()
	if err := RegisterAll(r, Deps{Version: "v", Hooks: urlHooks{db}, SettingLog: rec, CapsFor: caps,
		Repos: NewRepos(map[string]*Repo{"alpha": {Chat: "alpha", Index: wikiIndex(t)}, "beta": {Chat: "beta", Index: wikiIndex(t)}})}); err != nil {
		t.Fatal(err)
	}
	return r, db, rec
}

// The URL changes through the op; the secret, the events and the
// history stay; the trail names the two hosts and nothing secret.
func TestHookURLChangesItAndTrailsHostsOnly(t *testing.T) {
	r, db, rec := hookURLRegistry(t)
	w, err := db.AddWebhook("alpha", "https://old.example.test/h?token=hunter2", "ticket")
	if err != nil {
		t.Fatal(err)
	}
	db.RecordDelivery(oltp.Delivery{Sub: w.ID, Repo: "alpha", Kind: "ticket.new", Status: 200})
	out, err := r.Invoke(asUser("dan"), "hook.url", hookURLIn{Repo: "alpha", ID: w.ID, URL: "https://new.example.test:8443/in"})
	if err != nil {
		t.Fatalf("FAIL: %v", err)
	}
	if o := out.(hookURLOut); o.ID != w.ID || o.URL != "https://new.example.test:8443/in" {
		t.Errorf("FAIL: answered %+v", o)
	}
	got, _ := db.WebhookByID(w.ID)
	if got.URL != "https://new.example.test:8443/in" || got.Secret != w.Secret || got.Events != "ticket" {
		t.Errorf("FAIL: stored %+v", got)
	}
	if ds, _ := db.Deliveries(w.ID, 10); len(ds) != 1 {
		t.Errorf("FAIL: history %d rows, want 1", len(ds))
	}
	if len(rec.rows) != 1 {
		t.Fatalf("FAIL: trail rows %+v, want one", rec.rows)
	}
	row := rec.rows[0]
	if row.repo != "alpha" || row.actor != "dan" || row.field != "webhook-url" ||
		row.was != "old.example.test" || row.now != "new.example.test:8443" {
		t.Errorf("FAIL: trail row %+v", row)
	}
	body, _ := json.Marshal(rec.rows)
	for _, leak := range []string{w.Secret, "hunter2", "/in", "/h"} {
		if strings.Contains(string(body), leak) {
			t.Errorf("FAIL: the trail carries %q: %s", leak, body)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// Only an admin of the repository, the same letter that adds one.
func TestHookURLRefusesANonAdminAndAForeignEndpoint(t *testing.T) {
	r, db, rec := hookURLRegistry(t)
	w, _ := db.AddWebhook("alpha", "https://old.example.test/h", "*")
	in := hookURLIn{Repo: "alpha", ID: w.ID, URL: "https://new.example.test/h"}
	if _, err := r.Invoke(asUser("eve"), "hook.url", in); !errors.Is(err, ops.ErrForbidden) {
		t.Errorf("FAIL: a non-admin: %v", err)
	}
	// An admin, but of another repository's id.
	in.Repo = "beta"
	if _, err := r.Invoke(asUser("dan"), "hook.url", in); !errors.Is(err, ops.ErrNotFound) {
		t.Errorf("FAIL: a foreign endpoint: %v, want not found", err)
	}
	if got, _ := db.WebhookByID(w.ID); got.URL != "https://old.example.test/h" {
		t.Errorf("FAIL: a refused call moved the url: %q", got.URL)
	}
	if len(rec.rows) != 0 {
		t.Errorf("FAIL: refused calls wrote the trail: %+v", rec.rows)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A bad URL is refused and leaves neither the endpoint nor the trail
// changed.
func TestHookURLRefusesABadURL(t *testing.T) {
	r, db, rec := hookURLRegistry(t)
	w, _ := db.AddWebhook("alpha", "https://old.example.test/h", "*")
	for _, bad := range []string{"ftp://example.test/h", "http://example.test/h", "nonsense", "https://" + strings.Repeat("a", 400)} {
		_, err := r.Invoke(asUser("dan"), "hook.url", hookURLIn{Repo: "alpha", ID: w.ID, URL: bad})
		if err == nil {
			t.Errorf("FAIL: %.30q accepted", bad)
		}
	}
	if got, _ := db.WebhookByID(w.ID); got.URL != "https://old.example.test/h" {
		t.Errorf("FAIL: url = %q", got.URL)
	}
	if len(rec.rows) != 0 {
		t.Errorf("FAIL: trail %+v", rec.rows)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}