package api import ( "context" "errors" "fmt" "net/http" "net/http/httptest" "strings" "sync" "testing" "time" "connectrpc.com/connect" "google.golang.org/protobuf/types/known/durationpb" apiv1 "tangled.org/beardic.us/chatline/gen/chatto/api/v1" "tangled.org/beardic.us/chatline/gen/chatto/api/v1/apiv1connect" discoveryv1 "tangled.org/beardic.us/chatline/gen/chatto/discovery/v1" "tangled.org/beardic.us/chatline/gen/chatto/discovery/v1/discoveryv1connect" "tangled.org/beardic.us/chatline/internal/output" ) func TestMatchRoom(t *testing.T) { rooms := []*Room{{ID: "R1", Name: "général"}, {ID: "R2", Name: "dup"}, {ID: "R3", Name: "dup"}} // NFD input matches an NFC name. if r, err := matchRoom(rooms, "ge\u0301ne\u0301ral"); err != nil || r.ID != "R1" { t.Fatalf("NFD input: %v %v", r, err) } if r, err := matchRoom(rooms, "général"); err != nil || r.ID != "R1" { t.Fatalf("%v %v", r, err) } if _, err := matchRoom(rooms, "dup"); output.Classify(err).Code != "ambiguous_room" { t.Fatalf("dup: %v", err) } if _, err := matchRoom(rooms, "nope"); output.Classify(err).Exit != output.ExitNotFound { t.Fatalf("nope: %v", err) } } func TestCheckPlacement(t *testing.T) { if err := CheckPlacement(&Room{Threading: "disabled"}, true); output.Classify(err).Code != "threads_disabled" { t.Fatal(err) } if err := CheckPlacement(&Room{Threading: "disabled"}, false); err != nil { t.Fatal(err) } if err := CheckPlacement(&Room{Threading: "required"}, true); err != nil { t.Fatal(err) } } func TestRoomFromProtoThreading(t *testing.T) { dm := roomFromProto(&apiv1.RoomWithViewerState{Room: &apiv1.Room{Kind: apiv1.RoomKind_ROOM_KIND_DM}}) if dm.Kind != "dm" || dm.ThreadsAllowed() { t.Fatalf("UNSPECIFIED DM: %+v", dm) } ch := roomFromProto(&apiv1.RoomWithViewerState{Room: &apiv1.Room{Kind: apiv1.RoomKind_ROOM_KIND_CHANNEL}}) if !ch.ThreadsAllowed() { t.Fatal("UNSPECIFIED channel should allow threads") } } type viewerHandler struct { apiv1connect.UnimplementedViewerServiceHandler gotAuth string } func (h *viewerHandler) GetViewer(_ context.Context, req *connect.Request[apiv1.GetViewerRequest]) (*connect.Response[apiv1.GetViewerResponse], error) { h.gotAuth = req.Header().Get("Authorization") return connect.NewResponse(&apiv1.GetViewerResponse{User: &apiv1.ViewerUser{Profile: &apiv1.User{ Id: "UBOT00000000001", Login: "bot", Bot: &apiv1.BotInfo{OwnerUserId: "UOWNER000000001"}, }}}), nil } func TestWhoAmISendsBearer(t *testing.T) { h := &viewerHandler{} mux := http.NewServeMux() path, handler := apiv1connect.NewViewerServiceHandler(h) mux.Handle("/api/connect"+path, http.StripPrefix("/api/connect", handler)) srv := httptest.NewServer(mux) defer srv.Close() c := New(srv.URL, "cht_BK_secret", srv.Client()) me, err := c.WhoAmI(context.Background()) if err != nil { t.Fatal(err) } if me.OwnerID != "UOWNER000000001" || !me.Bot || h.gotAuth != "Bearer cht_BK_secret" { t.Fatalf("%+v auth=%q", me, h.gotAuth) } } func TestSameHost(t *testing.T) { if !sameHost("https://chat.example/a/b", "https://chat.example") { t.Fatal("same host not detected") } if sameHost("https://s3.example/a", "https://chat.example") { t.Fatal("key would leak to another host") } } func TestLooksLikeIDs(t *testing.T) { for _, id := range []string{"Ry1pnQR0p6lCCb8", "69863ed1f9d48a"} { if !LooksLikeRoomID(id) { t.Errorf("%s not recognised as a room ID", id) } } if LooksLikeRoomID("general chat") || LooksLikeRoomID("#ops") { t.Error("name taken for an ID") } if !LooksLikeUserID("U0sb9scAGJdhGaw") || LooksLikeUserID("beardicus") { t.Error("user ID detection") } } func TestReactionSummary(t *testing.T) { m := &Message{Reactions: []Reaction{{Emoji: "thumbsup", Count: 1}, {Emoji: "eyes", Count: 2}}} if got := m.ReactionSummary(); got != "reactions=thumbsup:1,eyes:2" { t.Fatal(got) } m = &Message{Reactions: []Reaction{{Emoji: "thumbsup", Count: 1, Users: []string{"dana"}}, {Emoji: "eyes", Count: 7, Users: []string{"a", "b"}}}} if got := m.ReactionSummary(); got != "reactions=thumbsup:1(dana),eyes:7(a,b,…)" { t.Fatal(got) } if got := (&Message{}).ReactionSummary(); got != "" { t.Fatal(got) } } func TestThumbnailFilename(t *testing.T) { for _, c := range []struct{ name, typ, want string }{ {"photo.png", "image/jpeg", "photo.thumb.jpg"}, {"clip.mp4", "image/webp", "clip.thumb.webp"}, {"diagram.png", "image/png", "diagram.thumb.png"}, {"noext", "", "noext.thumb"}, } { if got := ThumbnailFilename(c.name, c.typ); got != c.want { t.Errorf("ThumbnailFilename(%q, %q) = %q, want %q", c.name, c.typ, got, c.want) } } } // sendServer handles CreateMessage, deduplicating by key when version says // the server can, and drops the connection before the first `drop` answers. type sendServer struct { apiv1connect.UnimplementedMessageServiceHandler discoveryv1connect.UnimplementedServerDiscoveryServiceHandler version string drop int deny bool mu sync.Mutex keys []string posted map[string]string // key → message ID } func (s *sendServer) calls() ([]string, int) { s.mu.Lock() defer s.mu.Unlock() return append([]string(nil), s.keys...), len(s.posted) } func (s *sendServer) CreateMessage(_ context.Context, req *connect.Request[apiv1.CreateMessageRequest]) (*connect.Response[apiv1.CreateMessageResponse], error) { if s.deny { return nil, connect.NewError(connect.CodePermissionDenied, errors.New("no")) } s.mu.Lock() defer s.mu.Unlock() key := req.Msg.GetIdempotencyKey() s.keys = append(s.keys, key) id, ok := s.posted[key] if !ok || s.version < "0.5.0-beta.21" { id = fmt.Sprintf("E%d", len(s.keys)) s.posted[key] = id } return connect.NewResponse(&apiv1.CreateMessageResponse{Message: &apiv1.Message{Id: id}}), nil } func (s *sendServer) GetServer(context.Context, *connect.Request[discoveryv1.GetServerRequest]) (*connect.Response[discoveryv1.GetServerResponse], error) { return connect.NewResponse(&discoveryv1.GetServerResponse{Profile: &apiv1.ServerPublicProfile{Version: s.version}}), nil } func (s *sendServer) client(t *testing.T) *Client { mux := http.NewServeMux() path, h := apiv1connect.NewMessageServiceHandler(s) mux.Handle("/api/connect"+path, http.StripPrefix("/api/connect", h)) path, h = discoveryv1connect.NewServerDiscoveryServiceHandler(s) mux.Handle("/api/connect"+path, http.StripPrefix("/api/connect", h)) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s.mu.Lock() drop := strings.HasSuffix(r.URL.Path, "/CreateMessage") && s.drop > 0 if drop { s.drop-- } s.mu.Unlock() if drop { mux.ServeHTTP(httptest.NewRecorder(), r) // posted, but the answer is lost conn, _, _ := w.(http.Hijacker).Hijack() conn.Close() return } mux.ServeHTTP(w, r) })) t.Cleanup(srv.Close) return New(srv.URL, "k", srv.Client()) } func TestPostRetriesKeyedSend(t *testing.T) { sendRetryDelays = []time.Duration{0, 0} s := &sendServer{version: "0.5.0-beta.21", drop: 1, posted: map[string]string{}} m, err := s.client(t).Post(context.Background(), "R1", "hi", PostOptions{}) if err != nil { t.Fatal(err) } keys, posted := s.calls() if len(keys) != 2 || keys[0] != keys[1] || len(keys[0]) != 36 || m.ID != "E1" || posted != 1 { t.Fatalf("keys %q, id %s, posted %d", keys, m.ID, posted) } } func TestPostGivesUpAfterRetries(t *testing.T) { sendRetryDelays = []time.Duration{0, 0} s := &sendServer{version: "0.5.0-beta.21", drop: 3, posted: map[string]string{}} if _, err := s.client(t).Post(context.Background(), "R1", "hi", PostOptions{}); connect.CodeOf(err) != connect.CodeUnavailable { t.Fatal(err) } if keys, posted := s.calls(); len(keys) != 3 || posted != 1 { t.Fatalf("keys %q, posted %d", keys, posted) } } func TestPostDoesNotRetryWithoutKeySupport(t *testing.T) { sendRetryDelays = []time.Duration{0, 0} for _, v := range []string{"0.5.0-beta.20", "", "dev"} { s := &sendServer{version: v, drop: 1, posted: map[string]string{}} if _, err := s.client(t).Post(context.Background(), "R1", "hi", PostOptions{}); err == nil { t.Fatalf("%q: retried", v) } if keys, _ := s.calls(); len(keys) != 1 { t.Fatalf("%q: %d sends", v, len(keys)) } } } func TestPostDoesNotRetryServerErrors(t *testing.T) { sendRetryDelays = []time.Duration{0, 0} s := &sendServer{version: "0.5.0-beta.21", deny: true, posted: map[string]string{}} if _, err := s.client(t).Post(context.Background(), "R1", "hi", PostOptions{}); connect.CodeOf(err) != connect.CodePermissionDenied { t.Fatal(err) } } type searchHandler struct { apiv1connect.UnimplementedMessageSearchServiceHandler code connect.Code } func (h *searchHandler) SearchMessages(context.Context, *connect.Request[apiv1.SearchMessagesRequest]) (*connect.Response[apiv1.SearchMessagesResponse], error) { return nil, connect.NewError(h.code, errors.New("search is off")) } func (h *searchHandler) GetStatus(context.Context, *connect.Request[apiv1.GetStatusRequest]) (*connect.Response[apiv1.GetStatusResponse], error) { return connect.NewResponse(&apiv1.GetStatusResponse{ State: apiv1.MessageSearchState_MESSAGE_SEARCH_STATE_INDEXING, RetryAfter: durationpb.New(30 * time.Second), }), nil } // Search explains a disabled server, and a provider that isn't ready yet // with the state and retry delay from GetStatus. func TestSearchErrors(t *testing.T) { for code, want := range map[connect.Code]string{ connect.CodeFailedPrecondition: "search_disabled: message search is turned off on this server", connect.CodeUnavailable: "search_unavailable: message search isn't ready yet (indexing); try again in 30s", } { mux := http.NewServeMux() path, handler := apiv1connect.NewMessageSearchServiceHandler(&searchHandler{code: code}) mux.Handle("/api/connect"+path, http.StripPrefix("/api/connect", handler)) srv := httptest.NewServer(mux) _, err := New(srv.URL, "k", srv.Client()).Search(context.Background(), SearchSpec{Query: "x"}) srv.Close() if err == nil || !strings.Contains(err.Error(), want) { t.Errorf("%v: got %v, want %q", code, err, want) } } // A server that can't be reached is a network error, not an index // that's still building. srv := httptest.NewServer(http.NotFoundHandler()) url := srv.URL srv.Close() _, err := New(url, "k", nil).Search(context.Background(), SearchSpec{Query: "x"}) if err == nil || strings.Contains(err.Error(), "search_unavailable") { t.Fatalf("unreachable server: got %v", err) } } func TestParseSearchTime(t *testing.T) { for in, want := range map[string]string{ "": "0001-01-01T00:00:00Z", "2026-10-20": "2026-10-20T00:00:00Z", "2026-10-20T14:00:00Z": "2026-10-20T14:00:00Z", "yesterday": "bad", "2026-10-20 14:00": "bad", } { got, ok := ParseSearchTime(in) if s := got.Format(time.RFC3339); (!ok && want != "bad") || (ok && s != want) { t.Errorf("%q: got %s ok=%v, want %s", in, s, ok, want) } } }