package api
import (
"context"
"net/http"
"strings"
"testing"
"time"
"craftdesign.group/quarry/internal/ops"
)
type smsSaid struct {
user, kind, room string
ref uint64
text string
}
type smsRig2 struct {
h *ReplyReceiver
store *fakeReplyStore
chat *memChatSMS
said []smsSaid
notices []string // account
repos [][]string
open map[string]bool
caps map[string]string
}
func newInboundSMSRig(t *testing.T) *smsRig2 {
t.Helper()
g := &smsRig2{store: &fakeReplyStore{secret: "s3cret"}, chat: &memChatSMS{},
open: map[string]bool{"dan": true}, caps: map[string]string{"dan": "C"}}
now := time.Unix(1_800_000_000, 0)
g.h = &ReplyReceiver{
Store: g.store,
CapsFor: func(account, _ string) CapSet {
return capsOf(g.caps[account])
},
Open: func(name string) (bool, error) { return g.open[name], nil },
Say: func(ctx_ context.Context, kind, room string, ref uint64, text string) (uint64, error) {
g.said = append(g.said, smsSaid{ops.User(ctx_), kind, room, ref, text})
return 41, nil
},
SMSRecent: g.chat.RecentChatSMSSent,
SMSNotice: func(account, _, _ string, repos []string) {
g.notices = append(g.notices, account)
g.repos = append(g.repos, repos)
},
Now: func() time.Time { return now },
}
return g
}
func smsEvent(id, who, body string) map[string]any {
return map[string]any{"type": "sms.inbound", "subscriberId": who, "phoneVerified": true,
"from": "+15555550100", "to": "+15555550199", "body": body, "inboundMessageId": id,
"providerId": "twilio", "providerMessageId": "SM1", "receivedAt": "2026-11-24T15:00:00Z"}
}
// A verified text from an account lands in the channel that texted it
// last, as that account, once however often notify delivers it.
func TestInboundSMSPostsInTheChannelThatTextedLast(t *testing.T) {
g := newInboundSMSRig(t)
now := time.Unix(1_800_000_000, 0)
_ = g.chat.RecordChatSMSSent("dan", "alpha", now.Add(-100*time.Minute))
_ = g.chat.RecordChatSMSSent("dan", "beta", now.Add(-30*time.Minute))
_ = g.chat.RecordChatSMSSent("dan", "gamma", now.Add(-3*time.Hour))
for range 2 {
w := deliver(g.h, "s3cret", 1_800_000_000, smsEvent("in-1", "dan", " Running late \n"))
if w.Code != http.StatusCreated && w.Code != http.StatusOK {
t.Fatalf("FAIL: status %d: %s", w.Code, w.Body)
}
}
if len(g.said) != 1 {
t.Fatalf("FAIL: %d posts for one text delivered twice, want 1", len(g.said))
}
p := g.said[0]
if p.user != "dan" || p.kind != "chat" || p.room != "beta" || p.ref != 0 || p.text != "Running late" {
t.Errorf("FAIL: posted %+v", p)
}
if len(g.notices) != 0 {
t.Errorf("FAIL: a text that landed also sent a notice to %v", g.notices)
}
if len(g.store.seen) != 1 {
t.Errorf("FAIL: outcomes recorded = %v, want one", g.store.seen)
}
if !t.Failed() {
t.Log("ok")
}
}
// With no channel texting them in the last two hours there is nowhere
// to post: nothing is posted and the sender is told so.
func TestInboundSMSWithNoRecentChannelIsTold(t *testing.T) {
g := newInboundSMSRig(t)
now := time.Unix(1_800_000_000, 0)
_ = g.chat.RecordChatSMSSent("dan", "alpha", now.Add(-3*time.Hour))
for range 2 {
if w := deliver(g.h, "s3cret", 1_800_000_000, smsEvent("in-2", "dan", "hello?")); w.Code >= 400 {
t.Fatalf("FAIL: status %d: %s", w.Code, w.Body)
}
}
if len(g.said) != 0 {
t.Errorf("FAIL: posted %+v with no channel to post in", g.said)
}
if len(g.notices) != 1 || g.notices[0] != "dan" {
t.Errorf("FAIL: notices = %v, want one to dan (and not again on redelivery)", g.notices)
}
if !t.Failed() {
t.Log("ok")
}
}
// What is not a person writing to a channel is dropped quietly: an
// unverified phone, a subscriber that is no open account, an SMS
// keyword (notify answers those), an empty body, and an account that
// has since lost the chat letter.
func TestInboundSMSIgnoresWhatIsNotAReply(t *testing.T) {
now := time.Unix(1_800_000_000, 0)
cases := map[string]func(g *smsRig2, ev map[string]any){
"unverified phone": func(g *smsRig2, ev map[string]any) { ev["phoneVerified"] = false },
"unknown account": func(g *smsRig2, ev map[string]any) { ev["subscriberId"] = "mallory" },
"shut account": func(g *smsRig2, ev map[string]any) { g.open["dan"] = false },
"empty": func(g *smsRig2, ev map[string]any) { ev["body"] = " \n\t" },
"lost chat letter": func(g *smsRig2, ev map[string]any) { g.caps["dan"] = "o" },
"verification not stated": func(g *smsRig2, ev map[string]any) { delete(ev, "phoneVerified") },
}
for _, kw := range []string{"STOP", "stopall", "Unsubscribe", " cancel ", "END", "quit", "START", "yes", "UNSTOP", "help", "Info"} {
kw := kw
cases["keyword "+strings.TrimSpace(kw)] = func(g *smsRig2, ev map[string]any) { ev["body"] = kw }
}
for name, mutate := range cases {
g := newInboundSMSRig(t)
_ = g.chat.RecordChatSMSSent("dan", "alpha", now.Add(-time.Minute))
_ = g.chat.RecordChatSMSSent("mallory", "alpha", now.Add(-time.Minute))
ev := smsEvent("in-x", "dan", "on my way")
mutate(g, ev)
deliver(g.h, "s3cret", 1_800_000_000, ev)
if len(g.said) != 0 {
t.Errorf("FAIL: %s: posted %+v", name, g.said)
}
if len(g.notices) != 0 {
t.Errorf("FAIL: %s: told %v", name, g.notices)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A body past what a chat line may hold is cut to it rather than
// refused, so the part that fits is not lost.
func TestInboundSMSCapsTheBodyAtTheChatLimit(t *testing.T) {
g := newInboundSMSRig(t)
_ = g.chat.RecordChatSMSSent("dan", "alpha", time.Unix(1_800_000_000, 0).Add(-time.Minute))
deliver(g.h, "s3cret", 1_800_000_000, smsEvent("in-3", "dan", strings.Repeat("é", chatTextMax+500)))
if len(g.said) != 1 || len([]rune(g.said[0].text)) != chatTextMax {
n := 0
if len(g.said) == 1 {
n = len([]rune(g.said[0].text))
}
t.Fatalf("FAIL: %d posts, %d runes; want one of %d", len(g.said), n, chatTextMax)
}
if !t.Failed() {
t.Log("ok")
}
}
// The text stream is signed like the mail stream: an unsigned or stale
// delivery posts nothing, and a mail reply still works beside it.
func TestInboundSMSIsHeldToTheSignatureAndLeavesMailAlone(t *testing.T) {
g := newInboundSMSRig(t)
_ = g.chat.RecordChatSMSSent("dan", "alpha", time.Unix(1_800_000_000, 0).Add(-time.Minute))
if w := deliver(g.h, "wrong", 1_800_000_000, smsEvent("in-4", "dan", "hi")); w.Code != http.StatusUnauthorized {
t.Errorf("FAIL: a mis-signed text answered %d", w.Code)
}
if w := deliver(g.h, "s3cret", 1_700_000_000, smsEvent("in-4", "dan", "hi")); w.Code != http.StatusUnauthorized {
t.Errorf("FAIL: a stale text answered %d", w.Code)
}
if len(g.said) != 0 || len(g.store.seen) != 0 {
t.Errorf("FAIL: an unsigned text had effect: %+v %v", g.said, g.store.seen)
}
noID := smsEvent("", "dan", "hi")
if w := deliver(g.h, "s3cret", 1_800_000_000, noID); w.Code < 400 || len(g.said) != 0 {
t.Errorf("FAIL: a text with no inboundMessageId answered %d, posted %+v", w.Code, g.said)
}
mail := replyEvent("mention:chat:alpha:9:dan", "dan", "from mail")
if w := deliver(g.h, "s3cret", 1_800_000_000, mail); w.Code != http.StatusCreated {
t.Fatalf("FAIL: a mail reply answered %d: %s", w.Code, w.Body)
}
if len(g.said) != 1 || g.said[0].ref != 9 || g.said[0].text != "from mail" {
t.Errorf("FAIL: the mail reply posted %+v", g.said)
}
if w := deliver(g.h, "s3cret", 1_800_000_000, map[string]any{"type": "email.delivered"}); w.Code != http.StatusOK {
t.Errorf("FAIL: another event answered %d", w.Code)
}
if !t.Failed() {
t.Log("ok")
}
}
// Texts leave after notify's digest, so the channel that texted last is
// not always the one a reply answers. A reply that names its channel
// goes there; one that does not goes to the last channel only when no
// other texted close to it.
func TestInboundSMSRoutesByPrefixOrRefusesToGuess(t *testing.T) {
now := time.Unix(1_800_000_000, 0)
type want struct {
room, text string
notice bool
}
for name, c := range map[string]struct {
sent map[string]time.Duration // repo -> how long ago
body string
want want
}{
"one repo posts": {map[string]time.Duration{"alpha": 5 * time.Minute}, "on my way", want{"alpha", "on my way", false}},
"far apart posts last": {map[string]time.Duration{"alpha": 100 * time.Minute, "beta": 5 * time.Minute}, "ok", want{"beta", "ok", false}},
"close together asks": {map[string]time.Duration{"alpha": 8 * time.Minute, "beta": 5 * time.Minute}, "ok", want{notice: true}},
"prefix picks": {map[string]time.Duration{"alpha": 8 * time.Minute, "beta": 5 * time.Minute}, "#alpha ok then", want{"alpha", "ok then", false}},
"prefix with colon": {map[string]time.Duration{"alpha": 8 * time.Minute, "beta": 5 * time.Minute}, "#ALPHA: ok then", want{"alpha", "ok then", false}},
"prefix with no text": {map[string]time.Duration{"alpha": 8 * time.Minute}, "#beta ok", want{notice: true}},
"hash that is no repo": {map[string]time.Duration{"alpha": 8 * time.Minute}, "#42 is merged", want{"alpha", "#42 is merged", false}},
} {
g := newInboundSMSRig(t)
g.h.KnownRepo = func(n string) bool { return n == "alpha" || n == "beta" }
for repo, ago := range c.sent {
_ = g.chat.RecordChatSMSSent("dan", repo, now.Add(-ago))
}
if w := deliver(g.h, "s3cret", 1_800_000_000, smsEvent("in-r", "dan", c.body)); w.Code >= 400 {
t.Fatalf("FAIL: %s: status %d: %s", name, w.Code, w.Body)
}
switch {
case c.want.notice:
if len(g.said) != 0 || len(g.notices) != 1 {
t.Errorf("FAIL: %s: posted %+v, notices %v; want a notice and no post", name, g.said, g.notices)
}
if len(g.repos[0]) != len(c.sent) && name != "prefix with no text" {
t.Errorf("FAIL: %s: the notice listed %v, want every candidate", name, g.repos[0])
}
default:
if len(g.said) != 1 || g.said[0].room != c.want.room || g.said[0].text != c.want.text || len(g.notices) != 0 {
t.Errorf("FAIL: %s: posted %+v, notices %v; want %q in %q", name, g.said, g.notices, c.want.text, c.want.room)
}
}
}
if !t.Failed() {
t.Log("ok")
}
}