统一 frontend、backend、test、test-log 和 out 目录,更新构建、部署及测试入口;纳入配置管理兼容与首次安全引导修复;排除本机配置、密钥和测试产物。
This commit is contained in:
1 parent
28cd9d3406
commit
f60d3b0880
603 files changed
+2351
-660
No files matched your search
@@ -0,0 +1,225 @@
|
||||
package externalemail
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidBinding = errors.New("invalid external email binding")
|
||||
ErrBindingExists = errors.New("external email binding already exists")
|
||||
ErrPrimaryLimit = errors.New("primary external email already exists")
|
||||
ErrBackupLimit = errors.New("backup external email already exists")
|
||||
ErrBindingNotFound = errors.New("external email binding not found")
|
||||
ErrBindingOwnership = errors.New("external email binding ownership denied")
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
engine *xorm.Engine
|
||||
vault *Vault
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type BindRequest struct {
|
||||
UserID int
|
||||
Email string
|
||||
Type string
|
||||
}
|
||||
|
||||
func NewRepository(engine *xorm.Engine, vault *Vault) (*Repository, error) {
|
||||
if engine == nil || vault == nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
return &Repository{engine: engine, vault: vault, now: time.Now}, nil
|
||||
}
|
||||
|
||||
func (r *Repository) Bind(request BindRequest) (*models.ExternalEmail, error) {
|
||||
if r == nil || r.engine == nil || r.vault == nil || request.UserID <= 0 {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
if request.Type != models.ExternalEmailTypePrimary && request.Type != models.ExternalEmailTypeBackup {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
normalized, err := NormalizeEmail(request.Email)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
fingerprint, err := r.vault.Fingerprint(normalized)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ciphertext, err := r.vault.Encrypt(normalized)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var existing models.ExternalEmail
|
||||
has, err := r.engine.Where("user_id = ? AND email_fingerprint = ?", request.UserID, fingerprint).Get(&existing)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("check external email binding: %w", err)
|
||||
}
|
||||
if has {
|
||||
return nil, ErrBindingExists
|
||||
}
|
||||
var count int64
|
||||
count, err = r.engine.Where("user_id = ? AND email_type = ? AND status != ?", request.UserID, request.Type, models.ExternalEmailStatusDisabled).Count(&models.ExternalEmail{})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("count external email bindings: %w", err)
|
||||
}
|
||||
if request.Type == models.ExternalEmailTypePrimary && count >= 1 {
|
||||
return nil, ErrPrimaryLimit
|
||||
}
|
||||
if request.Type == models.ExternalEmailTypeBackup && count >= 1 {
|
||||
return nil, ErrBackupLimit
|
||||
}
|
||||
now := r.now().UTC()
|
||||
item := &models.ExternalEmail{
|
||||
UserID: request.UserID,
|
||||
EmailCiphertext: ciphertext,
|
||||
EmailFingerprint: fingerprint,
|
||||
EmailType: request.Type,
|
||||
Status: models.ExternalEmailStatusPending,
|
||||
CredentialVersion: 1,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if _, err := r.engine.Insert(item); err != nil {
|
||||
return nil, fmt.Errorf("create external email binding: %w", err)
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) List(userID int) ([]models.ExternalEmail, error) {
|
||||
if r == nil || r.engine == nil || userID <= 0 {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
var items []models.ExternalEmail
|
||||
if err := r.engine.Where("user_id = ?", userID).OrderBy("id asc").Find(&items); err != nil {
|
||||
return nil, fmt.Errorf("list external email bindings: %w", err)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// FindVerifiedByEmail 仅返回已验证且仍启用的邮箱绑定,调用方不能跨用户使用结果。
|
||||
func (r *Repository) FindVerifiedByEmail(email string) (*models.ExternalEmail, error) {
|
||||
if r == nil || r.engine == nil || r.vault == nil {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
normalized, err := NormalizeEmail(email)
|
||||
if err != nil {
|
||||
return nil, ErrBindingNotFound
|
||||
}
|
||||
fingerprint, err := r.vault.Fingerprint(normalized)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item := &models.ExternalEmail{}
|
||||
has, err := r.engine.Where("email_fingerprint = ? AND status = ?", fingerprint, models.ExternalEmailStatusVerified).Get(item)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find verified external email: %w", err)
|
||||
}
|
||||
if !has {
|
||||
return nil, ErrBindingNotFound
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) FindVerifiedByID(userID, id int) (*models.ExternalEmail, error) {
|
||||
if r == nil || r.engine == nil || userID <= 0 || id <= 0 {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
item := &models.ExternalEmail{}
|
||||
has, err := r.engine.Where("id = ? AND user_id = ? AND status = ?", id, userID, models.ExternalEmailStatusVerified).Get(item)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find verified external email by id: %w", err)
|
||||
}
|
||||
if !has {
|
||||
return nil, ErrBindingNotFound
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) Verify(userID, id int) error {
|
||||
if r == nil || r.engine == nil || userID <= 0 || id <= 0 {
|
||||
return ErrInvalidBinding
|
||||
}
|
||||
item := &models.ExternalEmail{}
|
||||
has, err := r.engine.Where("id = ? AND user_id = ?", id, userID).Get(item)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load external email binding: %w", err)
|
||||
}
|
||||
if !has {
|
||||
return ErrBindingOwnership
|
||||
}
|
||||
if item.Status == models.ExternalEmailStatusDisabled {
|
||||
return ErrBindingNotFound
|
||||
}
|
||||
item.Status = models.ExternalEmailStatusVerified
|
||||
item.VerifiedAt = timePtr(r.now().UTC())
|
||||
item.UpdatedAt = r.now().UTC()
|
||||
if _, err := r.engine.ID(id).Cols("status", "verified_at", "updated_at").Where("user_id = ?", userID).Update(item); err != nil {
|
||||
return fmt.Errorf("verify external email binding: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AbandonPending 删除当前请求刚创建且尚未验证的绑定,供投递失败时回滚。
|
||||
func (r *Repository) AbandonPending(userID, id int) error {
|
||||
if r == nil || r.engine == nil || userID <= 0 || id <= 0 {
|
||||
return ErrInvalidBinding
|
||||
}
|
||||
affected, err := r.engine.Where("id = ? AND user_id = ? AND status = ?", id, userID, models.ExternalEmailStatusPending).Delete(&models.ExternalEmail{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("abandon pending external email: %w", err)
|
||||
}
|
||||
if affected != 1 {
|
||||
return ErrBindingOwnership
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) Disable(userID, id int) error {
|
||||
if r == nil || r.engine == nil || userID <= 0 || id <= 0 {
|
||||
return ErrInvalidBinding
|
||||
}
|
||||
updated, err := r.engine.Table(&models.ExternalEmail{}).
|
||||
Where("id = ? AND user_id = ? AND status != ?", id, userID, models.ExternalEmailStatusDisabled).
|
||||
Cols("status", "updated_at").Update(&models.ExternalEmail{Status: models.ExternalEmailStatusDisabled, UpdatedAt: r.now().UTC()})
|
||||
if err != nil {
|
||||
return fmt.Errorf("disable external email binding: %w", err)
|
||||
}
|
||||
if updated == 0 {
|
||||
return ErrBindingOwnership
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindVerifiedPrimaryByUser 返回当前用户唯一有效的主要外部邮箱。
|
||||
func (r *Repository) FindVerifiedPrimaryByUser(userID int) (*models.ExternalEmail, error) {
|
||||
if r == nil || r.engine == nil || r.vault == nil || userID <= 0 {
|
||||
return nil, ErrInvalidBinding
|
||||
}
|
||||
item := &models.ExternalEmail{}
|
||||
has, err := r.engine.Where("user_id = ? AND email_type = ? AND status = ?", userID, models.ExternalEmailTypePrimary, models.ExternalEmailStatusVerified).Get(item)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find verified primary external email: %w", err)
|
||||
}
|
||||
if !has {
|
||||
return nil, ErrBindingNotFound
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
func (r *Repository) Decrypt(item models.ExternalEmail) (string, error) {
|
||||
if r == nil || r.vault == nil || strings.TrimSpace(item.EmailCiphertext) == "" {
|
||||
return "", ErrInvalidBinding
|
||||
}
|
||||
return r.vault.Decrypt(item.EmailCiphertext)
|
||||
}
|
||||
|
||||
func timePtr(value time.Time) *time.Time {
|
||||
return &value
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package externalemail
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
_ "modernc.org/sqlite"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
func TestRepositoryBindsVerifiesAndScopesByUser(t *testing.T) {
|
||||
engine, err := xorm.NewEngine("sqlite", filepath.Join(t.TempDir(), "external.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer engine.Close()
|
||||
if err := engine.Sync2(&models.ExternalEmail{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vault := NewVaultWithKeys([]byte("01234567890123456789012345678901"), []byte("abcdefabcdefabcdefabcdefabcdefab"))
|
||||
repo, err := NewRepository(engine, vault)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item, err := repo.Bind(BindRequest{UserID: 1, Email: "Owner@Example.com", Type: models.ExternalEmailTypePrimary})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if item.Status != models.ExternalEmailStatusPending || item.EmailCiphertext == "" {
|
||||
t.Fatalf("unexpected binding: %+v", item)
|
||||
}
|
||||
if _, err := repo.Bind(BindRequest{UserID: 1, Email: "other@example.com", Type: models.ExternalEmailTypePrimary}); err != ErrPrimaryLimit {
|
||||
t.Fatalf("primary limit error = %v", err)
|
||||
}
|
||||
if err := repo.Verify(2, item.ID); err != ErrBindingOwnership {
|
||||
t.Fatalf("cross-user verify error = %v", err)
|
||||
}
|
||||
if err := repo.Verify(1, item.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored, err := repo.List(1)
|
||||
if err != nil || len(stored) != 1 {
|
||||
t.Fatalf("list result = %v, %v", stored, err)
|
||||
}
|
||||
if stored[0].Status != models.ExternalEmailStatusVerified {
|
||||
t.Fatalf("status = %s", stored[0].Status)
|
||||
}
|
||||
decrypted, err := repo.Decrypt(stored[0])
|
||||
if err != nil || decrypted != "owner@example.com" {
|
||||
t.Fatalf("decrypted email = %q, err = %v", decrypted, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryRejectsInvalidEmailType(t *testing.T) {
|
||||
engine, err := xorm.NewEngine("sqlite", filepath.Join(t.TempDir(), "external.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer engine.Close()
|
||||
vault := NewVaultWithKeys([]byte("01234567890123456789012345678901"), []byte("abcdefabcdefabcdefabcdefabcdefab"))
|
||||
repo, err := NewRepository(engine, vault)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := repo.Bind(BindRequest{UserID: 1, Email: "owner@example.com", Type: "unknown"}); err != ErrInvalidBinding {
|
||||
t.Fatalf("error = %v, want invalid binding", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryAbandonsOnlyOwnedPendingBinding(t *testing.T) {
|
||||
engine, err := xorm.NewEngine("sqlite", filepath.Join(t.TempDir(), "external.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer engine.Close()
|
||||
if err := engine.Sync2(&models.ExternalEmail{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vault := NewVaultWithKeys([]byte("01234567890123456789012345678901"), []byte("abcdefabcdefabcdefabcdefabcdefab"))
|
||||
repo, err := NewRepository(engine, vault)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item, err := repo.Bind(BindRequest{UserID: 1, Email: "pending@example.com", Type: models.ExternalEmailTypePrimary})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.AbandonPending(2, item.ID); err != ErrBindingOwnership {
|
||||
t.Fatalf("cross-user abandon error = %v", err)
|
||||
}
|
||||
if err := repo.AbandonPending(1, item.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count, err := engine.ID(item.ID).Count(&models.ExternalEmail{}); err != nil || count != 0 {
|
||||
t.Fatalf("pending binding remains: count=%d err=%v", count, err)
|
||||
}
|
||||
verified, err := repo.Bind(BindRequest{UserID: 1, Email: "verified@example.com", Type: models.ExternalEmailTypePrimary})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.Verify(1, verified.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.AbandonPending(1, verified.ID); err != ErrBindingOwnership {
|
||||
t.Fatalf("verified binding was abandoned: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package externalemail
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"net/mail"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
keySize = 32
|
||||
ciphertextPrefix = "email:v1:"
|
||||
fingerprintPrefix = "email-fp:v1:"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidEmail = errors.New("invalid external email")
|
||||
ErrVaultUnavailable = errors.New("external email vault unavailable")
|
||||
ErrCiphertextInvalid = errors.New("external email ciphertext invalid")
|
||||
)
|
||||
|
||||
type Vault struct {
|
||||
encryptionKey [keySize]byte
|
||||
fingerprintKey [keySize]byte
|
||||
version string
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func NewVault(root string) (*Vault, error) {
|
||||
if strings.TrimSpace(root) == "" {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
configDir := filepath.Join(root, "config")
|
||||
if err := os.MkdirAll(configDir, 0700); err != nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
encryptionKey, err := loadKey(filepath.Join(configDir, "external-email-encryption.key"))
|
||||
if err != nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
fingerprintKey, err := loadKey(filepath.Join(configDir, "external-email-fingerprint.key"))
|
||||
if err != nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
return NewVaultWithKeys(encryptionKey, fingerprintKey), nil
|
||||
}
|
||||
|
||||
func NewVaultWithKeys(encryptionKey, fingerprintKey []byte) *Vault {
|
||||
vault := &Vault{version: "1"}
|
||||
copy(vault.encryptionKey[:], encryptionKey)
|
||||
copy(vault.fingerprintKey[:], fingerprintKey)
|
||||
return vault
|
||||
}
|
||||
|
||||
func NormalizeEmail(value string) (string, error) {
|
||||
normalized := strings.TrimSpace(strings.ToLower(value))
|
||||
if normalized == "" || strings.ContainsAny(normalized, "\r\n") {
|
||||
return "", ErrInvalidEmail
|
||||
}
|
||||
parsed, err := mail.ParseAddress(normalized)
|
||||
if err != nil || parsed.Address != normalized || !strings.Contains(normalized, "@") {
|
||||
return "", ErrInvalidEmail
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func (v *Vault) Fingerprint(email string) (string, error) {
|
||||
if v == nil {
|
||||
return "", ErrVaultUnavailable
|
||||
}
|
||||
normalized, err := NormalizeEmail(email)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
v.mu.RLock()
|
||||
defer v.mu.RUnlock()
|
||||
mac := hmac.New(sha256.New, v.fingerprintKey[:])
|
||||
_, _ = mac.Write([]byte(normalized))
|
||||
return fingerprintPrefix + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func (v *Vault) Encrypt(email string) (string, error) {
|
||||
if v == nil {
|
||||
return "", ErrVaultUnavailable
|
||||
}
|
||||
normalized, err := NormalizeEmail(email)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
v.mu.RLock()
|
||||
defer v.mu.RUnlock()
|
||||
block, err := aes.NewCipher(v.encryptionKey[:])
|
||||
if err != nil {
|
||||
return "", ErrVaultUnavailable
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", ErrVaultUnavailable
|
||||
}
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", ErrVaultUnavailable
|
||||
}
|
||||
sealed := gcm.Seal(nonce, nonce, []byte(normalized), []byte("smail-external-email-v1"))
|
||||
return ciphertextPrefix + v.version + ":" + base64.RawURLEncoding.EncodeToString(sealed), nil
|
||||
}
|
||||
|
||||
func (v *Vault) Decrypt(value string) (string, error) {
|
||||
if v == nil || !strings.HasPrefix(value, ciphertextPrefix) {
|
||||
return "", ErrCiphertextInvalid
|
||||
}
|
||||
parts := strings.SplitN(strings.TrimPrefix(value, ciphertextPrefix), ":", 2)
|
||||
if len(parts) != 2 || parts[0] != v.version {
|
||||
return "", ErrCiphertextInvalid
|
||||
}
|
||||
sealed, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil || base64.RawURLEncoding.EncodeToString(sealed) != parts[1] {
|
||||
return "", ErrCiphertextInvalid
|
||||
}
|
||||
v.mu.RLock()
|
||||
defer v.mu.RUnlock()
|
||||
block, err := aes.NewCipher(v.encryptionKey[:])
|
||||
if err != nil {
|
||||
return "", ErrCiphertextInvalid
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil || len(sealed) < gcm.NonceSize() {
|
||||
return "", ErrCiphertextInvalid
|
||||
}
|
||||
plaintext, err := gcm.Open(nil, sealed[:gcm.NonceSize()], sealed[gcm.NonceSize():], []byte("smail-external-email-v1"))
|
||||
if err != nil {
|
||||
return "", ErrCiphertextInvalid
|
||||
}
|
||||
result, err := NormalizeEmail(string(plaintext))
|
||||
for index := range plaintext {
|
||||
plaintext[index] = 0
|
||||
}
|
||||
if err != nil {
|
||||
return "", ErrCiphertextInvalid
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func loadKey(path string) ([]byte, error) {
|
||||
absolute, err := filepath.Abs(filepath.Clean(path))
|
||||
if err != nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
root, err := os.OpenRoot(filepath.Dir(absolute))
|
||||
if err != nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
defer root.Close()
|
||||
|
||||
name := filepath.Base(absolute)
|
||||
info, err := root.Lstat(name)
|
||||
if err == nil {
|
||||
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() || (runtime.GOOS != "windows" && (info.Mode().Perm()&0077) != 0) || info.Size() != keySize {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
key, err := root.ReadFile(name)
|
||||
if err != nil || len(key) != keySize {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
if !os.IsNotExist(err) {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
key := make([]byte, keySize)
|
||||
if _, err := io.ReadFull(rand.Reader, key); err != nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
file, err := root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
|
||||
if err != nil {
|
||||
if os.IsExist(err) {
|
||||
return loadKey(path)
|
||||
}
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
if _, err := file.Write(key); err != nil {
|
||||
_ = file.Close()
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
_ = file.Close()
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
return nil, ErrVaultUnavailable
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
func EqualFingerprint(left, right string) bool {
|
||||
return subtle.ConstantTimeCompare([]byte(left), []byte(right)) == 1
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package externalemail
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestVaultEncryptsAndFingerprintsWithoutPlaintext(t *testing.T) {
|
||||
vault := NewVaultWithKeys([]byte(strings.Repeat("a", 32)), []byte(strings.Repeat("b", 32)))
|
||||
ciphertext, err := vault.Encrypt("User@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(ciphertext, "User@example.com") || strings.Contains(ciphertext, "user@example.com") {
|
||||
t.Fatal("ciphertext contains plaintext email")
|
||||
}
|
||||
first, err := vault.Fingerprint("User@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := vault.Fingerprint("user@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !EqualFingerprint(first, second) {
|
||||
t.Fatal("normalized fingerprints differ")
|
||||
}
|
||||
decrypted, err := vault.Decrypt(ciphertext)
|
||||
if err != nil || decrypted != "user@example.com" {
|
||||
t.Fatalf("decrypted email = %q, error = %v", decrypted, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVaultRejectsTamperingAndInvalidEmail(t *testing.T) {
|
||||
vault := NewVaultWithKeys([]byte(strings.Repeat("a", 32)), []byte(strings.Repeat("b", 32)))
|
||||
if _, err := vault.Encrypt("bad"); err == nil {
|
||||
t.Fatal("invalid email accepted")
|
||||
}
|
||||
ciphertext, err := vault.Encrypt("user@example.com")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
last := ciphertext[len(ciphertext)-1]
|
||||
replacement := byte('A')
|
||||
if last == replacement {
|
||||
replacement = 'B'
|
||||
}
|
||||
tampered := ciphertext[:len(ciphertext)-1] + string(replacement)
|
||||
if _, err := vault.Decrypt(tampered); err == nil {
|
||||
t.Fatal("tampered ciphertext accepted")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user