phase 1 foundations: api types, store, crypto, auth
Lands the bottom three layers of Phase 1: P1-08 internal/api: protocol_version + envelope + every WS message shape from spec.md §6.2 (Hello, Heartbeat, Job*, Schedule*, etc). Wire-format tests pin the JSON shape so a rename here breaks tests instead of silently breaking the agent. P1-02 + P1-03 internal/store: SQLite via modernc.org/sqlite, embed.FS + a tiny version table for hand-rolled migrations. 0001_initial.sql covers every table from spec.md §5 plus enrollment_tokens and host_schedule_version. Typed accessors for users / sessions / enrollment / audit. WAL + foreign_keys + busy_timeout on by default. P1-06 internal/crypto: XChaCha20-Poly1305 AEAD wrapper with per-message random nonce. Key file lifecycle (generate + refuse-to-overwrite, load with size validation). Optional additionalData binds ciphertext to the row that owns it. P1-04 internal/auth (partial — passwords + tokens; sessions middleware lands with the HTTP handlers): argon2id following RFC 9106 (64 MiB / t=3 / p=4 / 32B), constant-time verify. HashToken stores SHA-256 of session/agent/enrollment tokens so a stolen DB doesn't hand over credentials. Build floor moves to Go 1.25 (modernc.org/sqlite v1.50+ requires it); CI + Dockerfile + README updated. Markdown lint diagnostics on tasks.md cleared. All packages tested. ~70 new tests pass in <1s. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CreateSession persists a session row. The token is hashed before
|
||||
// insert; the raw token is what the caller hands to the user (cookie).
|
||||
func (s *Store) CreateSession(ctx context.Context, sess Session, tokenHash string) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO sessions (id, user_id, created_at, expires_at, ip, ua)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
tokenHash,
|
||||
sess.UserID,
|
||||
sess.CreatedAt.UTC().Format(time.RFC3339Nano),
|
||||
sess.ExpiresAt.UTC().Format(time.RFC3339Nano),
|
||||
sess.IP, sess.UA)
|
||||
if err != nil {
|
||||
return fmt.Errorf("store: create session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LookupSession resolves a token hash to a session row, returning
|
||||
// ErrNotFound if the hash is unknown OR the session has expired.
|
||||
// We collapse "no row" and "expired" to the same error so the caller
|
||||
// can't tell them apart in error messages — that prevents enumeration
|
||||
// of valid token hashes.
|
||||
func (s *Store) LookupSession(ctx context.Context, tokenHash string) (*Session, error) {
|
||||
row := s.db.QueryRowContext(ctx,
|
||||
`SELECT id, user_id, created_at, expires_at, ip, ua
|
||||
FROM sessions
|
||||
WHERE id = ? AND expires_at > ?`,
|
||||
tokenHash, time.Now().UTC().Format(time.RFC3339Nano))
|
||||
|
||||
var sess Session
|
||||
var created, expires string
|
||||
var ip, ua sql.NullString
|
||||
if err := row.Scan(&sess.ID, &sess.UserID, &created, &expires, &ip, &ua); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("store: lookup session: %w", err)
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, created)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: parse created_at: %w", err)
|
||||
}
|
||||
sess.CreatedAt = t
|
||||
t, err = time.Parse(time.RFC3339Nano, expires)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: parse expires_at: %w", err)
|
||||
}
|
||||
sess.ExpiresAt = t
|
||||
if ip.Valid {
|
||||
sess.IP = ip.String
|
||||
}
|
||||
if ua.Valid {
|
||||
sess.UA = ua.String
|
||||
}
|
||||
return &sess, nil
|
||||
}
|
||||
|
||||
// DeleteSession removes a session row by token hash. Used on logout.
|
||||
func (s *Store) DeleteSession(ctx context.Context, tokenHash string) error {
|
||||
_, err := s.db.ExecContext(ctx, `DELETE FROM sessions WHERE id = ?`, tokenHash)
|
||||
if err != nil {
|
||||
return fmt.Errorf("store: delete session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PurgeExpiredSessions deletes session rows past their expires_at.
|
||||
// Run periodically from a background goroutine.
|
||||
func (s *Store) PurgeExpiredSessions(ctx context.Context) (int64, error) {
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
`DELETE FROM sessions WHERE expires_at <= ?`,
|
||||
time.Now().UTC().Format(time.RFC3339Nano))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("store: purge sessions: %w", err)
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return n, nil
|
||||
}
|
||||
Reference in New Issue
Block a user