* fix(ops): 修复运维监控系统的关键安全和稳定性问题
## 修复内容
### P0 严重问题
1. **DNS Rebinding防护** (ops_alert_service.go)
- 实现IP钉住机制防止验证后的DNS rebinding攻击
- 自定义Transport.DialContext强制只允许拨号到验证过的公网IP
- 扩展IP黑名单,包括云metadata地址(169.254.169.254)
- 添加完整的单元测试覆盖
2. **OpsAlertService生命周期管理** (wire.go)
- 在ProvideOpsMetricsCollector中添加opsAlertService.Start()调用
- 确保stopCtx正确初始化,避免nil指针问题
- 实现防御式启动,保证服务启动顺序
3. **数据库查询排序** (ops_repo.go)
- 在ListRecentSystemMetrics中添加显式ORDER BY updated_at DESC, id DESC
- 在GetLatestSystemMetric中添加排序保证
- 避免数据库返回顺序不确定导致告警误判
### P1 重要问题
4. **并发安全** (ops_metrics_collector.go)
- 为lastGCPauseTotal字段添加sync.Mutex保护
- 防止数据竞争
5. **Goroutine泄漏** (ops_error_logger.go)
- 实现worker pool模式限制并发goroutine数量
- 使用256容量缓冲队列和10个固定worker
- 非阻塞投递,队列满时丢弃任务
6. **生命周期控制** (ops_alert_service.go)
- 添加Start/Stop方法实现优雅关闭
- 使用context控制goroutine生命周期
- 实现WaitGroup等待后台任务完成
7. **Webhook URL验证** (ops_alert_service.go)
- 防止SSRF攻击:验证scheme、禁止内网IP
- DNS解析验证,拒绝解析到私有IP的域名
- 添加8个单元测试覆盖各种攻击场景
8. **资源泄漏** (ops_repo.go)
- 修复多处defer rows.Close()问题
- 简化冗余的defer func()包装
9. **HTTP超时控制** (ops_alert_service.go)
- 创建带10秒超时的http.Client
- 添加buildWebhookHTTPClient辅助函数
- 防止HTTP请求无限期挂起
10. **数据库查询优化** (ops_repo.go)
- 将GetWindowStats的4次独立查询合并为1次CTE查询
- 减少网络往返和表扫描次数
- 显著提升性能
11. **重试机制** (ops_alert_service.go)
- 实现邮件发送重试:最多3次,指数退避(1s/2s/4s)
- 添加webhook备用通道
- 实现完整的错误处理和日志记录
12. **魔法数字** (ops_repo.go, ops_metrics_collector.go)
- 提取硬编码数字为有意义的常量
- 提高代码可读性和可维护性
## 测试验证
- ✅ go test ./internal/service -tags opsalert_unit 通过
- ✅ 所有webhook验证测试通过
- ✅ 重试机制测试通过
## 影响范围
- 运维监控系统安全性显著提升
- 系统稳定性和性能优化
- 无破坏性变更,向后兼容
* feat(ops): 运维监控系统V2 - 完整实现
## 核心功能
- 运维监控仪表盘V2(实时监控、历史趋势、告警管理)
- WebSocket实时QPS/TPS监控(30s心跳,自动重连)
- 系统指标采集(CPU、内存、延迟、错误率等)
- 多维度统计分析(按provider、model、user等维度)
- 告警规则管理(阈值配置、通知渠道)
- 错误日志追踪(详细错误信息、堆栈跟踪)
## 数据库Schema (Migration 025)
### 扩展现有表
- ops_system_metrics: 新增RED指标、错误分类、延迟指标、资源指标、业务指标
- ops_alert_rules: 新增JSONB字段(dimension_filters, notify_channels, notify_config)
### 新增表
- ops_dimension_stats: 多维度统计数据
- ops_data_retention_config: 数据保留策略配置
### 新增视图和函数
- ops_latest_metrics: 最新1分钟窗口指标(已修复字段名和window过滤)
- ops_active_alerts: 当前活跃告警(已修复字段名和状态值)
- calculate_health_score: 健康分数计算函数
## 一致性修复(98/100分)
### P0级别(阻塞Migration)
- ✅ 修复ops_latest_metrics视图字段名(latency_p99→p99_latency_ms, cpu_usage→cpu_usage_percent)
- ✅ 修复ops_active_alerts视图字段名(metric→metric_type, triggered_at→fired_at, trigger_value→metric_value, threshold→threshold_value)
- ✅ 统一告警历史表名(删除ops_alert_history,使用ops_alert_events)
- ✅ 统一API参数限制(ListMetricsHistory和ListErrorLogs的limit改为5000)
### P1级别(功能完整性)
- ✅ 修复ops_latest_metrics视图未过滤window_minutes(添加WHERE m.window_minutes = 1)
- ✅ 修复数据回填UPDATE逻辑(QPS计算改为request_count/(window_minutes*60.0))
- ✅ 添加ops_alert_rules JSONB字段后端支持(Go结构体+序列化)
### P2级别(优化)
- ✅ 前端WebSocket自动重连(指数退避1s→2s→4s→8s→16s,最大5次)
- ✅ 后端WebSocket心跳检测(30s ping,60s pong超时)
## 技术实现
### 后端 (Go)
- Handler层: ops_handler.go(REST API), ops_ws_handler.go(WebSocket)
- Service层: ops_service.go(核心逻辑), ops_cache.go(缓存), ops_alerts.go(告警)
- Repository层: ops_repo.go(数据访问), ops.go(模型定义)
- 路由: admin.go(新增ops相关路由)
- 依赖注入: wire_gen.go(自动生成)
### 前端 (Vue3 + TypeScript)
- 组件: OpsDashboardV2.vue(仪表盘主组件)
- API: ops.ts(REST API + WebSocket封装)
- 路由: index.ts(新增/admin/ops路由)
- 国际化: en.ts, zh.ts(中英文支持)
## 测试验证
- ✅ 所有Go测试通过
- ✅ Migration可正常执行
- ✅ WebSocket连接稳定
- ✅ 前后端数据结构对齐
* refactor: 代码清理和测试优化
## 测试文件优化
- 简化integration test fixtures和断言
- 优化test helper函数
- 统一测试数据格式
## 代码清理
- 移除未使用的代码和注释
- 简化concurrency_cache实现
- 优化middleware错误处理
## 小修复
- 修复gateway_handler和openai_gateway_handler的小问题
- 统一代码风格和格式
变更统计: 27个文件,292行新增,322行删除(净减少30行)
* fix(ops): 运维监控系统安全加固和功能优化
## 安全增强
- feat(security): WebSocket日志脱敏机制,防止token/api_key泄露
- feat(security): X-Forwarded-Host白名单验证,防止CSRF绕过
- feat(security): Origin策略配置化,支持strict/permissive模式
- feat(auth): WebSocket认证支持query参数传递token
## 配置优化
- feat(config): 支持环境变量配置代理信任和Origin策略
- OPS_WS_TRUST_PROXY
- OPS_WS_TRUSTED_PROXIES
- OPS_WS_ORIGIN_POLICY
- fix(ops): 错误日志查询限流从5000降至500,优化内存使用
## 架构改进
- refactor(ops): 告警服务解耦,独立运行评估定时器
- refactor(ops): OpsDashboard统一版本,移除V2分离
## 测试和文档
- test(ops): 添加WebSocket安全验证单元测试(8个测试用例)
- test(ops): 添加告警服务集成测试
- docs(api): 更新API文档,标注限流变更
- docs: 添加CHANGELOG记录breaking changes
## 修复文件
Backend:
- backend/internal/server/middleware/logger.go
- backend/internal/handler/admin/ops_handler.go
- backend/internal/handler/admin/ops_ws_handler.go
- backend/internal/server/middleware/admin_auth.go
- backend/internal/service/ops_alert_service.go
- backend/internal/service/ops_metrics_collector.go
- backend/internal/service/wire.go
Frontend:
- frontend/src/views/admin/ops/OpsDashboard.vue
- frontend/src/router/index.ts
- frontend/src/api/admin/ops.ts
Tests:
- backend/internal/handler/admin/ops_ws_handler_test.go (新增)
- backend/internal/service/ops_alert_service_integration_test.go (新增)
Docs:
- CHANGELOG.md (新增)
- docs/API-运维监控中心2.0.md (更新)
* fix(migrations): 修复calculate_health_score函数类型匹配问题
在ops_latest_metrics视图中添加显式类型转换,确保参数类型与函数签名匹配
* fix(lint): 修复golangci-lint检查发现的所有问题
- 将Redis依赖从service层移到repository层
- 添加错误检查(WebSocket连接和读取超时)
- 运行gofmt格式化代码
- 添加nil指针检查
- 删除未使用的alertService字段
修复问题:
- depguard: 3个(service层不应直接import redis)
- errcheck: 3个(未检查错误返回值)
- gofmt: 2个(代码格式问题)
- staticcheck: 4个(nil指针解引用)
- unused: 1个(未使用字段)
代码统计:
- 修改文件:11个
- 删除代码:490行
- 新增代码:105行
- 净减少:385行
541 lines
15 KiB
Go
541 lines
15 KiB
Go
package service
|
|
|
|
import (
|
|
"archive/tar"
|
|
"bufio"
|
|
"compress/gzip"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
updateCacheKey = "update_check_cache"
|
|
updateCacheTTL = 1200 // 20 minutes
|
|
githubRepo = "Wei-Shaw/sub2api"
|
|
|
|
// Security: allowed download domains for updates
|
|
allowedDownloadHost = "github.com"
|
|
allowedAssetHost = "objects.githubusercontent.com"
|
|
|
|
// Security: max download size (500MB)
|
|
maxDownloadSize = 500 * 1024 * 1024
|
|
)
|
|
|
|
// UpdateCache defines cache operations for update service
|
|
type UpdateCache interface {
|
|
GetUpdateInfo(ctx context.Context) (string, error)
|
|
SetUpdateInfo(ctx context.Context, data string, ttl time.Duration) error
|
|
}
|
|
|
|
// GitHubReleaseClient 获取 GitHub release 信息的接口
|
|
type GitHubReleaseClient interface {
|
|
FetchLatestRelease(ctx context.Context, repo string) (*GitHubRelease, error)
|
|
DownloadFile(ctx context.Context, url, dest string, maxSize int64) error
|
|
FetchChecksumFile(ctx context.Context, url string) ([]byte, error)
|
|
}
|
|
|
|
// UpdateService handles software updates
|
|
type UpdateService struct {
|
|
cache UpdateCache
|
|
githubClient GitHubReleaseClient
|
|
currentVersion string
|
|
buildType string // "source" for manual builds, "release" for CI builds
|
|
}
|
|
|
|
// NewUpdateService creates a new UpdateService
|
|
func NewUpdateService(cache UpdateCache, githubClient GitHubReleaseClient, version, buildType string) *UpdateService {
|
|
return &UpdateService{
|
|
cache: cache,
|
|
githubClient: githubClient,
|
|
currentVersion: version,
|
|
buildType: buildType,
|
|
}
|
|
}
|
|
|
|
// UpdateInfo contains update information
|
|
type UpdateInfo struct {
|
|
CurrentVersion string `json:"current_version"`
|
|
LatestVersion string `json:"latest_version"`
|
|
HasUpdate bool `json:"has_update"`
|
|
ReleaseInfo *ReleaseInfo `json:"release_info,omitempty"`
|
|
Cached bool `json:"cached"`
|
|
Warning string `json:"warning,omitempty"`
|
|
BuildType string `json:"build_type"` // "source" or "release"
|
|
}
|
|
|
|
// ReleaseInfo contains GitHub release details
|
|
type ReleaseInfo struct {
|
|
Name string `json:"name"`
|
|
Body string `json:"body"`
|
|
PublishedAt string `json:"published_at"`
|
|
HTMLURL string `json:"html_url"`
|
|
Assets []Asset `json:"assets,omitempty"`
|
|
}
|
|
|
|
// Asset represents a release asset
|
|
type Asset struct {
|
|
Name string `json:"name"`
|
|
DownloadURL string `json:"download_url"`
|
|
Size int64 `json:"size"`
|
|
}
|
|
|
|
// GitHubRelease represents GitHub API response
|
|
type GitHubRelease struct {
|
|
TagName string `json:"tag_name"`
|
|
Name string `json:"name"`
|
|
Body string `json:"body"`
|
|
PublishedAt string `json:"published_at"`
|
|
HTMLURL string `json:"html_url"`
|
|
Assets []GitHubAsset `json:"assets"`
|
|
}
|
|
|
|
type GitHubAsset struct {
|
|
Name string `json:"name"`
|
|
BrowserDownloadURL string `json:"browser_download_url"`
|
|
Size int64 `json:"size"`
|
|
}
|
|
|
|
// CheckUpdate checks for available updates
|
|
func (s *UpdateService) CheckUpdate(ctx context.Context, force bool) (*UpdateInfo, error) {
|
|
// Try cache first
|
|
if !force {
|
|
if cached, err := s.getFromCache(ctx); err == nil && cached != nil {
|
|
return cached, nil
|
|
}
|
|
}
|
|
|
|
// Fetch from GitHub
|
|
info, err := s.fetchLatestRelease(ctx)
|
|
if err != nil {
|
|
// Return cached on error
|
|
if cached, cacheErr := s.getFromCache(ctx); cacheErr == nil && cached != nil {
|
|
cached.Warning = "Using cached data: " + err.Error()
|
|
return cached, nil
|
|
}
|
|
return &UpdateInfo{
|
|
CurrentVersion: s.currentVersion,
|
|
LatestVersion: s.currentVersion,
|
|
HasUpdate: false,
|
|
Warning: err.Error(),
|
|
BuildType: s.buildType,
|
|
}, nil
|
|
}
|
|
|
|
// Cache result
|
|
s.saveToCache(ctx, info)
|
|
return info, nil
|
|
}
|
|
|
|
// PerformUpdate downloads and applies the update
|
|
// Uses atomic file replacement pattern for safe in-place updates
|
|
func (s *UpdateService) PerformUpdate(ctx context.Context) error {
|
|
info, err := s.CheckUpdate(ctx, true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if !info.HasUpdate {
|
|
return fmt.Errorf("no update available")
|
|
}
|
|
|
|
// Find matching archive and checksum for current platform
|
|
archiveName := s.getArchiveName()
|
|
var downloadURL string
|
|
var checksumURL string
|
|
|
|
for _, asset := range info.ReleaseInfo.Assets {
|
|
if strings.Contains(asset.Name, archiveName) && !strings.HasSuffix(asset.Name, ".txt") {
|
|
downloadURL = asset.DownloadURL
|
|
}
|
|
if asset.Name == "checksums.txt" {
|
|
checksumURL = asset.DownloadURL
|
|
}
|
|
}
|
|
|
|
if downloadURL == "" {
|
|
return fmt.Errorf("no compatible release found for %s/%s", runtime.GOOS, runtime.GOARCH)
|
|
}
|
|
|
|
// SECURITY: Validate download URL is from trusted domain
|
|
if err := validateDownloadURL(downloadURL); err != nil {
|
|
return fmt.Errorf("invalid download URL: %w", err)
|
|
}
|
|
if checksumURL != "" {
|
|
if err := validateDownloadURL(checksumURL); err != nil {
|
|
return fmt.Errorf("invalid checksum URL: %w", err)
|
|
}
|
|
}
|
|
|
|
// Get current executable path
|
|
exePath, err := os.Executable()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get executable path: %w", err)
|
|
}
|
|
exePath, err = filepath.EvalSymlinks(exePath)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to resolve symlinks: %w", err)
|
|
}
|
|
|
|
exeDir := filepath.Dir(exePath)
|
|
|
|
// Create temp directory in the SAME directory as executable
|
|
// This ensures os.Rename is atomic (same filesystem)
|
|
tempDir, err := os.MkdirTemp(exeDir, ".sub2api-update-*")
|
|
if err != nil {
|
|
return fmt.Errorf("failed to create temp dir: %w", err)
|
|
}
|
|
defer func() { _ = os.RemoveAll(tempDir) }()
|
|
|
|
// Download archive
|
|
archivePath := filepath.Join(tempDir, filepath.Base(downloadURL))
|
|
if err := s.downloadFile(ctx, downloadURL, archivePath); err != nil {
|
|
return fmt.Errorf("download failed: %w", err)
|
|
}
|
|
|
|
// Verify checksum if available
|
|
if checksumURL != "" {
|
|
if err := s.verifyChecksum(ctx, archivePath, checksumURL); err != nil {
|
|
return fmt.Errorf("checksum verification failed: %w", err)
|
|
}
|
|
}
|
|
|
|
// Extract binary from archive
|
|
newBinaryPath := filepath.Join(tempDir, "sub2api")
|
|
if err := s.extractBinary(archivePath, newBinaryPath); err != nil {
|
|
return fmt.Errorf("extraction failed: %w", err)
|
|
}
|
|
|
|
// Set executable permission before replacement
|
|
if err := os.Chmod(newBinaryPath, 0755); err != nil {
|
|
return fmt.Errorf("chmod failed: %w", err)
|
|
}
|
|
|
|
// Atomic replacement using rename pattern:
|
|
// 1. Rename current -> backup (atomic on Unix)
|
|
// 2. Rename new -> current (atomic on Unix, same filesystem)
|
|
// If step 2 fails, restore backup
|
|
backupPath := exePath + ".backup"
|
|
|
|
// Remove old backup if exists
|
|
_ = os.Remove(backupPath)
|
|
|
|
// Step 1: Move current binary to backup
|
|
if err := os.Rename(exePath, backupPath); err != nil {
|
|
return fmt.Errorf("backup failed: %w", err)
|
|
}
|
|
|
|
// Step 2: Move new binary to target location (atomic, same filesystem)
|
|
if err := os.Rename(newBinaryPath, exePath); err != nil {
|
|
// Restore backup on failure
|
|
if restoreErr := os.Rename(backupPath, exePath); restoreErr != nil {
|
|
return fmt.Errorf("replace failed and restore failed: %w (restore error: %v)", err, restoreErr)
|
|
}
|
|
return fmt.Errorf("replace failed (restored backup): %w", err)
|
|
}
|
|
|
|
// Success - backup file is kept for rollback capability
|
|
// It will be cleaned up on next successful update
|
|
return nil
|
|
}
|
|
|
|
// Rollback restores the previous version
|
|
func (s *UpdateService) Rollback() error {
|
|
exePath, err := os.Executable()
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get executable path: %w", err)
|
|
}
|
|
exePath, err = filepath.EvalSymlinks(exePath)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to resolve symlinks: %w", err)
|
|
}
|
|
|
|
backupFile := exePath + ".backup"
|
|
if _, err := os.Stat(backupFile); os.IsNotExist(err) {
|
|
return fmt.Errorf("no backup found")
|
|
}
|
|
|
|
// Replace current with backup
|
|
if err := os.Rename(backupFile, exePath); err != nil {
|
|
return fmt.Errorf("rollback failed: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *UpdateService) fetchLatestRelease(ctx context.Context) (*UpdateInfo, error) {
|
|
release, err := s.githubClient.FetchLatestRelease(ctx, githubRepo)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
latestVersion := strings.TrimPrefix(release.TagName, "v")
|
|
|
|
assets := make([]Asset, len(release.Assets))
|
|
for i, a := range release.Assets {
|
|
assets[i] = Asset{
|
|
Name: a.Name,
|
|
DownloadURL: a.BrowserDownloadURL,
|
|
Size: a.Size,
|
|
}
|
|
}
|
|
|
|
return &UpdateInfo{
|
|
CurrentVersion: s.currentVersion,
|
|
LatestVersion: latestVersion,
|
|
HasUpdate: compareVersions(s.currentVersion, latestVersion) < 0,
|
|
ReleaseInfo: &ReleaseInfo{
|
|
Name: release.Name,
|
|
Body: release.Body,
|
|
PublishedAt: release.PublishedAt,
|
|
HTMLURL: release.HTMLURL,
|
|
Assets: assets,
|
|
},
|
|
Cached: false,
|
|
BuildType: s.buildType,
|
|
}, nil
|
|
}
|
|
|
|
func (s *UpdateService) downloadFile(ctx context.Context, downloadURL, dest string) error {
|
|
return s.githubClient.DownloadFile(ctx, downloadURL, dest, maxDownloadSize)
|
|
}
|
|
|
|
func (s *UpdateService) getArchiveName() string {
|
|
osName := runtime.GOOS
|
|
arch := runtime.GOARCH
|
|
return fmt.Sprintf("%s_%s", osName, arch)
|
|
}
|
|
|
|
// validateDownloadURL checks if the URL is from an allowed domain
|
|
// SECURITY: This prevents SSRF and ensures downloads only come from trusted GitHub domains
|
|
func validateDownloadURL(rawURL string) error {
|
|
parsedURL, err := url.Parse(rawURL)
|
|
if err != nil {
|
|
return fmt.Errorf("invalid URL: %w", err)
|
|
}
|
|
|
|
// Must be HTTPS
|
|
if parsedURL.Scheme != "https" {
|
|
return fmt.Errorf("only HTTPS URLs are allowed")
|
|
}
|
|
|
|
// Check against allowed hosts
|
|
host := parsedURL.Host
|
|
// GitHub release URLs can be from github.com or objects.githubusercontent.com
|
|
if host != allowedDownloadHost &&
|
|
!strings.HasSuffix(host, "."+allowedDownloadHost) &&
|
|
host != allowedAssetHost &&
|
|
!strings.HasSuffix(host, "."+allowedAssetHost) {
|
|
return fmt.Errorf("download from untrusted host: %s", host)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *UpdateService) verifyChecksum(ctx context.Context, filePath, checksumURL string) error {
|
|
// Download checksums file
|
|
checksumData, err := s.githubClient.FetchChecksumFile(ctx, checksumURL)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to download checksums: %w", err)
|
|
}
|
|
|
|
// Calculate file hash
|
|
f, err := os.Open(filePath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = f.Close() }()
|
|
|
|
h := sha256.New()
|
|
if _, err := io.Copy(h, f); err != nil {
|
|
return err
|
|
}
|
|
actualHash := hex.EncodeToString(h.Sum(nil))
|
|
|
|
// Find expected hash in checksums file
|
|
fileName := filepath.Base(filePath)
|
|
scanner := bufio.NewScanner(strings.NewReader(string(checksumData)))
|
|
for scanner.Scan() {
|
|
line := scanner.Text()
|
|
parts := strings.Fields(line)
|
|
if len(parts) == 2 && parts[1] == fileName {
|
|
if parts[0] == actualHash {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("checksum mismatch: expected %s, got %s", parts[0], actualHash)
|
|
}
|
|
}
|
|
|
|
return fmt.Errorf("checksum not found for %s", fileName)
|
|
}
|
|
|
|
func (s *UpdateService) extractBinary(archivePath, destPath string) error {
|
|
f, err := os.Open(archivePath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = f.Close() }()
|
|
|
|
var reader io.Reader = f
|
|
|
|
// Handle gzip compression
|
|
if strings.HasSuffix(archivePath, ".gz") || strings.HasSuffix(archivePath, ".tar.gz") || strings.HasSuffix(archivePath, ".tgz") {
|
|
gzr, err := gzip.NewReader(f)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = gzr.Close() }()
|
|
reader = gzr
|
|
}
|
|
|
|
// Handle tar archive
|
|
if strings.Contains(archivePath, ".tar") {
|
|
tr := tar.NewReader(reader)
|
|
for {
|
|
hdr, err := tr.Next()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// SECURITY: Prevent Zip Slip / Path Traversal attack
|
|
// Only allow files with safe base names, no directory traversal
|
|
baseName := filepath.Base(hdr.Name)
|
|
|
|
// Check for path traversal attempts
|
|
if strings.Contains(hdr.Name, "..") {
|
|
return fmt.Errorf("path traversal attempt detected: %s", hdr.Name)
|
|
}
|
|
|
|
// Validate the entry is a regular file
|
|
if hdr.Typeflag != tar.TypeReg {
|
|
continue // Skip directories and special files
|
|
}
|
|
|
|
// Only extract the specific binary we need
|
|
if baseName == "sub2api" || baseName == "sub2api.exe" {
|
|
// Additional security: limit file size (max 500MB)
|
|
const maxBinarySize = 500 * 1024 * 1024
|
|
if hdr.Size > maxBinarySize {
|
|
return fmt.Errorf("binary too large: %d bytes (max %d)", hdr.Size, maxBinarySize)
|
|
}
|
|
|
|
out, err := os.Create(destPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Use LimitReader to prevent decompression bombs
|
|
limited := io.LimitReader(tr, maxBinarySize)
|
|
if _, err := io.Copy(out, limited); err != nil {
|
|
_ = out.Close()
|
|
return err
|
|
}
|
|
if err := out.Close(); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
return fmt.Errorf("binary not found in archive")
|
|
}
|
|
|
|
// Direct copy for non-tar files (with size limit)
|
|
const maxBinarySize = 500 * 1024 * 1024
|
|
out, err := os.Create(destPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
limited := io.LimitReader(reader, maxBinarySize)
|
|
if _, err := io.Copy(out, limited); err != nil {
|
|
_ = out.Close()
|
|
return err
|
|
}
|
|
return out.Close()
|
|
}
|
|
|
|
func (s *UpdateService) getFromCache(ctx context.Context) (*UpdateInfo, error) {
|
|
data, err := s.cache.GetUpdateInfo(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var cached struct {
|
|
Latest string `json:"latest"`
|
|
ReleaseInfo *ReleaseInfo `json:"release_info"`
|
|
Timestamp int64 `json:"timestamp"`
|
|
}
|
|
if err := json.Unmarshal([]byte(data), &cached); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if time.Now().Unix()-cached.Timestamp > updateCacheTTL {
|
|
return nil, fmt.Errorf("cache expired")
|
|
}
|
|
|
|
return &UpdateInfo{
|
|
CurrentVersion: s.currentVersion,
|
|
LatestVersion: cached.Latest,
|
|
HasUpdate: compareVersions(s.currentVersion, cached.Latest) < 0,
|
|
ReleaseInfo: cached.ReleaseInfo,
|
|
Cached: true,
|
|
BuildType: s.buildType,
|
|
}, nil
|
|
}
|
|
|
|
func (s *UpdateService) saveToCache(ctx context.Context, info *UpdateInfo) {
|
|
cacheData := struct {
|
|
Latest string `json:"latest"`
|
|
ReleaseInfo *ReleaseInfo `json:"release_info"`
|
|
Timestamp int64 `json:"timestamp"`
|
|
}{
|
|
Latest: info.LatestVersion,
|
|
ReleaseInfo: info.ReleaseInfo,
|
|
Timestamp: time.Now().Unix(),
|
|
}
|
|
|
|
data, _ := json.Marshal(cacheData)
|
|
_ = s.cache.SetUpdateInfo(ctx, string(data), time.Duration(updateCacheTTL)*time.Second)
|
|
}
|
|
|
|
// compareVersions compares two semantic versions
|
|
func compareVersions(current, latest string) int {
|
|
currentParts := parseVersion(current)
|
|
latestParts := parseVersion(latest)
|
|
|
|
for i := 0; i < 3; i++ {
|
|
if currentParts[i] < latestParts[i] {
|
|
return -1
|
|
}
|
|
if currentParts[i] > latestParts[i] {
|
|
return 1
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func parseVersion(v string) [3]int {
|
|
v = strings.TrimPrefix(v, "v")
|
|
parts := strings.Split(v, ".")
|
|
result := [3]int{0, 0, 0}
|
|
for i := 0; i < len(parts) && i < 3; i++ {
|
|
if parsed, err := strconv.Atoi(parts[i]); err == nil {
|
|
result[i] = parsed
|
|
}
|
|
}
|
|
return result
|
|
}
|