c275f4ff4c
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>
35 lines
1.0 KiB
Go
35 lines
1.0 KiB
Go
package auth
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"fmt"
|
|
)
|
|
|
|
// TokenLen is the number of random bytes in session, CSRF, and
|
|
// enrollment tokens. 32 bytes = 256 bits of entropy, more than enough
|
|
// to be unguessable.
|
|
const TokenLen = 32
|
|
|
|
// NewToken returns a fresh URL-safe random token. Used for session
|
|
// IDs, CSRF tokens, agent bearer tokens, and one-time enrollment
|
|
// tokens. Returns base64url(no-padding) for compactness.
|
|
func NewToken() (string, error) {
|
|
buf := make([]byte, TokenLen)
|
|
if _, err := rand.Read(buf); err != nil {
|
|
return "", fmt.Errorf("auth: read random: %w", err)
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString(buf), nil
|
|
}
|
|
|
|
// HashToken returns a hex-encoded SHA-256 of the token. We store
|
|
// this rather than the raw token so a stolen DB doesn't yield
|
|
// session/agent credentials directly. SHA-256 (not argon2) is fine
|
|
// here because the input is already 256 bits of uniform random.
|
|
func HashToken(token string) string {
|
|
sum := sha256.Sum256([]byte(token))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|