Files
chat/internal/db/queries.go
clawbot a57a73e94e
All checks were successful
check / check (push) Successful in 2m19s
fix: address all PR #10 review findings
Security:
- Add channel membership check before PRIVMSG (prevents non-members from sending)
- Add membership check on history endpoint (channels require membership, DMs scoped to own nick)
- Enforce MaxBytesReader on all POST request bodies
- Fix rand.Read error being silently ignored in token generation

Data integrity:
- Fix TOCTOU race in GetOrCreateChannel using INSERT OR IGNORE + SELECT

Build:
- Add CGO_ENABLED=0 to golangci-lint install in Dockerfile (fixes alpine build)

Linting:
- Strict .golangci.yml: only wsl disabled (deprecated in v2)
- Re-enable exhaustruct, depguard, godot, wrapcheck, varnamelen
- Fix linters-settings -> linters.settings for v2 config format
- Fix ALL lint findings in actual code (no linter config weakening)
- Wrap all external package errors (wrapcheck)
- Fill struct fields or add targeted nolint:exhaustruct where appropriate
- Rename short variables (ts->timestamp, n->bufIndex, etc.)
- Add depguard deny policy for io/ioutil and math/rand
- Exclude G704 (SSRF) in gosec config (CLI client takes user-configured URLs)

Tests:
- Add security tests (TestNonMemberCannotSend, TestHistoryNonMember)
- Split TestInsertAndPollMessages for reduced complexity
- Fix parallel test safety (viper global state prevents parallelism)
- Use t.Context() instead of context.Background() in tests

Docker build verified passing locally.
2026-02-26 21:21:49 -08:00

721 lines
14 KiB
Go

package db
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
)
const (
tokenBytes = 32
defaultPollLimit = 100
defaultHistLimit = 50
)
func generateToken() (string, error) {
buf := make([]byte, tokenBytes)
_, err := rand.Read(buf)
if err != nil {
return "", fmt.Errorf("generate token: %w", err)
}
return hex.EncodeToString(buf), nil
}
// IRCMessage is the IRC envelope for all messages.
type IRCMessage struct {
ID string `json:"id"`
Command string `json:"command"`
From string `json:"from,omitempty"`
To string `json:"to,omitempty"`
Body json.RawMessage `json:"body,omitempty"`
TS string `json:"ts"`
Meta json.RawMessage `json:"meta,omitempty"`
DBID int64 `json:"-"`
}
// ChannelInfo is a lightweight channel representation.
type ChannelInfo struct {
ID int64 `json:"id"`
Name string `json:"name"`
Topic string `json:"topic"`
}
// MemberInfo represents a channel member.
type MemberInfo struct {
ID int64 `json:"id"`
Nick string `json:"nick"`
LastSeen time.Time `json:"lastSeen"`
}
// CreateUser registers a new user with the given nick.
func (database *Database) CreateUser(
ctx context.Context,
nick string,
) (int64, string, error) {
token, err := generateToken()
if err != nil {
return 0, "", err
}
now := time.Now()
res, err := database.conn.ExecContext(ctx,
`INSERT INTO users
(nick, token, created_at, last_seen)
VALUES (?, ?, ?, ?)`,
nick, token, now, now)
if err != nil {
return 0, "", fmt.Errorf("create user: %w", err)
}
userID, _ := res.LastInsertId()
return userID, token, nil
}
// GetUserByToken returns user id and nick for a token.
func (database *Database) GetUserByToken(
ctx context.Context,
token string,
) (int64, string, error) {
var userID int64
var nick string
err := database.conn.QueryRowContext(
ctx,
"SELECT id, nick FROM users WHERE token = ?",
token,
).Scan(&userID, &nick)
if err != nil {
return 0, "", fmt.Errorf("get user by token: %w", err)
}
_, _ = database.conn.ExecContext(
ctx,
"UPDATE users SET last_seen = ? WHERE id = ?",
time.Now(), userID,
)
return userID, nick, nil
}
// GetUserByNick returns user id for a given nick.
func (database *Database) GetUserByNick(
ctx context.Context,
nick string,
) (int64, error) {
var userID int64
err := database.conn.QueryRowContext(
ctx,
"SELECT id FROM users WHERE nick = ?",
nick,
).Scan(&userID)
if err != nil {
return 0, fmt.Errorf("get user by nick: %w", err)
}
return userID, nil
}
// GetChannelByName returns the channel ID for a name.
func (database *Database) GetChannelByName(
ctx context.Context,
name string,
) (int64, error) {
var channelID int64
err := database.conn.QueryRowContext(
ctx,
"SELECT id FROM channels WHERE name = ?",
name,
).Scan(&channelID)
if err != nil {
return 0, fmt.Errorf(
"get channel by name: %w", err,
)
}
return channelID, nil
}
// GetOrCreateChannel returns channel id, creating if needed.
// Uses INSERT OR IGNORE to avoid TOCTOU races.
func (database *Database) GetOrCreateChannel(
ctx context.Context,
name string,
) (int64, error) {
now := time.Now()
_, err := database.conn.ExecContext(ctx,
`INSERT OR IGNORE INTO channels
(name, created_at, updated_at)
VALUES (?, ?, ?)`,
name, now, now)
if err != nil {
return 0, fmt.Errorf("create channel: %w", err)
}
var channelID int64
err = database.conn.QueryRowContext(
ctx,
"SELECT id FROM channels WHERE name = ?",
name,
).Scan(&channelID)
if err != nil {
return 0, fmt.Errorf("get channel: %w", err)
}
return channelID, nil
}
// JoinChannel adds a user to a channel.
func (database *Database) JoinChannel(
ctx context.Context,
channelID, userID int64,
) error {
_, err := database.conn.ExecContext(ctx,
`INSERT OR IGNORE INTO channel_members
(channel_id, user_id, joined_at)
VALUES (?, ?, ?)`,
channelID, userID, time.Now())
if err != nil {
return fmt.Errorf("join channel: %w", err)
}
return nil
}
// PartChannel removes a user from a channel.
func (database *Database) PartChannel(
ctx context.Context,
channelID, userID int64,
) error {
_, err := database.conn.ExecContext(ctx,
`DELETE FROM channel_members
WHERE channel_id = ? AND user_id = ?`,
channelID, userID)
if err != nil {
return fmt.Errorf("part channel: %w", err)
}
return nil
}
// DeleteChannelIfEmpty removes a channel with no members.
func (database *Database) DeleteChannelIfEmpty(
ctx context.Context,
channelID int64,
) error {
_, err := database.conn.ExecContext(ctx,
`DELETE FROM channels WHERE id = ?
AND NOT EXISTS
(SELECT 1 FROM channel_members
WHERE channel_id = ?)`,
channelID, channelID)
if err != nil {
return fmt.Errorf(
"delete channel if empty: %w", err,
)
}
return nil
}
// scanChannels scans rows into a ChannelInfo slice.
func scanChannels(
rows *sql.Rows,
) ([]ChannelInfo, error) {
defer func() { _ = rows.Close() }()
var out []ChannelInfo
for rows.Next() {
var chanInfo ChannelInfo
err := rows.Scan(
&chanInfo.ID, &chanInfo.Name, &chanInfo.Topic,
)
if err != nil {
return nil, fmt.Errorf("scan channel: %w", err)
}
out = append(out, chanInfo)
}
err := rows.Err()
if err != nil {
return nil, fmt.Errorf("rows error: %w", err)
}
if out == nil {
out = []ChannelInfo{}
}
return out, nil
}
// ListChannels returns channels the user has joined.
func (database *Database) ListChannels(
ctx context.Context,
userID int64,
) ([]ChannelInfo, error) {
rows, err := database.conn.QueryContext(ctx,
`SELECT c.id, c.name, c.topic
FROM channels c
INNER JOIN channel_members cm
ON cm.channel_id = c.id
WHERE cm.user_id = ?
ORDER BY c.name`, userID)
if err != nil {
return nil, fmt.Errorf("list channels: %w", err)
}
return scanChannels(rows)
}
// ListAllChannels returns every channel.
func (database *Database) ListAllChannels(
ctx context.Context,
) ([]ChannelInfo, error) {
rows, err := database.conn.QueryContext(ctx,
`SELECT id, name, topic
FROM channels ORDER BY name`)
if err != nil {
return nil, fmt.Errorf(
"list all channels: %w", err,
)
}
return scanChannels(rows)
}
// ChannelMembers returns all members of a channel.
func (database *Database) ChannelMembers(
ctx context.Context,
channelID int64,
) ([]MemberInfo, error) {
rows, err := database.conn.QueryContext(ctx,
`SELECT u.id, u.nick, u.last_seen
FROM users u
INNER JOIN channel_members cm
ON cm.user_id = u.id
WHERE cm.channel_id = ?
ORDER BY u.nick`, channelID)
if err != nil {
return nil, fmt.Errorf(
"query channel members: %w", err,
)
}
defer func() { _ = rows.Close() }()
var members []MemberInfo
for rows.Next() {
var member MemberInfo
err = rows.Scan(
&member.ID, &member.Nick, &member.LastSeen,
)
if err != nil {
return nil, fmt.Errorf(
"scan member: %w", err,
)
}
members = append(members, member)
}
err = rows.Err()
if err != nil {
return nil, fmt.Errorf("rows error: %w", err)
}
if members == nil {
members = []MemberInfo{}
}
return members, nil
}
// IsChannelMember checks if a user belongs to a channel.
func (database *Database) IsChannelMember(
ctx context.Context,
channelID, userID int64,
) (bool, error) {
var count int
err := database.conn.QueryRowContext(ctx,
`SELECT COUNT(*) FROM channel_members
WHERE channel_id = ? AND user_id = ?`,
channelID, userID,
).Scan(&count)
if err != nil {
return false, fmt.Errorf(
"check membership: %w", err,
)
}
return count > 0, nil
}
// scanInt64s scans rows into an int64 slice.
func scanInt64s(rows *sql.Rows) ([]int64, error) {
defer func() { _ = rows.Close() }()
var ids []int64
for rows.Next() {
var val int64
err := rows.Scan(&val)
if err != nil {
return nil, fmt.Errorf(
"scan int64: %w", err,
)
}
ids = append(ids, val)
}
err := rows.Err()
if err != nil {
return nil, fmt.Errorf("rows error: %w", err)
}
return ids, nil
}
// GetChannelMemberIDs returns user IDs in a channel.
func (database *Database) GetChannelMemberIDs(
ctx context.Context,
channelID int64,
) ([]int64, error) {
rows, err := database.conn.QueryContext(ctx,
`SELECT user_id FROM channel_members
WHERE channel_id = ?`, channelID)
if err != nil {
return nil, fmt.Errorf(
"get channel member ids: %w", err,
)
}
return scanInt64s(rows)
}
// GetUserChannelIDs returns channel IDs the user is in.
func (database *Database) GetUserChannelIDs(
ctx context.Context,
userID int64,
) ([]int64, error) {
rows, err := database.conn.QueryContext(ctx,
`SELECT channel_id FROM channel_members
WHERE user_id = ?`, userID)
if err != nil {
return nil, fmt.Errorf(
"get user channel ids: %w", err,
)
}
return scanInt64s(rows)
}
// InsertMessage stores a message and returns its DB ID.
func (database *Database) InsertMessage(
ctx context.Context,
command, from, target string,
body json.RawMessage,
meta json.RawMessage,
) (int64, string, error) {
msgUUID := uuid.New().String()
now := time.Now().UTC()
if body == nil {
body = json.RawMessage("[]")
}
if meta == nil {
meta = json.RawMessage("{}")
}
res, err := database.conn.ExecContext(ctx,
`INSERT INTO messages
(uuid, command, msg_from, msg_to,
body, meta, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
msgUUID, command, from, target,
string(body), string(meta), now)
if err != nil {
return 0, "", fmt.Errorf(
"insert message: %w", err,
)
}
dbID, _ := res.LastInsertId()
return dbID, msgUUID, nil
}
// EnqueueMessage adds a message to a user's queue.
func (database *Database) EnqueueMessage(
ctx context.Context,
userID, messageID int64,
) error {
_, err := database.conn.ExecContext(ctx,
`INSERT OR IGNORE INTO client_queues
(user_id, message_id, created_at)
VALUES (?, ?, ?)`,
userID, messageID, time.Now())
if err != nil {
return fmt.Errorf("enqueue message: %w", err)
}
return nil
}
// PollMessages returns queued messages for a user.
func (database *Database) PollMessages(
ctx context.Context,
userID, afterQueueID int64,
limit int,
) ([]IRCMessage, int64, error) {
if limit <= 0 {
limit = defaultPollLimit
}
rows, err := database.conn.QueryContext(ctx,
`SELECT cq.id, m.uuid, m.command,
m.msg_from, m.msg_to,
m.body, m.meta, m.created_at
FROM client_queues cq
INNER JOIN messages m
ON m.id = cq.message_id
WHERE cq.user_id = ? AND cq.id > ?
ORDER BY cq.id ASC LIMIT ?`,
userID, afterQueueID, limit)
if err != nil {
return nil, afterQueueID, fmt.Errorf(
"poll messages: %w", err,
)
}
msgs, lastQID, scanErr := scanMessages(
rows, afterQueueID,
)
if scanErr != nil {
return nil, afterQueueID, scanErr
}
return msgs, lastQID, nil
}
// GetHistory returns message history for a target.
func (database *Database) GetHistory(
ctx context.Context,
target string,
beforeID int64,
limit int,
) ([]IRCMessage, error) {
if limit <= 0 {
limit = defaultHistLimit
}
rows, err := database.queryHistory(
ctx, target, beforeID, limit,
)
if err != nil {
return nil, err
}
msgs, _, scanErr := scanMessages(rows, 0)
if scanErr != nil {
return nil, scanErr
}
if msgs == nil {
msgs = []IRCMessage{}
}
reverseMessages(msgs)
return msgs, nil
}
func (database *Database) queryHistory(
ctx context.Context,
target string,
beforeID int64,
limit int,
) (*sql.Rows, error) {
if beforeID > 0 {
rows, err := database.conn.QueryContext(ctx,
`SELECT id, uuid, command, msg_from,
msg_to, body, meta, created_at
FROM messages
WHERE msg_to = ? AND id < ?
AND command = 'PRIVMSG'
ORDER BY id DESC LIMIT ?`,
target, beforeID, limit)
if err != nil {
return nil, fmt.Errorf(
"query history: %w", err,
)
}
return rows, nil
}
rows, err := database.conn.QueryContext(ctx,
`SELECT id, uuid, command, msg_from,
msg_to, body, meta, created_at
FROM messages
WHERE msg_to = ?
AND command = 'PRIVMSG'
ORDER BY id DESC LIMIT ?`,
target, limit)
if err != nil {
return nil, fmt.Errorf("query history: %w", err)
}
return rows, nil
}
func scanMessages(
rows *sql.Rows,
fallbackQID int64,
) ([]IRCMessage, int64, error) {
defer func() { _ = rows.Close() }()
var msgs []IRCMessage
lastQID := fallbackQID
for rows.Next() {
var (
msg IRCMessage
qID int64
body, meta string
createdAt time.Time
)
err := rows.Scan(
&qID, &msg.ID, &msg.Command,
&msg.From, &msg.To,
&body, &meta, &createdAt,
)
if err != nil {
return nil, fallbackQID, fmt.Errorf(
"scan message: %w", err,
)
}
msg.Body = json.RawMessage(body)
msg.Meta = json.RawMessage(meta)
msg.TS = createdAt.Format(time.RFC3339Nano)
msg.DBID = qID
lastQID = qID
msgs = append(msgs, msg)
}
err := rows.Err()
if err != nil {
return nil, fallbackQID, fmt.Errorf(
"rows error: %w", err,
)
}
if msgs == nil {
msgs = []IRCMessage{}
}
return msgs, lastQID, nil
}
func reverseMessages(msgs []IRCMessage) {
for i, j := 0, len(msgs)-1; i < j; i, j = i+1, j-1 {
msgs[i], msgs[j] = msgs[j], msgs[i]
}
}
// ChangeNick updates a user's nickname.
func (database *Database) ChangeNick(
ctx context.Context,
userID int64,
newNick string,
) error {
_, err := database.conn.ExecContext(ctx,
"UPDATE users SET nick = ? WHERE id = ?",
newNick, userID)
if err != nil {
return fmt.Errorf("change nick: %w", err)
}
return nil
}
// SetTopic sets the topic for a channel.
func (database *Database) SetTopic(
ctx context.Context,
channelName, topic string,
) error {
_, err := database.conn.ExecContext(ctx,
`UPDATE channels SET topic = ?,
updated_at = ? WHERE name = ?`,
topic, time.Now(), channelName)
if err != nil {
return fmt.Errorf("set topic: %w", err)
}
return nil
}
// DeleteUser removes a user and all their data.
func (database *Database) DeleteUser(
ctx context.Context,
userID int64,
) error {
_, err := database.conn.ExecContext(
ctx,
"DELETE FROM users WHERE id = ?",
userID,
)
if err != nil {
return fmt.Errorf("delete user: %w", err)
}
return nil
}
// GetAllChannelMembershipsForUser returns channels
// a user belongs to.
func (database *Database) GetAllChannelMembershipsForUser(
ctx context.Context,
userID int64,
) ([]ChannelInfo, error) {
rows, err := database.conn.QueryContext(ctx,
`SELECT c.id, c.name, c.topic
FROM channels c
INNER JOIN channel_members cm
ON cm.channel_id = c.id
WHERE cm.user_id = ?`, userID)
if err != nil {
return nil, fmt.Errorf(
"get memberships: %w", err,
)
}
return scanChannels(rows)
}