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:
@@ -1,3 +0,0 @@
|
||||
// Package auth handles password hashing (argon2id), session cookies,
|
||||
// CSRF tokens, and bearer-token verification for agents.
|
||||
package auth
|
||||
@@ -0,0 +1,87 @@
|
||||
// Package auth handles password hashing (argon2id), session
|
||||
// management, CSRF tokens, and bearer-token verification for agents.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// argon2id parameters following RFC 9106 §4 "second
|
||||
// recommended option" (memory-constrained):
|
||||
// - 64 MiB memory, 3 iterations, 4 lanes, 32-byte tag.
|
||||
// These are tunable per-deployment if a beefy controller wants to
|
||||
// crank them; we ship a defensible default.
|
||||
const (
|
||||
defaultMemoryKiB = 64 * 1024
|
||||
defaultIterations = 3
|
||||
defaultParallel = 4
|
||||
defaultSaltLen = 16
|
||||
defaultKeyLen = 32
|
||||
)
|
||||
|
||||
// HashPassword returns an argon2id-encoded string of the form
|
||||
// $argon2id$v=19$m=...,t=...,p=...$<salt>$<hash>
|
||||
// safe to store in a TEXT column. The salt is freshly random per call.
|
||||
func HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, defaultSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("auth: read salt: %w", err)
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), salt,
|
||||
defaultIterations, defaultMemoryKiB, defaultParallel, defaultKeyLen)
|
||||
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
defaultMemoryKiB, defaultIterations, defaultParallel,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(hash),
|
||||
), nil
|
||||
}
|
||||
|
||||
// VerifyPassword returns nil if password matches the encoded hash.
|
||||
// On any decode error or mismatch the error is non-nil — callers
|
||||
// should treat all non-nil returns as "invalid credentials" and not
|
||||
// leak which case it was.
|
||||
func VerifyPassword(encoded, password string) error {
|
||||
parts := strings.Split(encoded, "$")
|
||||
// "$argon2id$v=...$m=...,t=...,p=...$<salt>$<hash>" → 6 parts (leading empty)
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return errors.New("auth: unrecognised hash format")
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return fmt.Errorf("auth: parse version: %w", err)
|
||||
}
|
||||
if version != argon2.Version {
|
||||
return fmt.Errorf("auth: unsupported argon2 version %d", version)
|
||||
}
|
||||
var memory, iterations uint32
|
||||
var parallel uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d",
|
||||
&memory, &iterations, ¶llel); err != nil {
|
||||
return fmt.Errorf("auth: parse params: %w", err)
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return fmt.Errorf("auth: decode salt: %w", err)
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return fmt.Errorf("auth: decode hash: %w", err)
|
||||
}
|
||||
|
||||
got := argon2.IDKey([]byte(password), salt,
|
||||
iterations, memory, parallel, uint32(len(want)))
|
||||
|
||||
if subtle.ConstantTimeCompare(got, want) != 1 {
|
||||
return errors.New("auth: invalid password")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHashAndVerify(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pw := "correct horse battery staple"
|
||||
h, err := HashPassword(pw)
|
||||
if err != nil {
|
||||
t.Fatalf("hash: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(h, "$argon2id$") {
|
||||
t.Errorf("encoded form should start $argon2id$, got %q", h)
|
||||
}
|
||||
if err := VerifyPassword(h, pw); err != nil {
|
||||
t.Errorf("verify: %v", err)
|
||||
}
|
||||
if err := VerifyPassword(h, "wrong"); err == nil {
|
||||
t.Error("verify with wrong password should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEachHashIsUnique(t *testing.T) {
|
||||
t.Parallel()
|
||||
// Same password hashed twice → different encoded strings (different
|
||||
// salts). If this fails the salt is deterministic.
|
||||
a, _ := HashPassword("hunter2")
|
||||
b, _ := HashPassword("hunter2")
|
||||
if a == b {
|
||||
t.Fatal("two hashes of the same password collided — non-random salt?")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyRejectsMalformed(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []string{
|
||||
"",
|
||||
"not-a-hash",
|
||||
"$argon2i$v=19$m=64,t=3,p=4$AAAA$BBBB", // wrong variant
|
||||
"$argon2id$", // truncated
|
||||
"$argon2id$v=99$m=64,t=3,p=4$AAAA$BBBB", // bad version
|
||||
}
|
||||
for _, c := range cases {
|
||||
if err := VerifyPassword(c, "anything"); err == nil {
|
||||
t.Errorf("should reject malformed hash %q", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTokenUnique(t *testing.T) {
|
||||
t.Parallel()
|
||||
a, err := NewToken()
|
||||
if err != nil {
|
||||
t.Fatalf("token: %v", err)
|
||||
}
|
||||
b, _ := NewToken()
|
||||
if a == b {
|
||||
t.Fatal("two tokens collided — broken randomness")
|
||||
}
|
||||
if len(a) < 40 {
|
||||
t.Errorf("token suspiciously short: %q (%d bytes)", a, len(a))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashTokenStable(t *testing.T) {
|
||||
t.Parallel()
|
||||
// Same input → same hash. This is not a security property, just a
|
||||
// sanity check that we're using a regular hash not a salted one.
|
||||
h1 := HashToken("foo")
|
||||
h2 := HashToken("foo")
|
||||
if h1 != h2 {
|
||||
t.Errorf("HashToken not deterministic: %q vs %q", h1, h2)
|
||||
}
|
||||
if len(h1) != 64 { // sha256 hex
|
||||
t.Errorf("expected 64-char hex hash, got %d", len(h1))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
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[:])
|
||||
}
|
||||
Reference in New Issue
Block a user