Initial commit: CarrotAssistant backend (Go + Gin + SQLite, OpenAI-compatible agent runtime)
This commit is contained in:
97
internal/security/crypto.go
Normal file
97
internal/security/crypto.go
Normal file
@@ -0,0 +1,97 @@
|
||||
// Package security provides the security primitives used across the backend:
|
||||
// symmetric encryption for secrets at rest, hashing for access tokens and
|
||||
// passwords, and the prompt-injection / least-privilege controls applied by
|
||||
// the agent runtime.
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// Crypto wraps an AES-GCM cipher derived from a master key. It is used to
|
||||
// encrypt model API keys at rest.
|
||||
type Crypto struct {
|
||||
aead cipher.AEAD
|
||||
}
|
||||
|
||||
// NewCrypto initialises an AES-GCM cipher from a 32-byte master key.
|
||||
func NewCrypto(masterKey string) (*Crypto, error) {
|
||||
if len(masterKey) != 32 {
|
||||
return nil, fmt.Errorf("master key must be 32 bytes, got %d", len(masterKey))
|
||||
}
|
||||
block, err := aes.NewCipher([]byte(masterKey))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create aes cipher: %w", err)
|
||||
}
|
||||
aead, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create gcm: %w", err)
|
||||
}
|
||||
return &Crypto{aead: aead}, nil
|
||||
}
|
||||
|
||||
// Encrypt returns a base64-encoded ciphertext of the plaintext. A random
|
||||
// nonce is prepended to the ciphertext.
|
||||
func (c *Crypto) Encrypt(plaintext string) (string, error) {
|
||||
if plaintext == "" {
|
||||
return "", nil
|
||||
}
|
||||
nonce := make([]byte, c.aead.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", fmt.Errorf("read nonce: %w", err)
|
||||
}
|
||||
ct := c.aead.Seal(nonce, nonce, []byte(plaintext), nil)
|
||||
return base64.StdEncoding.EncodeToString(ct), nil
|
||||
}
|
||||
|
||||
// Decrypt reverses Encrypt. An empty input yields an empty output.
|
||||
func (c *Crypto) Decrypt(b64 string) (string, error) {
|
||||
if b64 == "" {
|
||||
return "", nil
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(b64)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("base64 decode: %w", err)
|
||||
}
|
||||
ns := c.aead.NonceSize()
|
||||
if len(raw) < ns {
|
||||
return "", errors.New("ciphertext too short")
|
||||
}
|
||||
pt, err := c.aead.Open(nil, raw[:ns], raw[ns:], nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("gcm open: %w", err)
|
||||
}
|
||||
return string(pt), nil
|
||||
}
|
||||
|
||||
// HashToken returns a hex SHA-256 digest of an app access token. Tokens are
|
||||
// random and high-entropy, so a plain hash (no salt) is sufficient and keeps
|
||||
// lookups O(1) on the unique index.
|
||||
func HashToken(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// HashPassword returns a bcrypt hash of a password.
|
||||
func HashPassword(password string) (string, error) {
|
||||
b, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("bcrypt: %w", err)
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// VerifyPassword checks a bcrypt hash against a plaintext password.
|
||||
func VerifyPassword(hash, password string) bool {
|
||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
|
||||
}
|
||||
66
internal/security/tokens.go
Normal file
66
internal/security/tokens.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// GenerateToken returns a cryptographically random access token. The prefix
|
||||
// makes accidentally-leaked tokens grep-able in logs and lets frontends tell
|
||||
// app tokens apart from other credential kinds.
|
||||
func GenerateToken(prefix string) (string, error) {
|
||||
b := make([]byte, 24)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("read random: %w", err)
|
||||
}
|
||||
p := strings.TrimSpace(prefix)
|
||||
if p == "" {
|
||||
p = "ca"
|
||||
}
|
||||
return fmt.Sprintf("%s_live_%s", p, hex.EncodeToString(b)), nil
|
||||
}
|
||||
|
||||
// GenerateAPIKeyPreview returns the last 4 characters of an API key, for
|
||||
// display in the admin UI ("...ab12") so operators can identify a key
|
||||
// without exposing it.
|
||||
func GenerateAPIKeyPreview(key string) string {
|
||||
key = strings.TrimSpace(key)
|
||||
if len(key) <= 4 {
|
||||
return ""
|
||||
}
|
||||
return key[len(key)-4:]
|
||||
}
|
||||
|
||||
// RandomSlug returns a short random slug for cases where a name has no
|
||||
// ASCII slug characters (pure CJK names, emoji, ...). Used as a fallback so
|
||||
// every app/skill is still addressable on disk.
|
||||
func RandomSlug() string {
|
||||
b := make([]byte, 5)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
// rand.Read failing is catastrophic; fall back to a fixed value so we
|
||||
// never return an empty slug.
|
||||
return "app"
|
||||
}
|
||||
return "app-" + hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// Slugify converts an arbitrary string into a filesystem- and URL-safe slug.
|
||||
// Used for app and skill identifiers that become directory / file names.
|
||||
// Non-ASCII characters (CJK, etc.) are dropped; callers that need a guaranteed
|
||||
// usable slug should fall back to a generated token when the result is empty.
|
||||
func Slugify(s string) string {
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
var b strings.Builder
|
||||
b.Grow(len(s))
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
|
||||
b.WriteRune(r)
|
||||
case r == ' ' || r == '-' || r == '_':
|
||||
b.WriteRune('-')
|
||||
}
|
||||
}
|
||||
return strings.Trim(b.String(), "-")
|
||||
}
|
||||
Reference in New Issue
Block a user