Files
restic-manager/internal/crypto/aead.go
T
steve f55747a281 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>
2026-05-01 00:24:40 +01:00

113 lines
3.7 KiB
Go

// Package crypto wraps AEAD encryption used to protect repo
// passwords, REST-server credentials, hook bodies, and any other
// secret that lands in the SQLite store.
//
// The threat model is "defense in depth against a stolen DB file" —
// not "an attacker with code execution can't read secrets at runtime."
// We need the encryption key at runtime to do any actual work, so
// anyone with a memory dump of the running server can extract it.
package crypto
import (
stdcipher "crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"os"
"golang.org/x/crypto/chacha20poly1305"
)
// KeyLen is the required length of the master key (XChaCha20-Poly1305
// uses a 32-byte key). Keys shorter than this are rejected at load.
const KeyLen = chacha20poly1305.KeySize // 32
// AEAD wraps an XChaCha20-Poly1305 instance with a 24-byte random
// nonce per message. Ciphertexts are encoded as
// base64(nonce || ciphertext_with_tag) for SQLite storage.
type AEAD struct {
cipher stdcipher.AEAD
}
// NewAEAD returns an AEAD using the given 32-byte key.
func NewAEAD(key []byte) (*AEAD, error) {
if len(key) != KeyLen {
return nil, fmt.Errorf("crypto: key must be %d bytes, got %d", KeyLen, len(key))
}
c, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, fmt.Errorf("crypto: init xchacha20poly1305: %w", err)
}
return &AEAD{cipher: c}, nil
}
// LoadKeyFromFile reads a 32-byte raw key from path. The file must
// be exactly KeyLen bytes long. Use GenerateKeyFile to mint a fresh
// one on first run.
func LoadKeyFromFile(path string) ([]byte, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("read key file %q: %w", path, err)
}
if len(data) != KeyLen {
return nil, fmt.Errorf("key file %q: expected %d bytes, got %d",
path, KeyLen, len(data))
}
return data, nil
}
// GenerateKeyFile writes a new 32-byte random key to path with mode
// 0600. It refuses to overwrite an existing file.
func GenerateKeyFile(path string) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return fmt.Errorf("create key file %q: %w", path, err)
}
defer f.Close()
key := make([]byte, KeyLen)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
return fmt.Errorf("read random: %w", err)
}
if _, err := f.Write(key); err != nil {
return fmt.Errorf("write key: %w", err)
}
return nil
}
// Encrypt seals plaintext under a fresh random nonce. The returned
// string is base64(nonce || ciphertext_with_tag) and is what gets
// stored in TEXT columns. Optional additionalData binds the
// ciphertext to a context (e.g. the row's primary key) so a swap
// attack between rows is detectable.
func (a *AEAD) Encrypt(plaintext, additionalData []byte) (string, error) {
nonce := make([]byte, a.cipher.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", fmt.Errorf("crypto: read nonce: %w", err)
}
ct := a.cipher.Seal(nil, nonce, plaintext, additionalData)
out := make([]byte, 0, len(nonce)+len(ct))
out = append(out, nonce...)
out = append(out, ct...)
return base64.StdEncoding.EncodeToString(out), nil
}
// Decrypt reverses Encrypt.
func (a *AEAD) Decrypt(ciphertext string, additionalData []byte) ([]byte, error) {
raw, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
return nil, fmt.Errorf("crypto: base64 decode: %w", err)
}
if len(raw) < a.cipher.NonceSize()+a.cipher.Overhead() {
return nil, errors.New("crypto: ciphertext too short")
}
nonce := raw[:a.cipher.NonceSize()]
ct := raw[a.cipher.NonceSize():]
pt, err := a.cipher.Open(nil, nonce, ct, additionalData)
if err != nil {
return nil, fmt.Errorf("crypto: open: %w", err)
}
return pt, nil
}