package oltp
import (
"errors"
"path/filepath"
"strings"
"testing"
"time"
)
func bridgeDB(t *testing.T) *DB {
t.Helper()
db, err := Open(filepath.Join(t.TempDir(), "oltp.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
return db
}
// The credential goes in and is readable only by the poller's own
// accessor; nothing a listing returns carries it.
func TestChatBridgeKeepsTheSecretOffEveryListing(t *testing.T) {
db := bridgeDB(t)
if err := db.SetChatBridge("alpha", "https://example.org/repo", "bot", "s3cret"); err != nil {
t.Fatal(err)
}
got, ok, err := db.ChatBridgeFor("alpha")
if err != nil || !ok {
t.Fatalf("bridge not stored: ok=%v err=%v", ok, err)
}
if got.URL != "https://example.org/repo" || got.User != "bot" {
t.Fatalf("bridge = %+v", got)
}
secret, ok := db.ChatBridgeSecret("alpha")
if !ok || secret != "s3cret" {
t.Fatalf("the poller cannot read the credential: %q %v", secret, ok)
}
list, err := db.ChatBridges()
if err != nil || len(list) != 1 || list[0].Repo != "alpha" {
t.Fatalf("bridges = %+v (%v)", list, err)
}
}
// Only http(s), the rule every URL quarry fetches on its own
// initiative lives under.
func TestChatBridgeRefusesAForeignScheme(t *testing.T) {
db := bridgeDB(t)
for _, bad := range []string{"file:///etc/passwd", "ssh://host/repo", "", "notaurl"} {
if err := db.SetChatBridge("alpha", bad, "bot", "pw"); err == nil {
t.Fatalf("%q was accepted as a bridge url", bad)
}
}
if err := db.SetChatBridge("alpha", "https://x.example/r", "", "pw"); err == nil {
t.Fatal("a bridge with no login was accepted")
}
}
// Reconfiguring keeps the cursor when the upstream is the same and
// resets it when it is not: msgids belong to the server that minted
// them, and replaying another's numbering imports the wrong messages.
func TestChatBridgeCursorFollowsTheUpstream(t *testing.T) {
db := bridgeDB(t)
if err := db.SetChatBridge("alpha", "https://a.example/r", "bot", "pw"); err != nil {
t.Fatal(err)
}
if err := db.SetChatBridgeCursor("alpha", 42, time.Now()); err != nil {
t.Fatal(err)
}
// Same URL, new password: the cursor stands.
if err := db.SetChatBridge("alpha", "https://a.example/r", "bot", "pw2"); err != nil {
t.Fatal(err)
}
if b, _, _ := db.ChatBridgeFor("alpha"); b.LastMsgID != 42 {
t.Fatalf("fixing a password reset the cursor to %d", b.LastMsgID)
}
// New URL: a different fossil, a different numbering.
if err := db.SetChatBridge("alpha", "https://b.example/r", "bot", "pw2"); err != nil {
t.Fatal(err)
}
if b, _, _ := db.ChatBridgeFor("alpha"); b.LastMsgID != 0 {
t.Fatalf("a new upstream kept the old cursor: %d", b.LastMsgID)
}
}
// A failure is remembered without moving the cursor — a failed poll
// read nothing — and the next message clears it.
func TestChatBridgeErrorDoesNotAdvanceTheCursor(t *testing.T) {
db := bridgeDB(t)
if err := db.SetChatBridge("alpha", "https://a.example/r", "bot", "pw"); err != nil {
t.Fatal(err)
}
if err := db.SetChatBridgeCursor("alpha", 7, time.Now()); err != nil {
t.Fatal(err)
}
if err := db.RecordChatBridgeError("alpha", errors.New("upstream is down")); err != nil {
t.Fatal(err)
}
b, _, _ := db.ChatBridgeFor("alpha")
if b.LastMsgID != 7 || b.LastErr != "upstream is down" {
t.Fatalf("after a failure: %+v", b)
}
if err := db.SetChatBridgeCursor("alpha", 8, time.Now()); err != nil {
t.Fatal(err)
}
if b, _, _ := db.ChatBridgeFor("alpha"); b.LastErr != "" || b.LastMsgID != 8 {
t.Fatalf("a message did not clear the error: %+v", b)
}
}
// The msgid map answers what a later mdel needs, prunes with the
// window, and dies with the bridge — a re-attach must not tombstone a
// quarry message on a number the new upstream reused.
func TestChatBridgeMsgMapLivesAndDiesWithTheBridge(t *testing.T) {
db := bridgeDB(t)
if err := db.SetChatBridge("alpha", "https://a.example/r", "bot", "pw"); err != nil {
t.Fatal(err)
}
for _, m := range []struct {
msgid int64
seq uint64
}{{1, 10}, {2, 20}, {3, 30}} {
if err := db.MapChatBridgeMsg("alpha", m.msgid, m.seq); err != nil {
t.Fatal(err)
}
}
if seq, ok := db.ChatBridgeSeq("alpha", 2); !ok || seq != 20 {
t.Fatalf("msgid 2 = %d %v, want 20", seq, ok)
}
// Idempotent: a replayed poll must not double anything.
if err := db.MapChatBridgeMsg("alpha", 2, 999); err != nil {
t.Fatal(err)
}
if seq, _ := db.ChatBridgeSeq("alpha", 2); seq != 20 {
t.Fatalf("a replay rewrote the mapping to %d", seq)
}
if err := db.PruneChatBridgeMsgs("alpha", 25); err != nil {
t.Fatal(err)
}
if _, ok := db.ChatBridgeSeq("alpha", 1); ok {
t.Fatal("a row outside the window survived the prune")
}
if _, ok := db.ChatBridgeSeq("alpha", 3); !ok {
t.Fatal("the prune took a row still inside the window")
}
if err := db.DetachChatBridge("alpha"); err != nil {
t.Fatal(err)
}
if _, ok, _ := db.ChatBridgeFor("alpha"); ok {
t.Fatal("detach left the bridge configured")
}
if _, ok := db.ChatBridgeSeq("alpha", 3); ok {
t.Fatal("detach left the msgid map behind")
}
}
// Purging a repository takes its bridge and map with it, like every
// other repo-keyed table.
func TestPurgeRepoTakesTheChatBridge(t *testing.T) {
db := bridgeDB(t)
if err := db.SetChatBridge("alpha", "https://a.example/r", "bot", "pw"); err != nil {
t.Fatal(err)
}
if err := db.MapChatBridgeMsg("alpha", 1, 10); err != nil {
t.Fatal(err)
}
if err := db.PurgeRepo("alpha"); err != nil {
t.Fatal(err)
}
if _, ok, _ := db.ChatBridgeFor("alpha"); ok {
t.Fatal("the bridge survived a repository purge")
}
if _, ok := db.ChatBridgeSeq("alpha", 1); ok {
t.Fatal("the msgid map survived a repository purge")
}
}
// A changed upstream invalidates the msgid map as well as the cursor.
// Msgids belong to the fossil that minted them, so a map carried
// across would let a new server's msgid tombstone a quarry message the
// old server's msgid had claimed — the hazard DetachChatBridge already
// handles, reached by reconfiguring instead of detaching.
func TestChatBridgeURLChangeClearsTheMsgMap(t *testing.T) {
db := bridgeDB(t)
if err := db.SetChatBridge("alpha", "https://a.example/r", "bot", "pw"); err != nil {
t.Fatal(err)
}
if err := db.MapChatBridgeMsg("alpha", 1, 10); err != nil {
t.Fatal(err)
}
// Same upstream: the map is still about the right server.
if err := db.SetChatBridge("alpha", "https://a.example/r", "bot", "pw2"); err != nil {
t.Fatal(err)
}
if _, ok := db.ChatBridgeSeq("alpha", 1); !ok {
t.Fatal("changing the password dropped the msgid map")
}
if err := db.SetChatBridge("alpha", "https://b.example/r", "bot", "pw2"); err != nil {
t.Fatal(err)
}
if _, ok := db.ChatBridgeSeq("alpha", 1); ok {
t.Fatal("a new upstream kept the old server's msgid map")
}
}
// Credentials belong in the columns the poller reads, not in a URL
// that every log line and status row would carry.
func TestChatBridgeRefusesCredentialsInTheURL(t *testing.T) {
db := bridgeDB(t)
for _, bad := range []string{
"https://bot:[email protected]/r",
"https://[email protected]/r",
} {
if err := db.SetChatBridge("alpha", bad, "bot", "pw"); err == nil {
t.Fatalf("%q was accepted", bad)
}
}
}
// A stored error is rendered on an admin page, so any URL inside it
// arrives without its credentials — stdlib transport errors quote the
// whole request URL.
func TestRecordChatBridgeErrorRedactsCredentials(t *testing.T) {
db := bridgeDB(t)
if err := db.SetChatBridge("alpha", "https://a.example/r", "bot", "pw"); err != nil {
t.Fatal(err)
}
if err := db.RecordChatBridgeError("alpha",
errors.New(`Get "https://bot:[email protected]/r/chat-poll": dial tcp: refused`)); err != nil {
t.Fatal(err)
}
b, _, _ := db.ChatBridgeFor("alpha")
if strings.Contains(b.LastErr, "hunter2") || strings.Contains(b.LastErr, "bot:") {
t.Fatalf("the stored error carries the credential: %q", b.LastErr)
}
// Userinfo may itself hold an `@` — an email-address login is
// ordinary — so the run has to reach the LAST one before the path.
if err := db.RecordChatBridgeError("alpha",
errors.New(`Get "https://bot@corp:[email protected]/r/chat-poll": refused`)); err != nil {
t.Fatal(err)
}
multi, _, _ := db.ChatBridgeFor("alpha")
if strings.Contains(multi.LastErr, "hunter2") || strings.Contains(multi.LastErr, "bot@corp") {
t.Fatalf("multi-@ userinfo survived redaction: %q", multi.LastErr)
}
if !strings.Contains(multi.LastErr, "https://a.example/r/chat-poll") {
t.Fatalf("multi-@ redaction took the host with it: %q", multi.LastErr)
}
// A URL with no userinfo must not swallow an `@` later in the
// sentence: `/` terminates the run.
if err := db.RecordChatBridgeError("alpha",
errors.New(`Get "https://a.example/r/chat-poll": rejected for user bot@corp`)); err != nil {
t.Fatal(err)
}
plain, _, _ := db.ChatBridgeFor("alpha")
if !strings.Contains(plain.LastErr, "https://a.example/r/chat-poll") {
t.Fatalf("a credential-free URL was mangled: %q", plain.LastErr)
}
if !strings.Contains(b.LastErr, "https://a.example/r/chat-poll") {
t.Fatalf("redaction took the host with it: %q", b.LastErr)
}
if !strings.Contains(b.LastErr, "dial tcp: refused") {
t.Fatalf("redaction took the reason with it: %q", b.LastErr)
}
}
// Chat is open while either category that nobody is named into holds
// C, and a stop keeps its first stamp until it is cleared.
func TestChatOpenToAndTheStop(t *testing.T) {
db := bridgeDB(t)
for _, cat := range []string{"nobody", "anonymous"} {
if err := db.SetCategoryCaps("r", cat, "gjorz"); err != nil {
t.Fatal(err)
}
}
if open := db.ChatOpenTo("r"); len(open) != 0 {
t.Fatalf("FAIL: closed chat reads as open to %v", open)
}
if err := db.SetCategoryCaps("r", "anonymous", "hmncC"); err != nil {
t.Fatal(err)
}
if open := db.ChatOpenTo("r"); len(open) != 1 || open[0] != "anonymous" {
t.Fatalf("FAIL: open to %v; want anonymous", open)
}
if err := db.SetChatBridge("r", "https://fossil.example/r", "bot", "pw"); err != nil {
t.Fatal(err)
}
t0 := time.Date(2026, 10, 26, 14, 2, 0, 0, time.UTC)
if now, err := db.StopChatBridge("r", t0); err != nil || !now {
t.Fatalf("FAIL: the first stop did not take: %v %v", now, err)
}
if now, _ := db.StopChatBridge("r", t0.Add(time.Hour)); now {
t.Error("FAIL: a second stop re-stamped the bridge")
}
if b, _, _ := db.ChatBridgeFor("r"); b.Stopped != "2026-10-26T14:02:00Z" {
t.Errorf("FAIL: stopped %q; want the first stop's time", b.Stopped)
}
if err := db.ResumeChatBridge("r"); err != nil {
t.Fatal(err)
}
if b, _, _ := db.ChatBridgeFor("r"); b.Stopped != "" {
t.Error("FAIL: the stop survived a resume")
}
}
// A halt (the other server refused, or stopped serving chat) is stored
// with its kind, reason and first time, apart from the chat-closed stop:
// neither hides or overwrites the other. Only a person's restart or a
// new credential clears it; the chat-closed resume leaves it alone.
func TestChatBridgeHaltIsIndependentOfTheChatClosedStop(t *testing.T) {
db := bridgeDB(t)
if err := db.SetChatBridge("r", "https://fossil.example/r", "bot", "old"); err != nil {
t.Fatal(err)
}
t0 := time.Date(2026, 11, 16, 9, 0, 0, 0, time.UTC)
// Chat is closed to named people... then opened: the chat stop is set.
if now, err := db.StopChatBridge("r", t0.Add(-time.Hour)); err != nil || !now {
t.Fatalf("FAIL: chat-closed stop did not take: %v %v", now, err)
}
if first, err := db.HaltChatBridge("r", "refused", "refused the login for bot", t0); err != nil || !first {
t.Fatalf("FAIL: a halt did not record beside the chat stop: %v %v", first, err)
}
if first, _ := db.HaltChatBridge("r", "unserved", "again", t0.Add(time.Hour)); first {
t.Error("FAIL: a second halt reported itself as the first, so the admins would be told twice")
}
b, _, _ := db.ChatBridgeFor("r")
if b.Halted != "2026-11-16T09:00:00Z" || b.HaltKind != "refused" || b.HaltWhy != "refused the login for bot" ||
b.Stopped != "2026-11-16T08:00:00Z" {
t.Errorf("FAIL: stored (%q %q %q, chat stop %q), want both facts intact", b.Halted, b.HaltKind, b.HaltWhy, b.Stopped)
}
// Chat reopens to named people: the chat-closed resume clears only its own.
if err := db.ResumeChatBridge("r"); err != nil {
t.Fatal(err)
}
b, _, _ = db.ChatBridgeFor("r")
if b.Stopped != "" || b.Halted == "" {
t.Errorf("FAIL: the chat resume touched the halt: %+v", b)
}
if secret, _ := db.ChatBridgeSecret("r"); secret != "old" {
t.Error("FAIL: a halt discarded the stored credential")
}
// A new credential clears the halt; so does a person's restart.
if err := db.SetChatBridge("r", "https://fossil.example/r", "bot", "new"); err != nil {
t.Fatal(err)
}
if b, _, _ := db.ChatBridgeFor("r"); b.Halted != "" || b.HaltKind != "" || b.HaltWhy != "" {
t.Errorf("FAIL: saving a credential left the halt: %+v", b)
}
if first, _ := db.HaltChatBridge("r", "unserved", "403", t0); !first {
t.Fatal("FAIL: a bridge cleared by a new credential cannot be halted again")
}
if err := db.RestartChatBridge("r"); err != nil {
t.Fatal(err)
}
if b, _, _ := db.ChatBridgeFor("r"); b.Halted != "" || b.HaltWhy != "" {
t.Errorf("FAIL: restart left the halt: %+v", b)
}
if !t.Failed() {
t.Log("ok")
}
}
// The admins told of a stop are the enabled accounts holding the admin
// letter on that repository, and nobody else.
func TestRepoAdminsAreTheEnabledHoldersOfTheAdminLetter(t *testing.T) {
db := bridgeDB(t)
for _, n := range []string{"ann", "bob", "cy", "dee"} {
if err := db.AddAccount(n, "pw-"+n+"-123456", false); err != nil {
t.Fatal(err)
}
}
if err := db.Grant("ann", "r", RepoAdmin); err != nil {
t.Fatal(err)
}
if err := db.Grant("bob", "r", Write); err != nil {
t.Fatal(err)
}
if err := db.Grant("cy", "r", RepoAdmin); err != nil {
t.Fatal(err)
}
if err := db.SetDisabled("cy", true); err != nil {
t.Fatal(err)
}
if err := db.Grant("dee", "other", RepoAdmin); err != nil {
t.Fatal(err)
}
got, err := db.RepoAdmins("r")
if err != nil || len(got) != 1 || got[0] != "ann" {
t.Errorf("FAIL: admins of r = %v (%v), want only ann", got, err)
}
if !t.Failed() {
t.Log("ok")
}
}
// Who is told of a stop: the admins; with none, whoever set the bridge
// up; with neither, the site admins.
func TestChatBridgeNotifiedFallsBackToTheSetterThenSiteAdmins(t *testing.T) {
db := bridgeDB(t)
for _, n := range []string{"ann", "setter", "root"} {
if err := db.AddAccount(n, "pw-"+n+"-123456", n == "root"); err != nil {
t.Fatal(err)
}
}
if err := db.Grant("ann", "r", RepoAdmin); err != nil {
t.Fatal(err)
}
if got, _ := db.ChatBridgeNotified("r"); len(got) != 1 || got[0] != "ann" {
t.Errorf("FAIL: with an admin, told %v, want ann", got)
}
if got, _ := db.ChatBridgeNotified("none"); len(got) != 1 || got[0] != "root" {
t.Errorf("FAIL: no admin and no setter, told %v, want the site admin", got)
}
if err := db.SetChatIdentity("none", "fossil:bot", "setter", "bridge"); err != nil {
t.Fatal(err)
}
if got, _ := db.ChatBridgeNotified("none"); len(got) != 1 || got[0] != "setter" {
t.Errorf("FAIL: no admin, told %v, want the account that set the bridge up", got)
}
if !t.Failed() {
t.Log("ok")
}
}