// chatkey_test.go proves a repository's chat is its own, not its project's:
// two repositories that hold one project code (two mirrors of one upstream,
// a mirror and a fork) must not share a channel, robot lines or unread
// counts, and what is said in a private one is never readable through a
// public one.
package harness
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"testing"
"craftdesign.group/quarry/internal/api"
"craftdesign.group/quarry/internal/chat"
"craftdesign.group/quarry/internal/events"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
const sharedProjectCode = "0123456789abcdef0123456789abcdef01234567"
func twinChatServer(t *testing.T) (*httptest.Server, *oltp.DB, *chat.Room) {
t.Helper()
dataDir := t.TempDir()
ev, err := events.Start(filepath.Join(dataDir, "nats"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
room, err := chat.New(ev.Conn(), ev.JS())
if err != nil {
t.Fatal(err)
}
odb, err := oltp.Open(filepath.Join(dataDir, "oltp.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { odb.Close() })
room.Robots = odb
if err := odb.AddAccount("dan", "pw12345678", false); err != nil {
t.Fatal(err)
}
repos := api.NewRepos(nil)
for _, name := range []string{"pubrepo", "privrepo"} {
if err := odb.SetCaps("dan", name, "C"); err != nil {
t.Fatal(err)
}
repos.Put(name, &api.Repo{Code: sharedProjectCode, Chat: chat.RepoKey(name)})
}
capsFor := func(account, repo string) api.CapSet { return odb.EffectiveCaps(account, repo) }
deps := api.Deps{Version: "0.0.0-harness", Repos: repos, Chat: room, Forum: odb,
ChatRefs: odb, Accounts: harnessAccounts{db: odb},
CanRead: func(_ context.Context, name string) bool { return true },
CapsFor: capsFor}
r := ops.NewRegistry()
if err := api.RegisterAll(r, deps); err != nil {
t.Fatal(err)
}
verify := func(repo, user, pass string, need ops.Auth) api.Decision {
if user == "" || pass != "pw12345678" {
return api.Denied
}
return api.Allowed
}
mux, err := api.RouterWithCaps(r, "0.0.0-harness", capsFor, deps.CanRead, verify)
if err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv, odb, room
}
func TestTwoRepositoriesOfOneProjectKeepSeparateChat(t *testing.T) {
srv, odb, room := twinChatServer(t)
dan := chatCaller{t: t, srv: srv, user: "dan"}
code, body := dan.do("POST", "/api/v1/r/privrepo/chat", url.Values{"text": {"only for the private one"}})
if code != http.StatusOK {
t.Fatalf("FAIL: post in privrepo: %d %s", code, body)
}
// The activity robot speaks in the private channel too.
if _, err := room.Post(chat.RepoKey("privrepo"), chat.Message{Kind: chat.KindRobot, Origin: "robot", User: "robot", Text: "a check-in"}); err != nil {
t.Fatal(err)
}
history := func(repo string) []string {
t.Helper()
code, body := dan.do("GET", "/api/v1/r/"+repo+"/chat?limit=50", nil)
if code != http.StatusOK {
t.Fatalf("FAIL: history of %s: %d %s", repo, code, body)
}
var out struct {
Messages []struct {
Text string `json:"text"`
} `json:"messages"`
}
if err := json.Unmarshal(body, &out); err != nil {
t.Fatalf("FAIL: history of %s: %v: %s", repo, err, body)
}
var texts []string
for _, m := range out.Messages {
texts = append(texts, m.Text)
}
return texts
}
if got := history("privrepo"); len(got) != 2 {
t.Fatalf("FAIL: privrepo reads %v, want its two lines", got)
}
if got := history("pubrepo"); len(got) != 0 {
t.Fatalf("FAIL: pubrepo reads the private channel: %v", got)
}
// Posting in the public one lands only there.
if code, body := dan.do("POST", "/api/v1/r/pubrepo/chat", url.Values{"text": {"for everybody"}}); code != http.StatusOK {
t.Fatalf("FAIL: post in pubrepo: %d %s", code, body)
}
if got := history("privrepo"); len(got) != 2 {
t.Errorf("FAIL: privrepo reads %v after a public post", got)
}
if got := history("pubrepo"); len(got) != 1 || got[0] != "for everybody" {
t.Errorf("FAIL: pubrepo reads %v, want its own line", got)
}
// Robot lines are counted per channel.
if n, _ := odb.RobotLines(chat.RepoKey("privrepo"), 0); n != 1 {
t.Errorf("FAIL: privrepo has %d robot lines, want 1", n)
}
if n, _ := odb.RobotLines(chat.RepoKey("pubrepo"), 0); n != 0 {
t.Errorf("FAIL: pubrepo has %d robot lines, want 0", n)
}
// Unread is per channel: nobody has read either.
unread := func(repo string) int {
n, err := room.Unread(chat.RepoKey(repo), 0)
if err != nil {
t.Fatal(err)
}
return n
}
if unread("privrepo") != 1 || unread("pubrepo") != 1 {
t.Errorf("FAIL: unread priv=%d pub=%d, want 1 and 1 (the robot line is not counted)", unread("privrepo"), unread("pubrepo"))
}
}
// A repository registered without a chat key answers every chat operation
// with an error and reaches no channel, its project code's included.
func TestARepositoryWithoutAChatKeyReachesNoChannel(t *testing.T) {
dataDir := t.TempDir()
ev, err := events.Start(filepath.Join(dataDir, "nats"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
room, err := chat.New(ev.Conn(), ev.JS())
if err != nil {
t.Fatal(err)
}
odb, err := oltp.Open(filepath.Join(dataDir, "oltp.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { odb.Close() })
if err := odb.AddAccount("dan", "pw12345678", false); err != nil {
t.Fatal(err)
}
if err := odb.SetCaps("dan", "keyless", "C"); err != nil {
t.Fatal(err)
}
repos := api.NewRepos(map[string]*api.Repo{"keyless": {Code: sharedProjectCode}})
capsFor := func(account, repo string) api.CapSet { return odb.EffectiveCaps(account, repo) }
deps := api.Deps{Version: "0.0.0-harness", Repos: repos, Chat: room, Forum: odb, ChatRefs: odb,
Accounts: harnessAccounts{db: odb}, CapsFor: capsFor,
CanRead: func(_ context.Context, name string) bool { return true }}
r := ops.NewRegistry()
if err := api.RegisterAll(r, deps); err != nil {
t.Fatal(err)
}
verify := func(repo, user, pass string, need ops.Auth) api.Decision {
if user == "" || pass != "pw12345678" {
return api.Denied
}
return api.Allowed
}
mux, err := api.RouterWithCaps(r, "0.0.0-harness", capsFor, deps.CanRead, verify)
if err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
dan := chatCaller{t: t, srv: srv, user: "dan"}
if code, _ := dan.do("POST", "/api/v1/r/keyless/chat", url.Values{"text": {"hello"}}); code == http.StatusOK {
t.Errorf("FAIL: a post to a repository with no chat key was accepted")
}
if msgs, _ := room.Range(sharedProjectCode, 0, 0); len(msgs) != 0 {
t.Errorf("FAIL: the project code's channel holds %d messages", len(msgs))
}
if last, _ := room.LastSeq(); last != 0 {
t.Errorf("FAIL: something was published (last seq %d)", last)
}
}