Skip to content
quarry Artifact [3c714fccaa]
Login

Artifact [3c714fccaa]

Artifact 3c714fccaad0e1217e28990276af709fb3d402d61694d7c92aeaa40264693cfb:


package cibridge

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

// 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)
	}
}