b6f8de1dcc
Cleanup pass over the repo so CI can enforce lint going forward
without the only-new-issues escape hatch:
* gofumpt -w across the tree (31 hits, all formatting)
* misspell --fix (25 hits, US-locale spelling) — but reverted on
api.JobCancelled = "cancelled" since that literal is the wire +
DB CHECK constraint value, plus matched the case in store/fleet.go
back to "cancelled" and added //nolint:misspell on both for the
next time someone reaches for the auto-fix
* Wrap every `defer rows.Close()` / `defer stmt.Close()` /
`defer res.Body.Close()` in `defer func() { _ = .Close() }()`
to satisfy errcheck without losing the close itself
* websocket.Dial callers (1 prod, 4 tests) now capture + close the
upgrade response Body — coder/websocket can return res with a nil
Body on success, so the test deferred-closes guard against that
* Annotate the two genuine-by-design nilerr cases with //nolint
comments explaining why nil-on-error is the contract (cookie
missing = no session; ctx cancelled mid-backoff = clean shutdown)
* Add brief godoc on the 10 exported const groups + types that
revive flagged (api.HostOS/HostArch/JobKind/JobStatus/LogStream/
ErrorCode, restic.EventKind, store.Role, web.FS)
* Drop the unused (*Server).userByID method
* Inline the unparam baseView(active) — every UI page is under
the dashboard primary nav today
Result: `golangci-lint run ./...` reports 0 issues. CI lint job
no longer needs only-new-issues: true; X-06 follow-up entry in
tasks.md removed.
113 lines
3.7 KiB
Go
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 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
|
|
}
|