package web
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"craftdesign.group/quarry/internal/api"
"craftdesign.group/quarry/internal/ops"
)
// Each row draws a form of its own for the address: the endpoint's id,
// its current URL in a url input, and a submit that says "url". Its own
// form, so the events field beside it is never submitted by Enter here.
func TestWebhookRowCarriesAURLForm(t *testing.T) {
got := renderSettings(t, pageData{Repo: "alpha", HasHooks: true, Hooks: []HookSub{
{ID: 7, URL: "https://example.test/h", Events: "ticket", Active: true},
}})
i := strings.Index(got, `data-hook="hook-url-form"`)
if i < 0 {
t.Fatal("FAIL: no URL form on the row")
}
form := got[i:]
form = form[:strings.Index(form, "</form>")]
for _, want := range []string{
`data-id="7"`, `name="id" value="7"`, `type="url"`, `name="url"`,
`value="https://example.test/h"`, `name="do" value="url"`, `maxlength="300"`,
} {
if !strings.Contains(form, want) {
t.Errorf("FAIL: the URL form lacks %s", want)
}
}
if strings.Contains(form, `name="events"`) {
t.Error("FAIL: the URL form also carries the events field")
}
if !t.Failed() {
t.Log("ok")
}
}
type urlOpIn struct {
Repo string `json:"repo"`
ID string `json:"id"`
URL string `json:"url"`
}
// do=url reaches the hook.url op with the repository, the endpoint and
// the new URL, and an op refusal comes back on the redirect as the
// page's error.
func TestWebhookURLFormCallsTheOp(t *testing.T) {
var mu sync.Mutex
var seen []urlOpIn
var refuse error
r := ops.NewRegistry()
if err := ops.Register(r, ops.Op[urlOpIn, stubOut]{
Name: "hook.url", Doc: "records", Kind: ops.Command, Auth: ops.Anonymous, Route: "POST /api/v1/stub/hook.url",
Run: func(_ context.Context, in urlOpIn) (stubOut, error) {
mu.Lock()
defer mu.Unlock()
seen = append(seen, in)
return stubOut{OK: refuse == nil}, refuse
},
}); err != nil {
t.Fatal(err)
}
if err := ops.Register(r, ops.Op[stubIn, struct {
Version string `json:"version"`
}]{
Name: "meta.version", Doc: "v", Kind: ops.Query, Auth: ops.Anonymous, Route: "GET /api/v1/stub/version",
Run: func(context.Context, stubIn) (struct {
Version string `json:"version"`
}, error) {
return struct {
Version string `json:"version"`
}{"v"}, nil
},
}); err != nil {
t.Fatal(err)
}
plane := &guardPlane{stubCaps: stubCaps{letters: "aC3kfeimnopqrtvwxyz8LS"}}
verify := Verify(func(string, string, string, ops.Auth) api.Decision { return api.Allowed })
srv := httptest.NewServer(HandlerWith(r, nil, nil, []Option{
WithSessions(fakeSessions{user: "dan", roles: map[string]ops.Auth{"alpha": ops.Admin, "": ops.Admin}}),
WithCaps(plane), WithHooks(fleetHooks{}),
}, verify))
t.Cleanup(srv.Close)
resp := postAsDan(t, srv, "/r/alpha/settings/hooks", url.Values{"do": {"url"}, "id": {"7"}, "url": {" https://new.example.test/h "}})
if resp.StatusCode >= 400 {
t.Fatalf("FAIL: answered %d", resp.StatusCode)
}
if len(seen) != 1 || seen[0] != (urlOpIn{Repo: "alpha", ID: "7", URL: "https://new.example.test/h"}) {
t.Fatalf("FAIL: the op saw %+v", seen)
}
if loc := resp.Header.Get("Location"); strings.Contains(loc, "e=") {
t.Errorf("FAIL: a good change redirected with an error: %s", loc)
}
refuse = errors.New("must be an https url")
resp = postAsDan(t, srv, "/r/alpha/settings/hooks", url.Values{"do": {"url"}, "id": {"7"}, "url": {"ftp://x"}})
if loc := resp.Header.Get("Location"); !strings.Contains(loc, "e=") || !strings.HasSuffix(loc, "#webhooks") {
t.Errorf("FAIL: a refusal came back as %q, want an e= and the webhooks anchor", loc)
}
if resp.StatusCode != http.StatusSeeOther {
t.Errorf("FAIL: status %d", resp.StatusCode)
}
if !t.Failed() {
t.Log("ok")
}
}
// A refusal from a webhook action is drawn in the webhooks section the
// reader was sent to, and not also in the banner at the top.
func TestAWebhookRefusalIsDrawnInItsSection(t *testing.T) {
section := renderSettings(t, pageData{Repo: "alpha", HasHooks: true, HookError: "must be https"})
if !strings.Contains(section, `data-hook="hook-error"`) {
t.Error("FAIL: no refusal drawn in the webhooks section")
}
banner := renderSettings(t, pageData{Repo: "alpha", HasHooks: true, Error: "something else"})
if strings.Contains(banner, `data-hook="hook-error"`) {
t.Error("FAIL: a refusal from elsewhere was drawn as a webhook one")
}
for _, c := range []struct {
query, hook, want string
}{
{"e=nope&eh=1", "1", "nope"}, {"e=nope&eh=1", "", ""},
{"e=nope", "", "nope"}, {"e=nope", "1", ""},
} {
req := httptest.NewRequest("GET", "/r/alpha/settings?"+c.query, nil)
if got := pageError(req, c.hook); got != c.want {
t.Errorf("FAIL: %s read for %q = %q, want %q", c.query, c.hook, got, c.want)
}
}
if !t.Failed() {
t.Log("ok")
}
}