Skip to content
quarry Artifact [1e323e31f4]
Login

Artifact [1e323e31f4]

Artifact 1e323e31f4365c80eedfcbcca7c114f2ca5db110708011cceb8fc788499dfbfa:


package cibridge

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

// A RUNNER READS ITS TASK'S CHANGED PATHS ONLY AS THE RUNNER HOLDING
// THE TASK, and what it is told is the forge's own record's answer.
func TestChangedPathsGoOnlyToTheRunnerHoldingTheTask(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
		}
	}))
	defer engine.Close()
	var asked []string
	changed := func(repo, taskID string) (ChangedPaths, error) {
		asked = append(asked, repo+" "+taskID)
		return ChangedPaths{Changed: []string{"a/b.txt"}}, nil
	}
	h, err := Handler(engine.URL, "ADMIN", func(string) string { return "g" }, func(r string) bool { return r == "alpha" }, nil, nil, WithChanged(changed))
	if err != nil {
		t.Fatal(err)
	}
	ask := func(bearer string) *httptest.ResponseRecorder {
		req := httptest.NewRequest("POST", "/r/alpha/ci/bridge/v1/tasks/run1.job/changed", strings.NewReader(`{}`))
		if bearer != "" {
			req.Header.Set("Authorization", "Bearer "+bearer)
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		return rec
	}
	rec := ask("CLAIMER")
	var out ChangedPaths
	json.Unmarshal(rec.Body.Bytes(), &out)
	if rec.Code != 200 || len(out.Changed) != 1 || out.Changed[0] != "a/b.txt" || out.Touched != nil || 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 := ask(b); rec.Code < 400 || strings.Contains(rec.Body.String(), "a/b.txt") {
			t.Errorf("FAIL: bearer %q got %d %q; want a refusal and no paths", b, rec.Code, rec.Body)
		}
	}
	if len(asked) != 1 {
		t.Errorf("FAIL: the forge was asked %v; want only for the claiming runner", asked)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}