package httpapi import ( "bytes" "context" "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io" "net/http" "sea-vhost/internal/scope" "sea-vhost/internal/store" "slices" "strconv" "strings" "time" ) const integrationKeyContext contextKey = "integration-key" var integrationScopes = []string{"users:read", "users:write", "hosts:read", "hosts:write", "tasks:read", "credentials:read"} func tokenHash(token string) string { sum := sha256.Sum256([]byte(token)) return hex.EncodeToString(sum[:]) } func (s *Server) adminIntegrationKeys(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { rows, e := s.store.IntegrationKeys(r.Context()) if e != nil { writeError(w, 503, "无法读取 API 密钥") return } deliveries, e := s.store.IntegrationWebhooks(r.Context(), false) if e != nil { writeError(w, 503, "无法读取回调记录") return } writeJSON(w, 200, map[string]any{"keys": rows, "scopes": integrationScopes, "webhooks": deliveries}) return } u := currentUser(r) if r.Method == "DELETE" { id, _ := strconv.ParseUint(r.PathValue("keyID"), 10, 64) if e := s.store.RevokeIntegrationKey(r.Context(), id); e != nil { writeError(w, 503, "吊销失败") return } s.store.Log(r.Context(), nil, u.ID, "revoke", "integration_key", fmt.Sprint(id), requestClientIP(r), true, "吊销管理端 API 密钥") w.WriteHeader(204) return } var input struct { Name string `json:"name"` Scopes []string `json:"scopes"` ExpiresAt time.Time `json:"expiresAt"` WebhookURL string `json:"webhookURL"` } if decodeJSON(r, &input) != nil || strings.TrimSpace(input.Name) == "" || len(input.Name) > 120 || len(input.Scopes) < 1 || len(input.Scopes) > len(integrationScopes) || !input.ExpiresAt.After(time.Now()) || input.ExpiresAt.After(time.Now().AddDate(1, 0, 0)) { writeError(w, 400, "名称、权限或有效期无效;有效期最长一年") return } for _, v := range input.Scopes { if !slices.Contains(integrationScopes, v) { writeError(w, 400, "权限范围无效") return } } if input.WebhookURL != "" { if _, e := validateWebhookURL(input.WebhookURL); e != nil { writeError(w, 422, e.Error()) return } } raw := make([]byte, 32) if _, e := rand.Read(raw); e != nil { writeError(w, 500, "无法生成密钥") return } token := "svh_live_" + hex.EncodeToString(raw) prefix := token[:21] secret := "" var cipher []byte if input.WebhookURL != "" { if _, e := rand.Read(raw); e != nil { writeError(w, 500, "无法生成回调密钥") return } secret = hex.EncodeToString(raw) var e error cipher, e = s.secretBox.Seal("integration-webhook:"+prefix, secret) if e != nil { writeError(w, 500, "无法保存回调密钥") return } } id, e := s.store.CreateIntegrationKey(r.Context(), store.IntegrationKey{AdministratorID: u.ID, Name: input.Name, Prefix: prefix, Scopes: input.Scopes, ExpiresAt: input.ExpiresAt, WebhookURL: input.WebhookURL, WebhookSecret: cipher}, tokenHash(token)) if e != nil { writeError(w, 503, "无法保存 API 密钥") return } s.store.Log(r.Context(), nil, u.ID, "create", "integration_key", fmt.Sprint(id), requestClientIP(r), true, "签发管理端 API 密钥") writeJSON(w, 201, map[string]any{"id": id, "token": token, "webhookSecret": secret}) } func (s *Server) requireIntegration(scopeName string, next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { header := r.Header.Get("Authorization") if !strings.HasPrefix(header, "Bearer ") || len(header) != len("Bearer svh_live_")+64 { writeError(w, 401, "需要管理端 API 密钥") return } key, e := s.store.IntegrationKeyByToken(r.Context(), tokenHash(strings.TrimPrefix(header, "Bearer "))) if e != nil { writeError(w, 401, "API 密钥无效、过期或已吊销") return } if !slices.Contains(key.Scopes, scopeName) { writeError(w, 403, "API 密钥缺少权限:"+scopeName) return } u, e := s.store.UserByID(r.Context(), key.AdministratorID) if e != nil || u.Role != "admin" { writeError(w, 401, "管理账号已失效") return } s.store.TouchIntegrationKey(r.Context(), key.ID) ctx := context.WithValue(context.WithValue(r.Context(), userKey, u), integrationKeyContext, key) ctx = scope.WithIntegrationKey(ctx, key.ID) next(w, r.WithContext(ctx)) } } func (s *Server) integrationList(w http.ResponseWriter, r *http.Request) { if r.PathValue("resource") == "users" { rows, e := s.store.ListTenants(r.Context()) if e != nil { writeError(w, 503, "无法读取用户") return } writeJSON(w, 200, map[string]any{"users": rows}) return } rows, e := s.store.ListAdminProjects(r.Context()) if e != nil { writeError(w, 503, "无法读取主机") return } writeJSON(w, 200, map[string]any{"hosts": rows}) } func (s *Server) integrationWrite(w http.ResponseWriter, r *http.Request) { key := r.Context().Value(integrationKeyContext).(store.IntegrationKey) idempotency := r.Header.Get("Idempotency-Key") if len(idempotency) < 8 || len(idempotency) > 128 || strings.ContainsAny(idempotency, "\x00\r\n") { writeError(w, 400, "写请求必须提供 8–128 字节的 Idempotency-Key") return } var input struct { Operation string `json:"operation"` Rows []batchRow `json:"rows"` } if decodeJSON(r, &input) != nil { writeError(w, 400, "请求格式无效") return } kind := r.PathValue("resource") if kind == "users" { if input.Operation == "" { input.Operation = "create_users" } if !slices.Contains([]string{"create_users", "user_enable", "user_disable"}, input.Operation) { writeError(w, 403, "用户接口不支持此操作") return } } else { if input.Operation == "" { input.Operation = "create_hosts" } if !slices.Contains([]string{"create_hosts", "assign_hosts", "host_subscription", "host_start", "host_stop", "host_password_reset"}, input.Operation) { writeError(w, 403, "主机接口不支持此操作") return } } sum := sha256.Sum256([]byte(fmt.Sprintf("integration:%d:%s", key.ID, idempotency))) raw, _ := json.Marshal(batchRequest{RequestKey: hex.EncodeToString(sum[:16]), Operation: input.Operation, Rows: input.Rows}) r.Body = io.NopCloser(bytes.NewReader(raw)) r.ContentLength = int64(len(raw)) s.adminBatches(w, r) } func (s *Server) integrationTask(w http.ResponseWriter, r *http.Request) { id, _ := strconv.ParseUint(r.PathValue("batchID"), 10, 64) key := r.Context().Value(integrationKeyContext).(store.IntegrationKey) owner, e := s.store.BatchIntegrationKey(r.Context(), id) if e != nil || owner != key.ID { writeError(w, 404, "任务不存在") return } if strings.HasSuffix(r.URL.Path, "/download") { s.adminBatchDownload(w, r) } else { s.adminBatch(w, r) } } func webhookSignature(secret, stamp, event string, body []byte) string { mac := hmac.New(sha256.New, []byte(secret)) fmt.Fprintf(mac, "%s.%s.", stamp, event) mac.Write(body) return hex.EncodeToString(mac.Sum(nil)) }