76ada04442
Resolve final-review findings: commandRole is now the single source of truth (Run resolves role once and threads it to handlers, replacing hardcoded openStore roles). Tighten crypto/SKILL/SPEC/USER-MANUAL wording and document init's agent-key-on-first-init-only semantics. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
79 lines
2.1 KiB
Go
79 lines
2.1 KiB
Go
// Package crypto provides AES-256-GCM field encryption; keys are loaded from EMCLI_KEY (agent) or EMCLI_ADMIN_KEY (admin).
|
|
package crypto
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
// keyFromEnv reads and validates a base64-encoded 32-byte AES key from the
|
|
// named environment variable. Errors name the variable so callers get a
|
|
// role-appropriate message.
|
|
func keyFromEnv(varName string) ([]byte, error) {
|
|
raw := os.Getenv(varName)
|
|
if raw == "" {
|
|
return nil, fmt.Errorf("%s is not set", varName)
|
|
}
|
|
key, err := base64.StdEncoding.DecodeString(raw)
|
|
if err != nil || len(key) != 32 {
|
|
return nil, fmt.Errorf("%s must be base64 of exactly 32 bytes", varName)
|
|
}
|
|
return key, nil
|
|
}
|
|
|
|
// AgentKeyFromEnv reads the agent KEK from EMCLI_KEY (agent commands only).
|
|
func AgentKeyFromEnv() ([]byte, error) { return keyFromEnv("EMCLI_KEY") }
|
|
|
|
// AdminKeyFromEnv reads the admin KEK from EMCLI_ADMIN_KEY (all commands).
|
|
func AdminKeyFromEnv() ([]byte, error) { return keyFromEnv("EMCLI_ADMIN_KEY") }
|
|
|
|
// NewDEK returns a fresh random 32-byte data-encryption key.
|
|
func NewDEK() ([]byte, error) {
|
|
dek := make([]byte, 32)
|
|
if _, err := io.ReadFull(rand.Reader, dek); err != nil {
|
|
return nil, err
|
|
}
|
|
return dek, nil
|
|
}
|
|
|
|
func newGCM(key []byte) (cipher.AEAD, error) {
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return cipher.NewGCM(block)
|
|
}
|
|
|
|
// Seal encrypts plaintext, returning nonce||ciphertext.
|
|
func Seal(key, plaintext []byte) ([]byte, error) {
|
|
gcm, err := newGCM(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return nil, err
|
|
}
|
|
return gcm.Seal(nonce, nonce, plaintext, nil), nil
|
|
}
|
|
|
|
// Open reverses Seal. A wrong key or tampered blob returns an error.
|
|
func Open(key, blob []byte) ([]byte, error) {
|
|
gcm, err := newGCM(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ns := gcm.NonceSize()
|
|
if len(blob) < ns {
|
|
return nil, errors.New("ciphertext too short")
|
|
}
|
|
nonce, ct := blob[:ns], blob[ns:]
|
|
return gcm.Open(nil, nonce, ct, nil)
|
|
}
|