ce2a155ebc
原「知识库映射 → WeKnora 连接」把地址、文件和绑定分散在多处,页面无法输入密钥, 也看不到候选实例真实可读的库。现在测试 090 / 生产 090 各自一个工作区:草稿填地址 与 API Key,服务器真实分页列库并区分空库/无权限/不可达,选内外库后一次保存连接与 绑定,回读真实生效值。 服务端以修订号 + 行锁 + 单事务写连接、绑定与待入库重排;旧部署无新行时继续使用文件 凭据/默认绑定。密钥只存 AES-256-GCM 密文,主密钥在独立文件;换地址必须重录,旧密钥 不转发、不跨环境取用。消费端(readiness/上传轮询/列库/探活/生产列库)统一从该存储 解析当前连接,避免只保存了页面数据。 验证:go test ./...;前端 606 项;隔离 PostgreSQL 集成用例覆盖保存/冲突/重排/拒错; make verify 在本提交上执行(结果见交付说明)。
67 lines
1.8 KiB
Go
67 lines
1.8 KiB
Go
// Package secretbox 是平台唯一的对称加密落库入口:主密钥来自独立文件
|
|
// (0600 常规文件,正好 32 字节),密文通过 AES-256-GCM 与调用方给出的
|
|
// Additional Authenticated Data 绑定。AAD 让一行密文无法被搬到另一行
|
|
// (换环境/换修订)后仍能解开。
|
|
package secretbox
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"errors"
|
|
"os"
|
|
)
|
|
|
|
var ErrUnavailable = errors.New("secret key is not available")
|
|
|
|
type Box struct {
|
|
aead cipher.AEAD
|
|
}
|
|
|
|
// Load 读取主密钥。拒绝非普通文件、非 0600 权限或长度不是 32 字节的密钥,
|
|
// 避免"碰巧能读到"就被当成已正确配置。
|
|
func Load(path string) (*Box, error) {
|
|
if path == "" {
|
|
return nil, ErrUnavailable
|
|
}
|
|
info, err := os.Lstat(path)
|
|
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0600 {
|
|
return nil, ErrUnavailable
|
|
}
|
|
key, err := os.ReadFile(path)
|
|
if err != nil || len(key) != 32 {
|
|
return nil, ErrUnavailable
|
|
}
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, ErrUnavailable
|
|
}
|
|
aead, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, ErrUnavailable
|
|
}
|
|
return &Box{aead: aead}, nil
|
|
}
|
|
|
|
func (box *Box) Seal(plaintext []byte, aad string) ([]byte, error) {
|
|
if box == nil || box.aead == nil {
|
|
return nil, ErrUnavailable
|
|
}
|
|
nonce := make([]byte, box.aead.NonceSize())
|
|
if _, err := rand.Read(nonce); err != nil {
|
|
return nil, ErrUnavailable
|
|
}
|
|
return box.aead.Seal(nonce, nonce, plaintext, []byte(aad)), nil
|
|
}
|
|
|
|
func (box *Box) Open(sealed []byte, aad string) ([]byte, error) {
|
|
if box == nil || box.aead == nil || len(sealed) < box.aead.NonceSize() {
|
|
return nil, ErrUnavailable
|
|
}
|
|
raw, err := box.aead.Open(nil, sealed[:box.aead.NonceSize()], sealed[box.aead.NonceSize():], []byte(aad))
|
|
if err != nil {
|
|
return nil, ErrUnavailable
|
|
}
|
|
return raw, nil
|
|
}
|