fixed a bug with NUL in strings

This commit is contained in:
Нурлыгаянова Екатерина
2026-10-29 14:34:10 +03:00
parent 98ffd9ff45
commit 5021df4ea8
10 changed files with 177 additions and 36 deletions
+3 -1
View File
@@ -50,7 +50,7 @@ func (c *Chats) CreateChat(ctx context.Context, callerID, title string, memberID
INSERT INTO chats (title)
VALUES ($1)
RETURNING id::text, created_at`,
title,
encodeText(title),
).Scan(&chat.ID, &chat.CreatedAt)
if err != nil {
return domain.Chat{}, mapErr(err)
@@ -95,6 +95,7 @@ func (c *Chats) ChatByID(ctx context.Context, callerID, chatID string) (domain.C
}
return domain.Chat{}, err
}
chat.Title = decodeText(chat.Title)
chat.CreatedAt = chat.CreatedAt.UTC()
return chat, nil
}
@@ -134,6 +135,7 @@ func (c *Chats) ListChats(ctx context.Context, callerID, cursor string, limit in
out, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (domain.Chat, error) {
var ch domain.Chat
err := r.Scan(&ch.ID, &ch.Title, &ch.CreatedAt, &ch.MemberIDs)
ch.Title = decodeText(ch.Title)
ch.CreatedAt = ch.CreatedAt.UTC()
return ch, err
})
+47
View File
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"errors"
"os"
"strings"
"sync"
"testing"
"time"
@@ -128,3 +129,49 @@ func TestMessageRequiresMembership(t *testing.T) {
t.Fatalf("err = %v, want ErrNotFound (→ 404)", err)
}
}
func TestNULRoundTrip(t *testing.T) {
d, _ := testDB(t)
ctx := context.Background()
const name = "A\x00B\\0\\"
u, err := d.CreateUser(ctx, "nul_"+suffix(), name, "$argon2id$test")
if err != nil {
t.Fatalf("CreateUser: %v", err)
}
if got, err := d.UserByID(ctx, u.ID); err != nil || got.DisplayName != name {
t.Fatalf("UserByID = %q, %v; want %q", got.DisplayName, err, name)
}
if _, _, err := d.CredentialsByUsername(ctx, "a\x00b"); !errors.Is(err, domain.ErrNotFound) {
t.Fatalf("CredentialsByUsername(NUL) err = %v, want ErrNotFound", err)
}
chat, err := d.CreateChat(ctx, u.ID, name, []string{u.ID})
if err != nil {
t.Fatalf("CreateChat: %v", err)
}
if got, err := d.ChatByID(ctx, u.ID, chat.ID); err != nil || got.Title != name {
t.Fatalf("ChatByID = %q, %v; want %q", got.Title, err, name)
}
texts := []string{"\x00", "a\x00b", `\0`, `\\`, strings.Repeat("\x00", 4000), strings.Repeat(`\`, 4000)}
for _, text := range texts {
if _, err := d.AddMessage(ctx, u.ID, chat.ID, text); err != nil {
t.Fatalf("AddMessage(%q...): %v", text[:min(len(text), 8)], err)
}
}
if _, err := d.AddMessage(ctx, u.ID, chat.ID, strings.Repeat(`\`, 4001)); !errors.Is(err, domain.ErrInvalidArgument) {
t.Fatalf("AddMessage(4001 code points) err = %v, want ErrInvalidArgument", err)
}
page, err := d.HistoryPage(ctx, chat.ID, "", 100)
if err != nil {
t.Fatal(err)
}
if len(page.Items) != len(texts) {
t.Fatalf("history len = %d, want %d", len(page.Items), len(texts))
}
for i, m := range page.Items {
if m.Text != texts[i] {
t.Fatalf("history[%d] = %q, want %q", i, m.Text, texts[i])
}
}
}
+2 -1
View File
@@ -26,7 +26,7 @@ func (m *Messages) AddMessage(ctx context.Context, callerID, chatID, text string
INSERT INTO messages (chat_id, sender_id, text)
VALUES ($1, $2, $3)
RETURNING id::text, created_at`,
chatID, callerID, text,
chatID, callerID, encodeText(text),
).Scan(&msg.ID, &msg.CreatedAt)
if err != nil {
if isFKViolation(err) {
@@ -107,6 +107,7 @@ func (m *Messages) HistoryPage(ctx context.Context, chatID, cursor string, limit
out, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (domain.Message, error) {
var msg domain.Message
err := r.Scan(&msg.ID, &msg.ChatID, &msg.AuthorID, &msg.Text, &msg.CreatedAt)
msg.Text = decodeText(msg.Text)
msg.CreatedAt = msg.CreatedAt.UTC()
return msg, err
})
+22
View File
@@ -0,0 +1,22 @@
package db
import "strings"
var (
textEncoder = strings.NewReplacer(`\`, `\\`, "\x00", `\0`)
textDecoder = strings.NewReplacer(`\\`, `\`, `\0`, "\x00")
)
func encodeText(s string) string {
if !strings.ContainsAny(s, "\\\x00") {
return s
}
return textEncoder.Replace(s)
}
func decodeText(s string) string {
if !strings.Contains(s, `\`) {
return s
}
return textDecoder.Replace(s)
}
+18
View File
@@ -0,0 +1,18 @@
package db
import "testing"
func TestTextEscapeRoundTrip(t *testing.T) {
cases := []string{"", "plain", "\x00", "a\x00b", `\`, `\0`, `\\0`, "\\\x00", "\x00\\0\x00", "привет\x00мир"}
for _, s := range cases {
enc := encodeText(s)
for i := 0; i < len(enc); i++ {
if enc[i] == 0 {
t.Fatalf("encodeText(%q) = %q содержит NUL", s, enc)
}
}
if got := decodeText(enc); got != s {
t.Fatalf("decodeText(encodeText(%q)) = %q", s, got)
}
}
}
+5 -3
View File
@@ -24,7 +24,7 @@ func (u *Users) CreateUser(ctx context.Context, username, displayName, passwordH
INSERT INTO users (username, display_name, password_hash)
VALUES ($1, $2, $3)
RETURNING id::text, created_at`,
username, displayName, passwordHash,
username, encodeText(displayName), passwordHash,
).Scan(&user.ID, &user.CreatedAt)
if err != nil {
return domain.User{}, mapErr(err)
@@ -51,6 +51,7 @@ func (u *Users) UserByID(ctx context.Context, id string) (domain.User, error) {
}
return domain.User{}, err
}
user.DisplayName = decodeText(user.DisplayName)
user.CreatedAt = user.CreatedAt.UTC()
return user, nil
}
@@ -65,11 +66,12 @@ func (u *Users) CredentialsByUsername(ctx context.Context, username string) (dom
SELECT id::text, username, display_name, created_at, password_hash
FROM users
WHERE username = $1`,
username,
encodeText(username),
).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
if err != nil {
return domain.User{}, "", mapErr(err)
}
user.DisplayName = decodeText(user.DisplayName)
user.CreatedAt = user.CreatedAt.UTC()
return user, hash, nil
}
@@ -81,7 +83,7 @@ func (u *Users) UsernameExists(ctx context.Context, username string) bool {
var exists bool
err := u.pool.QueryRow(ctx,
`SELECT EXISTS (SELECT 1 FROM users WHERE username = $1)`,
username,
encodeText(username),
).Scan(&exists)
return err == nil && exists
}