This commit is contained in:
2026-06-22 08:55:57 +08:00
parent dbb87823e8
commit 6ade6e8fa9
325 changed files with 41131 additions and 855 deletions
+44 -35
View File
@@ -3,61 +3,70 @@
//
// The master key is supplied by the caller (see config.MasterKey) and never
// stored alongside the ciphertext.
//
// As of the secret-hardening epic, the underlying engine is KeyedEncryptor:
// every blob is sealed under a key *version* whose number is persisted in a
// per-row key_version column (the key material stays in env/KMS). The legacy
// Encryptor type below is a thin version-1 shim so the ~30 existing call sites
// — which neither know nor care about versions — compile and behave unchanged.
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"context"
"fmt"
"io"
)
// Encryptor 用 AES-256-GCM 加解密 secret。
// 密文格式:nonce(12) || ciphertext || tag。
// Encryptor 用 AES-256-GCM 加解密 secret(version-1 shim over KeyedEncryptor)
// 密文格式:nonce(12) || ciphertext || tag(与历史一致,未变)
type Encryptor struct {
gcm cipher.AEAD
keyed *KeyedEncryptor
version int
}
// NewEncryptor constructs an Encryptor from a 32-byte (AES-256) key.
// Any other key length yields an error rather than silently downgrading.
// It builds a KeyedEncryptor backed by an EnvProvider seeded with this key at
// version 1 and a static version-1 store, preserving the previous semantics.
func NewEncryptor(key []byte) (*Encryptor, error) {
if len(key) != 32 {
return nil, fmt.Errorf("key must be 32 bytes (got %d)", len(key))
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("aes new cipher: %w", err)
keyed := NewKeyedEncryptor(NewEnvProvider(key), NewStaticKeyStore(1))
// Eagerly validate the key by building the v1 AEAD once.
if _, err := keyed.gcmFor(context.Background(), 1); err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("new gcm: %w", err)
}
return &Encryptor{gcm: gcm}, nil
return &Encryptor{keyed: keyed, version: 1}, nil
}
// Encrypt seals plaintext with a fresh random nonce and returns
// nonce || ciphertext || tag.
// NewEncryptorFromKeyed wraps an existing KeyedEncryptor as a fixed-version
// Encryptor shim. version is the version this shim seals/opens with (the call
// sites that use the shim only ever round-trip a single logical version because
// the DB column travels separately). app.go uses this so workspace/chat/acp/run
// keep the *crypto.Encryptor argument while sharing one KeyedEncryptor.
func NewEncryptorFromKeyed(keyed *KeyedEncryptor, version int) *Encryptor {
if version < 1 {
version = 1
}
return &Encryptor{keyed: keyed, version: version}
}
// Keyed exposes the underlying KeyedEncryptor so version-aware callers (the
// re-encrypt job, rotate-key endpoint) can use EncryptVersion/DecryptVersion.
func (e *Encryptor) Keyed() *KeyedEncryptor { return e.keyed }
// Encrypt seals plaintext under the shim's version and returns
// nonce || ciphertext || tag (version travels via the DB key_version column).
func (e *Encryptor) Encrypt(plaintext []byte) ([]byte, error) {
nonce := make([]byte, e.gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, fmt.Errorf("rand nonce: %w", err)
}
// Seal 把 nonce 作为 dst 前缀写入
return e.gcm.Seal(nonce, nonce, plaintext, nil), nil
return e.keyed.sealWith(context.Background(), e.version, plaintext)
}
// Decrypt verifies and opens a ciphertext produced by Encrypt.
// It returns an error if the input is too short or authentication fails.
// Decrypt verifies and opens a ciphertext produced by Encrypt. It is
// version-agnostic: it tries the active key version then falls back through
// older versions (GCM auth guarantees correctness), so blobs re-sealed onto a
// newer version after a key rotation still open without the call site needing to
// know the row's key_version. Returns an error if input is too short or no key
// authenticates.
func (e *Encryptor) Decrypt(ciphertext []byte) ([]byte, error) {
if len(ciphertext) < e.gcm.NonceSize() {
return nil, errors.New("ciphertext too short")
}
nonce, ct := ciphertext[:e.gcm.NonceSize()], ciphertext[e.gcm.NonceSize():]
pt, err := e.gcm.Open(nil, nonce, ct, nil)
if err != nil {
return nil, fmt.Errorf("gcm open: %w", err)
}
return pt, nil
return e.keyed.DecryptAny(context.Background(), ciphertext)
}