package main import ( "context" "errors" "net/http/httptest" "path/filepath" "strings" "testing" "github.com/slack-go/slack" ) 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 := LoadConfig("config.example.toml", ModeMaster) if err != nil { t.Fatal(err) } p := c.Permissions cases := []struct { kind OwnerKind channel, user string action Action want bool }{ {OwnerChannel, "C07ABC123", "U0111", ActMove, true}, {OwnerChannel, "C07ABC123", "U0111", ActScale, false}, {OwnerChannel, "C07ABC123", "U0222", ActKeep, true}, {OwnerChannel, "C07ABC123", "U0ADMIN", ActMove, false}, {OwnerChannel, "C0OTHER", "U0ADMIN", ActStorage, true}, {OwnerChannel, "C0OTHER", "U0111", ActMove, false}, {OwnerUser, "D1", "U9", ActScale, true}, {OwnerUser, "D1", "U9", 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", ActMove); len(h) != 2 { t.Errorf("move holders = %v", h) } if a := p.ActionsFor("C0OTHER", "U0ADMIN"); len(a) != len(allActions) { t.Errorf("all should expand to every action, got %v", a) } open := PermissionsConfig{Default: map[string][]string{"U1": {"all"}}} if !open.Allowed(OwnerUser, "D1", "U9", ActMove) { t.Error("DM permissions should default to allowed") } if (PermissionsConfig{}).validate() == nil { t.Error("a missing default super user should be refused") } bad := PermissionsConfig{Default: map[string][]string{"U1": {"delete-everything"}}} if bad.validate() == nil { t.Error("unknown permission names should be refused") } } func TestNeededPermission(t *testing.T) { for in, want := range map[[2]string]Action{ {"scale", "up"}: ActScale, {"scale", "8G 4cpu"}: ActScale, {"scale", "the db to 3 replicas"}: "", {"keep", ""}: "", {"keep", "24h"}: ActKeep, {"keep", "indefinite"}: ActKeep, {"keep", "the tests green"}: "", {"storage", ""}: "", {"storage", "20G"}: ActStorage, {"storage", "is full, clean it up"}: "", {"status", ""}: "", } { if got := neededPermission(in[0], in[1]); got != want { t.Errorf("%s %q needs %q, want %q", in[0], in[1], got, want) } } } func TestPermissionsSavedAndSeededOnce(t *testing.T) { path := filepath.Join(t.TempDir(), "state.json") s, _ := OpenStore(path) initial := PermissionsConfig{Managers: []string{"UBOSS"}, Default: map[string][]string{"UBOSS": {"all"}}} if seeded, err := s.SeedPermissions(initial); !seeded || err != nil { t.Fatalf("first start should seed: %v %v", seeded, err) } if err := s.UpdatePermissions(func(p *PermissionsConfig) error { p.Grant("C1", []string{"UANA"}, []Action{ActMove}) return nil }); err != nil { t.Fatal(err) } s2, _ := OpenStore(path) changed := PermissionsConfig{Managers: []string{"USOMEONE"}, Default: map[string][]string{"USOMEONE": {"all"}}} if seeded, _ := s2.SeedPermissions(changed); seeded { t.Fatal("config must not override saved permissions") } p := s2.Permissions() if !p.IsManager("UBOSS") || p.IsManager("USOMEONE") || !p.Allowed(OwnerChannel, "C1", "UANA", ActMove) { t.Fatalf("saved permissions lost: %+v", p) } if err := s2.UpdatePermissions(func(p *PermissionsConfig) error { p.Default["UX"] = []string{"teleport"} return nil }); err == nil { t.Fatal("invalid changes must be refused") } } func TestGrantRevoke(t *testing.T) { p := PermissionsConfig{Managers: []string{"UBOSS"}, Default: map[string][]string{"UDEF": {"all"}}}.clone() p.Grant("C1", []string{"UANA"}, []Action{ActMove}) if !p.Allowed(OwnerChannel, "C1", "UDEF", ActScale) { t.Fatal("first grant in a channel should keep everyone from the default list") } if !p.Allowed(OwnerChannel, "C1", "UANA", ActMove) || p.Allowed(OwnerChannel, "C1", "UANA", ActScale) { t.Fatal("grant should add exactly what was asked") } if p.Allowed(OwnerChannel, "C2", "UANA", ActMove) { t.Fatal("grants stay in their channel") } p.Grant("C1", []string{"UANA"}, []Action{"all"}) if p.CanManage("C1", "UANA") { t.Fatal("all must not include manage") } p.Grant("C1", []string{"UANA"}, []Action{ActManage}) if !p.CanManage("C1", "UANA") || p.CanManage("C2", "UANA") { t.Fatal("manage is per channel") } p.Revoke("C1", []string{"UDEF"}, []Action{ActScale}) if p.Allowed(OwnerChannel, "C1", "UDEF", ActScale) || !p.Allowed(OwnerChannel, "C1", "UDEF", 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"}, []Action{ActKeep}) if !p.Allowed(OwnerChannel, "C9", "UNEW", 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, 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") } } func TestParseGrant(t *testing.T) { g, err := parseGrant("<@U1> <@U2|bob>, move scale") if err != nil || len(g.users) != 2 || g.users[1] != "U2" || len(g.actions) != 2 { t.Fatalf("%+v %v", g, err) } if g, _ := parseGrant("default <@U1> all"); !g.toDefault || g.actions[0] != "all" { t.Fatalf("%+v", g) } for _, in := range []string{"me access to the repo", "all the things", ""} { if _, err := parseGrant(in); !errors.Is(err, errNotCommand) { t.Errorf("%q should go to the agent, got %v", in, err) } } if _, err := parseGrant("<@U1> teleport"); err == nil || errors.Is(err, errNotCommand) { t.Error("an unknown permission after a mention should be a usage error") } } func TestManageCommandsInSlack(t *testing.T) { log := &slackLog{text: map[string]string{}, under: map[string]string{}} srv := httptest.NewServer(log) defer srv.Close() store, _ := OpenStore(filepath.Join(t.TempDir(), "state.json")) store.SeedPermissions(PermissionsConfig{Managers: []string{"UBOSS"}, Default: map[string][]string{"UBOSS": {"all"}}}) b := &Bot{store: store, api: slack.New("xoxb", slack.OptionAPIURL(srv.URL+"/"))} ctx := context.Background() say := func(user, text string) string { m := incoming{user: user, channel: "C1", ts: "1.0", text: text} if !b.command(ctx, m) { return "(went to the agent)" } log.mu.Lock() defer log.mu.Unlock() return log.text[log.order[len(log.order)-1]] } if got := say("UANA", "grant <@UANA> all"); !strings.Contains(got, ":lock:") { t.Fatalf("non-managers can't grant: %q", got) } if got := say("UBOSS", "grant <@UANA> move manage"); !strings.Contains(got, "<@UANA> can now: move, manage") { t.Fatalf("manager grant: %q", got) } if got := say("UANA", "grant <@UCAL> scale"); !strings.Contains(got, "<@UCAL> can now: scale") { t.Fatalf("channel manager grant: %q", got) } if got := say("UANA", "grant default <@UCAL> all"); !strings.Contains(got, ":lock:") { t.Fatalf("channel managers can't touch the default list: %q", got) } if got := say("UANA", "managers add <@UCAL>"); !strings.Contains(got, ":lock:") { t.Fatalf("only user managers add managers: %q", got) } if got := say("UBOSS", "managers remove <@UBOSS>"); !strings.Contains(got, "nobody able to manage") { t.Fatalf("last manager guard: %q", got) } if got := say("UBOSS", "dm storage off"); !strings.Contains(got, "now turned off") { t.Fatalf("dm toggle: %q", got) } if store.Permissions().Allowed(OwnerUser, "D1", "UX", ActStorage) { t.Fatal("dm toggle not saved") } if got := say("UANA", "grant me access to the repo"); got != "(went to the agent)" { t.Fatalf("plain sentence: %q", got) } if got := say("UANA", "permissions reset"); !strings.Contains(got, "default super-user list again") { t.Fatalf("reset: %q", got) } if store.Permissions().Allowed(OwnerChannel, "C1", "UCAL", ActScale) { t.Fatal("reset should drop the channel's own list") } }