diff --git a/backend/biz/llmproxy/ohmyagent_prompt.go b/backend/biz/llmproxy/ohmyagent_prompt.go new file mode 100644 index 00000000..d61a5091 --- /dev/null +++ b/backend/biz/llmproxy/ohmyagent_prompt.go @@ -0,0 +1,135 @@ +package llmproxy + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "strings" +) + +const ohMyAgentSignatureHeader = "X-OhMyAgent-Signature" + +var ErrInvalidOhMyAgentPrompt = errors.New("invalid ohmyagent prompt") + +func ValidateOhMyAgentPrompt(body []byte, signature, secret string) error { + if secret == "" { + return fmt.Errorf("%w: signing secret is empty", ErrInvalidOhMyAgentPrompt) + } + prompt, err := extractOhMyAgentSystemPrompt(body) + if err != nil { + return err + } + provided, err := decodeOhMyAgentSignature(signature) + if err != nil { + return err + } + mac := hmac.New(sha256.New, []byte(secret)) + _, _ = mac.Write([]byte(prompt)) + if !hmac.Equal(provided, mac.Sum(nil)) { + return fmt.Errorf("%w: signature mismatch", ErrInvalidOhMyAgentPrompt) + } + return nil +} + +func decodeOhMyAgentSignature(signature string) ([]byte, error) { + encoded, ok := strings.CutPrefix(strings.TrimSpace(signature), "v1=") + if !ok { + return nil, fmt.Errorf("%w: unsupported signature", ErrInvalidOhMyAgentPrompt) + } + decoded, err := hex.DecodeString(encoded) + if err != nil || len(decoded) != sha256.Size { + return nil, fmt.Errorf("%w: malformed signature", ErrInvalidOhMyAgentPrompt) + } + return decoded, nil +} + +type ohMyAgentPromptPayload struct { + Messages []ohMyAgentMessage `json:"messages"` + Input []ohMyAgentMessage `json:"input"` + Instructions json.RawMessage `json:"instructions"` + System json.RawMessage `json:"system"` +} + +type ohMyAgentMessage struct { + Role string `json:"role"` + Content json.RawMessage `json:"content"` +} + +func extractOhMyAgentSystemPrompt(body []byte) (string, error) { + var payload ohMyAgentPromptPayload + if len(body) == 0 || json.Unmarshal(body, &payload) != nil { + return "", fmt.Errorf("%w: invalid request body", ErrInvalidOhMyAgentPrompt) + } + if prompt, ok := decodeFirstOhMyAgentPromptBlock(payload.System); ok { + return prompt, nil + } + if prompt, ok := decodeOhMyAgentPrompt(payload.Instructions); ok { + return prompt, nil + } + for _, message := range payload.Messages { + if message.Role == "system" { + if prompt, ok := decodeOhMyAgentPrompt(message.Content); ok { + return prompt, nil + } + break + } + } + for _, message := range payload.Input { + if message.Role == "developer" || message.Role == "system" { + if prompt, ok := decodeOhMyAgentPrompt(message.Content); ok { + return prompt, nil + } + break + } + } + return "", fmt.Errorf("%w: system prompt not found", ErrInvalidOhMyAgentPrompt) +} + +func decodeFirstOhMyAgentPromptBlock(raw json.RawMessage) (string, bool) { + if len(raw) == 0 { + return "", false + } + var text string + if json.Unmarshal(raw, &text) == nil { + return text, text != "" + } + var parts []struct { + Text string `json:"text"` + } + if json.Unmarshal(raw, &parts) != nil { + return "", false + } + if len(parts) == 0 || parts[0].Text == "" { + return "", false + } + return parts[0].Text, true +} + +func decodeOhMyAgentPrompt(raw json.RawMessage) (string, bool) { + if len(raw) == 0 { + return "", false + } + var text string + if json.Unmarshal(raw, &text) == nil { + return text, text != "" + } + var parts []struct { + Text string `json:"text"` + } + if json.Unmarshal(raw, &parts) != nil { + return "", false + } + texts := make([]string, 0, len(parts)) + for _, part := range parts { + if part.Text != "" { + texts = append(texts, part.Text) + } + } + if len(texts) == 0 { + return "", false + } + return strings.Join(texts, "\n"), true +} diff --git a/backend/biz/llmproxy/ohmyagent_prompt_test.go b/backend/biz/llmproxy/ohmyagent_prompt_test.go new file mode 100644 index 00000000..e1ae46f8 --- /dev/null +++ b/backend/biz/llmproxy/ohmyagent_prompt_test.go @@ -0,0 +1,89 @@ +package llmproxy + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "testing" +) + +const ( + testOhMyAgentPrompt = "You are OhMyAgent, an AI coding agent for software engineering tasks." + testSigningSecret = "omas_test_secret" +) + +func TestValidateOhMyAgentPromptProtocols(t *testing.T) { + cases := map[string]any{ + "openai-chat": map[string]any{"messages": []map[string]any{ + {"role": "system", "content": testOhMyAgentPrompt}, + {"role": "system", "content": "dynamic"}, + }}, + "responses": map[string]any{ + "instructions": testOhMyAgentPrompt, + "input": []map[string]any{{"role": "developer", "content": "dynamic"}}, + }, + "anthropic": map[string]any{"system": []map[string]any{ + {"type": "text", "text": testOhMyAgentPrompt}, + {"type": "text", "text": "dynamic"}, + }}, + } + for name, payload := range cases { + t.Run(name, func(t *testing.T) { + body, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + if err := ValidateOhMyAgentPrompt(body, testOhMyAgentSignature(testOhMyAgentPrompt), testSigningSecret); err != nil { + t.Fatalf("ValidateOhMyAgentPrompt() error = %v", err) + } + }) + } +} + +func TestValidateOhMyAgentPromptRejectsNonFirstAnthropicPrompt(t *testing.T) { + body, err := json.Marshal(map[string]any{"system": []map[string]any{ + {"type": "text", "text": ""}, + {"type": "text", "text": testOhMyAgentPrompt}, + }}) + if err != nil { + t.Fatal(err) + } + if err := ValidateOhMyAgentPrompt(body, testOhMyAgentSignature(testOhMyAgentPrompt), testSigningSecret); err == nil { + t.Fatal("ValidateOhMyAgentPrompt() error = nil") + } +} + +func TestValidateOhMyAgentPromptRejectsModifiedFirstPrompt(t *testing.T) { + body, err := json.Marshal(map[string]any{"instructions": "modified"}) + if err != nil { + t.Fatal(err) + } + if err := ValidateOhMyAgentPrompt(body, testOhMyAgentSignature(testOhMyAgentPrompt), testSigningSecret); err == nil { + t.Fatal("ValidateOhMyAgentPrompt() error = nil") + } +} + +func TestValidateOhMyAgentPromptRejectsInvalidCredentials(t *testing.T) { + body, err := json.Marshal(map[string]any{"instructions": testOhMyAgentPrompt}) + if err != nil { + t.Fatal(err) + } + for name, credentials := range map[string][2]string{ + "missing signature": {"", testSigningSecret}, + "malformed signature": {"v1=invalid", testSigningSecret}, + "missing secret": {testOhMyAgentSignature(testOhMyAgentPrompt), ""}, + } { + t.Run(name, func(t *testing.T) { + if err := ValidateOhMyAgentPrompt(body, credentials[0], credentials[1]); err == nil { + t.Fatal("ValidateOhMyAgentPrompt() error = nil") + } + }) + } +} + +func testOhMyAgentSignature(prompt string) string { + mac := hmac.New(sha256.New, []byte(testSigningSecret)) + _, _ = mac.Write([]byte(prompt)) + return "v1=" + hex.EncodeToString(mac.Sum(nil)) +} diff --git a/backend/biz/llmproxy/proxy.go b/backend/biz/llmproxy/proxy.go index 2ab83e89..5f35c391 100644 --- a/backend/biz/llmproxy/proxy.go +++ b/backend/biz/llmproxy/proxy.go @@ -18,15 +18,21 @@ import ( "github.com/google/uuid" + "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/modelapikey" "github.com/chaitin/MonkeyCode/backend/db/taskvirtualmachine" + "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/pkg/modelusage" "github.com/chaitin/MonkeyCode/backend/pkg/netguard" ) const upstreamFailureMessage = "连接上游模型失败,请检查模型配置,或重试" +var errModelForbidden = errors.New("model is not accessible") + var allowPaths = map[string]string{ "/v1/chat/completions": "/chat/completions", "/v1/responses": "/responses", @@ -36,13 +42,15 @@ var allowPaths = map[string]string{ type contextKey struct{} type modelContext struct { - modelID uuid.UUID - userID uuid.UUID - vmID string - provider string - modelName string - baseURL string - apiKey string + modelID uuid.UUID + userID uuid.UUID + vmID string + keyKind modelapikey.Kind + provider string + modelName string + baseURL string + apiKey string + signingSecret string } type proxyContext struct { @@ -137,17 +145,36 @@ func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { http.Error(w, "Bad Request", http.StatusBadRequest) return } - m, err := p.resolveModel(r.Context(), token) + m, err := p.resolveModel(r.Context(), token, reqMeta.Model) if err != nil { + if errors.Is(err, errModelForbidden) { + p.logger.WarnContext(r.Context(), "resolve ohmyagent model failed", "error", err) + http.Error(w, "Forbidden", http.StatusForbidden) + return + } p.logger.WarnContext(r.Context(), "resolve runtime model failed", "error", err) http.Error(w, "Unauthorized", http.StatusUnauthorized) return } - if reqMeta.Model != "" && reqMeta.Model != m.modelName { + if m.keyKind == modelapikey.KindRuntime && reqMeta.Model != "" && reqMeta.Model != m.modelName { p.logger.WarnContext(r.Context(), "model mismatch", "request_model", reqMeta.Model, "expected_model", m.modelName) http.Error(w, "Forbidden", http.StatusForbidden) return } + if m.keyKind == modelapikey.KindOhmyagent { + body, err = replaceRequestModel(body, m.modelName) + if err != nil { + http.Error(w, "Bad Request", http.StatusBadRequest) + return + } + r.Body = io.NopCloser(bytes.NewReader(body)) + r.ContentLength = int64(len(body)) + if err := ValidateOhMyAgentPrompt(body, r.Header.Get(ohMyAgentSignatureHeader), m.signingSecret); err != nil { + p.logger.WarnContext(r.Context(), "ohmyagent prompt validation failed", "error", err) + http.Error(w, "invalid ohmyagent request", http.StatusForbidden) + return + } + } ctx := context.WithValue(r.Context(), contextKey{}, &proxyContext{ model: m, @@ -157,7 +184,7 @@ func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { p.proxy.ServeHTTP(w, r.WithContext(ctx)) } -func (p *Proxy) resolveModel(ctx context.Context, token string) (*modelContext, error) { +func (p *Proxy) resolveModel(ctx context.Context, token, requestedModel string) (*modelContext, error) { keyID, err := uuid.Parse(token) query := p.db.ModelApiKey.Query(). WithModel(). @@ -171,20 +198,52 @@ func (p *Proxy) resolveModel(ctx context.Context, token string) (*modelContext, if err != nil { return nil, err } - if key.Edges.Model == nil { + + selected := key.Edges.Model + if key.Kind == modelapikey.KindOhmyagent { + selected, err = p.db.Model.Query(). + Where( + model.Model(requestedModel), + model.Or( + model.UserID(key.UserID), + model.HasGroupsWith(teamgroup.HasMembersWith(user.ID(key.UserID))), + model.HasUserWith(user.Role(consts.UserRoleAdmin)), + ), + ). + Only(ctx) + if err != nil { + return nil, fmt.Errorf("%w: %v", errModelForbidden, err) + } + } + if selected == nil { return nil, errors.New("model not found") } return &modelContext{ - modelID: key.Edges.Model.ID, - userID: key.UserID, - vmID: key.VirtualmachineID, - provider: key.Edges.Model.Provider, - modelName: key.Edges.Model.Model, - baseURL: key.Edges.Model.BaseURL, - apiKey: key.Edges.Model.APIKey, + modelID: selected.ID, + userID: key.UserID, + vmID: key.VirtualmachineID, + keyKind: key.Kind, + provider: selected.Provider, + modelName: selected.Model, + baseURL: selected.BaseURL, + apiKey: selected.APIKey, + signingSecret: key.SigningSecret, }, nil } +func replaceRequestModel(body []byte, modelName string) ([]byte, error) { + var payload map[string]json.RawMessage + if err := json.Unmarshal(body, &payload); err != nil { + return nil, err + } + encoded, err := json.Marshal(modelName) + if err != nil { + return nil, err + } + payload["model"] = encoded + return json.Marshal(payload) +} + var LLMAllowPaths []string = []string{ "/v1/messages", "/chat/completions", @@ -227,6 +286,7 @@ func (p *Proxy) rewrite(r *httputil.ProxyRequest) { r.Out.URL.Path = filepath.Join(ul.Path, uppath) r.Out.Header.Set("Authorization", "Bearer "+m.apiKey) r.Out.Header.Set("X-Api-Key", m.apiKey) + r.Out.Header.Del(ohMyAgentSignatureHeader) r.SetXForwarded() r.Out.Host = ul.Host p.logger.With( diff --git a/backend/biz/llmproxy/proxy_test.go b/backend/biz/llmproxy/proxy_test.go index 1616cf2b..44ceeab8 100644 --- a/backend/biz/llmproxy/proxy_test.go +++ b/backend/biz/llmproxy/proxy_test.go @@ -2,6 +2,8 @@ package llmproxy import ( "context" + "encoding/json" + "errors" "io" "log/slog" "net/http" @@ -17,6 +19,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db" "github.com/chaitin/MonkeyCode/backend/db/enttest" + "github.com/chaitin/MonkeyCode/backend/db/modelapikey" "github.com/chaitin/MonkeyCode/backend/pkg/modelusage" ) @@ -139,6 +142,77 @@ func (s *usageRecorderStub) waitForEvents(t *testing.T, want int) []modelusage.E } } +func TestProxyRejectsInvalidOhMyAgentSignature(t *testing.T) { + upstreamCalls := 0 + var upstreamSignature string + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls++ + upstreamSignature = r.Header.Get(ohMyAgentSignatureHeader) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"chatcmpl_test","choices":[]}`)) + })) + t.Cleanup(upstream.Close) + + client := newProxyTestDB(t) + key, _, _, modelID := seedProxyModelWithTask(t, client, upstream.URL+"/v1") + modelKey, err := client.ModelApiKey.Query().Where(modelapikey.APIKey(key)).Only(context.Background()) + if err != nil { + t.Fatal(err) + } + if err := client.ModelApiKey.UpdateOneID(modelKey.ID). + SetKind(modelapikey.KindOhmyagent). + SetSigningSecret(testSigningSecret). + ClearModelID(). + ClearVirtualmachineID(). + Exec(context.Background()); err != nil { + t.Fatal(err) + } + proxy := NewProxy(client, slog.New(slog.NewTextHandler(io.Discard, nil))) + if _, err := proxy.resolveModel(context.Background(), key, modelID); !errors.Is(err, errModelForbidden) { + t.Fatalf("UUID model selector error = %v, want errModelForbidden", err) + } + + payload := map[string]any{ + "model": "gpt-4o", + "messages": []map[string]any{ + {"role": "system", "content": testOhMyAgentPrompt}, + {"role": "system", "content": "dynamic"}, + }, + } + body, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + validReq := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(string(body))) + validReq.Header.Set("Authorization", "Bearer "+key) + validReq.Header.Set(ohMyAgentSignatureHeader, testOhMyAgentSignature(testOhMyAgentPrompt)) + validRec := httptest.NewRecorder() + proxy.ServeHTTP(validRec, validReq) + if validRec.Code != http.StatusOK { + t.Fatalf("valid prompt status = %d, body = %s", validRec.Code, validRec.Body.String()) + } + if upstreamSignature != "" { + t.Fatalf("signature was forwarded upstream: %q", upstreamSignature) + } + + payload["messages"] = []map[string]any{{"role": "system", "content": "modified"}} + body, err = json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + invalidReq := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(string(body))) + invalidReq.Header.Set("Authorization", "Bearer "+key) + invalidReq.Header.Set(ohMyAgentSignatureHeader, testOhMyAgentSignature(testOhMyAgentPrompt)) + invalidRec := httptest.NewRecorder() + proxy.ServeHTTP(invalidRec, invalidReq) + if invalidRec.Code != http.StatusForbidden { + t.Fatalf("invalid prompt status = %d, want %d", invalidRec.Code, http.StatusForbidden) + } + if upstreamCalls != 1 { + t.Fatalf("upstream calls = %d, want 1", upstreamCalls) + } +} + func TestProxyForwardsRuntimeKeyToUpstreamModel(t *testing.T) { var gotPath string var gotAuth string diff --git a/backend/biz/mcphub/auth/service.go b/backend/biz/mcphub/auth/service.go index 9faa9dae..4951f51c 100644 --- a/backend/biz/mcphub/auth/service.go +++ b/backend/biz/mcphub/auth/service.go @@ -57,7 +57,7 @@ func (s *Service) Resolve(ctx context.Context, token string) (*Subject, error) { } return nil, fmt.Errorf("query model api key: %w", err) } - if strings.TrimSpace(key.VirtualmachineID) == "" { + if key.Kind == modelapikey.KindOhmyagent || strings.TrimSpace(key.VirtualmachineID) == "" { return nil, ErrTaskNotBound } diff --git a/backend/biz/setting/handler/v1/model.go b/backend/biz/setting/handler/v1/model.go index 0c66b9bc..b3e9c87a 100644 --- a/backend/biz/setting/handler/v1/model.go +++ b/backend/biz/setting/handler/v1/model.go @@ -43,9 +43,60 @@ func NewModelHandler(i *do.Injector) (*ModelHandler, error) { v1.GET("/:id/health-check", web.BindHandler(h.CheckByID)) v1.POST("/health-check", web.BindHandler(h.CheckByConfig)) + apiKeys := w.Group("/api/v1/users/ohmyagent/api-keys") + apiKeys.Use(auth.Auth(), targetActive.TargetActive()) + apiKeys.POST("", web.BaseHandler(h.CreateOhMyAgentAPIKey)) + apiKeys.DELETE("/:id", web.BindHandler(h.DeleteOhMyAgentAPIKey)) + return h, nil } +// CreateOhMyAgentAPIKey 创建模型无关的 OhMyAgent 代理 Key。 +// +// Key 不绑定模型或任务;客户端应把每次代理请求的 model 设置为模型配置 ID。 +// 明文 api_key 仅在本接口响应中返回,调用方应立即安全保存。 +// +// @Summary 创建 OhMyAgent API Key +// @Description 创建当前用户的模型无关 OhMyAgent 代理 Key。请求无需模型参数;使用时在 LLM 请求的 model 字段传模型配置 ID。API Key 与签名 Secret 仅在创建响应中返回。 +// @Tags 【用户】OhMyAgent +// @Produce json +// @Security MonkeyCodeAIAuth +// @Success 200 {object} web.Resp{data=domain.CreateOhMyAgentAPIKeyResp} "成功" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器内部错误" +// @Router /api/v1/users/ohmyagent/api-keys [post] +func (h *ModelHandler) CreateOhMyAgentAPIKey(c *web.Context) error { + user := middleware.GetUser(c) + resp, err := h.usecase.CreateOhMyAgentAPIKey(c.Request().Context(), user.ID) + if err != nil { + h.logger.ErrorContext(c.Request().Context(), "failed to create ohmyagent api key", "error", err, "user_id", user.ID) + return errcode.ErrDatabaseOperation.Wrap(err) + } + return c.Success(resp) +} + +// DeleteOhMyAgentAPIKey 删除当前用户的 OhMyAgent 代理 Key。 +// +// @Summary 删除 OhMyAgent API Key +// @Description 按 Key ID 删除当前用户自己的 OhMyAgent 代理 Key;不能删除 runtime Key 或其他用户的 Key。 +// @Tags 【用户】OhMyAgent +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param id path string true "创建接口返回的 Key ID" +// @Success 200 {object} web.Resp{} "成功" +// @Failure 400 {object} web.Resp "请求参数错误" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器内部错误" +// @Router /api/v1/users/ohmyagent/api-keys/{id} [delete] +func (h *ModelHandler) DeleteOhMyAgentAPIKey(c *web.Context, req domain.DeleteOhMyAgentAPIKeyReq) error { + user := middleware.GetUser(c) + if err := h.usecase.DeleteOhMyAgentAPIKey(c.Request().Context(), user.ID, req.ID); err != nil { + h.logger.ErrorContext(c.Request().Context(), "failed to delete ohmyagent api key", "error", err, "user_id", user.ID, "key_id", req.ID) + return errcode.ErrDatabaseOperation.Wrap(err) + } + return c.Success(nil) +} + // List 获取当前用户的模型配置列表 // // @Summary 获取当前用户的模型配置列表 diff --git a/backend/biz/setting/repo/model.go b/backend/biz/setting/repo/model.go index c1f69242..14b5d9a3 100644 --- a/backend/biz/setting/repo/model.go +++ b/backend/biz/setting/repo/model.go @@ -2,7 +2,10 @@ package repo import ( "context" + "crypto/rand" + "encoding/base64" "fmt" + "strings" "time" "entgo.io/ent/dialect/sql" @@ -107,6 +110,31 @@ func (r *modelRepo) CreateRuntimeAPIKey(ctx context.Context, uid, modelID uuid.U return runtimeKey, nil } +func (r *modelRepo) CreateOhMyAgentAPIKey(ctx context.Context, uid uuid.UUID) (*db.ModelApiKey, error) { + secret := make([]byte, 32) + if _, err := rand.Read(secret); err != nil { + return nil, fmt.Errorf("generate signing secret: %w", err) + } + return r.db.ModelApiKey.Create(). + SetID(uuid.New()). + SetUserID(uid). + SetKind(modelapikey.KindOhmyagent). + SetAPIKey("oma_" + strings.ReplaceAll(uuid.NewString(), "-", "")). + SetSigningSecret("omas_" + base64.RawURLEncoding.EncodeToString(secret)). + Save(ctx) +} + +func (r *modelRepo) DeleteOhMyAgentAPIKey(ctx context.Context, uid, id uuid.UUID) error { + _, err := r.db.ModelApiKey.Delete(). + Where( + modelapikey.ID(id), + modelapikey.UserID(uid), + modelapikey.KindEQ(modelapikey.KindOhmyagent), + ). + Exec(ctx) + return err +} + func (r *modelRepo) List(ctx context.Context, uid uuid.UUID, cursor domain.CursorReq) ([]*db.Model, *db.Cursor, error) { var ( models []*db.Model diff --git a/backend/biz/setting/repo/model_test.go b/backend/biz/setting/repo/model_test.go index 055fa348..a07f6e79 100644 --- a/backend/biz/setting/repo/model_test.go +++ b/backend/biz/setting/repo/model_test.go @@ -2,6 +2,7 @@ package repo import ( "context" + "strings" "testing" _ "github.com/mattn/go-sqlite3" @@ -258,6 +259,34 @@ func TestModelRepoCreateRuntimeAPIKeyReusesVMRuntimeKey(t *testing.T) { } } +func TestModelRepoCreateAndDeleteOhMyAgentAPIKey(t *testing.T) { + client := enttest.Open(t, "sqlite3", "file:model-repo-ohmyagent-key?mode=memory&cache=shared&_fk=1") + t.Cleanup(func() { _ = client.Close() }) + ctx := context.Background() + userID := uuid.New() + repo := &modelRepo{db: client} + + key, err := repo.CreateOhMyAgentAPIKey(ctx, userID) + if err != nil { + t.Fatalf("CreateOhMyAgentAPIKey() error = %v", err) + } + if key.UserID != userID || key.Kind != modelapikey.KindOhmyagent || key.ModelID != uuid.Nil || key.VirtualmachineID != "" || !strings.HasPrefix(key.APIKey, "oma_") || !strings.HasPrefix(key.SigningSecret, "omas_") { + t.Fatalf("key = %+v, want model-independent ohmyagent key", key) + } + if err := repo.DeleteOhMyAgentAPIKey(ctx, uuid.New(), key.ID); err != nil { + t.Fatalf("delete key as another user: %v", err) + } + if _, err := client.ModelApiKey.Get(ctx, key.ID); err != nil { + t.Fatalf("key should still exist after another user deletes it: %v", err) + } + if err := repo.DeleteOhMyAgentAPIKey(ctx, userID, key.ID); err != nil { + t.Fatalf("DeleteOhMyAgentAPIKey() error = %v", err) + } + if _, err := client.ModelApiKey.Get(ctx, key.ID); !db.IsNotFound(err) { + t.Fatalf("deleted key lookup error = %v, want not found", err) + } +} + func createModelTestUser(t *testing.T, ctx context.Context, client *db.Client, id uuid.UUID, role consts.UserRole) { t.Helper() if _, err := client.User.Create(). diff --git a/backend/biz/setting/usecase/model.go b/backend/biz/setting/usecase/model.go index aa84e8cb..a53e9373 100644 --- a/backend/biz/setting/usecase/model.go +++ b/backend/biz/setting/usecase/model.go @@ -150,6 +150,26 @@ func (u *modelUsecase) Update(ctx context.Context, uid, id uuid.UUID, req *domai return nil } +func (u *modelUsecase) CreateOhMyAgentAPIKey(ctx context.Context, uid uuid.UUID) (*domain.CreateOhMyAgentAPIKeyResp, error) { + key, err := u.repo.CreateOhMyAgentAPIKey(ctx, uid) + if err != nil { + return nil, fmt.Errorf("failed to create ohmyagent api key: %w", err) + } + return &domain.CreateOhMyAgentAPIKeyResp{ + ID: key.ID, + APIKey: key.APIKey, + SigningSecret: key.SigningSecret, + CreatedAt: key.CreatedAt.Unix(), + }, nil +} + +func (u *modelUsecase) DeleteOhMyAgentAPIKey(ctx context.Context, uid, id uuid.UUID) error { + if err := u.repo.DeleteOhMyAgentAPIKey(ctx, uid, id); err != nil { + return fmt.Errorf("failed to delete ohmyagent api key: %w", err) + } + return nil +} + func (u *modelUsecase) Check(ctx context.Context, uid, id uuid.UUID) (*domain.CheckModelResp, error) { m, err := u.repo.Get(ctx, uid, id) if err != nil { diff --git a/backend/biz/setting/usecase/model_ohmyagent_key_test.go b/backend/biz/setting/usecase/model_ohmyagent_key_test.go new file mode 100644 index 00000000..289f9203 --- /dev/null +++ b/backend/biz/setting/usecase/model_ohmyagent_key_test.go @@ -0,0 +1,41 @@ +package usecase + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/domain" +) + +type ohMyAgentKeyRepoStub struct { + domain.ModelRepo + key *db.ModelApiKey + err error +} + +func (s *ohMyAgentKeyRepoStub) CreateOhMyAgentAPIKey(context.Context, uuid.UUID) (*db.ModelApiKey, error) { + return s.key, s.err +} + +func TestCreateOhMyAgentAPIKeyReturnsSigningSecret(t *testing.T) { + createdAt := time.Unix(123, 0) + repo := &ohMyAgentKeyRepoStub{key: &db.ModelApiKey{ + ID: uuid.New(), + APIKey: "oma_key", + SigningSecret: "omas_secret", + CreatedAt: createdAt, + }} + usecase := &modelUsecase{repo: repo} + + got, err := usecase.CreateOhMyAgentAPIKey(context.Background(), uuid.New()) + if err != nil { + t.Fatal(err) + } + if got.ID != repo.key.ID || got.APIKey != repo.key.APIKey || got.SigningSecret != repo.key.SigningSecret || got.CreatedAt != createdAt.Unix() { + t.Fatalf("response = %#v", got) + } +} diff --git a/backend/biz/task/usecase/task_switch_model_test.go b/backend/biz/task/usecase/task_switch_model_test.go index 25c6cfe2..9e961ec3 100644 --- a/backend/biz/task/usecase/task_switch_model_test.go +++ b/backend/biz/task/usecase/task_switch_model_test.go @@ -385,6 +385,13 @@ func (r *switchModelModelRepo) Update(context.Context, uuid.UUID, uuid.UUID, *do func (r *switchModelModelRepo) UpdateCheckResult(context.Context, uuid.UUID, bool, string) error { return errors.New("unused") } +func (r *switchModelModelRepo) CreateOhMyAgentAPIKey(context.Context, uuid.UUID) (*db.ModelApiKey, error) { + return nil, errors.New("unused") +} +func (r *switchModelModelRepo) DeleteOhMyAgentAPIKey(context.Context, uuid.UUID, uuid.UUID) error { + return errors.New("unused") +} + func (r *switchModelModelRepo) CreateRuntimeAPIKey(_ context.Context, uid, modelID uuid.UUID, vmID string) (string, error) { r.runtimeUserID = uid r.runtimeModelID = modelID diff --git a/backend/db/migrate/schema.go b/backend/db/migrate/schema.go index c1b55893..aa0ca026 100644 --- a/backend/db/migrate/schema.go +++ b/backend/db/migrate/schema.go @@ -867,10 +867,12 @@ var ( {Name: "id", Type: field.TypeUUID, Unique: true}, {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, {Name: "user_id", Type: field.TypeUUID}, + {Name: "kind", Type: field.TypeEnum, Enums: []string{"runtime", "ohmyagent"}, Default: "runtime"}, {Name: "virtualmachine_id", Type: field.TypeString, Nullable: true}, {Name: "api_key", Type: field.TypeString, Size: 2147483647}, + {Name: "signing_secret", Type: field.TypeString, Size: 2147483647, Default: ""}, {Name: "created_at", Type: field.TypeTime}, - {Name: "model_id", Type: field.TypeUUID}, + {Name: "model_id", Type: field.TypeUUID, Nullable: true}, } // ModelAPIKeysTable holds the schema information for the "model_api_keys" table. ModelAPIKeysTable = &schema.Table{ @@ -880,9 +882,9 @@ var ( ForeignKeys: []*schema.ForeignKey{ { Symbol: "model_api_keys_models_apikeys", - Columns: []*schema.Column{ModelAPIKeysColumns[6]}, + Columns: []*schema.Column{ModelAPIKeysColumns[8]}, RefColumns: []*schema.Column{ModelsColumns[0]}, - OnDelete: schema.NoAction, + OnDelete: schema.SetNull, }, }, } diff --git a/backend/db/modelapikey.go b/backend/db/modelapikey.go index 2a57a0bd..bfeceea2 100644 --- a/backend/db/modelapikey.go +++ b/backend/db/modelapikey.go @@ -25,10 +25,14 @@ type ModelApiKey struct { ModelID uuid.UUID `json:"model_id,omitempty"` // UserID holds the value of the "user_id" field. UserID uuid.UUID `json:"user_id,omitempty"` + // Kind holds the value of the "kind" field. + Kind modelapikey.Kind `json:"kind,omitempty"` // VirtualmachineID holds the value of the "virtualmachine_id" field. VirtualmachineID string `json:"virtualmachine_id,omitempty"` // APIKey holds the value of the "api_key" field. APIKey string `json:"api_key,omitempty"` + // SigningSecret holds the value of the "signing_secret" field. + SigningSecret string `json:"-"` // CreatedAt holds the value of the "created_at" field. CreatedAt time.Time `json:"created_at,omitempty"` // Edges holds the relations/edges for other nodes in the graph. @@ -62,7 +66,7 @@ func (*ModelApiKey) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { - case modelapikey.FieldVirtualmachineID, modelapikey.FieldAPIKey: + case modelapikey.FieldKind, modelapikey.FieldVirtualmachineID, modelapikey.FieldAPIKey, modelapikey.FieldSigningSecret: values[i] = new(sql.NullString) case modelapikey.FieldDeletedAt, modelapikey.FieldCreatedAt: values[i] = new(sql.NullTime) @@ -107,6 +111,12 @@ func (_m *ModelApiKey) assignValues(columns []string, values []any) error { } else if value != nil { _m.UserID = *value } + case modelapikey.FieldKind: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field kind", values[i]) + } else if value.Valid { + _m.Kind = modelapikey.Kind(value.String) + } case modelapikey.FieldVirtualmachineID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field virtualmachine_id", values[i]) @@ -119,6 +129,12 @@ func (_m *ModelApiKey) assignValues(columns []string, values []any) error { } else if value.Valid { _m.APIKey = value.String } + case modelapikey.FieldSigningSecret: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field signing_secret", values[i]) + } else if value.Valid { + _m.SigningSecret = value.String + } case modelapikey.FieldCreatedAt: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field created_at", values[i]) @@ -175,12 +191,17 @@ func (_m *ModelApiKey) String() string { builder.WriteString("user_id=") builder.WriteString(fmt.Sprintf("%v", _m.UserID)) builder.WriteString(", ") + builder.WriteString("kind=") + builder.WriteString(fmt.Sprintf("%v", _m.Kind)) + builder.WriteString(", ") builder.WriteString("virtualmachine_id=") builder.WriteString(_m.VirtualmachineID) builder.WriteString(", ") builder.WriteString("api_key=") builder.WriteString(_m.APIKey) builder.WriteString(", ") + builder.WriteString("signing_secret=") + builder.WriteString(", ") builder.WriteString("created_at=") builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) builder.WriteByte(')') diff --git a/backend/db/modelapikey/modelapikey.go b/backend/db/modelapikey/modelapikey.go index a4c2152f..963825f8 100644 --- a/backend/db/modelapikey/modelapikey.go +++ b/backend/db/modelapikey/modelapikey.go @@ -3,6 +3,7 @@ package modelapikey import ( + "fmt" "time" "entgo.io/ent" @@ -21,10 +22,14 @@ const ( FieldModelID = "model_id" // FieldUserID holds the string denoting the user_id field in the database. FieldUserID = "user_id" + // FieldKind holds the string denoting the kind field in the database. + FieldKind = "kind" // FieldVirtualmachineID holds the string denoting the virtualmachine_id field in the database. FieldVirtualmachineID = "virtualmachine_id" // FieldAPIKey holds the string denoting the api_key field in the database. FieldAPIKey = "api_key" + // FieldSigningSecret holds the string denoting the signing_secret field in the database. + FieldSigningSecret = "signing_secret" // FieldCreatedAt holds the string denoting the created_at field in the database. FieldCreatedAt = "created_at" // EdgeModel holds the string denoting the model edge name in mutations. @@ -46,8 +51,10 @@ var Columns = []string{ FieldDeletedAt, FieldModelID, FieldUserID, + FieldKind, FieldVirtualmachineID, FieldAPIKey, + FieldSigningSecret, FieldCreatedAt, } @@ -71,10 +78,38 @@ var ( Interceptors [1]ent.Interceptor // APIKeyValidator is a validator for the "api_key" field. It is called by the builders before save. APIKeyValidator func(string) error + // DefaultSigningSecret holds the default value on creation for the "signing_secret" field. + DefaultSigningSecret string // DefaultCreatedAt holds the default value on creation for the "created_at" field. DefaultCreatedAt func() time.Time ) +// Kind defines the type for the "kind" enum field. +type Kind string + +// KindRuntime is the default value of the Kind enum. +const DefaultKind = KindRuntime + +// Kind values. +const ( + KindRuntime Kind = "runtime" + KindOhmyagent Kind = "ohmyagent" +) + +func (k Kind) String() string { + return string(k) +} + +// KindValidator is a validator for the "kind" field enum values. It is called by the builders before save. +func KindValidator(k Kind) error { + switch k { + case KindRuntime, KindOhmyagent: + return nil + default: + return fmt.Errorf("modelapikey: invalid enum value for kind field: %q", k) + } +} + // OrderOption defines the ordering options for the ModelApiKey queries. type OrderOption func(*sql.Selector) @@ -98,6 +133,11 @@ func ByUserID(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldUserID, opts...).ToFunc() } +// ByKind orders the results by the kind field. +func ByKind(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldKind, opts...).ToFunc() +} + // ByVirtualmachineID orders the results by the virtualmachine_id field. func ByVirtualmachineID(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldVirtualmachineID, opts...).ToFunc() @@ -108,6 +148,11 @@ func ByAPIKey(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldAPIKey, opts...).ToFunc() } +// BySigningSecret orders the results by the signing_secret field. +func BySigningSecret(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSigningSecret, opts...).ToFunc() +} + // ByCreatedAt orders the results by the created_at field. func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() diff --git a/backend/db/modelapikey/where.go b/backend/db/modelapikey/where.go index 42596f58..646439b4 100644 --- a/backend/db/modelapikey/where.go +++ b/backend/db/modelapikey/where.go @@ -81,6 +81,11 @@ func APIKey(v string) predicate.ModelApiKey { return predicate.ModelApiKey(sql.FieldEQ(FieldAPIKey, v)) } +// SigningSecret applies equality check predicate on the "signing_secret" field. It's identical to SigningSecretEQ. +func SigningSecret(v string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldEQ(FieldSigningSecret, v)) +} + // CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. func CreatedAt(v time.Time) predicate.ModelApiKey { return predicate.ModelApiKey(sql.FieldEQ(FieldCreatedAt, v)) @@ -156,6 +161,16 @@ func ModelIDNotIn(vs ...uuid.UUID) predicate.ModelApiKey { return predicate.ModelApiKey(sql.FieldNotIn(FieldModelID, vs...)) } +// ModelIDIsNil applies the IsNil predicate on the "model_id" field. +func ModelIDIsNil() predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldIsNull(FieldModelID)) +} + +// ModelIDNotNil applies the NotNil predicate on the "model_id" field. +func ModelIDNotNil() predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldNotNull(FieldModelID)) +} + // UserIDEQ applies the EQ predicate on the "user_id" field. func UserIDEQ(v uuid.UUID) predicate.ModelApiKey { return predicate.ModelApiKey(sql.FieldEQ(FieldUserID, v)) @@ -196,6 +211,26 @@ func UserIDLTE(v uuid.UUID) predicate.ModelApiKey { return predicate.ModelApiKey(sql.FieldLTE(FieldUserID, v)) } +// KindEQ applies the EQ predicate on the "kind" field. +func KindEQ(v Kind) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldEQ(FieldKind, v)) +} + +// KindNEQ applies the NEQ predicate on the "kind" field. +func KindNEQ(v Kind) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldNEQ(FieldKind, v)) +} + +// KindIn applies the In predicate on the "kind" field. +func KindIn(vs ...Kind) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldIn(FieldKind, vs...)) +} + +// KindNotIn applies the NotIn predicate on the "kind" field. +func KindNotIn(vs ...Kind) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldNotIn(FieldKind, vs...)) +} + // VirtualmachineIDEQ applies the EQ predicate on the "virtualmachine_id" field. func VirtualmachineIDEQ(v string) predicate.ModelApiKey { return predicate.ModelApiKey(sql.FieldEQ(FieldVirtualmachineID, v)) @@ -336,6 +371,71 @@ func APIKeyContainsFold(v string) predicate.ModelApiKey { return predicate.ModelApiKey(sql.FieldContainsFold(FieldAPIKey, v)) } +// SigningSecretEQ applies the EQ predicate on the "signing_secret" field. +func SigningSecretEQ(v string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldEQ(FieldSigningSecret, v)) +} + +// SigningSecretNEQ applies the NEQ predicate on the "signing_secret" field. +func SigningSecretNEQ(v string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldNEQ(FieldSigningSecret, v)) +} + +// SigningSecretIn applies the In predicate on the "signing_secret" field. +func SigningSecretIn(vs ...string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldIn(FieldSigningSecret, vs...)) +} + +// SigningSecretNotIn applies the NotIn predicate on the "signing_secret" field. +func SigningSecretNotIn(vs ...string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldNotIn(FieldSigningSecret, vs...)) +} + +// SigningSecretGT applies the GT predicate on the "signing_secret" field. +func SigningSecretGT(v string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldGT(FieldSigningSecret, v)) +} + +// SigningSecretGTE applies the GTE predicate on the "signing_secret" field. +func SigningSecretGTE(v string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldGTE(FieldSigningSecret, v)) +} + +// SigningSecretLT applies the LT predicate on the "signing_secret" field. +func SigningSecretLT(v string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldLT(FieldSigningSecret, v)) +} + +// SigningSecretLTE applies the LTE predicate on the "signing_secret" field. +func SigningSecretLTE(v string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldLTE(FieldSigningSecret, v)) +} + +// SigningSecretContains applies the Contains predicate on the "signing_secret" field. +func SigningSecretContains(v string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldContains(FieldSigningSecret, v)) +} + +// SigningSecretHasPrefix applies the HasPrefix predicate on the "signing_secret" field. +func SigningSecretHasPrefix(v string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldHasPrefix(FieldSigningSecret, v)) +} + +// SigningSecretHasSuffix applies the HasSuffix predicate on the "signing_secret" field. +func SigningSecretHasSuffix(v string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldHasSuffix(FieldSigningSecret, v)) +} + +// SigningSecretEqualFold applies the EqualFold predicate on the "signing_secret" field. +func SigningSecretEqualFold(v string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldEqualFold(FieldSigningSecret, v)) +} + +// SigningSecretContainsFold applies the ContainsFold predicate on the "signing_secret" field. +func SigningSecretContainsFold(v string) predicate.ModelApiKey { + return predicate.ModelApiKey(sql.FieldContainsFold(FieldSigningSecret, v)) +} + // CreatedAtEQ applies the EQ predicate on the "created_at" field. func CreatedAtEQ(v time.Time) predicate.ModelApiKey { return predicate.ModelApiKey(sql.FieldEQ(FieldCreatedAt, v)) diff --git a/backend/db/modelapikey_create.go b/backend/db/modelapikey_create.go index a22ce902..487a849d 100644 --- a/backend/db/modelapikey_create.go +++ b/backend/db/modelapikey_create.go @@ -45,12 +45,34 @@ func (_c *ModelApiKeyCreate) SetModelID(v uuid.UUID) *ModelApiKeyCreate { return _c } +// SetNillableModelID sets the "model_id" field if the given value is not nil. +func (_c *ModelApiKeyCreate) SetNillableModelID(v *uuid.UUID) *ModelApiKeyCreate { + if v != nil { + _c.SetModelID(*v) + } + return _c +} + // SetUserID sets the "user_id" field. func (_c *ModelApiKeyCreate) SetUserID(v uuid.UUID) *ModelApiKeyCreate { _c.mutation.SetUserID(v) return _c } +// SetKind sets the "kind" field. +func (_c *ModelApiKeyCreate) SetKind(v modelapikey.Kind) *ModelApiKeyCreate { + _c.mutation.SetKind(v) + return _c +} + +// SetNillableKind sets the "kind" field if the given value is not nil. +func (_c *ModelApiKeyCreate) SetNillableKind(v *modelapikey.Kind) *ModelApiKeyCreate { + if v != nil { + _c.SetKind(*v) + } + return _c +} + // SetVirtualmachineID sets the "virtualmachine_id" field. func (_c *ModelApiKeyCreate) SetVirtualmachineID(v string) *ModelApiKeyCreate { _c.mutation.SetVirtualmachineID(v) @@ -71,6 +93,20 @@ func (_c *ModelApiKeyCreate) SetAPIKey(v string) *ModelApiKeyCreate { return _c } +// SetSigningSecret sets the "signing_secret" field. +func (_c *ModelApiKeyCreate) SetSigningSecret(v string) *ModelApiKeyCreate { + _c.mutation.SetSigningSecret(v) + return _c +} + +// SetNillableSigningSecret sets the "signing_secret" field if the given value is not nil. +func (_c *ModelApiKeyCreate) SetNillableSigningSecret(v *string) *ModelApiKeyCreate { + if v != nil { + _c.SetSigningSecret(*v) + } + return _c +} + // SetCreatedAt sets the "created_at" field. func (_c *ModelApiKeyCreate) SetCreatedAt(v time.Time) *ModelApiKeyCreate { _c.mutation.SetCreatedAt(v) @@ -133,6 +169,14 @@ func (_c *ModelApiKeyCreate) ExecX(ctx context.Context) { // defaults sets the default values of the builder before save. func (_c *ModelApiKeyCreate) defaults() error { + if _, ok := _c.mutation.Kind(); !ok { + v := modelapikey.DefaultKind + _c.mutation.SetKind(v) + } + if _, ok := _c.mutation.SigningSecret(); !ok { + v := modelapikey.DefaultSigningSecret + _c.mutation.SetSigningSecret(v) + } if _, ok := _c.mutation.CreatedAt(); !ok { if modelapikey.DefaultCreatedAt == nil { return fmt.Errorf("db: uninitialized modelapikey.DefaultCreatedAt (forgotten import db/runtime?)") @@ -145,12 +189,17 @@ func (_c *ModelApiKeyCreate) defaults() error { // check runs all checks and user-defined validators on the builder. func (_c *ModelApiKeyCreate) check() error { - if _, ok := _c.mutation.ModelID(); !ok { - return &ValidationError{Name: "model_id", err: errors.New(`db: missing required field "ModelApiKey.model_id"`)} - } if _, ok := _c.mutation.UserID(); !ok { return &ValidationError{Name: "user_id", err: errors.New(`db: missing required field "ModelApiKey.user_id"`)} } + if _, ok := _c.mutation.Kind(); !ok { + return &ValidationError{Name: "kind", err: errors.New(`db: missing required field "ModelApiKey.kind"`)} + } + if v, ok := _c.mutation.Kind(); ok { + if err := modelapikey.KindValidator(v); err != nil { + return &ValidationError{Name: "kind", err: fmt.Errorf(`db: validator failed for field "ModelApiKey.kind": %w`, err)} + } + } if _, ok := _c.mutation.APIKey(); !ok { return &ValidationError{Name: "api_key", err: errors.New(`db: missing required field "ModelApiKey.api_key"`)} } @@ -159,12 +208,12 @@ func (_c *ModelApiKeyCreate) check() error { return &ValidationError{Name: "api_key", err: fmt.Errorf(`db: validator failed for field "ModelApiKey.api_key": %w`, err)} } } + if _, ok := _c.mutation.SigningSecret(); !ok { + return &ValidationError{Name: "signing_secret", err: errors.New(`db: missing required field "ModelApiKey.signing_secret"`)} + } if _, ok := _c.mutation.CreatedAt(); !ok { return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "ModelApiKey.created_at"`)} } - if len(_c.mutation.ModelIDs()) == 0 { - return &ValidationError{Name: "model", err: errors.New(`db: missing required edge "ModelApiKey.model"`)} - } return nil } @@ -209,6 +258,10 @@ func (_c *ModelApiKeyCreate) createSpec() (*ModelApiKey, *sqlgraph.CreateSpec) { _spec.SetField(modelapikey.FieldUserID, field.TypeUUID, value) _node.UserID = value } + if value, ok := _c.mutation.Kind(); ok { + _spec.SetField(modelapikey.FieldKind, field.TypeEnum, value) + _node.Kind = value + } if value, ok := _c.mutation.VirtualmachineID(); ok { _spec.SetField(modelapikey.FieldVirtualmachineID, field.TypeString, value) _node.VirtualmachineID = value @@ -217,6 +270,10 @@ func (_c *ModelApiKeyCreate) createSpec() (*ModelApiKey, *sqlgraph.CreateSpec) { _spec.SetField(modelapikey.FieldAPIKey, field.TypeString, value) _node.APIKey = value } + if value, ok := _c.mutation.SigningSecret(); ok { + _spec.SetField(modelapikey.FieldSigningSecret, field.TypeString, value) + _node.SigningSecret = value + } if value, ok := _c.mutation.CreatedAt(); ok { _spec.SetField(modelapikey.FieldCreatedAt, field.TypeTime, value) _node.CreatedAt = value @@ -320,6 +377,12 @@ func (u *ModelApiKeyUpsert) UpdateModelID() *ModelApiKeyUpsert { return u } +// ClearModelID clears the value of the "model_id" field. +func (u *ModelApiKeyUpsert) ClearModelID() *ModelApiKeyUpsert { + u.SetNull(modelapikey.FieldModelID) + return u +} + // SetUserID sets the "user_id" field. func (u *ModelApiKeyUpsert) SetUserID(v uuid.UUID) *ModelApiKeyUpsert { u.Set(modelapikey.FieldUserID, v) @@ -332,6 +395,18 @@ func (u *ModelApiKeyUpsert) UpdateUserID() *ModelApiKeyUpsert { return u } +// SetKind sets the "kind" field. +func (u *ModelApiKeyUpsert) SetKind(v modelapikey.Kind) *ModelApiKeyUpsert { + u.Set(modelapikey.FieldKind, v) + return u +} + +// UpdateKind sets the "kind" field to the value that was provided on create. +func (u *ModelApiKeyUpsert) UpdateKind() *ModelApiKeyUpsert { + u.SetExcluded(modelapikey.FieldKind) + return u +} + // SetVirtualmachineID sets the "virtualmachine_id" field. func (u *ModelApiKeyUpsert) SetVirtualmachineID(v string) *ModelApiKeyUpsert { u.Set(modelapikey.FieldVirtualmachineID, v) @@ -362,6 +437,18 @@ func (u *ModelApiKeyUpsert) UpdateAPIKey() *ModelApiKeyUpsert { return u } +// SetSigningSecret sets the "signing_secret" field. +func (u *ModelApiKeyUpsert) SetSigningSecret(v string) *ModelApiKeyUpsert { + u.Set(modelapikey.FieldSigningSecret, v) + return u +} + +// UpdateSigningSecret sets the "signing_secret" field to the value that was provided on create. +func (u *ModelApiKeyUpsert) UpdateSigningSecret() *ModelApiKeyUpsert { + u.SetExcluded(modelapikey.FieldSigningSecret) + return u +} + // SetCreatedAt sets the "created_at" field. func (u *ModelApiKeyUpsert) SetCreatedAt(v time.Time) *ModelApiKeyUpsert { u.Set(modelapikey.FieldCreatedAt, v) @@ -457,6 +544,13 @@ func (u *ModelApiKeyUpsertOne) UpdateModelID() *ModelApiKeyUpsertOne { }) } +// ClearModelID clears the value of the "model_id" field. +func (u *ModelApiKeyUpsertOne) ClearModelID() *ModelApiKeyUpsertOne { + return u.Update(func(s *ModelApiKeyUpsert) { + s.ClearModelID() + }) +} + // SetUserID sets the "user_id" field. func (u *ModelApiKeyUpsertOne) SetUserID(v uuid.UUID) *ModelApiKeyUpsertOne { return u.Update(func(s *ModelApiKeyUpsert) { @@ -471,6 +565,20 @@ func (u *ModelApiKeyUpsertOne) UpdateUserID() *ModelApiKeyUpsertOne { }) } +// SetKind sets the "kind" field. +func (u *ModelApiKeyUpsertOne) SetKind(v modelapikey.Kind) *ModelApiKeyUpsertOne { + return u.Update(func(s *ModelApiKeyUpsert) { + s.SetKind(v) + }) +} + +// UpdateKind sets the "kind" field to the value that was provided on create. +func (u *ModelApiKeyUpsertOne) UpdateKind() *ModelApiKeyUpsertOne { + return u.Update(func(s *ModelApiKeyUpsert) { + s.UpdateKind() + }) +} + // SetVirtualmachineID sets the "virtualmachine_id" field. func (u *ModelApiKeyUpsertOne) SetVirtualmachineID(v string) *ModelApiKeyUpsertOne { return u.Update(func(s *ModelApiKeyUpsert) { @@ -506,6 +614,20 @@ func (u *ModelApiKeyUpsertOne) UpdateAPIKey() *ModelApiKeyUpsertOne { }) } +// SetSigningSecret sets the "signing_secret" field. +func (u *ModelApiKeyUpsertOne) SetSigningSecret(v string) *ModelApiKeyUpsertOne { + return u.Update(func(s *ModelApiKeyUpsert) { + s.SetSigningSecret(v) + }) +} + +// UpdateSigningSecret sets the "signing_secret" field to the value that was provided on create. +func (u *ModelApiKeyUpsertOne) UpdateSigningSecret() *ModelApiKeyUpsertOne { + return u.Update(func(s *ModelApiKeyUpsert) { + s.UpdateSigningSecret() + }) +} + // SetCreatedAt sets the "created_at" field. func (u *ModelApiKeyUpsertOne) SetCreatedAt(v time.Time) *ModelApiKeyUpsertOne { return u.Update(func(s *ModelApiKeyUpsert) { @@ -770,6 +892,13 @@ func (u *ModelApiKeyUpsertBulk) UpdateModelID() *ModelApiKeyUpsertBulk { }) } +// ClearModelID clears the value of the "model_id" field. +func (u *ModelApiKeyUpsertBulk) ClearModelID() *ModelApiKeyUpsertBulk { + return u.Update(func(s *ModelApiKeyUpsert) { + s.ClearModelID() + }) +} + // SetUserID sets the "user_id" field. func (u *ModelApiKeyUpsertBulk) SetUserID(v uuid.UUID) *ModelApiKeyUpsertBulk { return u.Update(func(s *ModelApiKeyUpsert) { @@ -784,6 +913,20 @@ func (u *ModelApiKeyUpsertBulk) UpdateUserID() *ModelApiKeyUpsertBulk { }) } +// SetKind sets the "kind" field. +func (u *ModelApiKeyUpsertBulk) SetKind(v modelapikey.Kind) *ModelApiKeyUpsertBulk { + return u.Update(func(s *ModelApiKeyUpsert) { + s.SetKind(v) + }) +} + +// UpdateKind sets the "kind" field to the value that was provided on create. +func (u *ModelApiKeyUpsertBulk) UpdateKind() *ModelApiKeyUpsertBulk { + return u.Update(func(s *ModelApiKeyUpsert) { + s.UpdateKind() + }) +} + // SetVirtualmachineID sets the "virtualmachine_id" field. func (u *ModelApiKeyUpsertBulk) SetVirtualmachineID(v string) *ModelApiKeyUpsertBulk { return u.Update(func(s *ModelApiKeyUpsert) { @@ -819,6 +962,20 @@ func (u *ModelApiKeyUpsertBulk) UpdateAPIKey() *ModelApiKeyUpsertBulk { }) } +// SetSigningSecret sets the "signing_secret" field. +func (u *ModelApiKeyUpsertBulk) SetSigningSecret(v string) *ModelApiKeyUpsertBulk { + return u.Update(func(s *ModelApiKeyUpsert) { + s.SetSigningSecret(v) + }) +} + +// UpdateSigningSecret sets the "signing_secret" field to the value that was provided on create. +func (u *ModelApiKeyUpsertBulk) UpdateSigningSecret() *ModelApiKeyUpsertBulk { + return u.Update(func(s *ModelApiKeyUpsert) { + s.UpdateSigningSecret() + }) +} + // SetCreatedAt sets the "created_at" field. func (u *ModelApiKeyUpsertBulk) SetCreatedAt(v time.Time) *ModelApiKeyUpsertBulk { return u.Update(func(s *ModelApiKeyUpsert) { diff --git a/backend/db/modelapikey_update.go b/backend/db/modelapikey_update.go index f08b0772..c742b154 100644 --- a/backend/db/modelapikey_update.go +++ b/backend/db/modelapikey_update.go @@ -65,6 +65,12 @@ func (_u *ModelApiKeyUpdate) SetNillableModelID(v *uuid.UUID) *ModelApiKeyUpdate return _u } +// ClearModelID clears the value of the "model_id" field. +func (_u *ModelApiKeyUpdate) ClearModelID() *ModelApiKeyUpdate { + _u.mutation.ClearModelID() + return _u +} + // SetUserID sets the "user_id" field. func (_u *ModelApiKeyUpdate) SetUserID(v uuid.UUID) *ModelApiKeyUpdate { _u.mutation.SetUserID(v) @@ -79,6 +85,20 @@ func (_u *ModelApiKeyUpdate) SetNillableUserID(v *uuid.UUID) *ModelApiKeyUpdate return _u } +// SetKind sets the "kind" field. +func (_u *ModelApiKeyUpdate) SetKind(v modelapikey.Kind) *ModelApiKeyUpdate { + _u.mutation.SetKind(v) + return _u +} + +// SetNillableKind sets the "kind" field if the given value is not nil. +func (_u *ModelApiKeyUpdate) SetNillableKind(v *modelapikey.Kind) *ModelApiKeyUpdate { + if v != nil { + _u.SetKind(*v) + } + return _u +} + // SetVirtualmachineID sets the "virtualmachine_id" field. func (_u *ModelApiKeyUpdate) SetVirtualmachineID(v string) *ModelApiKeyUpdate { _u.mutation.SetVirtualmachineID(v) @@ -113,6 +133,20 @@ func (_u *ModelApiKeyUpdate) SetNillableAPIKey(v *string) *ModelApiKeyUpdate { return _u } +// SetSigningSecret sets the "signing_secret" field. +func (_u *ModelApiKeyUpdate) SetSigningSecret(v string) *ModelApiKeyUpdate { + _u.mutation.SetSigningSecret(v) + return _u +} + +// SetNillableSigningSecret sets the "signing_secret" field if the given value is not nil. +func (_u *ModelApiKeyUpdate) SetNillableSigningSecret(v *string) *ModelApiKeyUpdate { + if v != nil { + _u.SetSigningSecret(*v) + } + return _u +} + // SetCreatedAt sets the "created_at" field. func (_u *ModelApiKeyUpdate) SetCreatedAt(v time.Time) *ModelApiKeyUpdate { _u.mutation.SetCreatedAt(v) @@ -172,14 +206,16 @@ func (_u *ModelApiKeyUpdate) ExecX(ctx context.Context) { // check runs all checks and user-defined validators on the builder. func (_u *ModelApiKeyUpdate) check() error { + if v, ok := _u.mutation.Kind(); ok { + if err := modelapikey.KindValidator(v); err != nil { + return &ValidationError{Name: "kind", err: fmt.Errorf(`db: validator failed for field "ModelApiKey.kind": %w`, err)} + } + } if v, ok := _u.mutation.APIKey(); ok { if err := modelapikey.APIKeyValidator(v); err != nil { return &ValidationError{Name: "api_key", err: fmt.Errorf(`db: validator failed for field "ModelApiKey.api_key": %w`, err)} } } - if _u.mutation.ModelCleared() && len(_u.mutation.ModelIDs()) > 0 { - return errors.New(`db: clearing a required unique edge "ModelApiKey.model"`) - } return nil } @@ -210,6 +246,9 @@ func (_u *ModelApiKeyUpdate) sqlSave(ctx context.Context) (_node int, err error) if value, ok := _u.mutation.UserID(); ok { _spec.SetField(modelapikey.FieldUserID, field.TypeUUID, value) } + if value, ok := _u.mutation.Kind(); ok { + _spec.SetField(modelapikey.FieldKind, field.TypeEnum, value) + } if value, ok := _u.mutation.VirtualmachineID(); ok { _spec.SetField(modelapikey.FieldVirtualmachineID, field.TypeString, value) } @@ -219,6 +258,9 @@ func (_u *ModelApiKeyUpdate) sqlSave(ctx context.Context) (_node int, err error) if value, ok := _u.mutation.APIKey(); ok { _spec.SetField(modelapikey.FieldAPIKey, field.TypeString, value) } + if value, ok := _u.mutation.SigningSecret(); ok { + _spec.SetField(modelapikey.FieldSigningSecret, field.TypeString, value) + } if value, ok := _u.mutation.CreatedAt(); ok { _spec.SetField(modelapikey.FieldCreatedAt, field.TypeTime, value) } @@ -307,6 +349,12 @@ func (_u *ModelApiKeyUpdateOne) SetNillableModelID(v *uuid.UUID) *ModelApiKeyUpd return _u } +// ClearModelID clears the value of the "model_id" field. +func (_u *ModelApiKeyUpdateOne) ClearModelID() *ModelApiKeyUpdateOne { + _u.mutation.ClearModelID() + return _u +} + // SetUserID sets the "user_id" field. func (_u *ModelApiKeyUpdateOne) SetUserID(v uuid.UUID) *ModelApiKeyUpdateOne { _u.mutation.SetUserID(v) @@ -321,6 +369,20 @@ func (_u *ModelApiKeyUpdateOne) SetNillableUserID(v *uuid.UUID) *ModelApiKeyUpda return _u } +// SetKind sets the "kind" field. +func (_u *ModelApiKeyUpdateOne) SetKind(v modelapikey.Kind) *ModelApiKeyUpdateOne { + _u.mutation.SetKind(v) + return _u +} + +// SetNillableKind sets the "kind" field if the given value is not nil. +func (_u *ModelApiKeyUpdateOne) SetNillableKind(v *modelapikey.Kind) *ModelApiKeyUpdateOne { + if v != nil { + _u.SetKind(*v) + } + return _u +} + // SetVirtualmachineID sets the "virtualmachine_id" field. func (_u *ModelApiKeyUpdateOne) SetVirtualmachineID(v string) *ModelApiKeyUpdateOne { _u.mutation.SetVirtualmachineID(v) @@ -355,6 +417,20 @@ func (_u *ModelApiKeyUpdateOne) SetNillableAPIKey(v *string) *ModelApiKeyUpdateO return _u } +// SetSigningSecret sets the "signing_secret" field. +func (_u *ModelApiKeyUpdateOne) SetSigningSecret(v string) *ModelApiKeyUpdateOne { + _u.mutation.SetSigningSecret(v) + return _u +} + +// SetNillableSigningSecret sets the "signing_secret" field if the given value is not nil. +func (_u *ModelApiKeyUpdateOne) SetNillableSigningSecret(v *string) *ModelApiKeyUpdateOne { + if v != nil { + _u.SetSigningSecret(*v) + } + return _u +} + // SetCreatedAt sets the "created_at" field. func (_u *ModelApiKeyUpdateOne) SetCreatedAt(v time.Time) *ModelApiKeyUpdateOne { _u.mutation.SetCreatedAt(v) @@ -427,14 +503,16 @@ func (_u *ModelApiKeyUpdateOne) ExecX(ctx context.Context) { // check runs all checks and user-defined validators on the builder. func (_u *ModelApiKeyUpdateOne) check() error { + if v, ok := _u.mutation.Kind(); ok { + if err := modelapikey.KindValidator(v); err != nil { + return &ValidationError{Name: "kind", err: fmt.Errorf(`db: validator failed for field "ModelApiKey.kind": %w`, err)} + } + } if v, ok := _u.mutation.APIKey(); ok { if err := modelapikey.APIKeyValidator(v); err != nil { return &ValidationError{Name: "api_key", err: fmt.Errorf(`db: validator failed for field "ModelApiKey.api_key": %w`, err)} } } - if _u.mutation.ModelCleared() && len(_u.mutation.ModelIDs()) > 0 { - return errors.New(`db: clearing a required unique edge "ModelApiKey.model"`) - } return nil } @@ -482,6 +560,9 @@ func (_u *ModelApiKeyUpdateOne) sqlSave(ctx context.Context) (_node *ModelApiKey if value, ok := _u.mutation.UserID(); ok { _spec.SetField(modelapikey.FieldUserID, field.TypeUUID, value) } + if value, ok := _u.mutation.Kind(); ok { + _spec.SetField(modelapikey.FieldKind, field.TypeEnum, value) + } if value, ok := _u.mutation.VirtualmachineID(); ok { _spec.SetField(modelapikey.FieldVirtualmachineID, field.TypeString, value) } @@ -491,6 +572,9 @@ func (_u *ModelApiKeyUpdateOne) sqlSave(ctx context.Context) (_node *ModelApiKey if value, ok := _u.mutation.APIKey(); ok { _spec.SetField(modelapikey.FieldAPIKey, field.TypeString, value) } + if value, ok := _u.mutation.SigningSecret(); ok { + _spec.SetField(modelapikey.FieldSigningSecret, field.TypeString, value) + } if value, ok := _u.mutation.CreatedAt(); ok { _spec.SetField(modelapikey.FieldCreatedAt, field.TypeTime, value) } diff --git a/backend/db/mutation.go b/backend/db/mutation.go index 158e970a..3130e129 100644 --- a/backend/db/mutation.go +++ b/backend/db/mutation.go @@ -26656,8 +26656,10 @@ type ModelApiKeyMutation struct { id *uuid.UUID deleted_at *time.Time user_id *uuid.UUID + kind *modelapikey.Kind virtualmachine_id *string api_key *string + signing_secret *string created_at *time.Time clearedFields map[string]struct{} model *uuid.UUID @@ -26851,9 +26853,22 @@ func (m *ModelApiKeyMutation) OldModelID(ctx context.Context) (v uuid.UUID, err return oldValue.ModelID, nil } +// ClearModelID clears the value of the "model_id" field. +func (m *ModelApiKeyMutation) ClearModelID() { + m.model = nil + m.clearedFields[modelapikey.FieldModelID] = struct{}{} +} + +// ModelIDCleared returns if the "model_id" field was cleared in this mutation. +func (m *ModelApiKeyMutation) ModelIDCleared() bool { + _, ok := m.clearedFields[modelapikey.FieldModelID] + return ok +} + // ResetModelID resets all changes to the "model_id" field. func (m *ModelApiKeyMutation) ResetModelID() { m.model = nil + delete(m.clearedFields, modelapikey.FieldModelID) } // SetUserID sets the "user_id" field. @@ -26892,6 +26907,42 @@ func (m *ModelApiKeyMutation) ResetUserID() { m.user_id = nil } +// SetKind sets the "kind" field. +func (m *ModelApiKeyMutation) SetKind(value modelapikey.Kind) { + m.kind = &value +} + +// Kind returns the value of the "kind" field in the mutation. +func (m *ModelApiKeyMutation) Kind() (r modelapikey.Kind, exists bool) { + v := m.kind + if v == nil { + return + } + return *v, true +} + +// OldKind returns the old "kind" field's value of the ModelApiKey entity. +// If the ModelApiKey object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ModelApiKeyMutation) OldKind(ctx context.Context) (v modelapikey.Kind, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKind is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKind requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKind: %w", err) + } + return oldValue.Kind, nil +} + +// ResetKind resets all changes to the "kind" field. +func (m *ModelApiKeyMutation) ResetKind() { + m.kind = nil +} + // SetVirtualmachineID sets the "virtualmachine_id" field. func (m *ModelApiKeyMutation) SetVirtualmachineID(s string) { m.virtualmachine_id = &s @@ -26977,6 +27028,42 @@ func (m *ModelApiKeyMutation) ResetAPIKey() { m.api_key = nil } +// SetSigningSecret sets the "signing_secret" field. +func (m *ModelApiKeyMutation) SetSigningSecret(s string) { + m.signing_secret = &s +} + +// SigningSecret returns the value of the "signing_secret" field in the mutation. +func (m *ModelApiKeyMutation) SigningSecret() (r string, exists bool) { + v := m.signing_secret + if v == nil { + return + } + return *v, true +} + +// OldSigningSecret returns the old "signing_secret" field's value of the ModelApiKey entity. +// If the ModelApiKey object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ModelApiKeyMutation) OldSigningSecret(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSigningSecret is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSigningSecret requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSigningSecret: %w", err) + } + return oldValue.SigningSecret, nil +} + +// ResetSigningSecret resets all changes to the "signing_secret" field. +func (m *ModelApiKeyMutation) ResetSigningSecret() { + m.signing_secret = nil +} + // SetCreatedAt sets the "created_at" field. func (m *ModelApiKeyMutation) SetCreatedAt(t time.Time) { m.created_at = &t @@ -27021,7 +27108,7 @@ func (m *ModelApiKeyMutation) ClearModel() { // ModelCleared reports if the "model" edge to the Model entity was cleared. func (m *ModelApiKeyMutation) ModelCleared() bool { - return m.clearedmodel + return m.ModelIDCleared() || m.clearedmodel } // ModelIDs returns the "model" edge IDs in the mutation. @@ -27074,7 +27161,7 @@ func (m *ModelApiKeyMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *ModelApiKeyMutation) Fields() []string { - fields := make([]string, 0, 6) + fields := make([]string, 0, 8) if m.deleted_at != nil { fields = append(fields, modelapikey.FieldDeletedAt) } @@ -27084,12 +27171,18 @@ func (m *ModelApiKeyMutation) Fields() []string { if m.user_id != nil { fields = append(fields, modelapikey.FieldUserID) } + if m.kind != nil { + fields = append(fields, modelapikey.FieldKind) + } if m.virtualmachine_id != nil { fields = append(fields, modelapikey.FieldVirtualmachineID) } if m.api_key != nil { fields = append(fields, modelapikey.FieldAPIKey) } + if m.signing_secret != nil { + fields = append(fields, modelapikey.FieldSigningSecret) + } if m.created_at != nil { fields = append(fields, modelapikey.FieldCreatedAt) } @@ -27107,10 +27200,14 @@ func (m *ModelApiKeyMutation) Field(name string) (ent.Value, bool) { return m.ModelID() case modelapikey.FieldUserID: return m.UserID() + case modelapikey.FieldKind: + return m.Kind() case modelapikey.FieldVirtualmachineID: return m.VirtualmachineID() case modelapikey.FieldAPIKey: return m.APIKey() + case modelapikey.FieldSigningSecret: + return m.SigningSecret() case modelapikey.FieldCreatedAt: return m.CreatedAt() } @@ -27128,10 +27225,14 @@ func (m *ModelApiKeyMutation) OldField(ctx context.Context, name string) (ent.Va return m.OldModelID(ctx) case modelapikey.FieldUserID: return m.OldUserID(ctx) + case modelapikey.FieldKind: + return m.OldKind(ctx) case modelapikey.FieldVirtualmachineID: return m.OldVirtualmachineID(ctx) case modelapikey.FieldAPIKey: return m.OldAPIKey(ctx) + case modelapikey.FieldSigningSecret: + return m.OldSigningSecret(ctx) case modelapikey.FieldCreatedAt: return m.OldCreatedAt(ctx) } @@ -27164,6 +27265,13 @@ func (m *ModelApiKeyMutation) SetField(name string, value ent.Value) error { } m.SetUserID(v) return nil + case modelapikey.FieldKind: + v, ok := value.(modelapikey.Kind) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKind(v) + return nil case modelapikey.FieldVirtualmachineID: v, ok := value.(string) if !ok { @@ -27178,6 +27286,13 @@ func (m *ModelApiKeyMutation) SetField(name string, value ent.Value) error { } m.SetAPIKey(v) return nil + case modelapikey.FieldSigningSecret: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSigningSecret(v) + return nil case modelapikey.FieldCreatedAt: v, ok := value.(time.Time) if !ok { @@ -27218,6 +27333,9 @@ func (m *ModelApiKeyMutation) ClearedFields() []string { if m.FieldCleared(modelapikey.FieldDeletedAt) { fields = append(fields, modelapikey.FieldDeletedAt) } + if m.FieldCleared(modelapikey.FieldModelID) { + fields = append(fields, modelapikey.FieldModelID) + } if m.FieldCleared(modelapikey.FieldVirtualmachineID) { fields = append(fields, modelapikey.FieldVirtualmachineID) } @@ -27238,6 +27356,9 @@ func (m *ModelApiKeyMutation) ClearField(name string) error { case modelapikey.FieldDeletedAt: m.ClearDeletedAt() return nil + case modelapikey.FieldModelID: + m.ClearModelID() + return nil case modelapikey.FieldVirtualmachineID: m.ClearVirtualmachineID() return nil @@ -27258,12 +27379,18 @@ func (m *ModelApiKeyMutation) ResetField(name string) error { case modelapikey.FieldUserID: m.ResetUserID() return nil + case modelapikey.FieldKind: + m.ResetKind() + return nil case modelapikey.FieldVirtualmachineID: m.ResetVirtualmachineID() return nil case modelapikey.FieldAPIKey: m.ResetAPIKey() return nil + case modelapikey.FieldSigningSecret: + m.ResetSigningSecret() + return nil case modelapikey.FieldCreatedAt: m.ResetCreatedAt() return nil diff --git a/backend/db/runtime/runtime.go b/backend/db/runtime/runtime.go index e543561a..f84f97bc 100644 --- a/backend/db/runtime/runtime.go +++ b/backend/db/runtime/runtime.go @@ -759,11 +759,15 @@ func init() { modelapikeyFields := schema.ModelApiKey{}.Fields() _ = modelapikeyFields // modelapikeyDescAPIKey is the schema descriptor for api_key field. - modelapikeyDescAPIKey := modelapikeyFields[4].Descriptor() + modelapikeyDescAPIKey := modelapikeyFields[5].Descriptor() // modelapikey.APIKeyValidator is a validator for the "api_key" field. It is called by the builders before save. modelapikey.APIKeyValidator = modelapikeyDescAPIKey.Validators[0].(func(string) error) + // modelapikeyDescSigningSecret is the schema descriptor for signing_secret field. + modelapikeyDescSigningSecret := modelapikeyFields[6].Descriptor() + // modelapikey.DefaultSigningSecret holds the default value on creation for the signing_secret field. + modelapikey.DefaultSigningSecret = modelapikeyDescSigningSecret.Default.(string) // modelapikeyDescCreatedAt is the schema descriptor for created_at field. - modelapikeyDescCreatedAt := modelapikeyFields[5].Descriptor() + modelapikeyDescCreatedAt := modelapikeyFields[7].Descriptor() // modelapikey.DefaultCreatedAt holds the default value on creation for the created_at field. modelapikey.DefaultCreatedAt = modelapikeyDescCreatedAt.Default.(func() time.Time) modelpricingFields := schema.ModelPricing{}.Fields() diff --git a/backend/docs/swagger.json b/backend/docs/swagger.json index c39d7000..37ce9cff 100644 --- a/backend/docs/swagger.json +++ b/backend/docs/swagger.json @@ -3915,7 +3915,7 @@ ], "description": "创建目录", "consumes": [ - "application/json" + "multipart/form-data" ], "produces": [ "application/json" @@ -7389,6 +7389,107 @@ } } }, + "/api/v1/users/ohmyagent/api-keys": { + "post": { + "security": [ + { + "MonkeyCodeAIAuth": [] + } + ], + "description": "创建当前用户的模型无关 OhMyAgent 代理 Key。请求无需模型参数;使用时在 LLM 请求的 model 字段传模型配置 ID。API Key 与签名 Secret 仅在创建响应中返回。", + "produces": [ + "application/json" + ], + "tags": [ + "【用户】OhMyAgent" + ], + "summary": "创建 OhMyAgent API Key", + "responses": { + "200": { + "description": "成功", + "schema": { + "allOf": [ + { + "$ref": "#/definitions/web.Resp" + }, + { + "type": "object", + "properties": { + "data": { + "$ref": "#/definitions/domain.CreateOhMyAgentAPIKeyResp" + } + } + } + ] + } + }, + "401": { + "description": "未授权", + "schema": { + "$ref": "#/definitions/web.Resp" + } + }, + "500": { + "description": "服务器内部错误", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, + "/api/v1/users/ohmyagent/api-keys/{id}": { + "delete": { + "security": [ + { + "MonkeyCodeAIAuth": [] + } + ], + "description": "按 Key ID 删除当前用户自己的 OhMyAgent 代理 Key;不能删除 runtime Key 或其他用户的 Key。", + "produces": [ + "application/json" + ], + "tags": [ + "【用户】OhMyAgent" + ], + "summary": "删除 OhMyAgent API Key", + "parameters": [ + { + "type": "string", + "description": "创建接口返回的 Key ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "成功", + "schema": { + "$ref": "#/definitions/web.Resp" + } + }, + "400": { + "description": "请求参数错误", + "schema": { + "$ref": "#/definitions/web.Resp" + } + }, + "401": { + "description": "未授权", + "schema": { + "$ref": "#/definitions/web.Resp" + } + }, + "500": { + "description": "服务器内部错误", + "schema": { + "$ref": "#/definitions/web.Resp" + } + } + } + } + }, "/api/v1/users/oidc/callback": { "get": { "description": "处理身份源回调并创建 MonkeyCode 登录会话", @@ -9052,7 +9153,7 @@ "MonkeyCodeAIAuth": [] } ], - "description": "数据格式约定:当前仅支持文本帧透传。服务端将 Agent 的原始文本数据包装为如下结构返回给前端(对应 domain.TaskStream):\n```json\n{ \"type\": \"string\", \"data\": \"string\", \"kind\": \"string\", \"timestamp\": 0 }\n```\n独立于 stream 的长生命周期 WebSocket 连接,用于处理 call/call-response(文件浏览、diff 查看等同步请求)。\ntask 结束后连接不断开,仍可用于文件操作。\n支持同一 taskID 多 tab 并发连接。\n\n## 上行消息\n\n### Type=call, Kind=repo_file_diff — 获取文件 diff\n请求 Data:\n```json\n{\"request_id\":\"string\",\"path\":\"string\",\"unified\":true,\"context_lines\":3}\n```\n响应 Data:\n```json\n{\"request_id\":\"string\",\"path\":\"string\",\"diff\":\"string\",\"success\":true,\"error\":\"string?\"}\n```\n\n### Type=call, Kind=repo_file_list — 列出目录文件\n请求 Data:\n```json\n{\"request_id\":\"string\",\"path\":\"string\",\"glob_pattern\":\"string?\",\"include_hidden\":false}\n```\n响应 Data:\n```json\n{\"request_id\":\"string\",\"path\":\"string\",\"files\":[{\"name\":\"string\",\"path\":\"string\",\"entry_mode\":0,\"size\":0,\"modified_at\":0}],\"success\":true,\"error\":\"string?\"}\n```\n\n### Type=call, Kind=repo_read_file — 读取文件内容\n请求 Data:\n```json\n{\"request_id\":\"string\",\"path\":\"string\",\"offset\":0,\"length\":0}\n```\n响应 Data:\n```json\n{\"request_id\":\"string\",\"path\":\"string\",\"content\":\"bytes\",\"total_size\":0,\"offset\":0,\"length\":0,\"is_truncated\":false,\"success\":true,\"error\":\"string?\"}\n```\n\n### Type=call, Kind=repo_file_changes — 查询变更文件列表\n请求 Data:\n```json\n{\"request_id\":\"string\"}\n```\n响应 Data:\n```json\n{\"request_id\":\"string\",\"changes\":[{\"path\":\"string\",\"status\":\"string\",\"additions\":0,\"deletions\":0,\"old_path\":\"string?\"}],\"branch\":\"string?\",\"commit_hash\":\"string?\",\"success\":true,\"error\":\"string?\"}\n```\n\n### Type=call, Kind=port_forward_list — 获取端口转发列表\n请求 Data:\n```json\n{\"request_id\":\"string\"}\n```\n响应 Data:\n```json\n{\"request_id\":\"string\",\"ports\":[{\"port\":0,\"status\":\"string\",\"process\":\"string\",\"forward_id\":\"string?\",\"access_url\":\"string?\",\"label\":\"string?\",\"error_message\":\"string?\",\"whitelist_ips\":[\"string\"]}]}\n```\n\n### Type=call, Kind=restart — 重启任务\n请求 Data:\n```json\n{\"request_id\":\"string\",\"load_session\":true}\n```\n响应 Data:\n```json\n{\"id\":\"uuid\",\"request_id\":\"string?\",\"success\":true,\"message\":\"string\",\"session_id\":\"string\"}\n```\n\n### Type=call, Kind=switch_model — 切换运行中任务模型\n请求 Data:\n```json\n{\"request_id\":\"string\",\"model_id\":\"uuid\",\"load_session\":true}\n```\n响应 Data:\n```json\n{\"id\":\"uuid\",\"request_id\":\"string?\",\"success\":true,\"message\":\"string\",\"session_id\":\"string\",\"model\":{}}\n```\n\n### Type=sync-my-ip — 同步 Web 客户端真实 IP\n请求 Data:\n```json\n{\"client_ip\":\"string\"}\n```\n\n## 下行消息\n\n- Type=call-response: 同步请求响应(Kind 与请求一致)。失败时 Data 为:\n```json\n{\"request_id\":\"string\",\"success\":false,\"error\":\"string\"}\n```\n- Type=task-event: 任务事件(从 TaskLive 订阅转发)\n- Type=ping: 心跳(无 Data)", + "description": "数据格式约定:当前仅支持文本帧透传。服务端将 Agent 的原始文本数据包装为如下结构返回给前端(对应 domain.TaskStream):\n```json\n{ \"type\": \"string\", \"data\": \"string\", \"kind\": \"string\", \"timestamp\": 0 }\n```\n独立于 stream 的长生命周期 WebSocket 连接,用于处理 call/call-response(文件浏览、diff 查看等同步请求)。\ntask 结束后连接不断开,仍可用于文件操作。\n支持同一 taskID 多 tab 并发连接。\n\n## 上行消息\n\n### Type=call, Kind=repo_file_diff — 获取文件 diff\n请求 Data:\n```json\n{\"request_id\":\"string\",\"path\":\"string\",\"unified\":true,\"context_lines\":3}\n```\n响应 Data:\n```json\n{\"request_id\":\"string\",\"path\":\"string\",\"diff\":\"string\",\"success\":true,\"error\":\"string?\"}\n```\n\n### Type=call, Kind=repo_file_list — 列出目录文件\n请求 Data:\n```json\n{\"request_id\":\"string\",\"path\":\"string\",\"glob_pattern\":\"string?\",\"include_hidden\":false}\n```\n响应 Data:\n```json\n{\"request_id\":\"string\",\"path\":\"string\",\"files\":[{\"name\":\"string\",\"path\":\"string\",\"entry_mode\":0,\"size\":0,\"modified_at\":0}],\"success\":true,\"error\":\"string?\"}\n```\n\n### Type=call, Kind=repo_read_file — 读取文件内容\n请求 Data:\n```json\n{\"request_id\":\"string\",\"path\":\"string\",\"offset\":0,\"length\":0}\n```\n响应 Data:\n```json\n{\"request_id\":\"string\",\"path\":\"string\",\"content\":\"bytes\",\"total_size\":0,\"offset\":0,\"length\":0,\"is_truncated\":false,\"success\":true,\"error\":\"string?\"}\n```\n\n### Type=call, Kind=repo_file_changes — 查询变更文件列表\n请求 Data:\n```json\n{\"request_id\":\"string\"}\n```\n响应 Data:\n```json\n{\"request_id\":\"string\",\"changes\":[{\"path\":\"string\",\"status\":\"string\",\"additions\":0,\"deletions\":0,\"old_path\":\"string?\"}],\"branch\":\"string?\",\"commit_hash\":\"string?\",\"success\":true,\"error\":\"string?\"}\n```\n\n### Type=call, Kind=port_forward_list — 获取端口转发列表\n请求 Data:\n```json\n{\"request_id\":\"string\"}\n```\n响应 Data:\n```json\n{\"request_id\":\"string\",\"ports\":[{\"port\":0,\"status\":\"string\",\"process\":\"string\",\"forward_id\":\"string?\",\"access_url\":\"string?\",\"label\":\"string?\",\"error_message\":\"string?\",\"whitelist_ips\":[\"string\"]}]}\n```\n\n### Type=call, Kind=restart — 重启任务\n请求 Data:\n```json\n{\"request_id\":\"string\",\"load_session\":true}\n```\n响应 Data:\n```json\n{\"id\":\"uuid\",\"request_id\":\"string?\",\"success\":true,\"message\":\"string\",\"session_id\":\"string\"}\n```\n\n### Type=call, Kind=switch_model — 切换运行中任务模型\n请求 Data:\n```json\n{\"request_id\":\"string\",\"model_id\":\"uuid\",\"load_session\":true}\n```\n响应 Data:\n```json\n{\"id\":\"uuid\",\"request_id\":\"string?\",\"success\":true,\"message\":\"string\",\"session_id\":\"string\",\"model\":{}}\n```\n\n### Type=call, Kind=switch_agent_resources — 运行中更新任务 skill/plugin 列表\n请求 Data (全量声明当前所选,非增量):\n```json\n{\"request_id\":\"string\",\"skill_ids\":[\"uuid\"],\"plugin_ids\":[\"uuid\"]}\n```\n响应 Data:\n```json\n{\"request_id\":\"string\",\"success\":true,\"message\":\"string\",\"session_id\":\"string\"}\n```\n\n### Type=sync-my-ip — 同步 Web 客户端真实 IP\n请求 Data:\n```json\n{\"client_ip\":\"string\"}\n```\n\n## 下行消息\n\n- Type=call-response: 同步请求响应(Kind 与请求一致)。失败时 Data 为:\n```json\n{\"request_id\":\"string\",\"success\":false,\"error\":\"string\"}\n```\n- Type=task-event: 任务事件(从 TaskLive 订阅转发)\n- Type=ping: 心跳(无 Data)", "consumes": [ "application/json" ], @@ -9994,15 +10095,6 @@ "x-enum-comments": { "UserPlatformBaizhi": "百智云平台" }, - "x-enum-descriptions": [ - "百智云平台", - "", - "", - "", - "", - "", - "" - ], "x-enum-varnames": [ "UserPlatformBaizhi", "UserPlatformGoogle", @@ -10029,13 +10121,6 @@ "UserRoleIndividual": "个人用户", "UserRoleSubAccount": "企业子账户" }, - "x-enum-descriptions": [ - "个人用户", - "企业用户", - "企业子账户", - "MonkeyCode-AI 管理员账号,用来配置公共资源. 如公共宿主机等", - "全自动 git 任务插入的用户" - ], "x-enum-varnames": [ "UserRoleIndividual", "UserRoleEnterprise", @@ -10730,6 +10815,23 @@ } } }, + "domain.CreateOhMyAgentAPIKeyResp": { + "type": "object", + "properties": { + "api_key": { + "type": "string" + }, + "created_at": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "signing_secret": { + "type": "string" + } + } + }, "domain.CreateProjectReq": { "type": "object", "properties": { @@ -12734,11 +12836,11 @@ "description": "消息序号,来自 ClickHouse msg_seq_start", "type": "integer" }, - "turn_seq": { - "description": "轮次号,可作为 cursor 翻页;仅日志存储为 ClickHouse 时有值", + "timestamp": { "type": "integer" }, - "timestamp": { + "turn_seq": { + "description": "轮次号,可作为 cursor 翻页;仅日志存储为 ClickHouse 时有值", "type": "integer" } } @@ -14556,7 +14658,6 @@ }, "types.ConditionStatus": { "type": "integer", - "format": "int32", "enum": [ 0, 1, diff --git a/backend/domain/model.go b/backend/domain/model.go index 44aec48c..b76a1893 100644 --- a/backend/domain/model.go +++ b/backend/domain/model.go @@ -18,12 +18,16 @@ type ModelUsecase interface { Check(ctx context.Context, uid, id uuid.UUID) (*CheckModelResp, error) CheckByConfig(ctx context.Context, req *CheckByConfigReq) (*CheckModelResp, error) GetProviderModelList(ctx context.Context, req *GetProviderModelListReq) (*GetProviderModelListResp, error) + CreateOhMyAgentAPIKey(ctx context.Context, uid uuid.UUID) (*CreateOhMyAgentAPIKeyResp, error) + DeleteOhMyAgentAPIKey(ctx context.Context, uid, id uuid.UUID) error } // ModelRepo 模型配置数据仓库接口 type ModelRepo interface { Get(ctx context.Context, uid, id uuid.UUID) (*db.Model, error) CreateRuntimeAPIKey(ctx context.Context, uid, modelID uuid.UUID, vmID string) (string, error) + CreateOhMyAgentAPIKey(ctx context.Context, uid uuid.UUID) (*db.ModelApiKey, error) + DeleteOhMyAgentAPIKey(ctx context.Context, uid, id uuid.UUID) error List(ctx context.Context, uid uuid.UUID, cursor CursorReq) ([]*db.Model, *db.Cursor, error) Create(ctx context.Context, uid uuid.UUID, req *CreateModelReq) (*db.Model, error) Delete(ctx context.Context, uid, id uuid.UUID) error @@ -217,6 +221,19 @@ type CreateModelResp struct { ID uuid.UUID `json:"id"` } +// CreateOhMyAgentAPIKeyResp 是创建模型无关代理 Key 的响应。APIKey 和 SigningSecret 仅在创建时返回。 +type CreateOhMyAgentAPIKeyResp struct { + ID uuid.UUID `json:"id"` + APIKey string `json:"api_key"` + SigningSecret string `json:"signing_secret"` + CreatedAt int64 `json:"created_at"` +} + +// DeleteOhMyAgentAPIKeyReq 删除当前用户的 OhMyAgent 代理 Key。 +type DeleteOhMyAgentAPIKeyReq struct { + ID uuid.UUID `param:"id" validate:"required"` +} + // DeleteModelConfigReq 删除模型配置请求 type DeleteModelConfigReq struct { ID uuid.UUID `param:"id" validate:"required"` diff --git a/backend/ent/schema/modelapikey.go b/backend/ent/schema/modelapikey.go index c60859cf..0b227c6e 100644 --- a/backend/ent/schema/modelapikey.go +++ b/backend/ent/schema/modelapikey.go @@ -34,10 +34,12 @@ func (ModelApiKey) Mixin() []ent.Mixin { func (ModelApiKey) Fields() []ent.Field { return []ent.Field{ field.UUID("id", uuid.UUID{}).Unique(), - field.UUID("model_id", uuid.UUID{}), + field.UUID("model_id", uuid.UUID{}).Optional(), field.UUID("user_id", uuid.UUID{}), + field.Enum("kind").Values("runtime", "ohmyagent").Default("runtime"), field.String("virtualmachine_id").Optional(), field.Text("api_key").NotEmpty(), + field.Text("signing_secret").Default("").Sensitive(), field.Time("created_at").Default(time.Now), } } @@ -45,6 +47,6 @@ func (ModelApiKey) Fields() []ent.Field { // Edges of the ModelApiKey. func (ModelApiKey) Edges() []ent.Edge { return []ent.Edge{ - edge.From("model", Model.Type).Ref("apikeys").Field("model_id").Unique().Required(), + edge.From("model", Model.Type).Ref("apikeys").Field("model_id").Unique(), } } diff --git a/backend/migration/000024_add_model_api_key_kind.down.sql b/backend/migration/000024_add_model_api_key_kind.down.sql new file mode 100644 index 00000000..a25d1c91 --- /dev/null +++ b/backend/migration/000024_add_model_api_key_kind.down.sql @@ -0,0 +1,12 @@ +ALTER TABLE model_api_keys + DROP CONSTRAINT IF EXISTS model_api_keys_kind_check; + +DELETE FROM model_api_keys + WHERE kind = 'ohmyagent'; + +ALTER TABLE model_api_keys + DROP COLUMN IF EXISTS kind, + DROP COLUMN IF EXISTS signing_secret; + +ALTER TABLE model_api_keys + ALTER COLUMN model_id SET NOT NULL; diff --git a/backend/migration/000024_add_model_api_key_kind.up.sql b/backend/migration/000024_add_model_api_key_kind.up.sql new file mode 100644 index 00000000..a7eb095b --- /dev/null +++ b/backend/migration/000024_add_model_api_key_kind.up.sql @@ -0,0 +1,18 @@ +ALTER TABLE model_api_keys + ALTER COLUMN model_id DROP NOT NULL; + +ALTER TABLE model_api_keys + ADD COLUMN IF NOT EXISTS kind VARCHAR(32) NOT NULL DEFAULT 'runtime', + ADD COLUMN IF NOT EXISTS signing_secret TEXT NOT NULL DEFAULT ''; + +ALTER TABLE model_api_keys + ADD CONSTRAINT model_api_keys_kind_check + CHECK ( + (kind = 'runtime' AND model_id IS NOT NULL) + OR ( + kind = 'ohmyagent' + AND model_id IS NULL + AND signing_secret <> '' + AND (virtualmachine_id IS NULL OR virtualmachine_id = '') + ) + ); diff --git a/backend/migration/migration_test.go b/backend/migration/migration_test.go index 5eafcf89..2af60b4a 100644 --- a/backend/migration/migration_test.go +++ b/backend/migration/migration_test.go @@ -75,6 +75,26 @@ func TestTeamMCPHubMigrationAddsTeamScopeAndCalls(t *testing.T) { } } +func TestOhMyAgentAPIKeyMigrationRequiresSigningSecret(t *testing.T) { + up, err := os.ReadFile("000024_add_model_api_key_kind.up.sql") + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"signing_secret TEXT NOT NULL", "signing_secret <> ''"} { + if !strings.Contains(string(up), want) { + t.Fatalf("up migration missing %q", want) + } + } + + down, err := os.ReadFile("000024_add_model_api_key_kind.down.sql") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(down), "DROP COLUMN IF EXISTS signing_secret") { + t.Fatal("down migration does not drop signing_secret") + } +} + func TestAgentRulesExtensionSourceMigrationExists(t *testing.T) { up, err := os.ReadFile("000021_agent_rules_extension_source.up.sql") if err != nil {