Files
sam 125457a391
publish / publish (push) Successful in 1m21s
feat(connector): declare privileged effects on every lookup and action (#2071)
Regenerate the connector SDK from the host contract, which adds the
effects_declared, privilege_change and secret_access fields. Every lookup and
action in this repository now states them, and a Semaphore template states
them in its effect settings or is unavailable in chat.
2026-11-21 21:29:49 +11:00

228 lines
8.8 KiB
Go

package main
import (
"encoding/json/jsontext"
json "encoding/json/v2"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/samcharles93/archipelago/sdk/connector"
)
// fakeSemaphore keeps tasks in memory. A launched task ends with finalStatus
// on its first status read, unless finalStatus is empty, when it runs for
// ever.
type fakeSemaphore struct {
mu sync.Mutex
tasks []task
launches int
finalStatus string
// failReads is how many status reads fail before one succeeds.
failReads int
// limitFixed is a template that ignores a task's limit.
limitFixed bool
lastLaunch launchBody
}
type launchBody struct {
TemplateID int `json:"template_id"`
Message string `json:"message"`
Environment string `json:"environment"`
Params struct {
Limit []string `json:"limit"`
} `json:"params"`
}
func (f *fakeSemaphore) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
if r.Header.Get("Authorization") != "Bearer plainly-fake-token" {
w.WriteHeader(http.StatusUnauthorized)
return
}
switch {
case r.Method == http.MethodGet && r.URL.Path == "/api/project/3/templates/7":
_ = json.MarshalWrite(w, map[string]any{"id": 7, "task_params": map[string]any{"allow_override_limit": !f.limitFixed}})
case r.Method == http.MethodGet && r.URL.Path == "/api/project/3/tasks/last":
_ = json.MarshalWrite(w, f.tasks)
case r.Method == http.MethodPost && r.URL.Path == "/api/project/3/tasks":
var body launchBody
_ = json.UnmarshalRead(r.Body, &body)
f.lastLaunch = body
f.launches++
t := task{ID: len(f.tasks) + 1, TemplateID: body.TemplateID, Status: "waiting", Message: body.Message}
f.tasks = append(f.tasks, t)
_ = json.MarshalWrite(w, t)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/output"):
_ = json.MarshalWrite(w, []outputLine{{Output: "removed 3 files"}})
case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/api/project/3/tasks/"):
if f.failReads > 0 {
f.failReads--
w.WriteHeader(http.StatusBadGateway)
return
}
id, _ := strconv.Atoi(strings.TrimPrefix(r.URL.Path, "/api/project/3/tasks/"))
if f.finalStatus != "" {
f.tasks[id-1].Status = f.finalStatus
}
_ = json.MarshalWrite(w, f.tasks[id-1])
default:
w.WriteHeader(http.StatusNotFound)
}
}
func newTestConnector(t *testing.T, url string) *semaphore {
t.Helper()
s, err := startConnector(url, "")
if err != nil {
t.Fatal(err)
}
return s
}
func startConnector(url, hostVar string) (*semaphore, error) {
s, err := newSemaphore(connector.Config{
Settings: map[string]string{
"base_url": url,
"project_id": "3",
"templates": `[{"action":"clean_tmp","template_id":7,"host_var":"` + hostVar + `","effect":{"reversibility":"irreversible","summary":"delete old files"},"target":{"kind":"host","environment":"non-production"},"vars":{"older_than_hours":"Age of files to delete"}}]`,
},
Secrets: map[string]string{"api.token": "plainly-fake-token"}, //nolint:gosec // a fake token the fake server checks
})
if err != nil {
return nil, err
}
s.pollEvery, s.deadline = time.Millisecond, 50*time.Millisecond
return s, nil
}
// TestLaunchHappensOncePerKey guards #2001's idempotency: a launch carries
// Archie's idempotency key, so invoking it again, from a connector that has
// restarted, finds the task already started instead of launching another. A
// task that ends in error is a known failure; one still running at the
// deadline is an unknown outcome.
func TestLaunchHappensOncePerKey(t *testing.T) {
input := jsontext.Value(`{"host":"web-1","older_than_hours":"24"}`)
tests := []struct {
name string
final string
failReads int
invokes int
wantLaunches int
wantErr bool
wantUnknown bool
}{
{name: "one invoke launches once", final: "success", invokes: 1, wantLaunches: 1},
{name: "invoking again after a restart doesn't launch again", final: "success", invokes: 2, wantLaunches: 1},
{name: "a status read that fails is retried", final: "success", failReads: 3, invokes: 1, wantLaunches: 1},
{name: "a task that fails is a known failure", final: "error", invokes: 1, wantLaunches: 1, wantErr: true},
{name: "a task still running at the deadline is unknown", final: "", invokes: 2, wantLaunches: 1, wantErr: true, wantUnknown: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fake := &fakeSemaphore{finalStatus: tt.final, failReads: tt.failReads}
srv := httptest.NewServer(fake)
defer srv.Close()
var (
err error
unknown bool
)
for range tt.invokes {
// A fresh connector each time, as after a restart.
_, unknown, err = newTestConnector(t, srv.URL).Invoke(t.Context(), "clean_tmp", input, "run-1:investigate:4")
}
if fake.launches != tt.wantLaunches {
t.Fatalf("launched %d times, want %d", fake.launches, tt.wantLaunches)
}
if (err != nil) != tt.wantErr || unknown != tt.wantUnknown {
t.Fatalf("err = %v, unknown = %v; want error %v, unknown %v", err, unknown, tt.wantErr, tt.wantUnknown)
}
})
}
}
// TestALaunchRunsOnlyOnItsHost guards the connector's confinement: Semaphore
// drops a task's limit unless the template allows overriding it, so a template
// that would run against the whole inventory is refused at start, and an input
// can neither widen the host nor add variables the operator didn't declare.
func TestALaunchRunsOnlyOnItsHost(t *testing.T) {
tests := []struct {
name string
limitFixed bool
hostVar string
input string
wantStart bool
wantLaunch bool
wantEnv string
}{
{name: "a template honouring the limit gets it", input: `{"host":"web-1","older_than_hours":"24"}`, wantStart: true, wantLaunch: true, wantEnv: `{"older_than_hours":"24"}`},
{name: "a template ignoring the limit is refused", limitFixed: true, wantStart: false},
{name: "a template ignoring the limit gets the host as its variable", limitFixed: true, hostVar: "clean_host", input: `{"host":"web-1","older_than_hours":"24"}`, wantStart: true, wantLaunch: true, wantEnv: `{"clean_host":"web-1","older_than_hours":"24"}`},
{name: "an undeclared variable isn't passed", input: `{"host":"web-1","older_than_hours":"24","ansible_become_user":"root"}`, wantStart: true},
{name: "a missing variable isn't launched", input: `{"host":"web-1"}`, wantStart: true},
{name: "all isn't a host", input: `{"host":"all","older_than_hours":"24"}`, wantStart: true},
{name: "a pattern isn't a host", input: `{"host":"web-*","older_than_hours":"24"}`, wantStart: true},
{name: "a list isn't a host", input: `{"host":"web-1,web-2","older_than_hours":"24"}`, wantStart: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fake := &fakeSemaphore{finalStatus: "success", limitFixed: tt.limitFixed}
srv := httptest.NewServer(fake)
defer srv.Close()
s, err := startConnector(srv.URL, tt.hostVar)
if (err == nil) != tt.wantStart {
t.Fatalf("start err = %v, want started %v", err, tt.wantStart)
}
if err != nil {
return
}
_, _, err = s.Invoke(t.Context(), "clean_tmp", jsontext.Value(tt.input), "run-1:investigate:4")
if launched := fake.launches > 0; launched != tt.wantLaunch || (err == nil) != tt.wantLaunch {
t.Fatalf("launched = %v, err = %v; want launched %v", launched, err, tt.wantLaunch)
}
if !tt.wantLaunch {
return
}
if got := fake.lastLaunch.Params.Limit; len(got) != 1 || got[0] != "web-1" {
t.Fatalf("limit = %v, want [web-1]", got)
}
if fake.lastLaunch.Environment != tt.wantEnv {
t.Fatalf("environment = %s, want %s", fake.lastLaunch.Environment, tt.wantEnv)
}
})
}
}
// TestTemplatesDeclareEffectsExplicitly guards the chat prohibition: a template
// is offered in chat only when the operator states both whether it changes
// privileges and whether it accesses secrets.
func TestTemplatesDeclareEffectsExplicitly(t *testing.T) {
tests := []struct {
name string
effect string
want [3]bool
}{
{name: "neither stated", effect: `{"reversibility":"irreversible"}`},
{name: "only one stated", effect: `{"reversibility":"irreversible","privilege_change":false}`},
{name: "both false", effect: `{"reversibility":"irreversible","privilege_change":false,"secret_access":false}`, want: [3]bool{true, false, false}},
{name: "secret access", effect: `{"reversibility":"irreversible","privilege_change":false,"secret_access":true}`, want: [3]bool{true, false, true}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var tpl Template
if err := json.Unmarshal([]byte(`{"action":"run","template_id":7,"effect":`+tt.effect+`}`), &tpl); err != nil {
t.Fatal(err)
}
e := (&semaphore{}).effect(tpl)
if got := [3]bool{e.GetEffectsDeclared(), e.GetPrivilegeChange(), e.GetSecretAccess()}; got != tt.want {
t.Fatalf("declared, privilege change, secret access = %v, want %v", got, tt.want)
}
})
}
}