clean up of the codebase

This commit is contained in:
ari committed 2026-11-01 13:01:54 -05:00
1 parent 7822529a38
commit 0ac61b4ece
52 files changed
+2545 -2274

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
package model
import (
"fmt"
"strconv"
"strings"
"time"
)
type Size struct {
MemoryMB int `toml:"memory_mb"`
CPUs float64 `toml:"cpus"`
}
func (s Size) Add(o Size) Size { return Size{s.MemoryMB + o.MemoryMB, s.CPUs + o.CPUs} }
func (s Size) Sub(o Size) Size { return Size{s.MemoryMB - o.MemoryMB, s.CPUs - o.CPUs} }
func (s Size) Fits(in Size) bool {
return s.MemoryMB <= in.MemoryMB && s.CPUs <= in.CPUs+1e-9
}
func (s Size) String() string {
mem := fmt.Sprintf("%d MB", s.MemoryMB)
if s.MemoryMB >= 1024 && s.MemoryMB%1024 == 0 {
mem = fmt.Sprintf("%d GB", s.MemoryMB/1024)
}
cpu := strconv.FormatFloat(s.CPUs, 'f', -1, 64) + " CPUs"
if s.CPUs == 1 {
cpu = "1 CPU"
}
return mem + " RAM, " + cpu
}
type OwnerKind string
const (
OwnerUser OwnerKind = "user"
OwnerChannel OwnerKind = "channel"
)
type Owner struct {
ID string `json:"id"`
Kind OwnerKind `json:"kind"`
Machine string `json:"machine"`
Secret string `json:"secret"`
Size Size `json:"size"`
LastActive time.Time `json:"last_active"`
Node string `json:"node,omitempty"`
Drive string `json:"drive,omitempty"`
StorageMinMB int64 `json:"storage_min_mb"`
StorageMaxMB int64 `json:"storage_max_mb"`
// 0 means the config default.
IdleTimeout time.Duration `json:"idle_timeout,omitempty"`
}
const Indefinite time.Duration = -1
type Session struct {
Channel string `json:"channel"`
ThreadTS string `json:"thread_ts"`
OwnerID string `json:"owner_id"`
ACPID string `json:"acp_id"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
}
func MachineName(id string, kind OwnerKind) string {
if kind == OwnerChannel {
return "c-" + strings.ToLower(id)
}
return "u-" + strings.ToLower(id)
}
func IsOurs(name string) bool { return strings.HasPrefix(name, "u-") || strings.HasPrefix(name, "c-") }
+244
View File
@@ -0,0 +1,244 @@
package model
import (
"errors"
"fmt"
"maps"
"slices"
"sort"
"strings"
)
type Action string
const (
ActScale Action = "scale"
ActStorage Action = "storage"
ActMove Action = "move"
ActKeep Action = "keep"
ActManage Action = "manage"
)
var (
AllActions = []Action{ActScale, ActStorage, ActMove, ActKeep}
GrantActions = append(slices.Clone(AllActions), ActManage)
ErrLastManager = errors.New("that would leave nobody able to manage permissions")
)
type PermissionsConfig struct {
Managers []string `toml:"managers" json:"managers"`
Default map[string][]string `toml:"default" json:"default"`
Channels map[string]map[string][]string `toml:"channels" json:"channels"`
DM map[string]bool `toml:"dm" json:"dm"`
}
func (p PermissionsConfig) Validate() error {
if len(p.Managers) == 0 {
return fmt.Errorf("permissions.managers must name at least one user manager")
}
if len(p.Default) == 0 {
return fmt.Errorf("[permissions.default] must name at least one super user, e.g. U0ADMIN = [\"all\"]")
}
check := func(where string, list map[string][]string) error {
for user, actions := range list {
for _, a := range actions {
if a != "all" && !slices.Contains(GrantActions, Action(a)) {
return fmt.Errorf("%s: unknown permission %q for %s (use %s, manage or all)", where, a, user, actionNames())
}
}
}
return nil
}
if err := check("permissions.default", p.Default); err != nil {
return err
}
for channel, list := range p.Channels {
if err := check("permissions.channels."+channel, list); err != nil {
return err
}
}
for a := range p.DM {
if !slices.Contains(AllActions, Action(a)) {
return fmt.Errorf("permissions.dm: unknown permission %q (use %s)", a, actionNames())
}
}
return nil
}
func (p PermissionsConfig) Clone() PermissionsConfig {
c := PermissionsConfig{
Managers: slices.Clone(p.Managers),
Default: cloneList(p.Default),
Channels: map[string]map[string][]string{},
DM: maps.Clone(p.DM),
}
for ch, list := range p.Channels {
c.Channels[ch] = cloneList(list)
}
if c.DM == nil {
c.DM = map[string]bool{}
}
return c
}
func cloneList(list map[string][]string) map[string][]string {
out := map[string][]string{}
for user, actions := range list {
out[user] = slices.Clone(actions)
}
return out
}
func actionNames() string {
names := make([]string, len(AllActions))
for i, a := range AllActions {
names[i] = string(a)
}
return strings.Join(names, ", ")
}
func (p PermissionsConfig) SuperUsers(channel string) (list map[string][]string, own bool) {
if l := p.Channels[channel]; len(l) > 0 {
return l, true
}
return p.Default, false
}
// "all" covers the container actions only; managing permissions is always granted by name.
func Grants(actions []string, a Action) bool {
if a == ActManage {
return slices.Contains(actions, string(ActManage))
}
return slices.Contains(actions, "all") || slices.Contains(actions, string(a))
}
func (p PermissionsConfig) Allowed(kind OwnerKind, channel, user string, a Action) bool {
if kind == OwnerUser {
allowed, set := p.DM[string(a)]
return !set || allowed
}
list, _ := p.SuperUsers(channel)
return Grants(list[user], a)
}
func (p PermissionsConfig) IsManager(user string) bool { return slices.Contains(p.Managers, user) }
func (p PermissionsConfig) CanManage(channel, user string) bool {
return p.IsManager(user) || p.Allowed(OwnerChannel, channel, user, ActManage)
}
func (p PermissionsConfig) Holders(channel string, a Action) []string {
list, _ := p.SuperUsers(channel)
var out []string
for user, actions := range list {
if Grants(actions, a) {
out = append(out, user)
}
}
sort.Strings(out)
return out
}
func (p PermissionsConfig) ActionsFor(channel, user string) []Action {
list, _ := p.SuperUsers(channel)
var out []Action
for _, a := range GrantActions {
if Grants(list[user], a) {
out = append(out, a)
}
}
return out
}
func expand(actions []Action) []Action {
if slices.Contains(actions, "all") {
out := slices.Clone(AllActions)
for _, a := range actions {
if a != "all" && !slices.Contains(out, a) {
out = append(out, a)
}
}
return out
}
return actions
}
// An empty channel means the default list. The first grant in a channel that
// still uses the default list copies it, so nobody loses access there.
func (p *PermissionsConfig) Grant(channel string, users []string, actions []Action) {
list := p.Default
if channel != "" {
if len(p.Channels[channel]) == 0 {
p.Channels[channel] = cloneList(p.Default)
}
list = p.Channels[channel]
}
for _, user := range users {
have := expandStrings(list[user])
for _, a := range expand(actions) {
if !slices.Contains(have, string(a)) {
have = append(have, string(a))
}
}
list[user] = have
}
}
// No actions means everything.
func (p *PermissionsConfig) Revoke(channel string, users []string, actions []Action) {
list := p.Default
if channel != "" {
if len(p.Channels[channel]) == 0 {
p.Channels[channel] = cloneList(p.Default)
}
list = p.Channels[channel]
}
remove := expand(actions)
for _, user := range users {
if len(actions) == 0 {
delete(list, user)
continue
}
var keep []string
for _, a := range expandStrings(list[user]) {
if !slices.Contains(remove, Action(a)) {
keep = append(keep, a)
}
}
if len(keep) == 0 {
delete(list, user)
} else {
list[user] = keep
}
}
}
func expandStrings(actions []string) []string {
as := make([]Action, len(actions))
for i, a := range actions {
as[i] = Action(a)
}
var out []string
for _, a := range expand(as) {
out = append(out, string(a))
}
return out
}
func (p *PermissionsConfig) AddManagers(users []string) {
for _, u := range users {
if !p.IsManager(u) {
p.Managers = append(p.Managers, u)
}
}
}
func (p *PermissionsConfig) RemoveManagers(users []string) error {
keep := slices.DeleteFunc(slices.Clone(p.Managers), func(u string) bool { return slices.Contains(users, u) })
if len(keep) == 0 {
return ErrLastManager
}
p.Managers = keep
return nil
}
@@ -0,0 +1,105 @@
package model_test
import (
"errors"
"testing"
"slackerbot/internal/config"
"slackerbot/internal/model"
)
func TestPermissions(t *testing.T) {
t.Setenv("SLACK_APP_TOKEN", "xapp-test")
t.Setenv("SLACK_BOT_TOKEN", "xoxb-test")
t.Setenv("CLUSTER_SECRET", "cluster-secret-1234567890")
c, err := config.LoadConfig("../../../config.example.toml", config.ModeMaster)
if err != nil {
t.Fatal(err)
}
p := c.Permissions
cases := []struct {
kind model.OwnerKind
channel, user string
action model.Action
want bool
}{
{model.OwnerChannel, "C07ABC123", "U0111", model.ActMove, true},
{model.OwnerChannel, "C07ABC123", "U0111", model.ActScale, false},
{model.OwnerChannel, "C07ABC123", "U0222", model.ActKeep, true},
{model.OwnerChannel, "C07ABC123", "U0ADMIN", model.ActMove, false},
{model.OwnerChannel, "C0OTHER", "U0ADMIN", model.ActStorage, true},
{model.OwnerChannel, "C0OTHER", "U0111", model.ActMove, false},
{model.OwnerUser, "D1", "U9", model.ActScale, true},
{model.OwnerUser, "D1", "U9", model.ActStorage, false},
}
for _, c := range cases {
if got := p.Allowed(c.kind, c.channel, c.user, c.action); got != c.want {
t.Errorf("%s %s %s %s = %v, want %v", c.kind, c.channel, c.user, c.action, got, c.want)
}
}
if h := p.Holders("C07ABC123", model.ActMove); len(h) != 2 {
t.Errorf("move holders = %v", h)
}
if a := p.ActionsFor("C0OTHER", "U0ADMIN"); len(a) != len(model.AllActions) {
t.Errorf("all should expand to every action, got %v", a)
}
open := model.PermissionsConfig{Default: map[string][]string{"U1": {"all"}}}
if !open.Allowed(model.OwnerUser, "D1", "U9", model.ActMove) {
t.Error("DM permissions should default to allowed")
}
if (model.PermissionsConfig{}).Validate() == nil {
t.Error("a missing default super user should be refused")
}
bad := model.PermissionsConfig{Default: map[string][]string{"U1": {"delete-everything"}}}
if bad.Validate() == nil {
t.Error("unknown permission names should be refused")
}
}
func TestGrantRevoke(t *testing.T) {
p := model.PermissionsConfig{Managers: []string{"UBOSS"}, Default: map[string][]string{"UDEF": {"all"}}}.Clone()
p.Grant("C1", []string{"UANA"}, []model.Action{model.ActMove})
if !p.Allowed(model.OwnerChannel, "C1", "UDEF", model.ActScale) {
t.Fatal("first grant in a channel should keep everyone from the default list")
}
if !p.Allowed(model.OwnerChannel, "C1", "UANA", model.ActMove) || p.Allowed(model.OwnerChannel, "C1", "UANA", model.ActScale) {
t.Fatal("grant should add exactly what was asked")
}
if p.Allowed(model.OwnerChannel, "C2", "UANA", model.ActMove) {
t.Fatal("grants stay in their channel")
}
p.Grant("C1", []string{"UANA"}, []model.Action{"all"})
if p.CanManage("C1", "UANA") {
t.Fatal("all must not include manage")
}
p.Grant("C1", []string{"UANA"}, []model.Action{model.ActManage})
if !p.CanManage("C1", "UANA") || p.CanManage("C2", "UANA") {
t.Fatal("manage is per channel")
}
p.Revoke("C1", []string{"UDEF"}, []model.Action{model.ActScale})
if p.Allowed(model.OwnerChannel, "C1", "UDEF", model.ActScale) || !p.Allowed(model.OwnerChannel, "C1", "UDEF", model.ActMove) {
t.Fatal("revoking one action out of all should keep the rest")
}
p.Revoke("C1", []string{"UANA"}, nil)
if len(p.ActionsFor("C1", "UANA")) != 0 {
t.Fatal("revoke with no actions removes the person")
}
p.Grant("", []string{"UNEW"}, []model.Action{model.ActKeep})
if !p.Allowed(model.OwnerChannel, "C9", "UNEW", model.ActKeep) {
t.Fatal("default grants apply to channels without their own list")
}
p.AddManagers([]string{"UTWO"})
if err := p.RemoveManagers([]string{"UBOSS", "UTWO"}); !errors.Is(err, model.ErrLastManager) {
t.Fatal("removing every manager must be refused")
}
if err := p.RemoveManagers([]string{"UBOSS"}); err != nil || p.IsManager("UBOSS") {
t.Fatal("removing one of two managers should work")
}
}