Files
restic-manager/internal/crypto/aead.go
T
steve f0dfa689fe P3 follow-up: editable target dir, conditional --no-ownership, UK lint
Three small follow-ups from review:

1. Restore target is now operator-editable. Default value is the
   literal '\$HOME/rm-restore/<job-id>/' (agent expands \$HOME at
   run time using os.UserHomeDir(); also handles \${HOME} and ~/
   prefixes). Operator can replace with any absolute path.
   - ui_restore.go validates the input is either absolute or starts
     with one of the recognised prefixes; other env-var refs (\$PATH
     etc.) are deliberately rejected so operator paths can't pick up
     arbitrary agent env values.
   - host_restore.html replaces the read-only mono-text display with
     a real <input>; help text spells out that \$HOME resolves
     agent-side and <job-id> is substituted on dispatch.
   - install.sh + the systemd unit prep /root/rm-restore so the
     default works under the sandbox: ReadWritePaths gains a soft
     '-/root/rm-restore' entry (the '-' makes the bind-mount soft-fail
     if missing, but install.sh pre-creates it root-owned 0700).

2. --no-ownership flag now gated on restic version. The flag was
   added in restic 0.17 and 0.16 rejects it. Previously dropped it
   wholesale — that meant new-dir restores silently preserved
   ownership against design intent on 0.17+. Now the agent threads
   its detected restic version (sysinfo already collects it) through
   runner.Config -> restic.Env, and RunRestore appends --no-ownership
   only when AtLeastVersion(0, 17) returns true. 0.16 hosts still
   restore with original uid/gid; help text in the wizard explicitly
   notes this. The previous 'Original ownership is preserved' copy
   was wrong for new-dir mode and is corrected.

3. golangci-lint misspell locale switched US -> UK and the codebase
   swept (73 corrections, mostly behaviour/serialise/recognise/honour).
   Wire-format ErrorCode 'unauthorized' -> 'unauthorised' is a tiny
   contract change but the agent doesn't parse those codes today and
   no external API consumers exist yet. Tests passed before + after.

Tests:
- internal/restic/version_test.go covers Env.AtLeastVersion across
  edge cases (empty, exact match, patch above, minor below, non-
  numeric) and expandHome on \$HOME / \${HOME} / ~/, plus
  pass-through for absolute paths and refusal of other env vars.
- ui_restore_test updated: TargetDir now starts '\$HOME/rm-restore/'
  with the job_id substituted into the placeholder.

Live verified on the smoke env: default target restored to
/root/rm-restore/<job-id>/ as the agent's expanded \$HOME (2 files,
14 bytes); custom override '/tmp/custom-restore/<job-id>/' restored
into the agent's PrivateTmp namespace (1 file, 6 bytes); both jobs
'succeeded', exit 0.
2026-05-04 17:27:52 +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 "defence 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 func() { _ = 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
}