mirror of
https://github.com/R0m1k3/FlowReader.git
synced 2026-10-22 22:58:06 +02:00
fix(backend): harden security and speed up feeds and article API
Security: - WebSocket events are routed to their owner only (no cross-user leak); hub close is idempotent (fixes double-close panic), adds ping/pong and write deadlines. - Session tokens stored as SHA-256 (migration 008 keeps sessions valid); single-query auth middleware puts the user in the request context. - Client IP only trusts X-Forwarded-For from TRUSTED_PROXIES; rate limiter map is bounded; per-user limit on AI summaries. - Argon2id at OWASP minimum with a concurrency cap; constant-time login for unknown emails; atomic first-admin bootstrap; REGISTRATION_ENABLED. - CSP/HSTS/COOP headers, same-origin guard on mutations, body size limits, wider SSRF denylist, bounded feed/page/AI response reads, generic errors. - Upgrade chi, pgx, x/net, x/text, x/crypto (known CVEs); commit go.sum. Performance: - List endpoints return a plain-text excerpt and reading time instead of full HTML; content is sanitized once at ingest (legacy rows backfilled). - Keyset pagination on (sort_at, id) with matching partial indexes; redundant indexes dropped (migration 007). - Fetcher: bounded worker pool, conditional GET (ETag/Last-Modified), exponential backoff, dedupe before insert, column-safe truncation, retention-aware ingest, per-user refresh coalescing. - Read/favorite/read-all are single ownership-scoped statements. - gzip compression, immutable caching for hashed assets, path-safe SPA handler, server timeouts; expired sessions purged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d037e2be34
commit
03e57e4308
40 files changed
+2231
-1898
No files matched your search
@@ -2,6 +2,8 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
@@ -12,6 +14,9 @@ import (
|
||||
)
|
||||
|
||||
// SessionRepository implements domain.SessionRepository using PostgreSQL.
|
||||
//
|
||||
// Only the SHA-256 of a session token is stored, so a database leak does not
|
||||
// hand out live sessions. Callers always pass the raw token.
|
||||
type SessionRepository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
@@ -21,6 +26,12 @@ func NewSessionRepository(pool *pgxpool.Pool) *SessionRepository {
|
||||
return &SessionRepository{pool: pool}
|
||||
}
|
||||
|
||||
// hashToken returns the hex SHA-256 of a raw session token.
|
||||
func hashToken(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// Create inserts a new session into the database.
|
||||
func (r *SessionRepository) Create(session *domain.Session) error {
|
||||
ctx := context.Background()
|
||||
@@ -33,7 +44,7 @@ func (r *SessionRepository) Create(session *domain.Session) error {
|
||||
_, err := r.pool.Exec(ctx, query,
|
||||
session.ID,
|
||||
session.UserID,
|
||||
session.Token,
|
||||
hashToken(session.Token),
|
||||
session.ExpiresAt,
|
||||
session.CreatedAt,
|
||||
session.UserAgent,
|
||||
@@ -47,22 +58,21 @@ func (r *SessionRepository) Create(session *domain.Session) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByToken retrieves a session by its token.
|
||||
// GetByToken retrieves a non-expired session by its raw token.
|
||||
func (r *SessionRepository) GetByToken(token string) (*domain.Session, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
query := `
|
||||
SELECT id, user_id, token, expires_at, created_at, user_agent, ip_address
|
||||
SELECT id, user_id, expires_at, created_at, user_agent, ip_address
|
||||
FROM sessions
|
||||
WHERE token = $1 AND expires_at > NOW()
|
||||
`
|
||||
|
||||
var session domain.Session
|
||||
var userAgent, ipAddress *string
|
||||
err := r.pool.QueryRow(ctx, query, token).Scan(
|
||||
err := r.pool.QueryRow(ctx, query, hashToken(token)).Scan(
|
||||
&session.ID,
|
||||
&session.UserID,
|
||||
&session.Token,
|
||||
&session.ExpiresAt,
|
||||
&session.CreatedAt,
|
||||
&userAgent,
|
||||
@@ -76,22 +86,40 @@ func (r *SessionRepository) GetByToken(token string) (*domain.Session, error) {
|
||||
return nil, fmt.Errorf("getting session by token: %w", err)
|
||||
}
|
||||
|
||||
if userAgent != nil {
|
||||
session.UserAgent = *userAgent
|
||||
}
|
||||
if ipAddress != nil {
|
||||
session.IPAddress = *ipAddress
|
||||
}
|
||||
session.Token = token
|
||||
session.UserAgent = deref(userAgent)
|
||||
session.IPAddress = deref(ipAddress)
|
||||
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
// Delete removes a session by its token.
|
||||
// GetUserByToken resolves a raw session token to its user in one round trip.
|
||||
// Returns nil, nil when the session is unknown or expired.
|
||||
func (r *SessionRepository) GetUserByToken(ctx context.Context, token string) (*domain.User, error) {
|
||||
const query = `
|
||||
SELECT u.id, u.email, u.created_at, u.role
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token = $1 AND s.expires_at > NOW()`
|
||||
|
||||
var u domain.User
|
||||
err := r.pool.QueryRow(ctx, query, hashToken(token)).Scan(&u.ID, &u.Email, &u.CreatedAt, &u.Role)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("resolving session: %w", err)
|
||||
}
|
||||
u.IsAdmin = u.Role == domain.RoleAdmin
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// Delete removes a session by its raw token.
|
||||
func (r *SessionRepository) Delete(token string) error {
|
||||
ctx := context.Background()
|
||||
|
||||
query := `DELETE FROM sessions WHERE token = $1`
|
||||
_, err := r.pool.Exec(ctx, query, token)
|
||||
_, err := r.pool.Exec(ctx, query, hashToken(token))
|
||||
if err != nil {
|
||||
return fmt.Errorf("deleting session: %w", err)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user