fix: 目录搜索转义 LIKE 通配符并拒绝编号 inline

This commit is contained in:
Nixevol
2026-09-30 16:21:51 +08:00
parent 05a3741fde
commit 8ca545ae99
6 changed files with 74 additions and 3 deletions
+5 -3
View File
@@ -122,13 +122,15 @@ WHERE id > ?
ORDER BY id ASC
LIMIT ?`, cursor, limit+1)
} else {
like := "%" + strings.ToLower(query) + "%"
prefix := strings.ToLower(query) + "%"
q := strings.ToLower(query)
esc := escapeLikePattern(q)
like := "%" + esc + "%"
prefix := esc + "%"
rows, err = a.db.Read.QueryContext(ctx, `
SELECT id, name, online_since, offline_since, talk_hash
FROM endpoints
WHERE id > ?
AND (lower(id) LIKE ? OR lower(name) LIKE ?)
AND (lower(id) LIKE ? ESCAPE '\' OR lower(name) LIKE ? ESCAPE '\')
ORDER BY id ASC
LIMIT ?`, cursor, prefix, like, limit+1)
}
+16
View File
@@ -0,0 +1,16 @@
package presence
import "strings"
func escapeLikePattern(s string) string {
var b strings.Builder
b.Grow(len(s) + 4)
for _, r := range s {
switch r {
case '\\', '%', '_':
b.WriteByte('\\')
}
b.WriteRune(r)
}
return b.String()
}
+29
View File
@@ -131,6 +131,35 @@ func TestF03PresenceAndDirectory(t *testing.T) {
}
}
func TestDirectoryLikeEscapesUnderscore(t *testing.T) {
t.Parallel()
app, db, _ := openPresence(t)
ctx := context.Background()
insertEP(t, db, "e_ab1", "underscore")
insertEP(t, db, "exab2", "wildcard")
insertEP(t, db, "pct", "has%percent")
q, _, err := app.Directory(ctx, &protocol.DirectoryList{
V: protocol.Version, Type: protocol.TypeDirectoryList, RID: "u1", Query: "e_ab", Limit: 10,
})
if err != nil {
t.Fatal(err)
}
if len(q) != 1 || q[0].ID != "e_ab1" {
t.Fatalf("want only e_ab1, got %+v", q)
}
q, _, err = app.Directory(ctx, &protocol.DirectoryList{
V: protocol.Version, Type: protocol.TypeDirectoryList, RID: "u2", Query: "%", Limit: 10,
})
if err != nil {
t.Fatal(err)
}
if len(q) != 1 || q[0].ID != "pct" {
t.Fatalf("literal %% should not match all, got %+v", q)
}
}
func TestF04PresenceWatch(t *testing.T) {
t.Parallel()
app, db, down := openPresence(t)