SPB Git

Repository Public

policy.go 17.6 KB 568 lines go

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Command Center (MCC)8 * File             : services/internal/agent/policy/policy.go9 * Module           : services10 * Repository       : https://git.spboucher.ai/maclustr-command-center11 * Project Website  : https://clustr.spboucher.ai12 * Created          : 2026-11-1813 * Last Modified    : 2026-11-1814 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Package policy is the node owner's local allowlist. The server can ask;43// only this file decides what the agent is willing to do on the machine.44//45// policy.json (in the state directory, owner-writable only):46//47//	{48//	  "allow": ["inventory.refresh", "diagnostic.run", "service.health_check", "service.logs.tail", "service.restart"],49//	  "services": { "pm2": ["api", "worker-*"], "launchd": ["io.example.*"], "systemd": ["caddy.service"] },50//	  "cache_roots": ["/Users/me/Library/Caches"],51//	  "caches": { "npm": "/Users/me/Library/Caches/npm" },52//	  "jobs": {53//	    "backup": {54//	      "argv": ["/usr/local/bin/backup", "--target", "{target}", "--level={level}"],55//	      "params": {56//	        "target": {"type": "enum", "values": ["db", "files"]},57//	        "level":  {"type": "int", "min": 0, "max": 9}58//	      },59//	      "env": {"BACKUP_MODE": "scheduled"},60//	      "timeout_s": 90061//	    }62//	  },63//	  "allow_reboot": false,64//	  "allow_shutdown": false65//	}66//67// When the file is absent the default policy applies (read-only commands).68// When it is present but invalid, or writable by group/others, every command69// is refused: a policy that cannot be trusted fails closed.70package policy7172import (73	"encoding/json"74	"errors"75	"fmt"76	"os"77	"path"78	"path/filepath"79	"regexp"80	"sort"81	"strconv"82	"strings"83)8485// Implemented lists every command type the agent can execute.86var Implemented = []string{87	"inventory.refresh", "diagnostic.run", "service.health_check", "service.logs.tail",88	"service.start", "service.stop", "service.restart", "agent.restart", "cache.purge",89	"job.run", "job.cancel", "system.reboot", "system.shutdown",90}9192// DefaultAllow is the allowlist used when no policy file exists.93var DefaultAllow = []string{"inventory.refresh", "diagnostic.run", "service.health_check", "service.logs.tail"}9495var implemented = func() map[string]bool {96	m := map[string]bool{}97	for _, t := range Implemented {98		m[t] = true99	}100	return m101}()102103// Policy is a validated policy file.104type Policy struct {105	Allow         []string            `json:"allow"`106	Services      map[string][]string `json:"services,omitempty"`107	CacheRoots    []string            `json:"cache_roots,omitempty"`108	Caches        map[string]string   `json:"caches,omitempty"`109	Jobs          map[string]*Job     `json:"jobs,omitempty"`110	AllowReboot   bool                `json:"allow_reboot,omitempty"`111	AllowShutdown bool                `json:"allow_shutdown,omitempty"`112113	allow map[string]bool114}115116// Job is a job template: a fixed argv with typed placeholders. There is no117// shell: each argv element becomes exactly one argument of the program.118type Job struct {119	Argv     []string          `json:"argv"`120	Params   map[string]*Param `json:"params,omitempty"`121	Env      map[string]string `json:"env,omitempty"`122	Cwd      string            `json:"cwd,omitempty"`123	TimeoutS int               `json:"timeout_s,omitempty"`124}125126// Param describes one job parameter.127type Param struct {128	Type     string   `json:"type"`              // string | int | enum | bool129	Pattern  string   `json:"pattern,omitempty"` // string: required, matched against the whole value130	MaxLen   int      `json:"max_len,omitempty"` // string: default 128131	Values   []string `json:"values,omitempty"`  // enum132	Min      *int64   `json:"min,omitempty"`     // int133	Max      *int64   `json:"max,omitempty"`     // int134	Optional bool     `json:"optional,omitempty"`135	Default  *string  `json:"default,omitempty"`136	// AllowLeadingDash permits values starting with "-". Off by default: a137	// value such as "--delete" would be read by the program as an option.138	AllowLeadingDash bool `json:"allow_leading_dash,omitempty"`139140	re *regexp.Regexp141}142143// Default returns the policy applied when no file exists.144func Default() *Policy {145	p := &Policy{Allow: append([]string(nil), DefaultAllow...)}146	p.index()147	return p148}149150// DenyAll returns a policy that refuses everything.151func DenyAll() *Policy {152	p := &Policy{Allow: []string{}}153	p.index()154	return p155}156157func (p *Policy) index() {158	p.allow = map[string]bool{}159	for _, t := range p.Allow {160		p.allow[t] = true161	}162}163164// Load reads and validates a policy file. A missing file yields Default().165// On any other problem the returned policy is DenyAll() and err explains why.166func Load(file string) (*Policy, error) {167	st, err := os.Lstat(file)168	if errors.Is(err, os.ErrNotExist) {169		return Default(), nil170	}171	if err != nil {172		return DenyAll(), err173	}174	if !st.Mode().IsRegular() {175		return DenyAll(), errors.New("policy.json must be a regular file")176	}177	if st.Mode().Perm()&0o022 != 0 {178		return DenyAll(), fmt.Errorf("policy.json is writable by group or others (mode %o): refusing every command", st.Mode().Perm())179	}180	b, err := os.ReadFile(file)181	if err != nil {182		return DenyAll(), err183	}184	p, err := Parse(b)185	if err != nil {186		return DenyAll(), err187	}188	return p, nil189}190191// Parse validates a policy document.192func Parse(b []byte) (*Policy, error) {193	dec := json.NewDecoder(strings.NewReader(string(b)))194	dec.DisallowUnknownFields() // a typo must not silently change the policy195	var p Policy196	if err := dec.Decode(&p); err != nil {197		return nil, fmt.Errorf("policy.json: %w", err)198	}199	if dec.More() {200		return nil, errors.New("policy.json: trailing data")201	}202	for _, t := range p.Allow {203		if !implemented[t] {204			return nil, fmt.Errorf("policy.json: unknown command type %q in allow", t)205		}206	}207	for mgr, pats := range p.Services {208		switch mgr {209		case "pm2", "launchd", "systemd", "docker":210		default:211			return nil, fmt.Errorf("policy.json: unknown service manager %q", mgr)212		}213		for _, pat := range pats {214			if pat == "" || strings.ContainsAny(pat, "/\x00\n") {215				return nil, fmt.Errorf("policy.json: invalid service pattern %q", pat)216			}217			if _, err := path.Match(pat, "x"); err != nil {218				return nil, fmt.Errorf("policy.json: invalid service pattern %q", pat)219			}220		}221	}222	for i, r := range p.CacheRoots {223		if !filepath.IsAbs(r) || filepath.Clean(r) != r || r == "/" {224			return nil, fmt.Errorf("policy.json: cache root %q must be a clean absolute path other than /", r)225		}226		p.CacheRoots[i] = r227	}228	for name, cp := range p.Caches {229		if !nameRE.MatchString(name) {230			return nil, fmt.Errorf("policy.json: invalid cache name %q", name)231		}232		if !filepath.IsAbs(cp) || filepath.Clean(cp) != cp {233			return nil, fmt.Errorf("policy.json: cache %q: path must be absolute and clean (no .. or trailing slash)", name)234		}235		if !underAny(cp, p.CacheRoots) {236			return nil, fmt.Errorf("policy.json: cache %q: path is not under a cache root", name)237		}238	}239	for name, j := range p.Jobs {240		if !nameRE.MatchString(name) {241			return nil, fmt.Errorf("policy.json: invalid job name %q", name)242		}243		if j == nil {244			return nil, fmt.Errorf("policy.json: job %q is empty", name)245		}246		if err := j.validate(); err != nil {247			return nil, fmt.Errorf("policy.json: job %q: %w", name, err)248		}249	}250	p.index()251	return &p, nil252}253254var (255	nameRE        = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)256	placeholderRE = regexp.MustCompile(`\{([A-Za-z_][A-Za-z0-9_]*)\}`)257	envNameRE     = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)258)259260func (j *Job) validate() error {261	if len(j.Argv) == 0 {262		return errors.New("argv is empty")263	}264	if !filepath.IsAbs(j.Argv[0]) || placeholderRE.MatchString(j.Argv[0]) || strings.ContainsAny(j.Argv[0], "{}") {265		return errors.New("argv[0] must be an absolute program path without placeholder")266	}267	if j.TimeoutS < 0 || j.TimeoutS > 24*3600 {268		return errors.New("timeout_s out of range")269	}270	if j.Cwd != "" && !filepath.IsAbs(j.Cwd) {271		return errors.New("cwd must be absolute")272	}273	for k, v := range j.Env {274		if !envNameRE.MatchString(k) || strings.ContainsRune(v, 0) {275			return fmt.Errorf("invalid env entry %q", k)276		}277	}278	used := map[string]bool{}279	for _, a := range j.Argv[1:] {280		if strings.ContainsRune(a, 0) {281			return errors.New("argv contains NUL")282		}283		for _, m := range placeholderRE.FindAllStringSubmatch(a, -1) {284			if j.Params[m[1]] == nil {285				return fmt.Errorf("placeholder {%s} has no declared parameter", m[1])286			}287			used[m[1]] = true288		}289		// Anything brace-like that is not a declared placeholder is a mistake.290		if rest := placeholderRE.ReplaceAllString(a, ""); strings.ContainsAny(rest, "{}") {291			return fmt.Errorf("argv element %q has a malformed placeholder", a)292		}293	}294	for name, sp := range j.Params {295		if sp == nil {296			return fmt.Errorf("parameter %q is empty", name)297		}298		if !used[name] {299			return fmt.Errorf("parameter %q is not used by argv", name)300		}301		switch sp.Type {302		case "string":303			if sp.Pattern == "" {304				return fmt.Errorf("parameter %q: a string needs a pattern", name)305			}306			re, err := regexp.Compile(`^(?:` + sp.Pattern + `)$`)307			if err != nil {308				return fmt.Errorf("parameter %q: bad pattern: %w", name, err)309			}310			sp.re = re311			if sp.MaxLen == 0 {312				sp.MaxLen = 128313			}314			if sp.MaxLen < 0 || sp.MaxLen > 4096 {315				return fmt.Errorf("parameter %q: max_len out of range", name)316			}317		case "int":318			if sp.Min != nil && sp.Max != nil && *sp.Min > *sp.Max {319				return fmt.Errorf("parameter %q: min > max", name)320			}321		case "enum":322			if len(sp.Values) == 0 {323				return fmt.Errorf("parameter %q: enum needs values", name)324			}325			for _, v := range sp.Values {326				if err := safeValue(v, sp.AllowLeadingDash); err != nil {327					return fmt.Errorf("parameter %q: enum value: %w", name, err)328				}329			}330		case "bool":331		default:332			return fmt.Errorf("parameter %q: unknown type %q", name, sp.Type)333		}334		if sp.Default != nil {335			if _, err := sp.check(name, *sp.Default); err != nil {336				return fmt.Errorf("default: %w", err)337			}338		}339	}340	return nil341}342343func safeValue(v string, allowDash bool) error {344	for _, r := range v {345		if r < 0x20 || r == 0x7f {346			return errors.New("control character in value")347		}348	}349	if !allowDash && strings.HasPrefix(v, "-") {350		return errors.New("value must not start with '-'")351	}352	return nil353}354355// check validates one raw value (JSON scalar rendered as text) and returns356// the argument text.357func (sp *Param) check(name string, v string) (string, error) {358	switch sp.Type {359	case "string":360		if len(v) > sp.MaxLen {361			return "", fmt.Errorf("parameter %q is too long", name)362		}363		if err := safeValue(v, sp.AllowLeadingDash); err != nil {364			return "", fmt.Errorf("parameter %q: %w", name, err)365		}366		if !sp.re.MatchString(v) {367			return "", fmt.Errorf("parameter %q does not match its pattern", name)368		}369		return v, nil370	case "int":371		n, err := strconv.ParseInt(v, 10, 64)372		if err != nil {373			return "", fmt.Errorf("parameter %q is not an integer", name)374		}375		if sp.Min != nil && n < *sp.Min || sp.Max != nil && n > *sp.Max {376			return "", fmt.Errorf("parameter %q is out of range", name)377		}378		if n < 0 && !sp.AllowLeadingDash && (sp.Min == nil || *sp.Min >= 0) {379			return "", fmt.Errorf("parameter %q must not be negative", name)380		}381		return strconv.FormatInt(n, 10), nil382	case "enum":383		for _, a := range sp.Values {384			if a == v {385				return v, nil386			}387		}388		return "", fmt.Errorf("parameter %q is not an allowed value", name)389	case "bool":390		if v == "true" || v == "false" {391			return v, nil392		}393		return "", fmt.Errorf("parameter %q is not a boolean", name)394	}395	return "", fmt.Errorf("parameter %q has an unknown type", name)396}397398// Allows reports whether a command type is permitted at all.399func (p *Policy) Allows(cmdType string) bool {400	if !implemented[cmdType] || !p.allow[cmdType] {401		return false402	}403	switch cmdType {404	case "system.reboot":405		return p.AllowReboot406	case "system.shutdown":407		return p.AllowShutdown408	}409	return true410}411412// Capabilities is the sorted list of command types this policy permits; it413// is what the agent declares to the server.414func (p *Policy) Capabilities() []string {415	out := []string{}416	for _, t := range Implemented {417		if p.Allows(t) {418			out = append(out, t)419		}420	}421	// A job template is runnable on this node only if the local policy422	// defines it; the server learns the names as "job.run:<template>".423	if p.Allows("job.run") {424		for name := range p.Jobs {425			out = append(out, "job.run:"+name)426		}427	}428	sort.Strings(out)429	return out430}431432// ServiceAllowed reports whether a service may be started, stopped or433// restarted. Patterns are exact names or globs (*, ?, [set]) on the whole name.434func (p *Policy) ServiceAllowed(manager, name string) bool {435	if name == "" || strings.ContainsAny(name, "\x00\n") {436		return false437	}438	for _, pat := range p.Services[manager] {439		if pat == name {440			return true441		}442		if ok, err := path.Match(pat, name); err == nil && ok {443			return true444		}445	}446	return false447}448449func underAny(p string, roots []string) bool {450	for _, r := range roots {451		if p == r || strings.HasPrefix(p, r+string(filepath.Separator)) {452			return true453		}454	}455	return false456}457458// CachePath resolves a logical cache name to the real directory to purge.459// The declared path and the declared roots are resolved through symlinks,460// and the real path must still lie under a real root: a cache directory461// replaced by a symlink to somewhere else is refused.462func (p *Policy) CachePath(name string) (string, error) {463	declared, ok := p.Caches[name]464	if !ok {465		return "", fmt.Errorf("cache %q is not in the local allowlist", name)466	}467	if !underAny(declared, p.CacheRoots) {468		return "", fmt.Errorf("cache %q is not under an allowed root", name)469	}470	real, err := filepath.EvalSymlinks(declared)471	if err != nil {472		return "", fmt.Errorf("cache %q: %w", name, err)473	}474	st, err := os.Stat(real)475	if err != nil || !st.IsDir() {476		return "", fmt.Errorf("cache %q is not a directory", name)477	}478	var realRoots []string479	for _, r := range p.CacheRoots {480		if rr, err := filepath.EvalSymlinks(r); err == nil {481			realRoots = append(realRoots, rr)482		}483	}484	if !underAny(real, realRoots) {485		return "", fmt.Errorf("cache %q resolves outside the allowed roots", name)486	}487	if home, err := os.UserHomeDir(); err == nil && (real == home || real == filepath.Dir(home)) {488		return "", fmt.Errorf("cache %q resolves to a home directory", name)489	}490	if real == "/" || strings.Count(real, string(filepath.Separator)) < 2 {491		return "", fmt.Errorf("cache %q resolves too close to the filesystem root", name)492	}493	return real, nil494}495496// JobCommand is a fully resolved job invocation.497type JobCommand struct {498	Argv     []string499	Env      map[string]string500	Cwd      string501	TimeoutS int502}503504// BuildJob validates the parameters of a job template and substitutes them505// into argv. Each placeholder is replaced inside its own argv element: a506// value can never add, split or reorder arguments, and no shell is involved.507func (p *Policy) BuildJob(template string, params map[string]any) (*JobCommand, error) {508	j, ok := p.Jobs[template]509	if !ok {510		return nil, fmt.Errorf("job template %q is not in the local allowlist", template)511	}512	for k := range params {513		if j.Params[k] == nil {514			return nil, fmt.Errorf("unknown parameter %q", k)515		}516	}517	vals := map[string]string{}518	for name, sp := range j.Params {519		raw, given := params[name]520		var text string521		switch {522		case given:523			switch t := raw.(type) {524			case string:525				text = t526			case bool:527				text = strconv.FormatBool(t)528			case float64:529				if t != float64(int64(t)) {530					return nil, fmt.Errorf("parameter %q is not an integer", name)531				}532				text = strconv.FormatInt(int64(t), 10)533			case json.Number:534				text = t.String()535			default:536				return nil, fmt.Errorf("parameter %q must be a string, number or boolean", name)537			}538			if sp.Type == "string" || sp.Type == "enum" {539				if _, isString := raw.(string); !isString {540					return nil, fmt.Errorf("parameter %q must be a string", name)541				}542			}543		case sp.Default != nil:544			text = *sp.Default545		case sp.Optional:546			text = ""547			vals[name] = ""548			continue549		default:550			return nil, fmt.Errorf("missing parameter %q", name)551		}552		v, err := sp.check(name, text)553		if err != nil {554			return nil, err555		}556		vals[name] = v557	}558	argv := make([]string, 0, len(j.Argv))559	argv = append(argv, j.Argv[0])560	for _, a := range j.Argv[1:] {561		// Single pass: a substituted value is never re-scanned for placeholders.562		argv = append(argv, placeholderRE.ReplaceAllStringFunc(a, func(m string) string {563			return vals[m[1:len(m)-1]]564		}))565	}566	return &JobCommand{Argv: argv, Env: j.Env, Cwd: j.Cwd, TimeoutS: j.TimeoutS}, nil567}568
Files main
Menu

Theme