Skip to content
quarry Artifact [2c455ed0ac]
Login

Artifact [2c455ed0ac]

Artifact 2c455ed0ac59c3454aa38f24209733155f782a7a7e4dc7e671b1c1f1cfdc8a52:


package webhook

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync/atomic"
	"testing"

	"craftdesign.group/quarry/internal/outbound"
	"craftdesign.group/quarry/internal/outbound/outboundtest"
)

// An endpoint stored before the forge refused private addresses is not
// deleted; each delivery fails with a refusal that names the host, never
// the path or query (which may hold a token), and nothing is sent.
func TestStoredPrivateEndpointIsRefusedAtDelivery(t *testing.T) {
	outboundtest.Set(t)
	var hits atomic.Int32
	srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { hits.Add(1) }))
	defer srv.Close()

	d := testDispatcher(t, &fakeSubs{subs: map[int64]Sub{}})
	status, err := d.deliverOnce(context.Background(),
		Sub{ID: 1, URL: srv.URL + "/hook/path?token=SECRETVALUE", Secret: "k", Active: true},
		Event{ID: "e1", Repo: "alpha", Kind: "ticket.new"}, []byte(`{}`))
	var ref *outbound.Refusal
	if !errors.As(err, &ref) || status != 0 {
		t.Errorf("FAIL: status=%d err=%v, want a refusal and no status", status, err)
	}
	if hits.Load() != 0 {
		t.Errorf("FAIL: the private endpoint was called")
	}
	if text := deliveryErr(err); strings.Contains(text, "SECRETVALUE") || strings.Contains(text, "/hook/path") {
		t.Errorf("FAIL: the recorded error carries part of the URL")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A 3xx from an endpoint is its answer; it is not followed, so a public
// endpoint cannot bounce a delivery onto an address the guard would
// refuse, nor onto one it would allow.
func TestDeliveryDoesNotFollowRedirects(t *testing.T) {
	var landed atomic.Int32
	target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { landed.Add(1) }))
	defer target.Close()
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, target.URL, http.StatusFound)
	}))
	defer srv.Close()

	d := testDispatcher(t, &fakeSubs{subs: map[int64]Sub{}})
	status, err := d.deliverOnce(context.Background(), Sub{ID: 1, URL: srv.URL, Secret: "k", Active: true},
		Event{ID: "e1", Repo: "alpha", Kind: "ticket.new"}, []byte(`{}`))
	if status != http.StatusFound || err == nil {
		t.Errorf("FAIL: status=%d err=%v, want the 302 reported as a failed delivery", status, err)
	}
	if landed.Load() != 0 {
		t.Errorf("FAIL: the redirect was followed")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}