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

407 lines
13 KiB
Go

package main
import (
"bytes"
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"maps"
"net/http"
"net/url"
"regexp"
"slices"
"strconv"
"strings"
"time"
"github.com/samcharles93/archipelago/sdk/connector"
connectorv1 "github.com/samcharles93/archipelago/sdk/connector/v1"
)
const (
pollEvery = 2 * time.Second
taskDeadline = 15 * time.Minute
outputLines = 60
recentTasks = 200
messagePrefix = "archie "
)
// Template is one job template the operator lets Archie launch, declared in
// the templates setting.
type Template struct {
Action string `json:"action"`
TemplateID int `json:"template_id"`
Description string `json:"description"`
Effect struct {
ReadOnly bool `json:"read_only"`
// Reversibility is "undone_automatically", "recoverable" or
// "irreversible".
Reversibility string `json:"reversibility"`
Summary string `json:"summary"`
// PrivilegeChange and SecretAccess say whether the template grants
// access, changes identities or policies, or reads or exports secrets.
// A template that sets both states its effects; one that omits either
// is unavailable in chat.
PrivilegeChange *bool `json:"privilege_change"`
SecretAccess *bool `json:"secret_access"`
} `json:"effect"`
Target struct {
Kind string `json:"kind"`
Environment string `json:"environment"`
Disposable bool `json:"disposable"`
} `json:"target"`
// Vars are the extra variables the template takes, each with a
// description. Every one is required, so the judged action is complete.
Vars map[string]string `json:"vars"`
// HostVar names an extra variable that also carries the host, for a
// template whose playbook targets it rather than honouring a task's limit.
HostVar string `json:"host_var"`
}
var validAction = regexp.MustCompile(`^[a-z][a-z0-9_]{0,62}$`)
type semaphore struct {
base *url.URL
project int
token string
templates map[string]Template
client *http.Client
pollEvery time.Duration
deadline time.Duration
}
func newSemaphore(cfg connector.Config) (*semaphore, error) {
base, err := url.Parse(cfg.Settings["base_url"])
if err != nil || (base.Scheme != "https" && base.Scheme != "http") || base.Host == "" {
return nil, fmt.Errorf("base_url %q must be an http or https URL", cfg.Settings["base_url"])
}
project, err := strconv.Atoi(cfg.Settings["project_id"])
if err != nil || project <= 0 {
return nil, fmt.Errorf("project_id %q must be a positive number", cfg.Settings["project_id"])
}
token := cfg.Secrets["api.token"]
if token == "" {
return nil, errors.New("the api credential slot needs a bearer token")
}
var list []Template
if err := json.Unmarshal([]byte(cfg.Settings["templates"]), &list); err != nil {
return nil, fmt.Errorf("templates setting: %w", err)
}
s := &semaphore{
base: base, project: project, token: token, templates: map[string]Template{}, client: &http.Client{Timeout: 30 * time.Second},
pollEvery: pollEvery, deadline: taskDeadline,
}
for _, t := range list {
if !validAction.MatchString(t.Action) || t.TemplateID <= 0 {
return nil, fmt.Errorf("template %q needs a lowercase action name and a template_id", t.Action)
}
if _, err := reversibility(t.Effect.Reversibility, t.Effect.ReadOnly); err != nil {
return nil, fmt.Errorf("template %q: %w", t.Action, err)
}
if _, ok := t.Vars[t.HostVar]; ok {
return nil, fmt.Errorf("template %q: host_var %q is also one of its vars", t.Action, t.HostVar)
}
s.templates[t.Action] = t
}
ctx, cancel := context.WithTimeout(context.Background(), s.client.Timeout)
defer cancel()
if err := s.confined(ctx); err != nil {
return nil, err
}
return s, nil
}
// confined refuses a template that would run against more than the host it
// is given. Semaphore drops a task's limit unless the template allows
// overriding it, so the playbook would run against the whole inventory.
func (s *semaphore) confined(ctx context.Context) error {
for _, name := range slices.Sorted(maps.Keys(s.templates)) {
t := s.templates[name]
var tpl struct {
TaskParams struct {
AllowOverrideLimit bool `json:"allow_override_limit"`
} `json:"task_params"`
}
if err := s.do(ctx, http.MethodGet, fmt.Sprintf("/api/project/%d/templates/%d", s.project, t.TemplateID), nil, &tpl); err != nil {
return fmt.Errorf("template %q: %w", t.Action, err)
}
if !tpl.TaskParams.AllowOverrideLimit && t.HostVar == "" {
return fmt.Errorf("template %q: Semaphore template %d ignores a task's limit, so it would run against every host; allow overriding the limit or set host_var", t.Action, t.TemplateID)
}
}
return nil
}
func reversibility(name string, readOnly bool) (connectorv1.Reversibility, error) {
switch name {
case "undone_automatically":
return connectorv1.Reversibility_REVERSIBILITY_UNDONE_AUTOMATICALLY, nil
case "recoverable":
return connectorv1.Reversibility_REVERSIBILITY_RECOVERABLE, nil
case "irreversible":
return connectorv1.Reversibility_REVERSIBILITY_IRREVERSIBLE, nil
case "":
if readOnly {
return connectorv1.Reversibility_REVERSIBILITY_UNSPECIFIED, nil
}
}
return 0, fmt.Errorf("reversibility %q must be undone_automatically, recoverable or irreversible", name)
}
func (s *semaphore) effect(t Template) *connectorv1.Effect {
r, _ := reversibility(t.Effect.Reversibility, t.Effect.ReadOnly)
e := &connectorv1.Effect{ReadOnly: t.Effect.ReadOnly, Reversibility: r, Summary: t.Effect.Summary}
if t.Effect.PrivilegeChange != nil && t.Effect.SecretAccess != nil {
e.EffectsDeclared = true
e.PrivilegeChange = *t.Effect.PrivilegeChange
e.SecretAccess = *t.Effect.SecretAccess
}
return e
}
func (s *semaphore) Describe() connector.Description {
var d connector.Description
for _, name := range slices.Sorted(maps.Keys(s.templates)) {
t := s.templates[name]
d.Actions = append(d.Actions, &connectorv1.ActionType{
Name: t.Action, Description: t.Description, InputSchema: inputSchema(t),
Effect: s.effect(t), Idempotent: true,
})
}
return d
}
// inputSchema is the host to limit the run to, and every declared variable.
func inputSchema(t Template) []byte {
props := map[string]any{"host": map[string]any{"type": "string", "description": "The inventory host to run against."}}
required := []string{"host"}
for name, desc := range t.Vars {
props[name] = map[string]any{"type": "string", "description": desc}
required = append(required, name)
}
slices.Sort(required)
b, _ := json.Marshal(map[string]any{"type": "object", "additionalProperties": false, "required": required, "properties": props})
return b
}
// actionInput is an action's host and the template's variables.
type actionInput struct {
Host string
Vars map[string]string
}
func (s *semaphore) parse(action string, raw jsontext.Value) (Template, actionInput, error) {
t, ok := s.templates[action]
if !ok {
return Template{}, actionInput{}, fmt.Errorf("no action named %q", action)
}
var in map[string]string
if err := json.Unmarshal(raw, &in); err != nil {
return Template{}, actionInput{}, fmt.Errorf("input: %w", err)
}
host := in["host"]
if !validHost.MatchString(host) || host == "all" {
return Template{}, actionInput{}, fmt.Errorf("host %q must name one inventory host", host)
}
delete(in, "host")
for name := range in {
if _, ok := t.Vars[name]; !ok {
return Template{}, actionInput{}, fmt.Errorf("%q isn't a variable of %s", name, action)
}
}
for name := range t.Vars {
if in[name] == "" {
return Template{}, actionInput{}, fmt.Errorf("input needs %s", name)
}
}
return t, actionInput{Host: host, Vars: in}, nil
}
// validHost is one inventory name: no patterns, lists or exclusions that
// would widen a limit.
var validHost = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,252}$`)
func (s *semaphore) Resolve(_ context.Context, action string, raw jsontext.Value) (*connectorv1.ResolveResponse, error) {
t, in, err := s.parse(action, raw)
if err != nil {
return nil, err
}
effect := s.effect(t)
effect.Summary = fill(effect.Summary, in)
return &connectorv1.ResolveResponse{
Target: &connectorv1.Target{Kind: t.Target.Kind, Id: in.Host, Environment: t.Target.Environment, Disposable: t.Target.Disposable},
Effect: effect,
}, nil
}
// fill puts this action's values into a declared summary's {host} and {var}
// placeholders, so the person approving it reads what this one does.
func fill(summary string, in actionInput) string {
pairs := []string{"{host}", in.Host}
for name, v := range in.Vars {
pairs = append(pairs, "{"+name+"}", v)
}
return strings.NewReplacer(pairs...).Replace(summary)
}
type task struct {
ID int `json:"id"`
TemplateID int `json:"template_id"`
Status string `json:"status"`
Message string `json:"message,omitempty"`
}
// Invoke launches the template, unless a task carrying this idempotency key
// already exists, and waits for it to finish. A task still running at the
// deadline is reported as an unknown outcome, never launched again.
func (s *semaphore) Invoke(ctx context.Context, action string, raw jsontext.Value, key string) (jsontext.Value, bool, error) {
t, in, err := s.parse(action, raw)
if err != nil {
return nil, false, err
}
if key == "" {
return nil, false, errors.New("an idempotency key is required")
}
message := messagePrefix + key
tk, found, err := s.findTask(ctx, t.TemplateID, message)
if err != nil {
return nil, true, err
}
if !found {
if tk, err = s.launch(ctx, t, in, message); err != nil {
return nil, true, err
}
}
done, err := s.wait(ctx, tk.ID)
if err != nil {
return nil, true, err
}
out, err := s.result(ctx, done)
return out, false, err
}
// findTask looks through the project's recent tasks for one this key
// started.
func (s *semaphore) findTask(ctx context.Context, templateID int, message string) (task, bool, error) {
var tasks []task
if err := s.do(ctx, http.MethodGet, fmt.Sprintf("/api/project/%d/tasks/last?count=%d", s.project, recentTasks), nil, &tasks); err != nil {
return task{}, false, fmt.Errorf("list tasks: %w", err)
}
for _, tk := range tasks {
if tk.TemplateID == templateID && tk.Message == message {
return tk, true, nil
}
}
return task{}, false, nil
}
func (s *semaphore) launch(ctx context.Context, t Template, in actionInput, message string) (task, error) {
vars := maps.Clone(in.Vars)
if vars == nil {
vars = map[string]string{}
}
if t.HostVar != "" {
vars[t.HostVar] = in.Host
}
env, err := json.Marshal(vars, json.Deterministic(true))
if err != nil {
return task{}, err
}
body := map[string]any{
"template_id": t.TemplateID, "environment": string(env), "message": message,
"params": map[string]any{"limit": []string{in.Host}},
}
var tk task
if err := s.do(ctx, http.MethodPost, fmt.Sprintf("/api/project/%d/tasks", s.project), body, &tk); err != nil {
return task{}, fmt.Errorf("launch template %d: %w", t.TemplateID, err)
}
return tk, nil
}
// wait polls the task until it ends. A failed status read is retried until
// the deadline: Semaphore can stall reads while a task starts, and the task
// runs on regardless.
func (s *semaphore) wait(ctx context.Context, id int) (task, error) {
ctx, cancel := context.WithTimeout(ctx, s.deadline)
defer cancel()
var last string
for {
var tk task
if err := s.do(ctx, http.MethodGet, fmt.Sprintf("/api/project/%d/tasks/%d", s.project, id), nil, &tk); err != nil {
last = err.Error()
} else {
switch tk.Status {
case "success", "error", "stopped", "rejected":
return tk, nil
}
last = tk.Status
}
select {
case <-ctx.Done():
return task{}, fmt.Errorf("task %d launched, last seen %s: %w", id, last, ctx.Err())
case <-time.After(s.pollEvery):
}
}
}
type outputLine struct {
Output string `json:"output"`
}
// result reports how the task ended with the tail of its log. A task that
// ended in error is a known failure.
func (s *semaphore) result(ctx context.Context, tk task) (jsontext.Value, error) {
var lines []outputLine
if err := s.do(ctx, http.MethodGet, fmt.Sprintf("/api/project/%d/tasks/%d/output", s.project, tk.ID), nil, &lines); err != nil {
return nil, fmt.Errorf("task %d output: %w", tk.ID, err)
}
tail := make([]string, 0, outputLines)
for _, l := range lines[max(0, len(lines)-outputLines):] {
tail = append(tail, l.Output)
}
out, err := json.Marshal(map[string]any{"task_id": tk.ID, "status": tk.Status, "output": strings.Join(tail, "\n")})
if err != nil {
return nil, err
}
if tk.Status != "success" {
return nil, fmt.Errorf("task %d ended %s: %s", tk.ID, tk.Status, strings.Join(tail, "\n"))
}
return out, nil
}
// do calls one API path (which may carry a query) and decodes the reply.
func (s *semaphore) do(ctx context.Context, method, path string, body, out any) error {
ref, err := url.Parse(path)
if err != nil {
return err
}
target := s.base.JoinPath(ref.Path)
target.RawQuery = ref.RawQuery
payload := []byte{}
if body != nil {
if payload, err = json.Marshal(body); err != nil {
return err
}
}
req, err := http.NewRequestWithContext(ctx, method, target.String(), bytes.NewReader(payload))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+s.token)
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := s.client.Do(req)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Errorf("%s %s: %s", method, ref.Path, resp.Status)
}
return json.UnmarshalRead(resp.Body, out)
}