Files
tenant-registry/internal/secretbox/secretbox.go
sharang 5b4590d3bc
ci / shared (push) Successful in 13s
ci / test (push) Successful in 25m10s
ci / image (push) Successful in 36s
feat(api-keys): CI licences by API key and integration keys (#71)
2026-10-13 22:12:05 +00:00

72 lines
1.9 KiB
Go

// Package secretbox seals small secrets the registry must hand out again
// (a CI licence's LiteLLM key, ADR 0001 §5) with AES-256-GCM under the
// SECRETS_ENCRYPTION_KEY. Format: nonce (12 bytes) || ciphertext+tag.
package secretbox
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
)
// Box seals and opens with one key. A nil *Box is valid and disabled.
type Box struct {
aead cipher.AEAD
}
// New parses a base64 (std or raw URL) encoded 32-byte key. Empty ⇒ nil, nil
// (disabled: callers fall back to not storing the secret).
func New(b64 string) (*Box, error) {
if b64 == "" {
return nil, nil
}
key, err := base64.StdEncoding.DecodeString(b64)
if err != nil {
if key, err = base64.RawURLEncoding.DecodeString(b64); err != nil {
return nil, errors.New("SECRETS_ENCRYPTION_KEY is not base64")
}
}
if len(key) != 32 {
return nil, fmt.Errorf("SECRETS_ENCRYPTION_KEY must be 32 bytes, got %d", len(key))
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aead, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
return &Box{aead: aead}, nil
}
// Enabled reports whether a key is configured.
func (b *Box) Enabled() bool { return b != nil }
// Seal encrypts plain; ad binds the ciphertext to its row (e.g. the licence id).
func (b *Box) Seal(plain, ad []byte) ([]byte, error) {
if b == nil {
return nil, errors.New("secretbox: disabled")
}
nonce := make([]byte, b.aead.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
return b.aead.Seal(nonce, nonce, plain, ad), nil
}
// Open decrypts what Seal produced with the same ad.
func (b *Box) Open(sealed, ad []byte) ([]byte, error) {
if b == nil {
return nil, errors.New("secretbox: disabled")
}
n := b.aead.NonceSize()
if len(sealed) < n {
return nil, errors.New("secretbox: ciphertext too short")
}
return b.aead.Open(nil, sealed[:n], sealed[n:], ad)
}