ds2api / internal /reqlog /keys.go
luckfun233
feat(logs): 请求日志页面与只读日志 API Key;修复禁言账号导致的 503
7e312e3
Raw History Blame Contribute Delete
5.26 kB
package reqlog
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
// LogKey 是只读日志 API 的访问凭证。只保存 SHA-256 哈希,明文仅在创建时返回一次。
type LogKey struct {
ID string `json:"id"`
Name string `json:"name"`
Prefix string `json:"prefix"`
Hash string `json:"hash"`
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at,omitempty"`
LastUsedAt int64 `json:"last_used_at,omitempty"`
RevokedAt int64 `json:"revoked_at,omitempty"`
}
// Public 用于返回给管理界面,隐藏哈希。
type PublicLogKey struct {
ID string `json:"id"`
Name string `json:"name"`
Prefix string `json:"prefix"`
CreatedAt int64 `json:"created_at"`
ExpiresAt int64 `json:"expires_at,omitempty"`
LastUsedAt int64 `json:"last_used_at,omitempty"`
Revoked bool `json:"revoked"`
}
func (k LogKey) Public() PublicLogKey {
return PublicLogKey{
ID: k.ID,
Name: k.Name,
Prefix: k.Prefix,
CreatedAt: k.CreatedAt,
ExpiresAt: k.ExpiresAt,
LastUsedAt: k.LastUsedAt,
Revoked: k.RevokedAt > 0,
}
}
// KeyStore 负责日志 API Key 的生成、校验与持久化。
type KeyStore struct {
mu sync.RWMutex
path string
keys []LogKey
byHash map[string]int
}
const KeyPrefix = "ds2log_"
func NewKeyStore(path string) *KeyStore {
s := &KeyStore{path: strings.TrimSpace(path), byHash: map[string]int{}}
s.load()
return s
}
func (s *KeyStore) load() {
if s.path == "" {
return
}
b, err := os.ReadFile(s.path)
if err != nil {
if !os.IsNotExist(err) {
// 读取失败时保持空列表,避免影响服务启动。
return
}
return
}
var keys []LogKey
if err := json.Unmarshal(b, &keys); err != nil {
return
}
s.mu.Lock()
s.keys = keys
s.rebuildLocked()
s.mu.Unlock()
}
func (s *KeyStore) rebuildLocked() {
s.byHash = make(map[string]int, len(s.keys))
for i, k := range s.keys {
if k.Hash != "" {
s.byHash[k.Hash] = i
}
}
}
func (s *KeyStore) saveLocked() error {
if s.path == "" {
return nil
}
if err := os.MkdirAll(filepath.Dir(s.path), 0o750); err != nil {
return err
}
b, err := json.MarshalIndent(s.keys, "", " ")
if err != nil {
return err
}
tmp := s.path + ".tmp"
if err := os.WriteFile(tmp, b, 0o600); err != nil {
return err
}
return os.Rename(tmp, s.path)
}
// Create 生成新 key,返回明文与记录。
func (s *KeyStore) Create(name string, ttl time.Duration) (string, PublicLogKey, error) {
name = strings.TrimSpace(name)
if name == "" {
name = "log-reader"
}
buf := make([]byte, 24)
if _, err := rand.Read(buf); err != nil {
return "", PublicLogKey{}, err
}
plain := KeyPrefix + hex.EncodeToString(buf)
sum := sha256.Sum256([]byte(plain))
now := time.Now()
item := LogKey{
ID: "lk_" + hex.EncodeToString(buf[:6]),
Name: name,
Prefix: plain[:len(KeyPrefix)+6],
Hash: hex.EncodeToString(sum[:]),
CreatedAt: now.Unix(),
}
if ttl > 0 {
item.ExpiresAt = now.Add(ttl).Unix()
}
s.mu.Lock()
s.keys = append(s.keys, item)
s.rebuildLocked()
err := s.saveLocked()
s.mu.Unlock()
if err != nil {
return "", PublicLogKey{}, err
}
return plain, item.Public(), nil
}
// Verify 校验 token;成功后刷新 last_used_at(最多每分钟写一次盘)。
func (s *KeyStore) Verify(token string) (PublicLogKey, bool) {
token = strings.TrimSpace(token)
if token == "" || !strings.HasPrefix(token, KeyPrefix) {
return PublicLogKey{}, false
}
sum := sha256.Sum256([]byte(token))
hash := hex.EncodeToString(sum[:])
now := time.Now().Unix()
s.mu.Lock()
defer s.mu.Unlock()
idx, ok := s.byHash[hash]
if !ok {
return PublicLogKey{}, false
}
item := s.keys[idx]
if item.RevokedAt > 0 {
return PublicLogKey{}, false
}
if item.ExpiresAt > 0 && item.ExpiresAt <= now {
return PublicLogKey{}, false
}
if now-item.LastUsedAt >= 60 {
s.keys[idx].LastUsedAt = now
if err := s.saveLocked(); err != nil {
// 使用记录写盘失败不影响鉴权结果。
_ = err
}
}
return s.keys[idx].Public(), true
}
// List 返回全部 key(新的在前)。
func (s *KeyStore) List() []PublicLogKey {
s.mu.RLock()
defer s.mu.RUnlock()
out := make([]PublicLogKey, 0, len(s.keys))
for _, k := range s.keys {
out = append(out, k.Public())
}
sort.SliceStable(out, func(i, j int) bool { return out[i].CreatedAt > out[j].CreatedAt })
return out
}
var ErrKeyNotFound = errors.New("log key not found")
// Revoke 立即吊销 key。
func (s *KeyStore) Revoke(id string) error {
id = strings.TrimSpace(id)
s.mu.Lock()
defer s.mu.Unlock()
for i := range s.keys {
if s.keys[i].ID != id {
continue
}
if s.keys[i].RevokedAt == 0 {
s.keys[i].RevokedAt = time.Now().Unix()
return s.saveLocked()
}
return nil
}
return ErrKeyNotFound
}
// Delete 永久删除 key 记录。
func (s *KeyStore) Delete(id string) error {
id = strings.TrimSpace(id)
s.mu.Lock()
defer s.mu.Unlock()
for i := range s.keys {
if s.keys[i].ID != id {
continue
}
s.keys = append(s.keys[:i], s.keys[i+1:]...)
s.rebuildLocked()
return s.saveLocked()
}
return ErrKeyNotFound
}