83 lines
2.7 KiB
Go
83 lines
2.7 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"database/sql"
|
|
"errors"
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func sealInstanceSecret(key []byte, instanceID, secret string) ([]byte, error) {
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err = rand.Read(nonce); err != nil {
|
|
return nil, err
|
|
}
|
|
return gcm.Seal(nonce, nonce, []byte(secret), []byte("instance-secret-v1:"+instanceID)), nil
|
|
}
|
|
func openInstanceSecret(key []byte, instanceID string, data []byte) (string, error) {
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(data) < gcm.NonceSize() {
|
|
return "", errors.New("invalid ciphertext")
|
|
}
|
|
plain, err := gcm.Open(nil, data[:gcm.NonceSize()], data[gcm.NonceSize():], []byte("instance-secret-v1:"+instanceID))
|
|
return string(plain), err
|
|
}
|
|
func (a *BusinessAPI) instanceCredentials(c *gin.Context) {
|
|
c.Header("Cache-Control", "no-store")
|
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
if err != nil || id == 0 {
|
|
apiError(c, 400, "invalid_request", "授权 ID 无效")
|
|
return
|
|
}
|
|
var instanceID, licenseKey string
|
|
var encrypted []byte
|
|
err = a.db.QueryRowContext(c, `SELECT i.instance_id,l.license_key,i.secret_encrypted FROM license_instances i JOIN licenses l ON l.id=i.license_id WHERE i.license_id=?`, id).Scan(&instanceID, &licenseKey, &encrypted)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
apiError(c, 404, "not_found", "实例不存在")
|
|
return
|
|
}
|
|
if err != nil {
|
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
|
return
|
|
}
|
|
if len(encrypted) == 0 {
|
|
apiError(c, 409, "credentials_not_retained", "旧实例仅保存密钥哈希,无法恢复激活凭据;请使用原始交付文件或重新签发授权")
|
|
return
|
|
}
|
|
if len(a.credentialEncryptionKey) == 0 {
|
|
apiError(c, 503, "credentials_unavailable", "未配置凭据加密密钥")
|
|
return
|
|
}
|
|
secret, err := openInstanceSecret(a.credentialEncryptionKey, instanceID, encrypted)
|
|
if err != nil {
|
|
apiError(c, 503, "credentials_unavailable", "凭据解密不可用,请检查加密密钥配置")
|
|
return
|
|
}
|
|
// No credential material in audit details. Do not disclose before audit succeeds.
|
|
_, err = a.db.ExecContext(c, `INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'instance.credentials.viewed','license',?,?)`, c.MustGet("admin_id"), id, `{}`)
|
|
if err != nil {
|
|
apiError(c, 500, "internal_error", "服务暂时不可用")
|
|
return
|
|
}
|
|
c.JSON(200, gin.H{"data": gin.H{"instance_id": instanceID, "license_key": licenseKey, "secret": secret}})
|
|
}
|