fix: address all PR #10 review findings
All checks were successful
check / check (push) Successful in 2m19s

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.
This commit is contained in:
clawbot
2026-02-26 21:21:49 -08:00
parent 4b4a337a88
commit a57a73e94e
22 changed files with 2650 additions and 1903 deletions

View File

@@ -18,11 +18,15 @@ const (
defaultHistLimit = 50
)
func generateToken() string {
b := make([]byte, tokenBytes)
_, _ = rand.Read(b)
func generateToken() (string, error) {
buf := make([]byte, tokenBytes)
return hex.EncodeToString(b)
_, 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.
@@ -52,14 +56,18 @@ type MemberInfo struct {
}
// CreateUser registers a new user with the given nick.
func (s *Database) CreateUser(
func (database *Database) CreateUser(
ctx context.Context,
nick string,
) (int64, string, error) {
token := generateToken()
token, err := generateToken()
if err != nil {
return 0, "", err
}
now := time.Now()
res, err := s.db.ExecContext(ctx,
res, err := database.conn.ExecContext(ctx,
`INSERT INTO users
(nick, token, created_at, last_seen)
VALUES (?, ?, ?, ?)`,
@@ -68,90 +76,88 @@ func (s *Database) CreateUser(
return 0, "", fmt.Errorf("create user: %w", err)
}
id, _ := res.LastInsertId()
userID, _ := res.LastInsertId()
return id, token, nil
return userID, token, nil
}
// GetUserByToken returns user id and nick for a token.
func (s *Database) GetUserByToken(
func (database *Database) GetUserByToken(
ctx context.Context,
token string,
) (int64, string, error) {
var id int64
var userID int64
var nick string
err := s.db.QueryRowContext(
err := database.conn.QueryRowContext(
ctx,
"SELECT id, nick FROM users WHERE token = ?",
token,
).Scan(&id, &nick)
).Scan(&userID, &nick)
if err != nil {
return 0, "", err
return 0, "", fmt.Errorf("get user by token: %w", err)
}
_, _ = s.db.ExecContext(
_, _ = database.conn.ExecContext(
ctx,
"UPDATE users SET last_seen = ? WHERE id = ?",
time.Now(), id,
time.Now(), userID,
)
return id, nick, nil
return userID, nick, nil
}
// GetUserByNick returns user id for a given nick.
func (s *Database) GetUserByNick(
func (database *Database) GetUserByNick(
ctx context.Context,
nick string,
) (int64, error) {
var id int64
var userID int64
err := s.db.QueryRowContext(
err := database.conn.QueryRowContext(
ctx,
"SELECT id FROM users WHERE nick = ?",
nick,
).Scan(&id)
).Scan(&userID)
if err != nil {
return 0, fmt.Errorf("get user by nick: %w", err)
}
return id, err
return userID, nil
}
// GetChannelByName returns the channel ID for a name.
func (s *Database) GetChannelByName(
func (database *Database) GetChannelByName(
ctx context.Context,
name string,
) (int64, error) {
var id int64
var channelID int64
err := s.db.QueryRowContext(
err := database.conn.QueryRowContext(
ctx,
"SELECT id FROM channels WHERE name = ?",
name,
).Scan(&id)
).Scan(&channelID)
if err != nil {
return 0, fmt.Errorf(
"get channel by name: %w", err,
)
}
return id, err
return channelID, nil
}
// GetOrCreateChannel returns channel id, creating if needed.
func (s *Database) GetOrCreateChannel(
// Uses INSERT OR IGNORE to avoid TOCTOU races.
func (database *Database) GetOrCreateChannel(
ctx context.Context,
name string,
) (int64, error) {
var id int64
err := s.db.QueryRowContext(
ctx,
"SELECT id FROM channels WHERE name = ?",
name,
).Scan(&id)
if err == nil {
return id, nil
}
now := time.Now()
res, err := s.db.ExecContext(ctx,
`INSERT INTO channels
_, err := database.conn.ExecContext(ctx,
`INSERT OR IGNORE INTO channels
(name, created_at, updated_at)
VALUES (?, ?, ?)`,
name, now, now)
@@ -159,51 +165,71 @@ func (s *Database) GetOrCreateChannel(
return 0, fmt.Errorf("create channel: %w", err)
}
id, _ = res.LastInsertId()
var channelID int64
return id, nil
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 (s *Database) JoinChannel(
func (database *Database) JoinChannel(
ctx context.Context,
channelID, userID int64,
) error {
_, err := s.db.ExecContext(ctx,
_, 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 err
return nil
}
// PartChannel removes a user from a channel.
func (s *Database) PartChannel(
func (database *Database) PartChannel(
ctx context.Context,
channelID, userID int64,
) error {
_, err := s.db.ExecContext(ctx,
_, 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 err
return nil
}
// DeleteChannelIfEmpty removes a channel with no members.
func (s *Database) DeleteChannelIfEmpty(
func (database *Database) DeleteChannelIfEmpty(
ctx context.Context,
channelID int64,
) error {
_, err := s.db.ExecContext(ctx,
_, 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 err
return nil
}
// scanChannels scans rows into a ChannelInfo slice.
@@ -215,19 +241,21 @@ func scanChannels(
var out []ChannelInfo
for rows.Next() {
var ch ChannelInfo
var chanInfo ChannelInfo
err := rows.Scan(&ch.ID, &ch.Name, &ch.Topic)
err := rows.Scan(
&chanInfo.ID, &chanInfo.Name, &chanInfo.Topic,
)
if err != nil {
return nil, err
return nil, fmt.Errorf("scan channel: %w", err)
}
out = append(out, ch)
out = append(out, chanInfo)
}
err := rows.Err()
if err != nil {
return nil, err
return nil, fmt.Errorf("rows error: %w", err)
}
if out == nil {
@@ -238,11 +266,11 @@ func scanChannels(
}
// ListChannels returns channels the user has joined.
func (s *Database) ListChannels(
func (database *Database) ListChannels(
ctx context.Context,
userID int64,
) ([]ChannelInfo, error) {
rows, err := s.db.QueryContext(ctx,
rows, err := database.conn.QueryContext(ctx,
`SELECT c.id, c.name, c.topic
FROM channels c
INNER JOIN channel_members cm
@@ -250,32 +278,34 @@ func (s *Database) ListChannels(
WHERE cm.user_id = ?
ORDER BY c.name`, userID)
if err != nil {
return nil, err
return nil, fmt.Errorf("list channels: %w", err)
}
return scanChannels(rows)
}
// ListAllChannels returns every channel.
func (s *Database) ListAllChannels(
func (database *Database) ListAllChannels(
ctx context.Context,
) ([]ChannelInfo, error) {
rows, err := s.db.QueryContext(ctx,
rows, err := database.conn.QueryContext(ctx,
`SELECT id, name, topic
FROM channels ORDER BY name`)
if err != nil {
return nil, err
return nil, fmt.Errorf(
"list all channels: %w", err,
)
}
return scanChannels(rows)
}
// ChannelMembers returns all members of a channel.
func (s *Database) ChannelMembers(
func (database *Database) ChannelMembers(
ctx context.Context,
channelID int64,
) ([]MemberInfo, error) {
rows, err := s.db.QueryContext(ctx,
rows, err := database.conn.QueryContext(ctx,
`SELECT u.id, u.nick, u.last_seen
FROM users u
INNER JOIN channel_members cm
@@ -283,7 +313,9 @@ func (s *Database) ChannelMembers(
WHERE cm.channel_id = ?
ORDER BY u.nick`, channelID)
if err != nil {
return nil, err
return nil, fmt.Errorf(
"query channel members: %w", err,
)
}
defer func() { _ = rows.Close() }()
@@ -291,19 +323,23 @@ func (s *Database) ChannelMembers(
var members []MemberInfo
for rows.Next() {
var m MemberInfo
var member MemberInfo
err = rows.Scan(&m.ID, &m.Nick, &m.LastSeen)
err = rows.Scan(
&member.ID, &member.Nick, &member.LastSeen,
)
if err != nil {
return nil, err
return nil, fmt.Errorf(
"scan member: %w", err,
)
}
members = append(members, m)
members = append(members, member)
}
err = rows.Err()
if err != nil {
return nil, err
return nil, fmt.Errorf("rows error: %w", err)
}
if members == nil {
@@ -313,6 +349,27 @@ func (s *Database) ChannelMembers(
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() }()
@@ -320,58 +377,64 @@ func scanInt64s(rows *sql.Rows) ([]int64, error) {
var ids []int64
for rows.Next() {
var id int64
var val int64
err := rows.Scan(&id)
err := rows.Scan(&val)
if err != nil {
return nil, err
return nil, fmt.Errorf(
"scan int64: %w", err,
)
}
ids = append(ids, id)
ids = append(ids, val)
}
err := rows.Err()
if err != nil {
return nil, err
return nil, fmt.Errorf("rows error: %w", err)
}
return ids, nil
}
// GetChannelMemberIDs returns user IDs in a channel.
func (s *Database) GetChannelMemberIDs(
func (database *Database) GetChannelMemberIDs(
ctx context.Context,
channelID int64,
) ([]int64, error) {
rows, err := s.db.QueryContext(ctx,
rows, err := database.conn.QueryContext(ctx,
`SELECT user_id FROM channel_members
WHERE channel_id = ?`, channelID)
if err != nil {
return nil, err
return nil, fmt.Errorf(
"get channel member ids: %w", err,
)
}
return scanInt64s(rows)
}
// GetUserChannelIDs returns channel IDs the user is in.
func (s *Database) GetUserChannelIDs(
func (database *Database) GetUserChannelIDs(
ctx context.Context,
userID int64,
) ([]int64, error) {
rows, err := s.db.QueryContext(ctx,
rows, err := database.conn.QueryContext(ctx,
`SELECT channel_id FROM channel_members
WHERE user_id = ?`, userID)
if err != nil {
return nil, err
return nil, fmt.Errorf(
"get user channel ids: %w", err,
)
}
return scanInt64s(rows)
}
// InsertMessage stores a message and returns its DB ID.
func (s *Database) InsertMessage(
func (database *Database) InsertMessage(
ctx context.Context,
command, from, to string,
command, from, target string,
body json.RawMessage,
meta json.RawMessage,
) (int64, string, error) {
@@ -386,38 +449,43 @@ func (s *Database) InsertMessage(
meta = json.RawMessage("{}")
}
res, err := s.db.ExecContext(ctx,
res, err := database.conn.ExecContext(ctx,
`INSERT INTO messages
(uuid, command, msg_from, msg_to,
body, meta, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
msgUUID, command, from, to,
msgUUID, command, from, target,
string(body), string(meta), now)
if err != nil {
return 0, "", err
return 0, "", fmt.Errorf(
"insert message: %w", err,
)
}
id, _ := res.LastInsertId()
dbID, _ := res.LastInsertId()
return id, msgUUID, nil
return dbID, msgUUID, nil
}
// EnqueueMessage adds a message to a user's queue.
func (s *Database) EnqueueMessage(
func (database *Database) EnqueueMessage(
ctx context.Context,
userID, messageID int64,
) error {
_, err := s.db.ExecContext(ctx,
_, 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 err
return nil
}
// PollMessages returns queued messages for a user.
func (s *Database) PollMessages(
func (database *Database) PollMessages(
ctx context.Context,
userID, afterQueueID int64,
limit int,
@@ -426,7 +494,7 @@ func (s *Database) PollMessages(
limit = defaultPollLimit
}
rows, err := s.db.QueryContext(ctx,
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
@@ -437,7 +505,9 @@ func (s *Database) PollMessages(
ORDER BY cq.id ASC LIMIT ?`,
userID, afterQueueID, limit)
if err != nil {
return nil, afterQueueID, err
return nil, afterQueueID, fmt.Errorf(
"poll messages: %w", err,
)
}
msgs, lastQID, scanErr := scanMessages(
@@ -451,7 +521,7 @@ func (s *Database) PollMessages(
}
// GetHistory returns message history for a target.
func (s *Database) GetHistory(
func (database *Database) GetHistory(
ctx context.Context,
target string,
beforeID int64,
@@ -461,7 +531,7 @@ func (s *Database) GetHistory(
limit = defaultHistLimit
}
rows, err := s.queryHistory(
rows, err := database.queryHistory(
ctx, target, beforeID, limit,
)
if err != nil {
@@ -482,14 +552,14 @@ func (s *Database) GetHistory(
return msgs, nil
}
func (s *Database) queryHistory(
func (database *Database) queryHistory(
ctx context.Context,
target string,
beforeID int64,
limit int,
) (*sql.Rows, error) {
if beforeID > 0 {
return s.db.QueryContext(ctx,
rows, err := database.conn.QueryContext(ctx,
`SELECT id, uuid, command, msg_from,
msg_to, body, meta, created_at
FROM messages
@@ -497,9 +567,16 @@ func (s *Database) queryHistory(
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
}
return s.db.QueryContext(ctx,
rows, err := database.conn.QueryContext(ctx,
`SELECT id, uuid, command, msg_from,
msg_to, body, meta, created_at
FROM messages
@@ -507,6 +584,11 @@ func (s *Database) queryHistory(
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(
@@ -521,33 +603,37 @@ func scanMessages(
for rows.Next() {
var (
m IRCMessage
msg IRCMessage
qID int64
body, meta string
ts time.Time
createdAt time.Time
)
err := rows.Scan(
&qID, &m.ID, &m.Command,
&m.From, &m.To,
&body, &meta, &ts,
&qID, &msg.ID, &msg.Command,
&msg.From, &msg.To,
&body, &meta, &createdAt,
)
if err != nil {
return nil, fallbackQID, err
return nil, fallbackQID, fmt.Errorf(
"scan message: %w", err,
)
}
m.Body = json.RawMessage(body)
m.Meta = json.RawMessage(meta)
m.TS = ts.Format(time.RFC3339Nano)
m.DBID = qID
msg.Body = json.RawMessage(body)
msg.Meta = json.RawMessage(meta)
msg.TS = createdAt.Format(time.RFC3339Nano)
msg.DBID = qID
lastQID = qID
msgs = append(msgs, m)
msgs = append(msgs, msg)
}
err := rows.Err()
if err != nil {
return nil, fallbackQID, err
return nil, fallbackQID, fmt.Errorf(
"rows error: %w", err,
)
}
if msgs == nil {
@@ -564,59 +650,70 @@ func reverseMessages(msgs []IRCMessage) {
}
// ChangeNick updates a user's nickname.
func (s *Database) ChangeNick(
func (database *Database) ChangeNick(
ctx context.Context,
userID int64,
newNick string,
) error {
_, err := s.db.ExecContext(ctx,
_, err := database.conn.ExecContext(ctx,
"UPDATE users SET nick = ? WHERE id = ?",
newNick, userID)
if err != nil {
return fmt.Errorf("change nick: %w", err)
}
return err
return nil
}
// SetTopic sets the topic for a channel.
func (s *Database) SetTopic(
func (database *Database) SetTopic(
ctx context.Context,
channelName, topic string,
) error {
_, err := s.db.ExecContext(ctx,
_, 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 err
return nil
}
// DeleteUser removes a user and all their data.
func (s *Database) DeleteUser(
func (database *Database) DeleteUser(
ctx context.Context,
userID int64,
) error {
_, err := s.db.ExecContext(
_, err := database.conn.ExecContext(
ctx,
"DELETE FROM users WHERE id = ?",
userID,
)
if err != nil {
return fmt.Errorf("delete user: %w", err)
}
return err
return nil
}
// GetAllChannelMembershipsForUser returns channels
// a user belongs to.
func (s *Database) GetAllChannelMembershipsForUser(
func (database *Database) GetAllChannelMembershipsForUser(
ctx context.Context,
userID int64,
) ([]ChannelInfo, error) {
rows, err := s.db.QueryContext(ctx,
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, err
return nil, fmt.Errorf(
"get memberships: %w", err,
)
}
return scanChannels(rows)