Skip to content
quarry Artifact [fe69a5b19b]
Login

Artifact [fe69a5b19b]

Artifact fe69a5b19b9c1c0a61112d74276c2574ec8bac20b702f937469416b665bd27be:


package cibridge

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"craftdesign.group/quarry/internal/ci"
)

// A RUNNER GETS ITS TASK'S CHECKOUT LOGIN ONLY AS THE RUNNER HOLDING
// THE TASK, and a task that is resolved for good tells the forge so,
// once, and only when the engine accepted the resolve.
func TestCheckoutLoginGoesOnlyToTheRunnerHoldingTheTask(t *testing.T) {
	engine := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/v1/tasks/run1.job/resolve" || r.Header.Get("Authorization") != "Bearer CLAIMER" {
			http.Error(w, "task not claimed by this token", http.StatusForbidden)
			return
		}
		if strings.Contains(r.Header.Get("X-Test-Conflict"), "yes") {
			http.Error(w, "resolved", http.StatusConflict)
		}
	}))
	defer engine.Close()
	var asked, ended []string
	checkout := func(repo, taskID string) (CheckoutLogin, error) {
		asked = append(asked, repo+" "+taskID)
		return CheckoutLogin{User: "run-x", Token: "qrt_x_secret", Expires: "2030-01-01T00:00:00Z"}, nil
	}
	over := func(repo, taskID string) { ended = append(ended, repo+" "+taskID) }
	h, err := Handler(engine.URL, "ADMIN", func(string) string { return "g" }, func(r string) bool { return r == "alpha" }, nil, nil,
		WithCheckout(checkout, over))
	if err != nil {
		t.Fatal(err)
	}
	post := func(path, bearer, body string, hdr ...string) *httptest.ResponseRecorder {
		req := httptest.NewRequest("POST", "/r/alpha/ci/bridge/v1/tasks/run1.job/"+path, strings.NewReader(body))
		if bearer != "" {
			req.Header.Set("Authorization", "Bearer "+bearer)
		}
		for i := 0; i+1 < len(hdr); i += 2 {
			req.Header.Set(hdr[i], hdr[i+1])
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		return rec
	}
	rec := post("checkout", "CLAIMER", `{}`)
	var out CheckoutLogin
	json.Unmarshal(rec.Body.Bytes(), &out)
	if rec.Code != 200 || out.User != "run-x" || out.Token != "qrt_x_secret" || rec.Header().Get("Cache-Control") != "no-store" {
		t.Errorf("FAIL: the claiming runner got %d %q", rec.Code, rec.Body)
	}
	for _, b := range []string{"OTHER", "ADMIN", ""} {
		if rec := post("checkout", b, `{}`); rec.Code < 400 || strings.Contains(rec.Body.String(), "qrt_") {
			t.Errorf("FAIL: bearer %q got %d %q; want a refusal and no token", b, rec.Code, rec.Body)
		}
	}
	if len(asked) != 1 {
		t.Errorf("FAIL: the forge was asked %v; want only for the claiming runner", asked)
	}

	for _, action := range []string{"heartbeat", "pause", "nonsense"} {
		post("resolve", "CLAIMER", `{"action":"`+action+`"}`)
	}
	post("resolve", "OTHER", `{"action":"complete"}`)
	post("resolve", "CLAIMER", `{"action":"complete"}`, "X-Test-Conflict", "yes")
	post("resolve", "CLAIMER", `not json`)
	if len(ended) != 0 {
		t.Errorf("FAIL: the task was reported over by %v; want nothing yet", ended)
	}
	for _, action := range []string{"complete", "fail"} {
		if rec := post("resolve", "CLAIMER", `{"action":"`+action+`","output":{}}`); rec.Code != 200 {
			t.Errorf("FAIL: %s was answered %d", action, rec.Code)
		}
	}
	if len(ended) != 2 || ended[0] != "alpha run1.job" {
		t.Errorf("FAIL: the task was reported over %v; want twice, for alpha run1.job", ended)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A forge that was given no checkout route has none: the runner's 404
// is how it knows to use the credentials it was started with.
func TestNoCheckoutRouteWithoutADeliverer(t *testing.T) {
	h, err := Handler("http://engine.invalid", "ADMIN", func(string) string { return "g" }, func(string) bool { return true }, nil, nil)
	if err != nil {
		t.Fatal(err)
	}
	req := httptest.NewRequest("POST", "/r/alpha/ci/bridge/v1/tasks/run1.job/checkout", strings.NewReader(`{}`))
	req.Header.Set("Authorization", "Bearer CLAIMER")
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	if rec.Code != http.StatusNotFound {
		t.Errorf("FAIL: a bridge with no checkout deliverer answered %d, want 404", rec.Code)
	}
}

// A FAULT OF THE FORGE'S OWN IS NOT A REFUSAL. A delivery the rule
// refuses is a final 403; anything else (a database that is locked) is
// a 503 the runner may retry.
func TestACheckoutFaultIsRetryableAndARefusalIsFinal(t *testing.T) {
	engine := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
	defer engine.Close()
	for name, c := range map[string]struct {
		err  error
		want int
	}{
		"a refusal":        {fmt.Errorf("%w: the run is over", ErrRefused), http.StatusForbidden},
		"a database fault": {errors.New("database is locked"), http.StatusServiceUnavailable},
	} {
		h, err := Handler(engine.URL, "ADMIN", func(string) string { return "g" }, func(string) bool { return true }, nil, nil,
			WithCheckout(func(string, string) (CheckoutLogin, error) { return CheckoutLogin{}, c.err }, nil))
		if err != nil {
			t.Fatal(err)
		}
		req := httptest.NewRequest("POST", "/r/alpha/ci/bridge/v1/tasks/run1.job/checkout", strings.NewReader(`{}`))
		req.Header.Set("Authorization", "Bearer CLAIMER")
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		if rec.Code != c.want {
			t.Errorf("FAIL: %s was answered %d, want %d", name, rec.Code, c.want)
		}
		if strings.Contains(rec.Body.String(), "locked") {
			t.Errorf("FAIL: %s: the body carries the fault's own words: %q", name, rec.Body)
		}
	}
}

// A RUNNER READS TRUNK'S TASK NAMES AT START-UP WITH ITS WORKER TOKEN
// ALONE, from the forge's record of that token, never from the engine.
func TestTrunkTasksGoToAWorkerTokenOfThisRepository(t *testing.T) {
	engine := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Errorf("FAIL: the engine was contacted") }))
	defer engine.Close()
	ledger := map[string]string{ci.TokenHash("ALPHA"): "alpha", ci.TokenHash("BETA"): "beta"}
	owner := func(h string) (string, bool) { r, ok := ledger[h]; return r, ok }
	var asked []string
	tasks := func(repo string) ([]string, error) {
		asked = append(asked, repo)
		return []string{"lint", "test"}, nil
	}
	h, err := Handler(engine.URL, "ADMIN", func(string) string { return "g" }, func(r string) bool { return r == "alpha" }, nil, nil,
		WithTokenOwner(owner), WithTrunkTasks(tasks))
	if err != nil {
		t.Fatal(err)
	}
	post := func(bearer string) *httptest.ResponseRecorder {
		req := httptest.NewRequest("POST", "/r/alpha/ci/bridge/v1/trunk/tasks", strings.NewReader(`{}`))
		if bearer != "" {
			req.Header.Set("Authorization", "Bearer "+bearer)
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		return rec
	}
	rec := post("ALPHA")
	var out struct {
		Tasks []string `json:"tasks"`
	}
	json.Unmarshal(rec.Body.Bytes(), &out)
	if rec.Code != 200 || len(out.Tasks) != 2 || out.Tasks[0] != "lint" || rec.Header().Get("Cache-Control") != "no-store" {
		t.Errorf("FAIL: the repository's own worker token got %d %q", rec.Code, rec.Body)
	}
	for _, b := range []string{"BETA", "UNRECORDED", "ADMIN", ""} {
		if rec := post(b); rec.Code < 400 || strings.Contains(rec.Body.String(), "lint") {
			t.Errorf("FAIL: bearer %q got %d %q; want a refusal and no names", b, rec.Code, rec.Body)
		}
	}
	if len(asked) != 1 || asked[0] != "alpha" {
		t.Errorf("FAIL: the forge was asked %v; want once, for alpha", asked)
	}
	// With no ledger, or no lister, there is no route: a 404 is how a
	// runner knows to read trunk itself.
	for name, opts := range map[string][]Option{"no ledger": {WithTrunkTasks(tasks)}, "no lister": {WithTokenOwner(owner)}} {
		h, err := Handler(engine.URL, "ADMIN", func(string) string { return "g" }, func(string) bool { return true }, nil, nil, opts...)
		if err != nil {
			t.Fatal(err)
		}
		req := httptest.NewRequest("POST", "/r/alpha/ci/bridge/v1/trunk/tasks", strings.NewReader(`{}`))
		req.Header.Set("Authorization", "Bearer ALPHA")
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		if rec.Code != http.StatusNotFound {
			t.Errorf("FAIL: %s answered %d, want 404", name, rec.Code)
		}
	}
}