Files
coredns-web-ui/session_store.go
T
bryanpedini 53444bec7a test(ui): avoid a literal em dash in the em dash check
- test(ui): avoid a literal em dash in the em dash check
- fix(cli): accept any positive int64 audit count and share the last active admin rule
- fix(api): limit audit before_id to 2^53-1
- fix(api): audit unmatched api requests, bound every request body and record audit write failures
- fix(ui): recheck the account in the login transaction and require existing zones on zone pages
- fix(api): recheck the acting admin and the stored password hash in change transactions
- fix(db): keep committed outcomes on lock release failure, narrow the records contract and trace sql statements
- fix(db): make the initial migration restartable and verify the application schema
- fix(auth): never move last_seen_at backwards on concurrent session touches
- test(api): cover lock release failure after commit and handler tracing without secrets
- fix(test): redact credentials from mysql setup errors
- fix(audit): retain addressed objects on admin refusals
- test(db): cover migration restarts and records contract ranges in mysql
- test(api): verify account races and audit rollback in mysql
- fix(auth): reject password changes after account deletion
- docs: document unknown api audit entries
- fix(audit): bound failure retries and redact sensitive sql parameters
- fix(test): isolate docker resources and cover image cli commands
- test(auth): expect unauthorized after an account deletion race
- fix(db): verify application column widths and foreign keys
2026-11-19 15:46:12 +01:00

114 lines
3.9 KiB
Go

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
)
type sessionRow struct {
TokenHash []byte
UserID int64
CreatedAt time.Time
LastSeenAt time.Time
ExpiresAt time.Time
Origin string
UserAgent string
}
type sessionWithUser struct {
Session sessionRow
User userRow
}
type sessionStore struct {
q dbtx
t tableNames
}
func newSessionStore(q dbtx, t tableNames) sessionStore {
return sessionStore{q: q, t: t}
}
func (s sessionStore) CreateSession(ctx context.Context, row sessionRow) error {
defer traceStore(ctx, "sessionStore.CreateSession")()
_, err := s.q.ExecContext(privateSQLArgs(ctx, 7),
s.t.sql("INSERT INTO {sessions} (`token_hash`, `user_id`, `created_at`, `last_seen_at`, `expires_at`, `origin`, `user_agent`) VALUES (?, ?, ?, ?, ?, ?, ?)"),
row.TokenHash, row.UserID, dbTime(row.CreatedAt), dbTime(row.LastSeenAt), dbTime(row.ExpiresAt), row.Origin, row.UserAgent)
if err != nil {
return fmt.Errorf("create session: %w", err)
}
return nil
}
func (s sessionStore) SessionByTokenHash(ctx context.Context, tokenHash []byte) (sessionWithUser, error) {
defer traceStore(ctx, "sessionStore.SessionByTokenHash")()
var r sessionWithUser
u, err := scanUser(s.q.QueryRowContext(ctx,
s.t.sql("SELECT "+userColumns+", x.`token_hash`, x.`user_id`, x.`created_at`, x.`last_seen_at`, x.`expires_at`, x.`origin`, x.`user_agent` "+
"FROM {sessions} x JOIN {users} u ON u.`id` = x.`user_id` WHERE x.`token_hash` = ?"), tokenHash),
&r.Session.TokenHash, &r.Session.UserID, &r.Session.CreatedAt, &r.Session.LastSeenAt, &r.Session.ExpiresAt, &r.Session.Origin, &r.Session.UserAgent)
if errors.Is(err, sql.ErrNoRows) {
return sessionWithUser{}, errRowNotFound
}
if err != nil {
return sessionWithUser{}, fmt.Errorf("read session: %w", err)
}
r.User = u
scanUTC(&r.Session.CreatedAt)
scanUTC(&r.Session.LastSeenAt)
scanUTC(&r.Session.ExpiresAt)
return r, nil
}
func (s sessionStore) TouchSession(ctx context.Context, tokenHash []byte, now time.Time) error {
defer traceStore(ctx, "sessionStore.TouchSession")()
now = dbTime(now)
if _, err := s.q.ExecContext(ctx, s.t.sql("UPDATE {sessions} SET `last_seen_at` = ? WHERE `token_hash` = ? AND `last_seen_at` <= ?"),
now, tokenHash, now.Add(-sessionTouchInterval)); err != nil {
return fmt.Errorf("touch session: %w", err)
}
return nil
}
func (s sessionStore) deleted(ctx context.Context, what, query string, args ...any) (int64, error) {
res, err := s.q.ExecContext(ctx, s.t.sql(query), args...)
if err != nil {
return 0, fmt.Errorf("%s: %w", what, err)
}
n, err := res.RowsAffected()
if err != nil {
return 0, fmt.Errorf("%s: %w", what, err)
}
return n, nil
}
func (s sessionStore) DeleteSession(ctx context.Context, tokenHash []byte) (bool, error) {
defer traceStore(ctx, "sessionStore.DeleteSession")()
n, err := s.deleted(ctx, "delete session", "DELETE FROM {sessions} WHERE `token_hash` = ?", tokenHash)
return n > 0, err
}
func (s sessionStore) DeleteUserSessions(ctx context.Context, userID int64) (int64, error) {
defer traceStore(ctx, "sessionStore.DeleteUserSessions")()
return s.deleted(ctx, "delete user sessions", "DELETE FROM {sessions} WHERE `user_id` = ?", userID)
}
func (s sessionStore) DeleteUserSessionsExcept(ctx context.Context, userID int64, keepTokenHash []byte) (int64, error) {
defer traceStore(ctx, "sessionStore.DeleteUserSessionsExcept")()
return s.deleted(ctx, "delete user sessions",
"DELETE FROM {sessions} WHERE `user_id` = ? AND `token_hash` <> ?", userID, keepTokenHash)
}
func (s sessionStore) DeleteExpiredSessions(ctx context.Context, now time.Time, idleTimeout time.Duration) (int64, error) {
defer traceStore(ctx, "sessionStore.DeleteExpiredSessions")()
now = dbTime(now)
return s.deleted(ctx, "delete expired sessions",
"DELETE FROM {sessions} WHERE `expires_at` <= ? OR `last_seen_at` <= ?", now, now.Add(-idleTimeout))
}