SPB Git

Repository Public

policy_test.go 9.1 KB 222 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_test.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 */4142package policy4344import (45	"os"46	"path/filepath"47	"strings"48	"testing"49)5051func TestDefaultAndFiles(t *testing.T) {52	dir := t.TempDir()53	file := filepath.Join(dir, "policy.json")54	p, err := Load(file)55	if err != nil || strings.Join(p.Capabilities(), ",") != "diagnostic.run,inventory.refresh,service.health_check,service.logs.tail" {56		t.Fatalf("default policy: %v %v", p.Capabilities(), err)57	}58	if p.Allows("service.restart") || p.Allows("system.reboot") || p.Allows("job.run") {59		t.Fatal("default policy too permissive")60	}61	// Invalid JSON, unknown field, unknown type: deny all.62	for _, bad := range []string{`{`, `{"alow":["diagnostic.run"]}`, `{"allow":["rm.rf"]}`, `{"allow":[]} trailing`} {63		os.WriteFile(file, []byte(bad), 0o600)64		p, err := Load(file)65		if err == nil || len(p.Capabilities()) != 0 {66			t.Errorf("%q: must fail closed, got %v %v", bad, p.Capabilities(), err)67		}68	}69	// Writable by others: deny all even though the content is valid.70	os.WriteFile(file, []byte(`{"allow":["diagnostic.run"]}`), 0o600)71	os.Chmod(file, 0o666)72	if p, err := Load(file); err == nil || len(p.Capabilities()) != 0 {73		t.Error("world-writable policy accepted")74	}75	os.Chmod(file, 0o600)76	if p, err := Load(file); err != nil || !p.Allows("diagnostic.run") || p.Allows("inventory.refresh") {77		t.Errorf("valid policy: %v", err)78	}79	// Reboot needs both the type and the explicit switch.80	p, _ = Parse([]byte(`{"allow":["system.reboot","system.shutdown"],"allow_reboot":true}`))81	if !p.Allows("system.reboot") || p.Allows("system.shutdown") {82		t.Error("reboot switches")83	}84	if p, _ = Parse([]byte(`{"allow":["system.reboot"]}`)); p.Allows("system.reboot") {85		t.Error("reboot must default to refused")86	}87}8889func TestServiceGlobs(t *testing.T) {90	p, err := Parse([]byte(`{"allow":["service.restart"],"services":{"pm2":["api","worker-*","job-?"],"launchd":["io.example.*"]}}`))91	if err != nil {92		t.Fatal(err)93	}94	yes := [][2]string{{"pm2", "api"}, {"pm2", "worker-1"}, {"pm2", "worker-"}, {"pm2", "job-a"}, {"launchd", "io.example.web"}}95	no := [][2]string{{"pm2", "api2"}, {"pm2", "xworker-1"}, {"pm2", "job-ab"}, {"launchd", "io.other.web"}, {"systemd", "api"}, {"pm2", ""}, {"pm2", "worker-1\nrm"}, {"launchd", "com.apple.x"}}96	for _, c := range yes {97		if !p.ServiceAllowed(c[0], c[1]) {98			t.Errorf("%v should be allowed", c)99		}100	}101	for _, c := range no {102		if p.ServiceAllowed(c[0], c[1]) {103			t.Errorf("%v should be refused", c)104		}105	}106	if _, err := Parse([]byte(`{"allow":[],"services":{"pm2":["a/b"]}}`)); err == nil {107		t.Error("slash in pattern accepted")108	}109	if _, err := Parse([]byte(`{"allow":[],"services":{"cron":["a"]}}`)); err == nil {110		t.Error("unknown manager accepted")111	}112}113114func TestCachePaths(t *testing.T) {115	base, _ := filepath.EvalSymlinks(t.TempDir())116	root := filepath.Join(base, "caches")117	outside := filepath.Join(base, "precious")118	os.MkdirAll(filepath.Join(root, "npm"), 0o755)119	os.MkdirAll(outside, 0o755)120	os.Symlink(outside, filepath.Join(root, "evil")) // a cache replaced by a link pointing out121	os.WriteFile(filepath.Join(root, "file"), []byte("x"), 0o600)122	q := func(s string) string { return `"` + s + `"` }123124	// Declarations refused at load time.125	for name, path := range map[string]string{126		"traversal":   root + "/../precious",127		"relative":    "caches/npm",128		"outsideroot": outside,129		"trailing":    root + "/npm/",130		"prefixtrick": root + "-other/x",131	} {132		doc := `{"allow":["cache.purge"],"cache_roots":[` + q(root) + `],"caches":{"c":` + q(path) + `}}`133		if _, err := Parse([]byte(doc)); err == nil {134			t.Errorf("%s: declaration %q accepted", name, path)135		}136	}137	if _, err := Parse([]byte(`{"allow":[],"cache_roots":["/"],"caches":{}}`)); err == nil {138		t.Error("root / accepted")139	}140	doc := `{"allow":["cache.purge"],"cache_roots":[` + q(root) + `],"caches":{"npm":` + q(root+"/npm") + `,"evil":` + q(root+"/evil") + `,"file":` + q(root+"/file") + `,"gone":` + q(root+"/gone") + `}}`141	p, err := Parse([]byte(doc))142	if err != nil {143		t.Fatal(err)144	}145	if got, err := p.CachePath("npm"); err != nil || got != filepath.Join(root, "npm") {146		t.Errorf("npm: %q %v", got, err)147	}148	for _, name := range []string{"evil", "file", "gone", "undeclared", "../npm"} {149		if got, err := p.CachePath(name); err == nil {150			t.Errorf("cache %q resolved to %q; must be refused", name, got)151		}152	}153}154155const jobPolicy = `{"allow":["job.run"],"jobs":{"backup":{156  "argv":["/usr/local/bin/backup","--target","{target}","--level={level}","{name}","{dry}"],157  "params":{"target":{"type":"enum","values":["db","files"]},"level":{"type":"int","min":0,"max":9},158            "name":{"type":"string","pattern":"[a-z0-9_]+","max_len":16},"dry":{"type":"bool","default":"false"}},159  "env":{"MODE":"scheduled"},"timeout_s":60}}}`160161func TestJobTemplates(t *testing.T) {162	p, err := Parse([]byte(jobPolicy))163	if err != nil {164		t.Fatal(err)165	}166	jc, err := p.BuildJob("backup", map[string]any{"target": "db", "level": float64(3), "name": "nightly_1"})167	if err != nil {168		t.Fatal(err)169	}170	want := []string{"/usr/local/bin/backup", "--target", "db", "--level=3", "nightly_1", "false"}171	if strings.Join(jc.Argv, "\x00") != strings.Join(want, "\x00") || jc.Env["MODE"] != "scheduled" || jc.TimeoutS != 60 {172		t.Fatalf("%q", jc.Argv)173	}174	attacks := []map[string]any{175		{"target": "db; rm -rf /", "level": float64(1), "name": "a"},176		{"target": "db", "level": float64(1), "name": "a b"},177		{"target": "db", "level": float64(1), "name": "$(id)"},178		{"target": "db", "level": float64(1), "name": "a\nb"},179		{"target": "db", "level": float64(1), "name": "--delete"},180		{"target": "db", "level": float64(1), "name": "{target}"},181		{"target": "db", "level": float64(1), "name": "aaaaaaaaaaaaaaaaaaaaaaaaa"},182		{"target": "db", "level": float64(10), "name": "a"},183		{"target": "db", "level": float64(-1), "name": "a"},184		{"target": "db", "level": 1.5, "name": "a"},185		{"target": "db", "level": "1; id", "name": "a"},186		{"target": "db", "level": float64(1), "name": float64(7)},187		{"target": []any{"db"}, "level": float64(1), "name": "a"},188		{"target": "db", "level": float64(1), "name": "a", "extra": "x"},189		{"target": "db", "level": float64(1)},190		{"target": "db", "level": float64(1), "name": "a", "dry": "yes"},191	}192	for i, a := range attacks {193		if jc, err := p.BuildJob("backup", a); err == nil {194			t.Errorf("attack %d accepted: %q", i, jc.Argv)195		}196	}197	if _, err := p.BuildJob("nope", nil); err == nil {198		t.Error("unknown template accepted")199	}200	// A value is substituted once and never re-scanned.201	p2, _ := Parse([]byte(`{"allow":["job.run"],"jobs":{"j":{"argv":["/bin/echo","{a}","{b}"],"params":{"a":{"type":"string","pattern":".*"},"b":{"type":"string","pattern":".*"}}}}}`))202	jc, err = p2.BuildJob("j", map[string]any{"a": "{b}", "b": "SECRET"})203	if err != nil || jc.Argv[1] != "{b}" || len(jc.Argv) != 3 {204		t.Errorf("re-scan: %+v %v", jc, err)205	}206	bad := []string{207		`{"allow":[],"jobs":{"j":{"argv":["backup"]}}}`,208		`{"allow":[],"jobs":{"j":{"argv":["{prog}"],"params":{"prog":{"type":"string","pattern":".*"}}}}}`,209		`{"allow":[],"jobs":{"j":{"argv":["/bin/sh","-c","{x}"]}}}`,210		`{"allow":[],"jobs":{"j":{"argv":["/bin/x","{x}"],"params":{"x":{"type":"string"}}}}}`,211		`{"allow":[],"jobs":{"j":{"argv":["/bin/x","{x"],"params":{}}}}}`,212		`{"allow":[],"jobs":{"j":{"argv":["/bin/x"],"params":{"unused":{"type":"bool"}}}}}`,213		`{"allow":[],"jobs":{"j":{"argv":["/bin/x","{x}"],"params":{"x":{"type":"enum","values":["-rf"]}}}}}`,214		`{"allow":[],"jobs":{"../j":{"argv":["/bin/x"]}}}`,215	}216	for _, b := range bad {217		if _, err := Parse([]byte(b)); err == nil {218			t.Errorf("template accepted: %s", b)219		}220	}221}222
Files main
Menu

Theme