From 51feaaf597f9fb1612638fa36e3b8ba85dedbebb Mon Sep 17 00:00:00 2001 From: momo-mnsjtxy <122842784+momo-mnsjtxy@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:52:08 +0800 Subject: [PATCH 1/4] Integrate 19 Zakura security fixes Harden identity, runtime isolation, connectors, outbound requests and deployment defaults. Verify the combined changes against the affected server and agent packages. --- apps/agent/internal/rpc/handler.go | 10 +- .../internal/rpc/sandbox_validation_test.go | 17 + apps/server/README.md | 5 +- .../integration/postgres_integration_test.go | 3 +- apps/server/internal/integrations/channels.go | 524 +++++++++++++++--- .../integrations/channels_security_test.go | 201 +++++++ .../internal/integrations/email_poller.go | 13 +- .../integrations/email_poller_test.go | 5 + apps/server/internal/integrations/http.go | 168 ++++-- .../integrations/integrations_test.go | 159 +++++- apps/server/internal/integrations/outbound.go | 157 ++++++ .../internal/integrations/outbound_test.go | 112 ++++ apps/server/internal/integrations/service.go | 2 +- apps/server/internal/platform/admin/routes.go | 17 +- apps/server/internal/platform/appdeps/deps.go | 3 + .../server/internal/platform/config/config.go | 75 ++- .../internal/platform/config/config_test.go | 30 +- .../internal/platform/db/models/users.gen.go | 1 + .../internal/platform/emailverify/binding.go | 33 ++ .../internal/platform/identity/account.go | 8 +- .../platform/identity/account_test.go | 113 ++++ .../platform/identity/client_ip_test.go | 38 ++ .../internal/platform/identity/enterprise.go | 10 +- apps/server/internal/platform/identity/mfa.go | 4 +- .../platform/identity/oauth_tokens.go | 9 +- .../internal/platform/identity/routes.go | 140 +++-- .../internal/platform/identity/routes_test.go | 327 ++++++++++- .../internal/platform/identity/service.go | 71 ++- .../platform/identity/social_oauth.go | 14 +- apps/server/internal/platform/identity/sso.go | 4 +- .../internal/platform/identity/webauthn.go | 4 +- .../internal/platform/migrations/migrate.go | 6 +- .../platform/migrations/migrate_test.go | 2 +- .../platform/migrations/sql/0001_platform.sql | 1 + .../sql/0030_connector_oauth_states.sql | 12 + .../server/internal/platform/server/router.go | 2 +- .../server/router_space_integrations_test.go | 2 +- .../server/internal/platform/system/routes.go | 8 +- apps/server/internal/runtime/acp_runtime.go | 4 + apps/server/internal/runtime/agent_loop.go | 4 +- .../runtime/agent_tool_runners_web.go | 154 ++++- .../runtime/agent_tool_runners_web_test.go | 89 ++- apps/server/internal/runtime/authz.go | 12 + .../skills/deliver-artifacts/SKILL.md | 4 +- apps/server/internal/runtime/codemode.go | 5 + .../internal/runtime/computer_server_http.go | 2 +- ...container_allocation_authorization_test.go | 45 ++ apps/server/internal/runtime/file_share.go | 44 +- apps/server/internal/runtime/gateway.go | 52 +- apps/server/internal/runtime/gateway_http.go | 6 +- .../internal/runtime/gateway_perf_test.go | 2 +- .../runtime/gateway_regression_test.go | 8 +- .../internal/runtime/gateway_transport.go | 2 +- apps/server/internal/runtime/http.go | 10 +- apps/server/internal/runtime/instances.go | 24 +- .../server/internal/runtime/jev_evaluation.go | 4 +- .../internal/runtime/jev_evaluation_test.go | 2 +- apps/server/internal/runtime/mcp.go | 227 ++++++-- apps/server/internal/runtime/mcp_extra.go | 18 +- .../internal/runtime/mcp_space_policy.go | 67 +++ .../server/internal/runtime/mcp_space_test.go | 7 + .../server/internal/runtime/mcp_stdio_test.go | 99 +++- .../internal/runtime/memory_embedding.go | 20 +- apps/server/internal/runtime/misc_routes.go | 184 ++++-- .../internal/runtime/model_inventory.go | 10 +- .../internal/runtime/model_inventory_test.go | 20 +- apps/server/internal/runtime/models_extra.go | 3 + apps/server/internal/runtime/network.go | 8 +- .../internal/runtime/node_installation.go | 5 +- .../internal/runtime/platform_services.go | 4 +- .../internal/runtime/provider_egress.go | 226 ++++++++ .../internal/runtime/provider_egress_test.go | 141 +++++ .../internal/runtime/public_protocols_test.go | 100 +++- apps/server/internal/runtime/runner_hub.go | 3 + ...runtime_node_install_authorization_test.go | 114 ++++ .../internal/runtime/runtime_nodes_extra.go | 71 ++- apps/server/internal/runtime/runtime_test.go | 94 +++- .../runtime_update_authorization_test.go | 48 ++ apps/server/internal/runtime/skills.go | 4 +- .../internal/runtime/space_workspace_proxy.go | 19 +- .../runtime/space_workspace_proxy_test.go | 46 ++ .../tool_approval_jev_execution_test.go | 4 +- .../runtime/tool_approval_jev_test.go | 8 +- apps/server/internal/runtime/workspace.go | 1 + .../runtime/workspace_host_terminal_test.go | 101 ++-- .../internal/runtime/workspace_proxy.go | 42 +- docker-compose.yml | 7 +- docker/nginx/proxy_locations.conf | 3 +- 88 files changed, 3890 insertions(+), 597 deletions(-) create mode 100644 apps/server/internal/integrations/channels_security_test.go create mode 100644 apps/server/internal/integrations/outbound.go create mode 100644 apps/server/internal/integrations/outbound_test.go create mode 100644 apps/server/internal/platform/emailverify/binding.go create mode 100644 apps/server/internal/platform/identity/client_ip_test.go create mode 100644 apps/server/internal/platform/migrations/sql/0030_connector_oauth_states.sql create mode 100644 apps/server/internal/runtime/container_allocation_authorization_test.go create mode 100644 apps/server/internal/runtime/provider_egress.go create mode 100644 apps/server/internal/runtime/provider_egress_test.go create mode 100644 apps/server/internal/runtime/runtime_node_install_authorization_test.go diff --git a/apps/agent/internal/rpc/handler.go b/apps/agent/internal/rpc/handler.go index f024c0b4..f9de3a31 100644 --- a/apps/agent/internal/rpc/handler.go +++ b/apps/agent/internal/rpc/handler.go @@ -525,11 +525,15 @@ func (h *Handler) hostExecKill(raw json.RawMessage) (any, error) { func (h *Handler) ptyStart(raw json.RawMessage, send func(Msg)) (any, error) { var p struct { host.ExecParams - SpaceID string `json:"spaceId"` - Cols int `json:"cols"` - Rows int `json:"rows"` + SpaceID string `json:"spaceId"` + AllowHostWorkspace bool `json:"allowHostWorkspace"` + Cols int `json:"cols"` + Rows int `json:"rows"` } _ = json.Unmarshal(raw, &p) + if p.SpaceID != "" && !p.AllowHostWorkspace { + return nil, fmt.Errorf("space-scoped host terminals are disabled; migrate the workspace to container mode") + } root := h.StorageRoot if p.SpaceID != "" { root = h.workspace(p.SpaceID) diff --git a/apps/agent/internal/rpc/sandbox_validation_test.go b/apps/agent/internal/rpc/sandbox_validation_test.go index 045ad1cc..0563e0e5 100644 --- a/apps/agent/internal/rpc/sandbox_validation_test.go +++ b/apps/agent/internal/rpc/sandbox_validation_test.go @@ -74,6 +74,23 @@ func TestSandboxRPCRejectsUnsupportedTransports(t *testing.T) { } } +func TestHostPTYRejectsSpaceScopedExecution(t *testing.T) { + t.Setenv("ZAKURA_SANDBOX_ENABLED", "") + h := New("computer", t.TempDir()) + result := sandboxCall(t, h, "host.pty.start", map[string]any{"spaceId": "space-a", "command": []string{os.Args[0]}}) + if result.Error == "" || !strings.Contains(result.Error, "container mode") { + t.Fatalf("space-scoped host terminal was not refused: %+v", result) + } + if _, err := os.Stat(h.workspace("space-a")); !os.IsNotExist(err) { + t.Fatalf("space-scoped host terminal created a workspace: %v", err) + } + h.mu.Lock() + defer h.mu.Unlock() + if len(h.ptys) != 0 { + t.Fatalf("space-scoped host terminal allocated %d streams", len(h.ptys)) + } +} + func TestSandboxRPCRequiresWorkspaceAndAvailableBackend(t *testing.T) { t.Setenv("ZAKURA_SANDBOX_ENABLED", "") t.Setenv("ZAKURA_SANDBOX_IMAGE", "") diff --git a/apps/server/README.md b/apps/server/README.md index 0683f238..17bca8f6 100644 --- a/apps/server/README.md +++ b/apps/server/README.md @@ -25,7 +25,7 @@ it with SQLite defaults (`PUBLIC_BASE_URL=http://localhost:8787`, `WEB_PUBLIC_URL=http://localhost:3001`). Equivalent manual invocation: ```sh -export ZAKURA_SECRET='replace-with-at-least-32-random-bytes' +export ZAKURA_SECRET="$(openssl rand -hex 32)" export DATABASE_URL='file:./data/zakura.db' export DATA_DIR='./data' export PUBLIC_BASE_URL='http://localhost:8787' @@ -78,7 +78,8 @@ flow, race/vet/build, and all native stdio sidecar image builds. - Set the canonical HTTPS `PUBLIC_BASE_URL` and `WEB_PUBLIC_URL` - Keep migrations enabled for a single release task, or run them once before rolling out application replicas -- Terminate TLS at a trusted proxy and preserve the original client IP headers +- Terminate TLS at a trusted proxy, set `TRUSTED_PROXY_CIDRS` to its + comma-separated CIDR allowlist, and have it overwrite `X-Real-IP` - Use `/api/livez` for liveness and `/api/health` for database readiness - Back up the database and any runtime workspace volumes together diff --git a/apps/server/integration/postgres_integration_test.go b/apps/server/integration/postgres_integration_test.go index f2f80fa6..db8656e8 100644 --- a/apps/server/integration/postgres_integration_test.go +++ b/apps/server/integration/postgres_integration_test.go @@ -55,7 +55,8 @@ func TestPostgresCoreWorkflow(t *testing.T) { NewID: func() string { seq++; return fmt.Sprintf("pg-%023d", seq) }, Secret: bytes.Repeat([]byte("p"), 32), PublicURL: cfg.PublicURL, WebURL: cfg.WebURL, Edition: cfg.Edition, MultiTenant: cfg.MultiTenant, - VerifyDomain: func(context.Context, string, string) error { return nil }, + VerifyDomain: func(context.Context, string, string) error { return nil }, + ProviderTestPrivate: true, } srv := httptest.NewServer(platformserver.Router(cfg, deps, slog.New(slog.NewTextHandler(io.Discard, nil)))) defer srv.Close() diff --git a/apps/server/internal/integrations/channels.go b/apps/server/internal/integrations/channels.go index a05a3e67..16dcffa3 100644 --- a/apps/server/internal/integrations/channels.go +++ b/apps/server/internal/integrations/channels.go @@ -2,6 +2,7 @@ package integrations import ( + "bytes" "context" "crypto/hmac" "crypto/sha256" @@ -130,6 +131,247 @@ func pendingUserKey(entry any) string { return "" } +type remoteSender struct { + UserKey string + Email string + DisplayName string +} + +func webhookObject(raw []byte) (map[string]any, error) { + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + var payload map[string]any + if e := decoder.Decode(&payload); e != nil || payload == nil { + if e == nil { + e = errors.New("JSON object required") + } + return nil, e + } + var extra any + if e := decoder.Decode(&extra); !errors.Is(e, io.EOF) { + if e == nil { + e = errors.New("multiple JSON values") + } + return nil, e + } + return payload, nil +} + +func objectValue(values map[string]any, key string) map[string]any { + value, _ := values[key].(map[string]any) + return value +} + +func firstObject(value any) map[string]any { + items, _ := value.([]any) + if len(items) == 0 { + return nil + } + item, _ := items[0].(map[string]any) + return item +} + +func identityValue(value any) string { + switch typed := value.(type) { + case string: + return strings.TrimSpace(typed) + case json.Number: + return strings.TrimSpace(typed.String()) + default: + return "" + } +} + +func senderFromObject(values map[string]any, idKeys, emailKeys, nameKeys []string) remoteSender { + if values == nil { + return remoteSender{} + } + sender := remoteSender{} + for _, key := range idKeys { + if sender.UserKey = identityValue(values[key]); sender.UserKey != "" { + break + } + } + for _, key := range emailKeys { + if sender.Email = identityValue(values[key]); sender.Email != "" { + break + } + } + for _, key := range nameKeys { + if sender.DisplayName = identityValue(values[key]); sender.DisplayName != "" { + break + } + } + if sender.UserKey == "" { + sender.UserKey = sender.Email + } + return sender +} + +func remoteWebhookSender(platform string, payload map[string]any) (remoteSender, bool) { + var sender remoteSender + switch platform { + case "zakurabot": + sender = senderFromObject(payload, []string{"senderId", "userId"}, []string{"email"}, []string{"senderName", "userName"}) + case "slack": + event := objectValue(payload, "event") + sender = senderFromObject(event, []string{"user"}, nil, nil) + if sender.UserKey == "" { + sender = senderFromObject(objectValue(payload, "user"), []string{"id"}, []string{"email"}, []string{"name", "real_name"}) + } + case "teams": + sender = senderFromObject(objectValue(payload, "from"), []string{"id", "aadObjectId"}, []string{"email"}, []string{"name"}) + case "gchat": + sender = senderFromObject(objectValue(objectValue(payload, "message"), "sender"), []string{"name"}, []string{"email"}, []string{"displayName"}) + if sender.UserKey == "" { + sender = senderFromObject(objectValue(payload, "user"), []string{"name"}, []string{"email"}, []string{"displayName"}) + } + case "discord": + sender = senderFromObject(objectValue(objectValue(payload, "member"), "user"), []string{"id"}, nil, []string{"global_name", "username"}) + if sender.UserKey == "" { + sender = senderFromObject(objectValue(payload, "author"), []string{"id"}, nil, []string{"global_name", "username"}) + } + if sender.UserKey == "" { + sender = senderFromObject(objectValue(payload, "user"), []string{"id"}, nil, []string{"global_name", "username"}) + } + case "telegram": + for _, key := range []string{"message", "edited_message", "channel_post", "edited_channel_post"} { + sender = senderFromObject(objectValue(objectValue(payload, key), "from"), []string{"id"}, nil, []string{"username", "first_name"}) + if sender.UserKey != "" { + break + } + } + if sender.UserKey == "" { + sender = senderFromObject(objectValue(objectValue(payload, "callback_query"), "from"), []string{"id"}, nil, []string{"username", "first_name"}) + } + case "github": + sender = senderFromObject(objectValue(payload, "sender"), []string{"id"}, []string{"email"}, []string{"login"}) + case "linear": + sender = senderFromObject(objectValue(payload, "actor"), []string{"id"}, []string{"email"}, []string{"name"}) + case "whatsapp": + entry := firstObject(payload["entry"]) + change := firstObject(entry["changes"]) + value := objectValue(change, "value") + message := firstObject(value["messages"]) + sender = senderFromObject(message, []string{"from"}, nil, nil) + if contact := firstObject(value["contacts"]); contact != nil { + if sender.UserKey == "" { + sender.UserKey = identityValue(contact["wa_id"]) + } + sender.DisplayName = identityValue(objectValue(contact, "profile")["name"]) + } + case "twilio": + sender = senderFromObject(payload, []string{"From", "from"}, nil, nil) + case "messenger": + entry := firstObject(payload["entry"]) + message := firstObject(entry["messaging"]) + sender = senderFromObject(objectValue(message, "sender"), []string{"id"}, nil, nil) + case "resend": + data := objectValue(payload, "data") + sender = senderFromObject(data, []string{"from"}, []string{"from"}, nil) + address := emailAddress(sender.UserKey) + sender.UserKey, sender.Email = address, address + case "webex": + data := objectValue(payload, "data") + sender = senderFromObject(data, []string{"personId"}, []string{"personEmail"}, []string{"personDisplayName"}) + case "mattermost": + sender = senderFromObject(payload, []string{"user_id", "userId"}, []string{"user_email"}, []string{"user_name", "userName"}) + case "weixin": + sender = senderFromObject(payload, []string{"from_user_id", "fromUserId", "senderId"}, nil, []string{"from_user_name", "fromUserName"}) + if sender.UserKey == "" { + sender = senderFromObject(objectValue(payload, "from"), []string{"id", "userId"}, nil, []string{"name"}) + } + } + sender.UserKey = strings.TrimSpace(sender.UserKey) + return sender, sender.UserKey != "" +} + +func remoteChannelAllowsAll(settings map[string]any) (bool, error) { + if raw, ok := settings["allowAll"]; ok { + allowAll, valid := raw.(bool) + if !valid { + return false, errors.New("invalid allowAll setting") + } + return allowAll, nil + } + return false, nil +} + +func remoteSenderAllowed(settings map[string]any, sender remoteSender) (bool, error) { + raw, ok := settings["allowedUsers"] + if !ok { + return false, nil + } + allowed, valid := raw.([]any) + if !valid { + return false, errors.New("invalid allowedUsers setting") + } + for _, value := range allowed { + key, valid := value.(string) + if !valid { + return false, errors.New("invalid allowedUsers entry") + } + if strings.EqualFold(strings.TrimSpace(key), sender.UserKey) { + return true, nil + } + } + return false, nil +} + +func addPendingSender(settings map[string]any, sender remoteSender, requestedAt string) (bool, error) { + pending := []any{} + if raw, ok := settings["pendingUsers"]; ok { + var valid bool + pending, valid = raw.([]any) + if !valid { + return false, errors.New("invalid pendingUsers setting") + } + } + for _, entry := range pending { + if strings.EqualFold(pendingUserKey(entry), sender.UserKey) { + return false, nil + } + } + entry := map[string]any{"userKey": sender.UserKey, "requestedAt": requestedAt} + if sender.Email != "" { + entry["email"] = sender.Email + } + if sender.DisplayName != "" { + entry["displayName"] = sender.DisplayName + } + settings["pendingUsers"] = append(pending, entry) + return true, nil +} + +func emailSenderValue(value any) string { + switch typed := value.(type) { + case string: + return emailAddress(typed) + case map[string]any: + if value, ok := typed["email"]; ok { + return emailAddress(identityValue(value)) + } + if value, ok := typed["address"]; ok { + return emailAddress(identityValue(value)) + } + } + return "" +} + +func emailWebhookSender(payload map[string]any) string { + data := objectValue(payload, "data") + if value, ok := data["from"]; ok { + return emailSenderValue(value) + } + if value, ok := payload["from"]; ok { + return emailSenderValue(value) + } + if value, ok := payload["sender"]; ok { + return emailSenderValue(value) + } + return "" +} + func (h *handler) listRemoteChannels(w http.ResponseWriter, r *http.Request) { tenant := principal(r).TenantID space, e := h.requestedSpace(r) @@ -450,53 +692,121 @@ func (h *handler) updateRemoteChannelAccess(w http.ResponseWriter, r *http.Reque } func (h *handler) remoteWebhook(w http.ResponseWriter, r *http.Request) { tenant, bindingID := chi.URLParam(r, "tenantId"), chi.URLParam(r, "bindingId") - var binding models.AgentChannelBinding - e := h.deps.Gorm.WithContext(r.Context()).Where("tenant_id = ? AND id = ?", tenant, bindingID).First(&binding).Error - if e != nil || !binding.Enabled || binding.AgentID == "" { - httpx.Error(w, 404, "Channel not found") - return - } raw, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 2<<20)) if e != nil { httpx.Error(w, 413, "payload too large") return } - configRaw, e := decrypt(h.deps.Secret, tenant+":"+bindingID, binding.ConfigEnc) - if e != nil { - httpx.Error(w, 401, "invalid channel configuration") - return - } - var cfg map[string]any - _ = json.Unmarshal(configRaw, &cfg) - if !verifyWebhook(binding.Platform, cfg, r.Header, raw) { - httpx.Error(w, 401, "invalid signature") - return - } external := r.Header.Get("X-Event-Id") if external == "" { sum := sha256.Sum256(raw) external = hex.EncodeToString(sum[:]) } - res := h.deps.Gorm.WithContext(r.Context()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "binding_id"}, {Name: "external_event_id"}}, DoNothing: true}).Create(&models.AgentChannelEvent{ID: strPtr(h.id()), TenantID: tenant, BindingID: bindingID, ExternalEventID: external, ReceivedAt: h.now().Format(time.RFC3339Nano)}) - if res.Error != nil { - writeErr(w, res.Error) + var duplicate, pending bool + var responseErr string + e = h.deps.Gorm.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error { + var binding models.AgentChannelBinding + if e := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("tenant_id = ? AND id = ?", tenant, bindingID).First(&binding).Error; e != nil || !binding.Enabled || binding.AgentID == "" { + responseErr = "not_found" + if e != nil && !errors.Is(e, gorm.ErrRecordNotFound) { + return e + } + return errors.New("channel not found") + } + configRaw, e := decrypt(h.deps.Secret, tenant+":"+bindingID, binding.ConfigEnc) + if e != nil { + responseErr = "configuration" + return e + } + var cfg map[string]any + if json.Unmarshal(configRaw, &cfg) != nil { + responseErr = "configuration" + return errors.New("invalid channel configuration") + } + if !verifyWebhook(binding.Platform, cfg, r.Header, raw) { + responseErr = "signature" + return errors.New("invalid signature") + } + payload, e := webhookObject(raw) + if e != nil { + responseErr = "json" + return e + } + settings := map[string]any{} + if json.Unmarshal([]byte(binding.SettingsJSON), &settings) != nil || settings == nil { + responseErr = "policy" + return errors.New("invalid channel access policy") + } + allowed, e := remoteChannelAllowsAll(settings) + if e != nil { + responseErr = "policy" + return e + } + if !allowed { + sender, ok := remoteWebhookSender(binding.Platform, payload) + if !ok { + responseErr = "sender" + return errors.New("webhook sender missing") + } + allowed, e = remoteSenderAllowed(settings, sender) + if e != nil { + responseErr = "policy" + return e + } + if !allowed { + changed, e := addPendingSender(settings, sender, h.now().Format(time.RFC3339Nano)) + if e != nil { + responseErr = "policy" + return e + } + if changed { + settingsRaw, _ := json.Marshal(settings) + if e = tx.Model(&models.AgentChannelBinding{}).Where("tenant_id = ? AND id = ?", tenant, bindingID).Updates(map[string]any{"settings_json": string(settingsRaw), "updated_at": h.now().Format(time.RFC3339Nano)}).Error; e != nil { + return e + } + } + pending = true + return nil + } + } + res := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "binding_id"}, {Name: "external_event_id"}}, DoNothing: true}).Create(&models.AgentChannelEvent{ID: strPtr(h.id()), TenantID: tenant, BindingID: bindingID, ExternalEventID: external, ReceivedAt: h.now().Format(time.RFC3339Nano)}) + if res.Error != nil { + return res.Error + } + if res.RowsAffected == 0 { + duplicate = true + return nil + } + payload["agentId"] = binding.AgentID + payloadRaw, _ := json.Marshal(payload) + event := models.ChannelEvent{ID: strPtr(h.id()), TenantID: tenant, Provider: binding.Platform, ExternalID: bindingID + ":" + external, PayloadJSON: string(payloadRaw), DeliveryStatus: "pending", Attempts: 0, CreatedAt: h.now().Format(time.RFC3339Nano)} + return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "provider"}, {Name: "external_id"}}, DoNothing: true}).Create(&event).Error + }) + if e != nil { + switch responseErr { + case "not_found": + httpx.Error(w, 404, "Channel not found") + case "configuration": + httpx.Error(w, 401, "invalid channel configuration") + case "signature": + httpx.Error(w, 401, "invalid signature") + case "json": + httpx.Error(w, 400, "invalid JSON") + case "sender": + httpx.Error(w, 400, "webhook sender missing") + case "policy": + httpx.Error(w, 400, "invalid channel access policy") + default: + writeErr(w, e) + } return } - if res.RowsAffected == 0 { + if duplicate { httpx.JSON(w, 202, map[string]any{"accepted": true, "duplicate": true}) return } - var payload map[string]any - if json.Unmarshal(raw, &payload) != nil { - httpx.Error(w, 400, "invalid JSON") - return - } - payload["agentId"] = binding.AgentID - payloadRaw, _ := json.Marshal(payload) - event := models.ChannelEvent{ID: strPtr(h.id()), TenantID: tenant, Provider: binding.Platform, ExternalID: bindingID + ":" + external, PayloadJSON: string(payloadRaw), DeliveryStatus: "pending", Attempts: 0, CreatedAt: h.now().Format(time.RFC3339Nano)} - e = h.deps.Gorm.WithContext(r.Context()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "provider"}, {Name: "external_id"}}, DoNothing: true}).Create(&event).Error - if e != nil { - writeErr(w, e) + if pending { + httpx.JSON(w, 202, map[string]any{"accepted": true, "pending": true}) return } httpx.JSON(w, 202, map[string]any{"accepted": true, "externalId": external}) @@ -599,72 +909,112 @@ func emailProductForRef(ref string) (string, bool) { } func (h *handler) emailInbound(w http.ResponseWriter, r *http.Request) { tenant, id := chi.URLParam(r, "tenantId"), chi.URLParam(r, "connectorId") - q := h.deps.Gorm.WithContext(r.Context()).Where("tenant_id = ? AND enabled = true", tenant) - if id != "" { - if product, ok := emailProductForRef(id); ok { - q = q.Where("product = ?", product) - } else { - q = q.Where("id = ?", id) - } - } - var connector models.EmailConnectorInstance - e := q.Order("created_at").First(&connector).Error - if errors.Is(e, gorm.ErrRecordNotFound) { - httpx.Error(w, 404, "Email connector not found") - return - } - if e != nil { - writeErr(w, e) - return - } - enc := connector.ConfigEnc raw, e := io.ReadAll(http.MaxBytesReader(w, r.Body, 10<<20)) if e != nil { httpx.Error(w, 413, "payload too large") return } - cfgRaw, e := decrypt(h.deps.Secret, tenant+":email:"+*connector.ID, enc) - if e != nil { - httpx.Error(w, 401, "invalid connector configuration") - return - } - var cfg map[string]any - _ = json.Unmarshal(cfgRaw, &cfg) - secret, _ := cfg["inboundSecret"].(string) - if secret == "" { - secret, _ = cfg["webhookSecret"].(string) - } - sig := strings.TrimPrefix(r.Header.Get("X-Zakura-Signature"), "sha256=") - mac := hmac.New(sha256.New, []byte(secret)) - mac.Write(raw) - if secret == "" || !hmac.Equal([]byte(sig), []byte(hex.EncodeToString(mac.Sum(nil)))) { - httpx.Error(w, 401, "invalid signature") - return - } - var payload map[string]any - if json.Unmarshal(raw, &payload) != nil { - httpx.Error(w, 400, "invalid JSON") - return - } - agent, _ := cfg["inboundAgentId"].(string) - if agent == "" { - agent, _ = cfg["agentId"].(string) - } - if agent == "" { - httpx.Error(w, 400, "email connector has no agentId") - return - } - payload["agentId"] = agent eventID := r.Header.Get("Message-Id") if eventID == "" { sum := sha256.Sum256(raw) eventID = hex.EncodeToString(sum[:]) } - eventRaw, _ := json.Marshal(payload) - event := models.ChannelEvent{ID: strPtr(h.id()), TenantID: tenant, Provider: "email", ExternalID: eventID, PayloadJSON: string(eventRaw), DeliveryStatus: "pending", Attempts: 0, CreatedAt: h.now().Format(time.RFC3339Nano)} - e = h.deps.Gorm.WithContext(r.Context()).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "provider"}, {Name: "external_id"}}, DoNothing: true}).Create(&event).Error + ignored := false + responseErr := "" + e = h.deps.Gorm.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error { + q := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("tenant_id = ? AND enabled = true", tenant) + if id != "" { + if product, ok := emailProductForRef(id); ok { + q = q.Where("product = ?", product) + } else { + q = q.Where("id = ?", id) + } + } + var connector models.EmailConnectorInstance + if e := q.Order("created_at").First(&connector).Error; e != nil { + if errors.Is(e, gorm.ErrRecordNotFound) { + responseErr = "not_found" + } + return e + } + if connector.ID == nil { + responseErr = "configuration" + return errors.New("email connector has no id") + } + cfgRaw, e := decrypt(h.deps.Secret, tenant+":email:"+*connector.ID, connector.ConfigEnc) + if e != nil { + responseErr = "configuration" + return e + } + var cfg map[string]any + if json.Unmarshal(cfgRaw, &cfg) != nil { + responseErr = "configuration" + return errors.New("invalid connector configuration") + } + secret := emailStringValue(cfg, "inboundSecret") + if secret == "" { + secret = emailStringValue(cfg, "webhookSecret") + } + sig := strings.TrimPrefix(r.Header.Get("X-Zakura-Signature"), "sha256=") + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write(raw) + if secret == "" || !hmac.Equal([]byte(sig), []byte(hex.EncodeToString(mac.Sum(nil)))) { + responseErr = "signature" + return errors.New("invalid signature") + } + payload, e := webhookObject(raw) + if e != nil { + responseErr = "json" + return e + } + if !emailBoolValue(cfg, "inboundEnabled") { + ignored = true + return nil + } + sender := emailWebhookSender(payload) + if sender == "" { + responseErr = "sender" + return errors.New("email sender missing") + } + allowlist := emailListValue(cfg["allowedEmails"]) + if len(allowlist) == 0 || !allowedSender(sender, allowlist) { + ignored = true + return nil + } + agent := emailStringValue(cfg, "inboundAgentId") + if agent == "" { + agent = emailStringValue(cfg, "agentId") + } + if agent == "" { + responseErr = "agent" + return errors.New("email connector has no agentId") + } + payload["agentId"] = agent + eventRaw, _ := json.Marshal(payload) + event := models.ChannelEvent{ID: strPtr(h.id()), TenantID: tenant, Provider: "email", ExternalID: eventID, PayloadJSON: string(eventRaw), DeliveryStatus: "pending", Attempts: 0, CreatedAt: h.now().Format(time.RFC3339Nano)} + return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "provider"}, {Name: "external_id"}}, DoNothing: true}).Create(&event).Error + }) if e != nil { - writeErr(w, e) + switch responseErr { + case "not_found": + httpx.Error(w, 404, "Email connector not found") + case "configuration": + httpx.Error(w, 401, "invalid connector configuration") + case "signature": + httpx.Error(w, 401, "invalid signature") + case "json": + httpx.Error(w, 400, "invalid JSON") + case "sender": + httpx.Error(w, 400, "email sender missing") + case "agent": + httpx.Error(w, 400, "email connector has no agentId") + default: + writeErr(w, e) + } + return + } + if ignored { + httpx.JSON(w, 202, map[string]any{"accepted": true, "ignored": true}) return } httpx.JSON(w, 202, map[string]any{"accepted": true, "externalId": eventID}) diff --git a/apps/server/internal/integrations/channels_security_test.go b/apps/server/internal/integrations/channels_security_test.go new file mode 100644 index 00000000..f7d8eeb5 --- /dev/null +++ b/apps/server/internal/integrations/channels_security_test.go @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +package integrations + +import ( + "bytes" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/Moonrend/Zakura/apps/server/internal/platform/appdeps" + "github.com/Moonrend/Zakura/apps/server/internal/platform/db/models" + "github.com/go-chi/chi/v5" +) + +func signedWebhookRequest(t *testing.T, client *http.Client, target string, body []byte, headers map[string]string) (int, map[string]any) { + t.Helper() + req, e := http.NewRequest(http.MethodPost, target, bytes.NewReader(body)) + if e != nil { + t.Fatal(e) + } + for key, value := range headers { + req.Header.Set(key, value) + } + resp, e := client.Do(req) + if e != nil { + t.Fatal(e) + } + defer resp.Body.Close() + out := map[string]any{} + _ = json.NewDecoder(resp.Body).Decode(&out) + return resp.StatusCode, out +} + +func slackWebhookSignature(secret string, body []byte) map[string]string { + timestamp := "1700000000" + mac := hmac.New(sha256.New, []byte(secret)) + _, _ = mac.Write([]byte("v0:" + timestamp + ":" + string(body))) + return map[string]string{ + "X-Slack-Request-Timestamp": timestamp, + "X-Slack-Signature": "v0=" + hex.EncodeToString(mac.Sum(nil)), + } +} + +func emailWebhookSignature(secret, messageID string, body []byte) map[string]string { + mac := hmac.New(sha256.New, []byte(secret)) + _, _ = mac.Write(body) + return map[string]string{ + "Message-Id": messageID, + "X-Zakura-Signature": "sha256=" + hex.EncodeToString(mac.Sum(nil)), + } +} + +func channelEventCount(t *testing.T, deps *appdeps.Dependencies, provider string) int { + t.Helper() + var count int + if e := deps.DB.QueryRow(`SELECT COUNT(*) FROM channel_events WHERE tenant_id='ta' AND provider=?`, provider).Scan(&count); e != nil { + t.Fatal(e) + } + return count +} + +func TestRemoteWebhookEnforcesSenderPolicyBeforeQueue(t *testing.T) { + deps, token, _ := setup(t) + router := chi.NewRouter() + RegisterRoutes(router, deps) + server := httptest.NewServer(router) + defer server.Close() + + code, out := request(t, server.Client(), http.MethodPost, server.URL+"/api/remote-channels", token, map[string]any{ + "agentId": "agent-ta", + "platform": "slack", + "label": "Slack", + "enabled": true, + "credentials": map[string]any{"signingSecret": "remote-secret"}, + "credentialsEnabled": true, + "settings": map[string]any{"allowAll": false, "allowedUsers": []string{}, "pendingUsers": []any{}}, + }) + if code != http.StatusCreated { + t.Fatalf("create remote channel: %d %#v", code, out) + } + binding := out["binding"].(map[string]any) + bindingID := binding["id"].(string) + webhookURL := server.URL + "/api/remote-channels/ta/" + bindingID + "/webhook" + + unknownBody := []byte(`{"event":{"user":"U-unknown"},"text":"untrusted"}`) + code, out = signedWebhookRequest(t, server.Client(), webhookURL, unknownBody, slackWebhookSignature("remote-secret", unknownBody)) + if code != http.StatusAccepted || out["pending"] != true { + t.Fatalf("unknown sender should be pending: %d %#v", code, out) + } + if got := channelEventCount(t, deps, "slack"); got != 0 { + t.Fatalf("unknown sender created %d executable events", got) + } + var receiptCount int + if e := deps.DB.QueryRow(`SELECT COUNT(*) FROM agent_channel_events WHERE tenant_id='ta' AND binding_id=?`, bindingID).Scan(&receiptCount); e != nil || receiptCount != 0 { + t.Fatalf("unknown sender created receipt events: count=%d err=%v", receiptCount, e) + } + var settingsJSON string + if e := deps.DB.QueryRow(`SELECT settings_json FROM agent_channel_bindings WHERE id=?`, bindingID).Scan(&settingsJSON); e != nil { + t.Fatal(e) + } + var settings map[string]any + _ = json.Unmarshal([]byte(settingsJSON), &settings) + pending := settings["pendingUsers"].([]any) + if len(pending) != 1 || pending[0].(map[string]any)["userKey"] != "U-unknown" { + t.Fatalf("unknown sender was not quarantined: %#v", settings) + } + + code, out = request(t, server.Client(), http.MethodPost, server.URL+"/api/remote-channels/"+bindingID+"/access/approve", token, map[string]any{"userKey": "U-unknown"}) + if code != http.StatusOK { + t.Fatalf("approve sender: %d %#v", code, out) + } + spoofedBody := []byte(`{"event":{"user":"U-blocked"},"user":{"id":"U-unknown"},"text":"spoofed"}`) + code, out = signedWebhookRequest(t, server.Client(), webhookURL, spoofedBody, slackWebhookSignature("remote-secret", spoofedBody)) + if code != http.StatusAccepted || out["pending"] != true || channelEventCount(t, deps, "slack") != 0 { + t.Fatalf("non-canonical sender alias bypassed policy: %d %#v", code, out) + } + + allowedBody := unknownBody + code, out = signedWebhookRequest(t, server.Client(), webhookURL, allowedBody, slackWebhookSignature("remote-secret", allowedBody)) + if code != http.StatusAccepted || out["externalId"] == "" { + t.Fatalf("approved sender was rejected: %d %#v", code, out) + } + if got := channelEventCount(t, deps, "slack"); got != 1 { + t.Fatalf("approved sender created %d events", got) + } + + if _, e := deps.DB.Exec(`UPDATE agent_channel_bindings SET settings_json=? WHERE id=?`, `{"allowAll":true,"allowedUsers":[],"pendingUsers":[]}`, bindingID); e != nil { + t.Fatal(e) + } + allowAllBody := []byte(`{"text":"allowed without sender identity"}`) + code, out = signedWebhookRequest(t, server.Client(), webhookURL, allowAllBody, slackWebhookSignature("remote-secret", allowAllBody)) + if code != http.StatusAccepted || out["externalId"] == "" || channelEventCount(t, deps, "slack") != 2 { + t.Fatalf("allowAll channel rejected a signed event: %d %#v", code, out) + } +} + +func TestEmailWebhookEnforcesInboundPolicyBeforeQueue(t *testing.T) { + deps, _, _ := setup(t) + router := chi.NewRouter() + RegisterRoutes(router, deps) + server := httptest.NewServer(router) + defer server.Close() + + storeConfig := func(config map[string]any) string { + raw, _ := json.Marshal(config) + enc, e := encrypt(deps.Secret, "ta:email:mail-1", raw) + if e != nil { + t.Fatal(e) + } + return enc + } + now := deps.Clock().Format(time.RFC3339Nano) + connector := models.EmailConnectorInstance{ + ID: strPtr("mail-1"), TenantID: "ta", Name: "Inbound", Product: "smtp", Enabled: true, + ConfigEnc: storeConfig(map[string]any{"inboundSecret": "email-secret", "inboundEnabled": false, "inboundAgentId": "agent-ta", "allowedEmails": "*"}), + CreatedAt: now, UpdatedAt: now, + } + if e := deps.Gorm.Create(&connector).Error; e != nil { + t.Fatal(e) + } + webhookURL := server.URL + "/api/email/inbound/ta/mail-1" + body := []byte(`{"from":"Alice ","text":"hello"}`) + code, out := signedWebhookRequest(t, server.Client(), webhookURL, body, emailWebhookSignature("email-secret", "disabled", body)) + if code != http.StatusAccepted || out["ignored"] != true || channelEventCount(t, deps, "email") != 0 { + t.Fatalf("disabled inbound email was queued: %d %#v", code, out) + } + + config := storeConfig(map[string]any{"inboundSecret": "email-secret", "inboundEnabled": true, "inboundAgentId": "agent-ta", "allowedEmails": "alice@example.com"}) + if e := deps.Gorm.Model(&models.EmailConnectorInstance{}).Where("id = ?", "mail-1").Update("config_enc", config).Error; e != nil { + t.Fatal(e) + } + blockedBody := []byte(`{"from":"mallory@example.net","text":"blocked"}`) + code, out = signedWebhookRequest(t, server.Client(), webhookURL, blockedBody, emailWebhookSignature("email-secret", "blocked", blockedBody)) + if code != http.StatusAccepted || out["ignored"] != true || channelEventCount(t, deps, "email") != 0 { + t.Fatalf("non-allowlisted email was queued: %d %#v", code, out) + } + aliasBody := []byte(`{"from":"alice@example.com","data":{"from":"mallory@example.net"},"text":"alias"}`) + code, out = signedWebhookRequest(t, server.Client(), webhookURL, aliasBody, emailWebhookSignature("email-secret", "alias", aliasBody)) + if code != http.StatusAccepted || out["ignored"] != true || channelEventCount(t, deps, "email") != 0 { + t.Fatalf("non-canonical email alias bypassed policy: %d %#v", code, out) + } + + code, out = signedWebhookRequest(t, server.Client(), webhookURL, body, emailWebhookSignature("email-secret", "allowed", body)) + if code != http.StatusAccepted || out["externalId"] != "allowed" { + t.Fatalf("allowlisted email was rejected: %d %#v", code, out) + } + if got := channelEventCount(t, deps, "email"); got != 1 { + t.Fatalf("allowlisted email created %d events", got) + } + + malformedBody := []byte(`{"from":"Alice , Mallory ","text":"ambiguous"}`) + code, _ = signedWebhookRequest(t, server.Client(), webhookURL, malformedBody, emailWebhookSignature("email-secret", "ambiguous", malformedBody)) + if code != http.StatusBadRequest || channelEventCount(t, deps, "email") != 1 { + t.Fatalf("ambiguous sender reached the queue: status=%d", code) + } +} diff --git a/apps/server/internal/integrations/email_poller.go b/apps/server/internal/integrations/email_poller.go index b21fe798..b26dae53 100644 --- a/apps/server/internal/integrations/email_poller.go +++ b/apps/server/internal/integrations/email_poller.go @@ -10,6 +10,7 @@ import ( "fmt" "io" "net/http" + "net/mail" "net/url" "strconv" "strings" @@ -224,16 +225,18 @@ func emailMailContent(mail bettermailMail) string { } func emailAddress(value string) string { - if i := strings.Index(value, "<"); i >= 0 { - if j := strings.Index(value[i+1:], ">"); j >= 0 { - return strings.ToLower(strings.TrimSpace(value[i+1 : i+1+j])) - } + address, e := mail.ParseAddress(strings.TrimSpace(value)) + if e != nil { + return "" } - return strings.ToLower(strings.TrimSpace(value)) + return strings.ToLower(strings.TrimSpace(address.Address)) } func allowedSender(sender string, allowlist []string) bool { address := emailAddress(sender) + if address == "" { + return false + } for _, rule := range allowlist { normalized := strings.ToLower(strings.TrimSpace(rule)) if normalized == "" { diff --git a/apps/server/internal/integrations/email_poller_test.go b/apps/server/internal/integrations/email_poller_test.go index c7885fa2..4e6648b0 100644 --- a/apps/server/internal/integrations/email_poller_test.go +++ b/apps/server/internal/integrations/email_poller_test.go @@ -51,6 +51,8 @@ func TestAllowedSenderSemantics(t *testing.T) { {"alice@example.com", "Alice@Example.com", true}, {"alice@example.com", "Bob ", true}, {"alice@example.com", "bob@example.com", false}, + {"*", "", false}, + {"*", "Alice , Mallory ", false}, } for _, tc := range cases { if got := allowedSender(tc.sender, []string{tc.rule}); got != tc.want { @@ -60,6 +62,9 @@ func TestAllowedSenderSemantics(t *testing.T) { if emailAddress("Bob ") != "bob@x.com" { t.Fatalf("emailAddress extraction failed: %q", emailAddress("Bob ")) } + if emailAddress("Bob , Mallory ") != "" { + t.Fatal("emailAddress accepted multiple sender identities") + } } func TestParseBettermailMailsShapes(t *testing.T) { diff --git a/apps/server/internal/integrations/http.go b/apps/server/internal/integrations/http.go index 6e8a6af4..a5bf5c92 100644 --- a/apps/server/internal/integrations/http.go +++ b/apps/server/internal/integrations/http.go @@ -42,7 +42,11 @@ type handler struct { } func RegisterRoutes(r chi.Router, deps *appdeps.Dependencies, lifecycle ...MCPInstanceLifecycle) { - h := &handler{deps: deps, client: &http.Client{Timeout: 60 * time.Second}} + registerRoutesWithClient(r, deps, newConnectorHTTPClient(), lifecycle...) +} + +func registerRoutesWithClient(r chi.Router, deps *appdeps.Dependencies, client *http.Client, lifecycle ...MCPInstanceLifecycle) { + h := &handler{deps: deps, client: client} if len(lifecycle) > 0 { h.lifecycle = lifecycle[0] } @@ -440,21 +444,56 @@ func (h *handler) sharedOAuth(w http.ResponseWriter, r *http.Request) { } httpx.JSON(w, 200, map[string]any{"profiles": items}) } -func (h *handler) profileConfig(ctx context.Context, tenant, key string) (map[string]any, error) { + +type connectorOAuthState struct { + ID string `gorm:"column:id;primaryKey"` + TenantID string `gorm:"column:tenant_id"` + SourceScope string `gorm:"column:source_scope"` + SourceProfileID string `gorm:"column:source_profile_id"` + DestinationScope string `gorm:"column:destination_scope"` + DestinationProfileID string `gorm:"column:destination_profile_id"` + ExpiresAt int64 `gorm:"column:expires_at"` + CreatedAt string `gorm:"column:created_at"` +} + +func (connectorOAuthState) TableName() string { return "connector_oauth_states" } + +type connectorOAuthStatePayload struct { + StateID string `json:"stateId"` + TenantID string `json:"tenantId"` + UserID string `json:"userId"` + AgentID string `json:"agentId"` + SpaceID string `json:"spaceId"` + Ref string `json:"ref"` + ProfileKey string `json:"profileKey"` + SourceScope string `json:"sourceScope"` + SourceProfileID string `json:"sourceProfileId"` + DestinationScope string `json:"destinationScope"` + DestinationProfileID string `json:"destinationProfileId"` + RedirectURI string `json:"redirectUri"` + Exp int64 `json:"exp"` +} + +func (h *handler) profileConfigRow(ctx context.Context, tenant, key string) (models.ConnectorAuthProfile, map[string]any, error) { var row models.ConnectorAuthProfile e := h.deps.Gorm.WithContext(ctx). Where("scope_key IN ? AND profile_key = ? AND enabled = true", []string{tenant, "platform"}, key). Order(clause.OrderBy{Expression: clause.Expr{SQL: "CASE WHEN scope_key = ? THEN 0 ELSE 1 END", Vars: []any{tenant}}}). First(&row).Error if e != nil { - return nil, e + return row, nil, e } raw, e := decrypt(h.deps.Secret, row.ScopeKey+":"+key, row.ConfigEnc) if e != nil { - return nil, e + return row, nil, e } var cfg map[string]any e = json.Unmarshal(raw, &cfg) + return row, cfg, e +} + +func (h *handler) profileConfig(ctx context.Context, tenant, key string) (map[string]any, error) { + _, cfg, e := h.profileConfigRow(ctx, tenant, key) return cfg, e } func (h *handler) oauthStart(w http.ResponseWriter, r *http.Request) { @@ -477,7 +516,7 @@ func (h *handler) oauthStart(w http.ResponseWriter, r *http.Request) { } b.SpaceID = space } - cfg, e := h.profileConfig(r.Context(), p.TenantID, b.ProfileKey) + row, cfg, e := h.profileConfigRow(r.Context(), p.TenantID, b.ProfileKey) if e != nil { writeErr(w, e) return @@ -488,15 +527,40 @@ func (h *handler) oauthStart(w http.ResponseWriter, r *http.Request) { httpx.Error(w, 400, "OAuth profile is incomplete") return } - statePayload, _ := json.Marshal(map[string]any{"tenantId": p.TenantID, "userId": p.UserID, "agentId": b.AgentID, "spaceId": b.SpaceID, "ref": ref, "profileKey": b.ProfileKey, "redirectUri": b.RedirectURI, "exp": h.now().Add(10 * time.Minute).Unix()}) - sig := hmac.New(sha256.New, h.deps.Secret) - sig.Write(statePayload) - state := base64.RawURLEncoding.EncodeToString(statePayload) + "." + base64.RawURLEncoding.EncodeToString(sig.Sum(nil)) u, e := url.Parse(authURL) if e != nil { writeErr(w, e) return } + if row.ID == nil || *row.ID == "" { + httpx.Error(w, 400, "profile unavailable") + return + } + now := h.now() + destinationProfileID := *row.ID + if row.ScopeKey == "platform" { + destinationProfileID = h.id() + } + sp := connectorOAuthStatePayload{ + StateID: h.id(), TenantID: p.TenantID, UserID: p.UserID, AgentID: b.AgentID, SpaceID: b.SpaceID, + Ref: ref, ProfileKey: b.ProfileKey, SourceScope: row.ScopeKey, SourceProfileID: *row.ID, + DestinationScope: p.TenantID, DestinationProfileID: destinationProfileID, RedirectURI: b.RedirectURI, + Exp: now.Add(10 * time.Minute).Unix(), + } + _ = h.deps.Gorm.WithContext(r.Context()).Where("tenant_id = ? AND expires_at < ?", p.TenantID, now.Unix()).Delete(&connectorOAuthState{}).Error + issued := connectorOAuthState{ + ID: sp.StateID, TenantID: sp.TenantID, SourceScope: sp.SourceScope, SourceProfileID: sp.SourceProfileID, + DestinationScope: sp.DestinationScope, DestinationProfileID: sp.DestinationProfileID, + ExpiresAt: sp.Exp, CreatedAt: now.Format(time.RFC3339Nano), + } + if e = h.deps.Gorm.WithContext(r.Context()).Create(&issued).Error; e != nil { + writeErr(w, e) + return + } + statePayload, _ := json.Marshal(sp) + sig := hmac.New(sha256.New, h.deps.Secret) + sig.Write(statePayload) + state := base64.RawURLEncoding.EncodeToString(statePayload) + "." + base64.RawURLEncoding.EncodeToString(sig.Sum(nil)) q := u.Query() q.Set("client_id", clientID) q.Set("response_type", "code") @@ -512,7 +576,7 @@ func (h *handler) oauthStart(w http.ResponseWriter, r *http.Request) { q.Set("scope", strings.Join(vals, " ")) } u.RawQuery = q.Encode() - httpx.JSON(w, 200, map[string]any{"authorizeUrl": u.String(), "state": state, "expiresAt": h.now().Add(10 * time.Minute)}) + httpx.JSON(w, 200, map[string]any{"authorizeUrl": u.String(), "state": state, "expiresAt": time.Unix(sp.Exp, 0).UTC()}) } func (h *handler) oauthComplete(w http.ResponseWriter, r *http.Request) { var b struct{ Code, State string } @@ -541,29 +605,44 @@ func (h *handler) oauthComplete(w http.ResponseWriter, r *http.Request) { httpx.Error(w, 400, "invalid state") return } - var sp struct { - TenantID string `json:"tenantId"` - UserID string `json:"userId"` - AgentID string `json:"agentId"` - SpaceID string `json:"spaceId"` - Ref string `json:"ref"` - ProfileKey string `json:"profileKey"` - RedirectURI string `json:"redirectUri"` - Exp int64 `json:"exp"` - } + var sp connectorOAuthStatePayload if e = json.Unmarshal(payload, &sp); e != nil { httpx.Error(w, 400, "invalid state") return } + if sp.StateID == "" || sp.TenantID == "" || sp.ProfileKey == "" || sp.SourceProfileID == "" || sp.DestinationProfileID == "" || sp.DestinationScope != sp.TenantID || (sp.SourceScope != sp.TenantID && sp.SourceScope != "platform") || (sp.SourceScope == sp.TenantID && sp.SourceProfileID != sp.DestinationProfileID) || (sp.SourceScope == "platform" && sp.SourceProfileID == sp.DestinationProfileID) { + httpx.Error(w, 400, "invalid state") + return + } if sp.Exp < h.now().Unix() { httpx.Error(w, 400, "state expired") return } - cfg, e := h.profileConfig(r.Context(), sp.TenantID, sp.ProfileKey) + consumed := h.deps.Gorm.WithContext(r.Context()). + Where("id = ? AND tenant_id = ? AND source_scope = ? AND source_profile_id = ? AND destination_scope = ? AND destination_profile_id = ? AND expires_at = ?", sp.StateID, sp.TenantID, sp.SourceScope, sp.SourceProfileID, sp.DestinationScope, sp.DestinationProfileID, sp.Exp). + Delete(&connectorOAuthState{}) + if consumed.Error != nil || consumed.RowsAffected != 1 { + httpx.Error(w, 400, "invalid or already used state") + return + } + var row models.ConnectorAuthProfile + e = h.deps.Gorm.WithContext(r.Context()). + Where("id = ? AND scope_key = ? AND profile_key = ? AND enabled = true", sp.SourceProfileID, sp.SourceScope, sp.ProfileKey). + First(&row).Error + if e != nil { + httpx.Error(w, 400, "profile unavailable") + return + } + rawConfig, e := decrypt(h.deps.Secret, row.ScopeKey+":"+row.ProfileKey, row.ConfigEnc) if e != nil { httpx.Error(w, 400, "profile unavailable") return } + var cfg map[string]any + if e = json.Unmarshal(rawConfig, &cfg); e != nil { + httpx.Error(w, 400, "profile unavailable") + return + } tokenURL, _ := cfg["tokenUrl"].(string) clientID, _ := cfg["clientId"].(string) clientSecret, _ := cfg["clientSecret"].(string) @@ -571,6 +650,11 @@ func (h *handler) oauthComplete(w http.ResponseWriter, r *http.Request) { httpx.Error(w, 400, "OAuth profile is incomplete") return } + tokenURL, e = connectorURL(tokenURL) + if e != nil { + httpx.Error(w, 400, "token exchange failed") + return + } form := url.Values{} form.Set("grant_type", "authorization_code") form.Set("code", b.Code) @@ -584,11 +668,7 @@ func (h *handler) oauthComplete(w http.ResponseWriter, r *http.Request) { } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Accept", "application/json") - client := h.deps.HTTPClient - if client == nil { - client = h.client - } - resp, e := client.Do(req) + resp, e := h.client.Do(req) if e != nil { httpx.Error(w, 400, "token exchange failed") return @@ -609,30 +689,38 @@ func (h *handler) oauthComplete(w http.ResponseWriter, r *http.Request) { httpx.Error(w, 400, msg) return } - var row models.ConnectorAuthProfile - e = h.deps.Gorm.WithContext(r.Context()). - Where("scope_key IN ? AND profile_key = ? AND enabled = true", []string{sp.TenantID, "platform"}, sp.ProfileKey). - Order(clause.OrderBy{Expression: clause.Expr{SQL: "CASE WHEN scope_key = ? THEN 0 ELSE 1 END", Vars: []any{sp.TenantID}}}). - First(&row).Error - if e != nil { - httpx.Error(w, 400, "profile unavailable") - return + if row.ScopeKey == "platform" { + delete(cfg, "accessToken") + delete(cfg, "refreshToken") } cfg["accessToken"] = accessToken if refreshToken, _ := tr["refresh_token"].(string); refreshToken != "" { cfg["refreshToken"] = refreshToken } merged, _ := json.Marshal(cfg) - enc, e := encrypt(h.deps.Secret, row.ScopeKey+":"+row.ProfileKey, merged) + enc, e := encrypt(h.deps.Secret, sp.DestinationScope+":"+row.ProfileKey, merged) if e != nil { writeErr(w, e) return } - if e = h.deps.Gorm.WithContext(r.Context()).Model(&models.ConnectorAuthProfile{}). - Where("scope_key = ? AND profile_key = ?", row.ScopeKey, row.ProfileKey). - Updates(map[string]any{"config_enc": enc, "updated_at": h.now().Format(time.RFC3339Nano)}).Error; e != nil { - writeErr(w, e) - return + now := h.now().Format(time.RFC3339Nano) + if row.ScopeKey == sp.DestinationScope { + updated := h.deps.Gorm.WithContext(r.Context()).Model(&models.ConnectorAuthProfile{}). + Where("id = ? AND scope_key = ? AND profile_key = ?", sp.DestinationProfileID, sp.DestinationScope, sp.ProfileKey). + Updates(map[string]any{"config_enc": enc, "updated_at": now}) + if updated.Error != nil || updated.RowsAffected != 1 { + httpx.Error(w, 400, "profile unavailable") + return + } + } else { + destination := models.ConnectorAuthProfile{ + ID: &sp.DestinationProfileID, ScopeKey: sp.DestinationScope, ProfileKey: sp.ProfileKey, + Label: row.Label, Kind: row.Kind, Enabled: row.Enabled, ConfigEnc: enc, CreatedAt: now, UpdatedAt: now, + } + if e = h.deps.Gorm.WithContext(r.Context()).Create(&destination).Error; e != nil { + httpx.Error(w, 400, "profile unavailable") + return + } } httpx.JSON(w, 200, map[string]any{"ok": true, "ref": sp.Ref, "profileKey": sp.ProfileKey, "agentId": sp.AgentID, "spaceId": sp.SpaceID}) } diff --git a/apps/server/internal/integrations/integrations_test.go b/apps/server/internal/integrations/integrations_test.go index fcc2aa31..57ac83a6 100644 --- a/apps/server/internal/integrations/integrations_test.go +++ b/apps/server/internal/integrations/integrations_test.go @@ -12,6 +12,7 @@ import ( "encoding/json" "fmt" "io" + "net" "net/http" "net/http/httptest" "net/url" @@ -87,6 +88,20 @@ func request(t *testing.T, c *http.Client, method, url, token string, v any) (in return resp.StatusCode, out } +const fixtureConnectorEndpoint = "http://provider.example.test" + +func fixtureConnectorClient(server *httptest.Server) *http.Client { + dialer := net.Dialer{} + return &http.Client{Transport: &http.Transport{ + DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { + if address != "provider.example.test:80" { + return nil, fmt.Errorf("unexpected fixture destination %s", address) + } + return dialer.DialContext(ctx, network, server.Listener.Addr().String()) + }, + }} +} + func TestConnectorEncryptionRetryIsolationAndWebhookIdempotency(t *testing.T) { d, tokA, tokB := setup(t) var attempts atomic.Int32 @@ -103,11 +118,11 @@ func TestConnectorEncryptionRetryIsolationAndWebhookIdempotency(t *testing.T) { })) defer provider.Close() router := chi.NewRouter() - RegisterRoutes(router, d) + registerRoutesWithClient(router, d, fixtureConnectorClient(provider)) server := httptest.NewServer(router) defer server.Close() client := server.Client() - code, out := request(t, client, "PUT", server.URL+"/api/connectors/profiles/slack-main", tokA, map[string]any{"label": "Slack", "kind": "oauth2", "config": map[string]any{"baseUrl": provider.URL, "accessToken": "secret-token", "webhookSecret": "hook-secret"}}) + code, out := request(t, client, "PUT", server.URL+"/api/connectors/profiles/slack-main", tokA, map[string]any{"label": "Slack", "kind": "oauth2", "config": map[string]any{"baseUrl": fixtureConnectorEndpoint, "accessToken": "secret-token", "webhookSecret": "hook-secret"}}) if code != 200 { t.Fatalf("profile %d %#v", code, out) } @@ -483,21 +498,30 @@ func TestPlatformProfileScopes(t *testing.T) { } } -func oauthTestState(t *testing.T, secret []byte, payload map[string]any) string { +func startConnectorOAuth(t *testing.T, client *http.Client, serverURL, token, ref, profileKey, redirectURI string) string { t.Helper() - raw, e := json.Marshal(payload) + code, out := request(t, client, "POST", serverURL+"/api/connectors/"+ref+"/oauth/start", token, map[string]any{"profileKey": profileKey, "redirectURI": redirectURI}) + if code != 200 { + t.Fatalf("start OAuth %d %#v", code, out) + } + authorizeURL, _ := out["authorizeUrl"].(string) + u, e := url.Parse(authorizeURL) if e != nil { t.Fatal(e) } - mac := hmac.New(sha256.New, secret) - mac.Write(raw) - return base64.RawURLEncoding.EncodeToString(raw) + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) + state := u.Query().Get("state") + if state == "" { + t.Fatalf("authorizeUrl missing state: %q", authorizeURL) + } + return state } func TestConnectorOAuthCompleteExchange(t *testing.T) { d, tokA, _ := setup(t) var form url.Values + var tokenCalls atomic.Int32 token := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + tokenCalls.Add(1) _ = r.ParseForm() form = r.Form w.Header().Set("Content-Type", "application/json") @@ -505,15 +529,15 @@ func TestConnectorOAuthCompleteExchange(t *testing.T) { })) defer token.Close() r := chi.NewRouter() - RegisterRoutes(r, d) + registerRoutesWithClient(r, d, fixtureConnectorClient(token)) srv := httptest.NewServer(r) defer srv.Close() client := srv.Client() - code, out := request(t, client, "PUT", srv.URL+"/api/connectors/profiles/slack-main", tokA, map[string]any{"label": "Slack", "kind": "oauth2", "config": map[string]any{"authorizationUrl": "https://slack.test/authorize", "tokenUrl": token.URL, "clientId": "cid", "clientSecret": "csecret"}}) + code, out := request(t, client, "PUT", srv.URL+"/api/connectors/profiles/slack-main", tokA, map[string]any{"label": "Slack", "kind": "oauth2", "config": map[string]any{"authorizationUrl": "https://slack.test/authorize", "tokenUrl": fixtureConnectorEndpoint, "clientId": "cid", "clientSecret": "csecret"}}) if code != 200 { t.Fatalf("profile %d %#v", code, out) } - state := oauthTestState(t, d.Secret, map[string]any{"tenantId": "ta", "userId": "user-ta", "agentId": "agent-ta", "ref": "slack", "profileKey": "slack-main", "redirectUri": "http://app.test/console/connectors/oauth/callback", "exp": d.Clock().Add(10 * time.Minute).Unix()}) + state := startConnectorOAuth(t, client, srv.URL, tokA, "slack", "slack-main", "http://app.test/console/connectors/oauth/callback") code, out = request(t, client, "POST", srv.URL+"/api/connectors/oauth/complete", "", map[string]any{"code": "abc", "state": state}) if code != 200 || out["ok"] != true { t.Fatalf("complete %d %#v", code, out) @@ -534,53 +558,146 @@ func TestConnectorOAuthCompleteExchange(t *testing.T) { if cfg["accessToken"] != "tok-123" || cfg["refreshToken"] != "ref-456" { t.Fatalf("tokens not persisted: %#v", cfg) } + code, out = request(t, client, "POST", srv.URL+"/api/connectors/oauth/complete", "", map[string]any{"code": "abc", "state": state}) + if code != 400 || out["error"] != "invalid or already used state" || tokenCalls.Load() != 1 { + t.Fatalf("replayed state reached token exchange: code=%d calls=%d %#v", code, tokenCalls.Load(), out) + } } func TestConnectorOAuthCompleteRejectsBadState(t *testing.T) { d, tokA, _ := setup(t) + now := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC) + d.Clock = func() time.Time { return now } token := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") io.WriteString(w, `{"access_token":"tok-123"}`) })) defer token.Close() r := chi.NewRouter() - RegisterRoutes(r, d) + registerRoutesWithClient(r, d, fixtureConnectorClient(token)) srv := httptest.NewServer(r) defer srv.Close() client := srv.Client() - code, out := request(t, client, "PUT", srv.URL+"/api/connectors/profiles/slack-main", tokA, map[string]any{"label": "Slack", "kind": "oauth2", "config": map[string]any{"authorizationUrl": "https://slack.test/authorize", "tokenUrl": token.URL, "clientId": "cid", "clientSecret": "csecret"}}) + code, out := request(t, client, "PUT", srv.URL+"/api/connectors/profiles/slack-main", tokA, map[string]any{"label": "Slack", "kind": "oauth2", "config": map[string]any{"authorizationUrl": "https://slack.test/authorize", "tokenUrl": fixtureConnectorEndpoint, "clientId": "cid", "clientSecret": "csecret"}}) if code != 200 { t.Fatalf("profile %d %#v", code, out) } - base := map[string]any{"tenantId": "ta", "userId": "user-ta", "agentId": "agent-ta", "ref": "slack", "profileKey": "slack-main", "redirectUri": "http://app.test/console/connectors/oauth/callback"} - base["exp"] = d.Clock().Add(10 * time.Minute).Unix() - good := oauthTestState(t, d.Secret, base) - tampered := oauthTestState(t, []byte("wrong-secret-wrong-secret-wrong"), base) + good := startConnectorOAuth(t, client, srv.URL, tokA, "slack", "slack-main", "http://app.test/console/connectors/oauth/callback") + goodParts := strings.Split(good, ".") + if len(goodParts) != 2 || goodParts[1] == "" { + t.Fatalf("invalid issued state: %q", good) + } + replacement := byte('A') + if goodParts[1][0] == replacement { + replacement = 'B' + } + tampered := goodParts[0] + "." + string(replacement) + goodParts[1][1:] code, _ = request(t, client, "POST", srv.URL+"/api/connectors/oauth/complete", "", map[string]any{"code": "abc", "state": tampered}) if code != 400 { t.Fatalf("tampered state should 400: %d", code) } - expiredPayload := map[string]any{"tenantId": "ta", "userId": "user-ta", "agentId": "agent-ta", "ref": "slack", "profileKey": "slack-main", "redirectUri": "http://app.test/console/connectors/oauth/callback", "exp": d.Clock().Add(-time.Minute).Unix()} - code, out = request(t, client, "POST", srv.URL+"/api/connectors/oauth/complete", "", map[string]any{"code": "abc", "state": oauthTestState(t, d.Secret, expiredPayload)}) + expired := startConnectorOAuth(t, client, srv.URL, tokA, "slack", "slack-main", "http://app.test/console/connectors/oauth/callback") + now = now.Add(11 * time.Minute) + code, out = request(t, client, "POST", srv.URL+"/api/connectors/oauth/complete", "", map[string]any{"code": "abc", "state": expired}) if code != 400 || out["error"] != "state expired" { t.Fatalf("expired state should 400 state expired: %d %#v", code, out) } + now = now.Add(-11 * time.Minute) code, out = request(t, client, "POST", srv.URL+"/api/connectors/oauth/complete", "", map[string]any{"code": "abc", "state": good}) if code != 200 { t.Fatalf("good state should complete: %d %#v", code, out) } - code, out = request(t, client, "PUT", srv.URL+"/api/connectors/profiles/incomplete", tokA, map[string]any{"label": "Incomplete", "kind": "oauth2", "config": map[string]any{"clientId": "cid", "clientSecret": "csecret"}}) + code, out = request(t, client, "PUT", srv.URL+"/api/connectors/profiles/incomplete", tokA, map[string]any{"label": "Incomplete", "kind": "oauth2", "config": map[string]any{"authorizationUrl": "https://slack.test/authorize", "clientId": "cid"}}) if code != 200 { t.Fatalf("incomplete profile %d %#v", code, out) } - incompletePayload := map[string]any{"tenantId": "ta", "userId": "user-ta", "agentId": "agent-ta", "ref": "slack", "profileKey": "incomplete", "redirectUri": "http://app.test/cb", "exp": d.Clock().Add(10 * time.Minute).Unix()} - code, out = request(t, client, "POST", srv.URL+"/api/connectors/oauth/complete", "", map[string]any{"code": "abc", "state": oauthTestState(t, d.Secret, incompletePayload)}) + incomplete := startConnectorOAuth(t, client, srv.URL, tokA, "slack", "incomplete", "http://app.test/cb") + code, out = request(t, client, "POST", srv.URL+"/api/connectors/oauth/complete", "", map[string]any{"code": "abc", "state": incomplete}) if code != 400 || out["error"] != "OAuth profile is incomplete" { t.Fatalf("missing tokenUrl should 400: %d %#v", code, out) } } +func TestConnectorOAuthPlatformProfileCreatesTenantGrant(t *testing.T) { + d, tokA, _ := setup(t) + var tokenCalls atomic.Int32 + token := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + tokenCalls.Add(1) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"access_token":"tenant-access"}`) + })) + defer token.Close() + r := chi.NewRouter() + registerRoutesWithClient(r, d, fixtureConnectorClient(token)) + srv := httptest.NewServer(r) + defer srv.Close() + client := srv.Client() + admin := platformAdminSession(t, d, "ta") + code, out := request(t, client, "PUT", srv.URL+"/api/connectors/profiles/slack?scope=platform", admin, map[string]any{ + "label": "Shared Slack", "kind": "oauth2", "enabled": true, + "config": map[string]any{"authorizationUrl": "https://slack.test/authorize", "tokenUrl": fixtureConnectorEndpoint, "clientId": "shared-client", "clientSecret": "shared-secret", "accessToken": "platform-access", "refreshToken": "platform-refresh"}, + }) + if code != 200 { + t.Fatalf("platform profile %d %#v", code, out) + } + state := startConnectorOAuth(t, client, srv.URL, tokA, "slack", "slack", "http://app.test/callback") + parts := strings.Split(state, ".") + if len(parts) != 2 { + t.Fatalf("invalid issued state: %q", state) + } + payload, e := base64.RawURLEncoding.DecodeString(parts[0]) + if e != nil { + t.Fatal(e) + } + var issued connectorOAuthStatePayload + if e = json.Unmarshal(payload, &issued); e != nil { + t.Fatal(e) + } + if issued.SourceScope != "platform" || issued.DestinationScope != "ta" || issued.SourceProfileID == issued.DestinationProfileID { + t.Fatalf("state did not pin isolated destination: %#v", issued) + } + var pending int + if e = d.DB.QueryRow(`SELECT COUNT(*) FROM connector_oauth_states WHERE id=? AND tenant_id='ta' AND source_scope='platform' AND destination_scope='ta'`, issued.StateID).Scan(&pending); e != nil || pending != 1 { + t.Fatalf("single-use state not issued: count=%d err=%v", pending, e) + } + code, out = request(t, client, "POST", srv.URL+"/api/connectors/oauth/complete", "", map[string]any{"code": "abc", "state": state}) + if code != 200 || out["ok"] != true { + t.Fatalf("complete platform template %d %#v", code, out) + } + var platformEnc, tenantEnc string + if e = d.DB.QueryRow(`SELECT config_enc FROM connector_auth_profiles WHERE scope_key='platform' AND profile_key='slack'`).Scan(&platformEnc); e != nil { + t.Fatal(e) + } + if e = d.DB.QueryRow(`SELECT config_enc FROM connector_auth_profiles WHERE id=? AND scope_key='ta' AND profile_key='slack'`, issued.DestinationProfileID).Scan(&tenantEnc); e != nil { + t.Fatal(e) + } + platformRaw, e := decrypt(d.Secret, "platform:slack", platformEnc) + if e != nil { + t.Fatal(e) + } + tenantRaw, e := decrypt(d.Secret, "ta:slack", tenantEnc) + if e != nil { + t.Fatal(e) + } + var platformConfig, tenantConfig map[string]any + _ = json.Unmarshal(platformRaw, &platformConfig) + _ = json.Unmarshal(tenantRaw, &tenantConfig) + if platformConfig["accessToken"] != "platform-access" || platformConfig["refreshToken"] != "platform-refresh" { + t.Fatalf("platform grant changed: %#v", platformConfig) + } + if tenantConfig["accessToken"] != "tenant-access" || tenantConfig["refreshToken"] != nil || tenantConfig["clientId"] != "shared-client" { + t.Fatalf("tenant grant not isolated from shared client config: %#v", tenantConfig) + } + if e = d.DB.QueryRow(`SELECT COUNT(*) FROM connector_oauth_states WHERE id=?`, issued.StateID).Scan(&pending); e != nil || pending != 0 { + t.Fatalf("OAuth state not consumed: count=%d err=%v", pending, e) + } + code, out = request(t, client, "POST", srv.URL+"/api/connectors/oauth/complete", "", map[string]any{"code": "abc", "state": state}) + if code != 400 || tokenCalls.Load() != 1 { + t.Fatalf("platform state replay reached exchange: code=%d calls=%d %#v", code, tokenCalls.Load(), out) + } +} + func TestPlatformCustomProfileHasNoRefs(t *testing.T) { d, _, _ := setup(t) r := chi.NewRouter() diff --git a/apps/server/internal/integrations/outbound.go b/apps/server/internal/integrations/outbound.go new file mode 100644 index 00000000..3a6ab98f --- /dev/null +++ b/apps/server/internal/integrations/outbound.go @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +package integrations + +import ( + "context" + "errors" + "fmt" + "net" + "net/http" + "net/netip" + "net/url" + "strings" + "time" +) + +type resolveIPsFunc func(context.Context, string) ([]net.IP, error) +type dialContextFunc func(context.Context, string, string) (net.Conn, error) + +var wellKnownNAT64Prefix = netip.MustParsePrefix("64:ff9b::/96") + +var nonPublicIPPrefixes = []netip.Prefix{ + netip.MustParsePrefix("0.0.0.0/8"), + netip.MustParsePrefix("10.0.0.0/8"), + netip.MustParsePrefix("100.64.0.0/10"), + netip.MustParsePrefix("127.0.0.0/8"), + netip.MustParsePrefix("169.254.0.0/16"), + netip.MustParsePrefix("172.16.0.0/12"), + netip.MustParsePrefix("192.0.0.0/24"), + netip.MustParsePrefix("192.0.2.0/24"), + netip.MustParsePrefix("192.88.99.0/24"), + netip.MustParsePrefix("192.168.0.0/16"), + netip.MustParsePrefix("198.18.0.0/15"), + netip.MustParsePrefix("198.51.100.0/24"), + netip.MustParsePrefix("203.0.113.0/24"), + netip.MustParsePrefix("240.0.0.0/4"), + netip.MustParsePrefix("::/96"), + netip.MustParsePrefix("::ffff:0:0:0/96"), + netip.MustParsePrefix("64:ff9b:1::/48"), + netip.MustParsePrefix("100::/64"), + netip.MustParsePrefix("2001::/32"), + netip.MustParsePrefix("2001:2::/48"), + netip.MustParsePrefix("2001:10::/28"), + netip.MustParsePrefix("2001:20::/28"), + netip.MustParsePrefix("2001:db8::/32"), + netip.MustParsePrefix("2002::/16"), + netip.MustParsePrefix("3fff::/20"), + netip.MustParsePrefix("5f00::/16"), + netip.MustParsePrefix("fc00::/7"), + netip.MustParsePrefix("fe80::/10"), + netip.MustParsePrefix("fec0::/10"), +} + +func isPublicIP(ip net.IP) bool { + addr, ok := netip.AddrFromSlice(ip) + if !ok { + return false + } + addr = addr.Unmap() + if wellKnownNAT64Prefix.Contains(addr) { + bytes := addr.As16() + return isPublicIP(net.IPv4(bytes[12], bytes[13], bytes[14], bytes[15])) + } + if !addr.IsGlobalUnicast() || addr.IsPrivate() { + return false + } + for _, prefix := range nonPublicIPPrefixes { + if prefix.Contains(addr) { + return false + } + } + return true +} + +func connectorURL(raw string) (string, error) { + target, err := safeURL(raw) + if err != nil { + return "", err + } + u, _ := url.Parse(target) + host := strings.Trim(u.Hostname(), "[]") + if strings.Contains(host, "%") { + return "", errors.New("unsafe endpoint") + } + if ip := net.ParseIP(host); ip != nil && !isPublicIP(ip) { + return "", errors.New("unsafe endpoint") + } + return target, nil +} + +func lookupConnectorIPs(ctx context.Context, host string) ([]net.IP, error) { + if ip := net.ParseIP(host); ip != nil { + return []net.IP{ip}, nil + } + addresses, err := net.DefaultResolver.LookupIPAddr(ctx, host) + if err != nil { + return nil, err + } + ips := make([]net.IP, 0, len(addresses)) + for _, address := range addresses { + ips = append(ips, address.IP) + } + return ips, nil +} + +func resolvePublicIPs(ctx context.Context, resolve resolveIPsFunc, host string) ([]net.IP, error) { + if host == "" || resolve == nil { + return nil, errors.New("unsafe endpoint") + } + ips, err := resolve(ctx, host) + if err != nil || len(ips) == 0 { + return nil, errors.New("endpoint could not be resolved") + } + for _, ip := range ips { + if !isPublicIP(ip) { + return nil, errors.New("unsafe endpoint") + } + } + return ips, nil +} + +func publicDialContext(resolve resolveIPsFunc, dial dialContextFunc) dialContextFunc { + return func(ctx context.Context, network, address string) (net.Conn, error) { + host, port, err := net.SplitHostPort(address) + if err != nil { + return nil, errors.New("invalid endpoint address") + } + ips, err := resolvePublicIPs(ctx, resolve, host) + if err != nil { + return nil, err + } + var lastErr error + for _, ip := range ips { + conn, dialErr := dial(ctx, network, net.JoinHostPort(ip.String(), port)) + if dialErr == nil { + return conn, nil + } + lastErr = dialErr + } + return nil, fmt.Errorf("endpoint connection failed: %w", lastErr) + } +} + +func newConnectorHTTPClient() *http.Client { + dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second} + transport := http.DefaultTransport.(*http.Transport).Clone() + // A proxy would resolve the target itself and bypass the validated, pinned destination. + transport.Proxy = nil + transport.DialContext = publicDialContext(lookupConnectorIPs, dialer.DialContext) + transport.DialTLSContext = nil + return &http.Client{ + Transport: transport, + Timeout: 60 * time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + } +} diff --git a/apps/server/internal/integrations/outbound_test.go b/apps/server/internal/integrations/outbound_test.go new file mode 100644 index 00000000..d7bd4155 --- /dev/null +++ b/apps/server/internal/integrations/outbound_test.go @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +package integrations + +import ( + "context" + "errors" + "net" + "net/http" + "testing" +) + +func TestConnectorPublicIPPolicy(t *testing.T) { + tests := []struct { + address string + public bool + }{ + {"8.8.8.8", true}, + {"2606:4700:4700::1111", true}, + {"64:ff9b::808:808", true}, + {"127.0.0.1", false}, + {"10.0.0.1", false}, + {"100.64.0.1", false}, + {"169.254.169.254", false}, + {"192.0.2.1", false}, + {"::1", false}, + {"::ffff:127.0.0.1", false}, + {"64:ff9b::7f00:1", false}, + {"fc00::1", false}, + {"fe80::1", false}, + } + for _, test := range tests { + if got := isPublicIP(net.ParseIP(test.address)); got != test.public { + t.Errorf("isPublicIP(%q) = %v, want %v", test.address, got, test.public) + } + } +} + +func TestConnectorDialRejectsMixedDNSBeforeConnecting(t *testing.T) { + dialed := false + dial := publicDialContext( + func(context.Context, string) ([]net.IP, error) { + return []net.IP{net.ParseIP("8.8.8.8"), net.ParseIP("10.0.0.1")}, nil + }, + func(context.Context, string, string) (net.Conn, error) { + dialed = true + return nil, errors.New("unexpected dial") + }, + ) + if _, err := dial(context.Background(), "tcp", "provider.example:443"); err == nil { + t.Fatal("mixed public and private DNS results must be rejected") + } + if dialed { + t.Fatal("dial must not run when any DNS result is non-public") + } +} + +func TestConnectorDialPinsResolvedPublicAddress(t *testing.T) { + stop := errors.New("stop after observing address") + gotAddress := "" + dial := publicDialContext( + func(_ context.Context, host string) ([]net.IP, error) { + if host != "provider.example" { + t.Fatalf("resolved host = %q", host) + } + return []net.IP{net.ParseIP("8.8.8.8")}, nil + }, + func(_ context.Context, network, address string) (net.Conn, error) { + if network != "tcp" { + t.Fatalf("network = %q", network) + } + gotAddress = address + return nil, stop + }, + ) + if _, err := dial(context.Background(), "tcp", "provider.example:443"); !errors.Is(err, stop) { + t.Fatalf("dial error = %v", err) + } + if gotAddress != "8.8.8.8:443" { + t.Fatalf("dial address = %q", gotAddress) + } +} + +func TestConnectorClientDisablesRedirectsAndProxy(t *testing.T) { + client := newConnectorHTTPClient() + req, _ := http.NewRequest(http.MethodGet, "https://provider.example/next", nil) + if err := client.CheckRedirect(req, nil); !errors.Is(err, http.ErrUseLastResponse) { + t.Fatalf("redirect policy = %v", err) + } + transport := client.Transport.(*http.Transport) + if transport.Proxy != nil || transport.DialContext == nil || transport.DialTLSContext != nil { + t.Fatal("connector transport must use only its pinned direct dialer") + } +} + +func TestConnectorURLRejectsNonPublicLiterals(t *testing.T) { + for _, raw := range []string{ + "http://127.0.0.1/service", + "http://10.0.0.1/service", + "http://[::ffff:127.0.0.1]/service", + "http://[fe80::1%25eth0]/service", + } { + if _, err := connectorURL(raw); err == nil { + t.Errorf("connectorURL(%q) accepted a non-public literal", raw) + } + } + if got, err := connectorURL("https://provider.example/api"); err != nil || got != "https://provider.example/api" { + t.Fatalf("public provider URL rejected: got %q err %v", got, err) + } + if got, err := connectorURL("http://provider.example/api"); err != nil || got != "http://provider.example/api" { + t.Fatalf("public HTTP provider URL rejected: got %q err %v", got, err) + } +} diff --git a/apps/server/internal/integrations/service.go b/apps/server/internal/integrations/service.go index ad3cfeca..a9a2b659 100644 --- a/apps/server/internal/integrations/service.go +++ b/apps/server/internal/integrations/service.go @@ -168,7 +168,7 @@ func (h *handler) callProvider(ctx context.Context, tenant, agent, ref, action s if pathValue == "" { pathValue = "/" + strings.TrimPrefix(action, "/") } - target, e := safeURL(strings.TrimRight(base, "/") + "/" + strings.TrimLeft(pathValue, "/")) + target, e := connectorURL(strings.TrimRight(base, "/") + "/" + strings.TrimLeft(pathValue, "/")) if e != nil { return 0, nil, e } diff --git a/apps/server/internal/platform/admin/routes.go b/apps/server/internal/platform/admin/routes.go index b4bee335..96291971 100644 --- a/apps/server/internal/platform/admin/routes.go +++ b/apps/server/internal/platform/admin/routes.go @@ -13,6 +13,7 @@ import ( "github.com/go-chi/chi/v5" "golang.org/x/crypto/bcrypt" + "gorm.io/gorm" "github.com/Moonrend/Zakura/apps/server/internal/platform/agentconfig" "github.com/Moonrend/Zakura/apps/server/internal/platform/appdeps" @@ -357,7 +358,21 @@ func (a *routes) patchUser(w http.ResponseWriter, r *http.Request) { password = string(hash) passwordChanged = true } - err := a.d.Gorm.WithContext(r.Context()).Model(&models.User{}).Where("id=?", id).Updates(map[string]any{"name": nullIfBlank(name), "email": email, "password_hash": password, "is_platform_admin": admin, "can_use_local_runner": runner, "updated_at": a.now()}).Error + now := a.now() + emailChanged := email != current.Email + updates := map[string]any{"name": nullIfBlank(name), "email": email, "password_hash": password, "is_platform_admin": admin, "can_use_local_runner": runner, "updated_at": now} + if emailChanged { + updates["email_version"] = gorm.Expr("email_version + 1") + } + err := a.d.Gorm.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error { + if err := tx.Model(&models.User{}).Where("id=?", id).Updates(updates).Error; err != nil { + return err + } + if emailChanged { + return tx.Model(&models.AuthToken{}).Where("user_id=? AND kind='email_verify' AND consumed_at IS NULL", id).Update("consumed_at", now).Error + } + return nil + }) if err != nil { httpx.Error(w, 409, "update conflict") return diff --git a/apps/server/internal/platform/appdeps/deps.go b/apps/server/internal/platform/appdeps/deps.go index 528eaf82..78429fce 100644 --- a/apps/server/internal/platform/appdeps/deps.go +++ b/apps/server/internal/platform/appdeps/deps.go @@ -7,6 +7,7 @@ import ( "errors" "net" "net/http" + "net/netip" "strings" "time" @@ -47,6 +48,8 @@ type Dependencies struct { SendTransactionalEmail func(context.Context, string, string, string, string) error RecordUsage func(context.Context, UsageRecord) error Redis RedisCache + ProviderTestPrivate bool // Loopback provider fixtures only; production leaves this false. + TrustedProxyCIDRs []netip.Prefix } type UsageRecord struct { diff --git a/apps/server/internal/platform/config/config.go b/apps/server/internal/platform/config/config.go index d2a4ef7a..2aa4b5ab 100644 --- a/apps/server/internal/platform/config/config.go +++ b/apps/server/internal/platform/config/config.go @@ -2,6 +2,7 @@ package config import ( "errors" + "net/netip" "net/url" "os" "strconv" @@ -9,18 +10,24 @@ import ( "time" ) +const ( + publishedComposeSecret = "zakura-local-dev-secret-change-me-0123456789abcdef" + publishedReadmeSecret = "replace-with-at-least-32-random-bytes" +) + type Config struct { - ListenAddr string - DatabaseURL string - DataDir string - Secret string - PublicURL string - WebURL string - Edition string - MultiTenant bool - AutoMigrate bool - ReadTimeout time.Duration - WriteTimeout time.Duration + ListenAddr string + DatabaseURL string + DataDir string + Secret string + PublicURL string + WebURL string + Edition string + MultiTenant bool + AutoMigrate bool + ReadTimeout time.Duration + WriteTimeout time.Duration + TrustedProxyCIDRs []netip.Prefix } func Load() (Config, error) { @@ -40,22 +47,31 @@ func Load() (Config, error) { if err != nil { return Config{}, err } + trustedProxyCIDRs, err := prefixListEnv("TRUSTED_PROXY_CIDRS") + if err != nil { + return Config{}, err + } c := Config{ - ListenAddr: env("LISTEN_ADDR", ":8787"), - DatabaseURL: env("DATABASE_URL", "file:./data/zakura.db"), - DataDir: env("DATA_DIR", ""), - Secret: os.Getenv("ZAKURA_SECRET"), - PublicURL: strings.TrimRight(env("PUBLIC_BASE_URL", "http://localhost:8787"), "/"), - WebURL: strings.TrimRight(env("WEB_PUBLIC_URL", "http://localhost:3000"), "/"), - Edition: env("ZAKURA_EDITION", "oss"), - MultiTenant: multiTenant, - AutoMigrate: autoMigrate, - ReadTimeout: readTimeout, - WriteTimeout: writeTimeout, + ListenAddr: env("LISTEN_ADDR", ":8787"), + DatabaseURL: env("DATABASE_URL", "file:./data/zakura.db"), + DataDir: env("DATA_DIR", ""), + Secret: os.Getenv("ZAKURA_SECRET"), + PublicURL: strings.TrimRight(env("PUBLIC_BASE_URL", "http://localhost:8787"), "/"), + WebURL: strings.TrimRight(env("WEB_PUBLIC_URL", "http://localhost:3000"), "/"), + Edition: env("ZAKURA_EDITION", "oss"), + MultiTenant: multiTenant, + AutoMigrate: autoMigrate, + ReadTimeout: readTimeout, + WriteTimeout: writeTimeout, + TrustedProxyCIDRs: trustedProxyCIDRs, } if len(c.Secret) < 32 { return Config{}, errors.New("ZAKURA_SECRET must contain at least 32 bytes") } + normalizedSecret := strings.TrimSpace(c.Secret) + if normalizedSecret == publishedComposeSecret || normalizedSecret == publishedReadmeSecret { + return Config{}, errors.New("ZAKURA_SECRET must not use a published placeholder value") + } if err := validBaseURL(c.PublicURL); err != nil { return Config{}, errors.New("invalid PUBLIC_BASE_URL") } @@ -107,6 +123,21 @@ func durationEnvAllowZero(k string, fallback time.Duration) (time.Duration, erro } return d, nil } +func prefixListEnv(k string) ([]netip.Prefix, error) { + raw := strings.TrimSpace(os.Getenv(k)) + if raw == "" { + return nil, nil + } + prefixes := make([]netip.Prefix, 0, strings.Count(raw, ",")+1) + for _, value := range strings.Split(raw, ",") { + prefix, err := netip.ParsePrefix(strings.TrimSpace(value)) + if err != nil { + return nil, errors.New(k + " must be a comma-separated list of IP prefixes") + } + prefixes = append(prefixes, prefix.Masked()) + } + return prefixes, nil +} func validBaseURL(raw string) error { u, err := url.ParseRequestURI(raw) if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" { diff --git a/apps/server/internal/platform/config/config_test.go b/apps/server/internal/platform/config/config_test.go index d6158fba..e66200bb 100644 --- a/apps/server/internal/platform/config/config_test.go +++ b/apps/server/internal/platform/config/config_test.go @@ -2,6 +2,23 @@ package config import "testing" +func TestLoadRejectsUnsafeSecrets(t *testing.T) { + for _, tc := range []struct{ name, secret string }{ + {"missing", ""}, + {"short", "too-short"}, + {"published Compose default", publishedComposeSecret}, + {"published README placeholder", publishedReadmeSecret}, + {"whitespace-wrapped default", " " + publishedComposeSecret + " "}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("ZAKURA_SECRET", tc.secret) + if _, err := Load(); err == nil { + t.Fatal("unsafe ZAKURA_SECRET was accepted") + } + }) + } +} + func TestLoadRejectsAmbiguousProductionConfiguration(t *testing.T) { t.Setenv("ZAKURA_SECRET", "0123456789abcdef0123456789abcdef") t.Setenv("PUBLIC_BASE_URL", "relative/path") @@ -29,12 +46,23 @@ func TestLoadValidConfiguration(t *testing.T) { t.Setenv("MULTI_TENANT", "true") t.Setenv("HTTP_READ_TIMEOUT", "20s") t.Setenv("HTTP_WRITE_TIMEOUT", "2m") + t.Setenv("TRUSTED_PROXY_CIDRS", "127.0.0.1/32, 10.0.0.0/8") t.Setenv("ZAKURA_EDITION", "saas") cfg, err := Load() if err != nil { t.Fatal(err) } - if cfg.AutoMigrate || !cfg.MultiTenant || cfg.ReadTimeout.String() != "20s" || cfg.WriteTimeout.String() != "2m0s" { + if cfg.AutoMigrate || !cfg.MultiTenant || cfg.ReadTimeout.String() != "20s" || cfg.WriteTimeout.String() != "2m0s" || len(cfg.TrustedProxyCIDRs) != 2 { t.Fatalf("unexpected config: %+v", cfg) } } + +func TestLoadRejectsInvalidTrustedProxyCIDRs(t *testing.T) { + t.Setenv("ZAKURA_SECRET", "0123456789abcdef0123456789abcdef") + t.Setenv("PUBLIC_BASE_URL", "https://api.example.test") + t.Setenv("WEB_PUBLIC_URL", "https://web.example.test") + t.Setenv("TRUSTED_PROXY_CIDRS", "127.0.0.1") + if _, err := Load(); err == nil { + t.Fatal("trusted proxy without an explicit prefix was accepted") + } +} diff --git a/apps/server/internal/platform/db/models/users.gen.go b/apps/server/internal/platform/db/models/users.gen.go index 5b0cdf39..5f4f1b62 100644 --- a/apps/server/internal/platform/db/models/users.gen.go +++ b/apps/server/internal/platform/db/models/users.gen.go @@ -18,6 +18,7 @@ type User struct { AvatarData *[]byte `gorm:"column:avatar_data;type:BLOB" json:"avatar_data"` AvatarUpdatedAt *string `gorm:"column:avatar_updated_at;type:TEXT" json:"avatar_updated_at"` EmailVerifiedAt *string `gorm:"column:email_verified_at;type:TEXT" json:"email_verified_at"` + EmailVersion int64 `gorm:"column:email_version;type:INTEGER;not null;default:1" json:"email_version"` TotpSecret *string `gorm:"column:totp_secret;type:TEXT" json:"totp_secret"` TotpPendingSecret *string `gorm:"column:totp_pending_secret;type:TEXT" json:"totp_pending_secret"` TotpEnabledAt *string `gorm:"column:totp_enabled_at;type:TEXT" json:"totp_enabled_at"` diff --git a/apps/server/internal/platform/emailverify/binding.go b/apps/server/internal/platform/emailverify/binding.go new file mode 100644 index 00000000..e91574e4 --- /dev/null +++ b/apps/server/internal/platform/emailverify/binding.go @@ -0,0 +1,33 @@ +package emailverify + +import ( + "encoding/json" + "errors" + "strings" +) + +// Binding records the mutable account state an email-verification token proves. +type Binding struct { + TargetEmail string `json:"targetEmail"` + EmailVersion int64 `json:"emailVersion"` +} + +func Normalize(email string) string { + return strings.ToLower(strings.TrimSpace(email)) +} + +func Encode(email string, version int64) string { + raw, _ := json.Marshal(Binding{TargetEmail: Normalize(email), EmailVersion: version}) + return string(raw) +} + +func Decode(raw string) (Binding, error) { + var binding Binding + if err := json.Unmarshal([]byte(raw), &binding); err != nil { + return Binding{}, errors.New("invalid email verification binding") + } + if binding.TargetEmail == "" || binding.TargetEmail != Normalize(binding.TargetEmail) || binding.EmailVersion < 1 { + return Binding{}, errors.New("invalid email verification binding") + } + return binding, nil +} diff --git a/apps/server/internal/platform/identity/account.go b/apps/server/internal/platform/identity/account.go index 11df6f37..17232576 100644 --- a/apps/server/internal/platform/identity/account.go +++ b/apps/server/internal/platform/identity/account.go @@ -58,7 +58,11 @@ func (s *Service) changeMyEmail(w http.ResponseWriter, r *http.Request) { return } err := appdeps.InTx(r.Context(), s.deps.DB, func(tx *sql.Tx) error { - if _, e := tx.ExecContext(r.Context(), s.q(`UPDATE users SET email=?,email_verified_at=NULL,updated_at=? WHERE id=?`), email, s.now(), p.UserID); e != nil { + now := s.now() + if _, e := tx.ExecContext(r.Context(), s.q(`UPDATE users SET email=?,email_verified_at=NULL,email_version=email_version+1,updated_at=? WHERE id=?`), email, now, p.UserID); e != nil { + return e + } + if _, e := tx.ExecContext(r.Context(), s.q(`UPDATE auth_tokens SET consumed_at=? WHERE user_id=? AND kind='email_verify' AND consumed_at IS NULL`), now, p.UserID); e != nil { return e } return s.appendAuditTx(r.Context(), tx, p.TenantID, "auth.email_change", p.UserID, "user", p.UserID, nil) @@ -67,7 +71,7 @@ func (s *Service) changeMyEmail(w http.ResponseWriter, r *http.Request) { httpx.Error(w, 500, "update failed") return } - sent, _ := s.sendVerificationEmail(r.Context(), p.UserID, email) + sent, _ := s.sendVerificationEmail(r.Context(), p.UserID) httpx.JSON(w, 200, map[string]any{"ok": true, "sent": sent}) } diff --git a/apps/server/internal/platform/identity/account_test.go b/apps/server/internal/platform/identity/account_test.go index 5da6b965..f9f4c3a0 100644 --- a/apps/server/internal/platform/identity/account_test.go +++ b/apps/server/internal/platform/identity/account_test.go @@ -1,11 +1,17 @@ package identity_test import ( + "context" + "crypto/sha256" "database/sql" + "encoding/hex" "net/http" + "net/url" + "strings" "testing" "time" + "github.com/Moonrend/Zakura/apps/server/internal/platform/emailverify" "github.com/Moonrend/Zakura/apps/server/internal/platform/identity" "github.com/go-chi/chi/v5" ) @@ -62,6 +68,113 @@ func TestChangeMyEmailSuccess(t *testing.T) { } } +func TestEmailVerificationRejectsStaleAddressBinding(t *testing.T) { + deps := testDeps(t) + tokens := map[string]string{} + deps.SendTransactionalEmail = func(_ context.Context, recipient, _ string, _ string, text string) error { + tokens[recipient] = verificationTokenFromEmail(t, text) + return nil + } + r := chi.NewRouter() + identity.RegisterRoutes(r, deps) + session := setupUser(t, r, "email-binding@example.com", "Email Binding Team") + + var uid string + if err := deps.DB.QueryRow(`SELECT id FROM users WHERE email=?`, "email-binding@example.com").Scan(&uid); err != nil { + t.Fatal(err) + } + now := deps.Clock().Format(time.RFC3339Nano) + tenantID, domainID := deps.NewID(), deps.NewID() + if _, err := deps.DB.Exec(`INSERT INTO tenants(id,slug,name,is_default,onboarding_completed,onboarding_steps,status,created_at,updated_at) VALUES(?,?,?,0,0,'{}','active',?,?)`, tenantID, "bound-domain", "Bound Domain", now, now); err != nil { + t.Fatal(err) + } + if _, err := deps.DB.Exec(`INSERT INTO tenant_domains(id,tenant_id,domain,join_mode,verification_token,verified_at,created_at,updated_at) VALUES(?,?,?,'auto_join','verified',?,?,?)`, domainID, tenantID, "target.example", now, now, now); err != nil { + t.Fatal(err) + } + + first := call(t, r, http.MethodPost, "/api/me/email", map[string]any{"newEmail": "controlled@example.com", "currentPassword": "setup-password-123"}, session) + if first.Code != http.StatusOK { + t.Fatalf("first email change: %d %s", first.Code, first.Body.String()) + } + staleToken := tokens["controlled@example.com"] + staleHash := sha256.Sum256([]byte(staleToken)) + var staleMeta string + if err := deps.DB.QueryRow(`SELECT meta_json FROM auth_tokens WHERE token_hash=?`, hex.EncodeToString(staleHash[:])).Scan(&staleMeta); err != nil { + t.Fatal(err) + } + staleBinding, err := emailverify.Decode(staleMeta) + if err != nil || staleBinding.TargetEmail != "controlled@example.com" { + t.Fatalf("unexpected stale token binding: %+v err=%v", staleBinding, err) + } + + second := call(t, r, http.MethodPost, "/api/me/email", map[string]any{"newEmail": "member@target.example", "currentPassword": "setup-password-123"}, session) + if second.Code != http.StatusOK { + t.Fatalf("second email change: %d %s", second.Code, second.Body.String()) + } + currentToken := tokens["member@target.example"] + var currentVersion int64 + var staleConsumed sql.NullString + if err := deps.DB.QueryRow(`SELECT u.email_version,t.consumed_at FROM users u JOIN auth_tokens t ON t.user_id=u.id WHERE u.id=? AND t.token_hash=?`, uid, hex.EncodeToString(staleHash[:])).Scan(¤tVersion, &staleConsumed); err != nil { + t.Fatal(err) + } + if currentVersion != staleBinding.EmailVersion+1 || !staleConsumed.Valid { + t.Fatalf("email change did not revoke stale token: version=%d binding=%d consumed=%v", currentVersion, staleBinding.EmailVersion, staleConsumed.Valid) + } + + // Simulate an issuance racing after revocation: the address and version checks + // must still reject a stale capability that remains marked unconsumed. + if _, err := deps.DB.Exec(`UPDATE auth_tokens SET consumed_at=NULL WHERE token_hash=?`, hex.EncodeToString(staleHash[:])); err != nil { + t.Fatal(err) + } + stale := call(t, r, http.MethodPost, "/api/auth/verify-email", map[string]any{"token": staleToken}, "") + if stale.Code != http.StatusBadRequest { + t.Fatalf("stale token status=%d body=%s", stale.Code, stale.Body.String()) + } + var verified sql.NullString + var memberships int + if err := deps.DB.QueryRow(`SELECT email_verified_at FROM users WHERE id=?`, uid).Scan(&verified); err != nil { + t.Fatal(err) + } + if err := deps.DB.QueryRow(`SELECT COUNT(*) FROM tenant_memberships WHERE tenant_id=? AND user_id=?`, tenantID, uid).Scan(&memberships); err != nil { + t.Fatal(err) + } + if verified.Valid || memberships != 0 { + t.Fatalf("stale token changed protected state: verified=%v memberships=%d", verified.Valid, memberships) + } + + current := call(t, r, http.MethodPost, "/api/auth/verify-email", map[string]any{"token": currentToken}, "") + if current.Code != http.StatusOK { + t.Fatalf("current token status=%d body=%s", current.Code, current.Body.String()) + } + if err := deps.DB.QueryRow(`SELECT email_verified_at FROM users WHERE id=?`, uid).Scan(&verified); err != nil { + t.Fatal(err) + } + if err := deps.DB.QueryRow(`SELECT COUNT(*) FROM tenant_memberships WHERE tenant_id=? AND user_id=?`, tenantID, uid).Scan(&memberships); err != nil { + t.Fatal(err) + } + if !verified.Valid || memberships != 1 { + t.Fatalf("current token did not preserve verification behavior: verified=%v memberships=%d", verified.Valid, memberships) + } +} + +func verificationTokenFromEmail(t *testing.T, text string) string { + t.Helper() + const marker = "token=" + start := strings.Index(text, marker) + if start < 0 { + t.Fatalf("verification token missing from email: %q", text) + } + raw := text[start+len(marker):] + if end := strings.IndexAny(raw, "\r\n \t"); end >= 0 { + raw = raw[:end] + } + token, err := url.QueryUnescape(raw) + if err != nil || token == "" { + t.Fatalf("invalid verification token in email: %q", text) + } + return token +} + func TestChangeMyEmailDuplicate(t *testing.T) { deps := testDeps(t) r := chi.NewRouter() diff --git a/apps/server/internal/platform/identity/client_ip_test.go b/apps/server/internal/platform/identity/client_ip_test.go new file mode 100644 index 00000000..08cb67d8 --- /dev/null +++ b/apps/server/internal/platform/identity/client_ip_test.go @@ -0,0 +1,38 @@ +package identity + +import ( + "net/http/httptest" + "net/netip" + "testing" + + "github.com/Moonrend/Zakura/apps/server/internal/platform/appdeps" +) + +func TestRequestIPRequiresTrustedPeer(t *testing.T) { + service := New(&appdeps.Dependencies{TrustedProxyCIDRs: []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")}}) + tests := []struct { + name string + remoteAddr string + xRealIP string + cfIP string + xForwarded string + want string + }{ + {name: "untrusted peer", remoteAddr: "198.51.100.10:1234", xRealIP: "203.0.113.1", cfIP: "203.0.113.2", xForwarded: "203.0.113.3", want: "198.51.100.10"}, + {name: "trusted proxy", remoteAddr: "10.0.0.2:1234", xRealIP: "203.0.113.4", want: "203.0.113.4"}, + {name: "ignored aliases", remoteAddr: "10.0.0.3:1234", cfIP: "203.0.113.5", xForwarded: "203.0.113.6", want: "10.0.0.3"}, + {name: "invalid trusted header", remoteAddr: "10.0.0.4:1234", xRealIP: "not-an-ip", want: "10.0.0.4"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr = test.remoteAddr + r.Header.Set("X-Real-IP", test.xRealIP) + r.Header.Set("CF-Connecting-IP", test.cfIP) + r.Header.Set("X-Forwarded-For", test.xForwarded) + if got := service.requestIP(r); got != test.want { + t.Fatalf("requestIP()=%q, want %q", got, test.want) + } + }) + } +} diff --git a/apps/server/internal/platform/identity/enterprise.go b/apps/server/internal/platform/identity/enterprise.go index 882ef2be..2ddb6281 100644 --- a/apps/server/internal/platform/identity/enterprise.go +++ b/apps/server/internal/platform/identity/enterprise.go @@ -800,7 +800,15 @@ func (s *Service) scimUpdateUser(w http.ResponseWriter, r *http.Request, replace if (next.Email != mapped.Email || next.Name != mapped.Name) && s.scimHasOtherMembership(r.Context(), tx, tid, mapped.UserID) { return errSCIMSharedProfile } - if _, e = tx.ExecContext(r.Context(), s.q(`UPDATE users SET email=?,name=?,updated_at=? WHERE id=?`), next.Email, next.Name, s.now(), mapped.UserID); e != nil { + now := s.now() + if next.Email != mapped.Email { + if _, e = tx.ExecContext(r.Context(), s.q(`UPDATE users SET email=?,name=?,email_version=email_version+1,updated_at=? WHERE id=?`), next.Email, next.Name, now, mapped.UserID); e != nil { + return e + } + if _, e = tx.ExecContext(r.Context(), s.q(`UPDATE auth_tokens SET consumed_at=? WHERE user_id=? AND kind='email_verify' AND consumed_at IS NULL`), now, mapped.UserID); e != nil { + return e + } + } else if _, e = tx.ExecContext(r.Context(), s.q(`UPDATE users SET name=?,updated_at=? WHERE id=?`), next.Name, now, mapped.UserID); e != nil { return e } if _, e = tx.ExecContext(r.Context(), s.q(`UPDATE tenant_memberships SET status=?,updated_at=? WHERE tenant_id=? AND user_id=?`), scimMembershipStatus(next.Active), s.now(), tid, mapped.UserID); e != nil { diff --git a/apps/server/internal/platform/identity/mfa.go b/apps/server/internal/platform/identity/mfa.go index 630ae01d..78286106 100644 --- a/apps/server/internal/platform/identity/mfa.go +++ b/apps/server/internal/platform/identity/mfa.go @@ -365,7 +365,7 @@ func (s *Service) completeMFALogin(w http.ResponseWriter, r *http.Request) { httpx.Error(w, 409, err.Error()) return } - res, err := s.sessionForTicket(r.Context(), t, requestIP(r), r.UserAgent()) + res, err := s.sessionForTicket(r.Context(), t, s.requestIP(r), r.UserAgent()) if err != nil { httpx.Error(w, 500, "session issue failed: "+err.Error()) return @@ -410,7 +410,7 @@ func (s *Service) completeTicketTOTP(w http.ResponseWriter, r *http.Request) { httpx.Error(w, 409, err.Error()) return } - res, err := s.sessionForTicket(r.Context(), t, requestIP(r), r.UserAgent()) + res, err := s.sessionForTicket(r.Context(), t, s.requestIP(r), r.UserAgent()) if err != nil { httpx.Error(w, 500, "session issue failed: "+err.Error()) return diff --git a/apps/server/internal/platform/identity/oauth_tokens.go b/apps/server/internal/platform/identity/oauth_tokens.go index 5d1b90b9..fb849880 100644 --- a/apps/server/internal/platform/identity/oauth_tokens.go +++ b/apps/server/internal/platform/identity/oauth_tokens.go @@ -171,7 +171,8 @@ func (s *Service) exchangeRefresh(w http.ResponseWriter, r *http.Request, c oaut } func (s *Service) issueOAuthTokensTx(ctx context.Context, tx *sql.Tx, key *oauthSigningKey, clientID, userID, tenantID string, agentID any, scope string, resource any, family string) (map[string]any, error) { var email, name, role string - if tx.QueryRowContext(ctx, s.q(`SELECT u.email,COALESCE(u.name,''),m.role FROM users u JOIN tenant_memberships m ON m.user_id=u.id JOIN tenants t ON t.id=m.tenant_id WHERE u.id=? AND m.tenant_id=? AND u.status='active' AND m.status='active' AND t.status='active'`), userID, tenantID).Scan(&email, &name, &role) != nil { + var emailVerifiedAt sql.NullString + if tx.QueryRowContext(ctx, s.q(`SELECT u.email,COALESCE(u.name,''),u.email_verified_at,m.role FROM users u JOIN tenant_memberships m ON m.user_id=u.id JOIN tenants t ON t.id=m.tenant_id WHERE u.id=? AND m.tenant_id=? AND u.status='active' AND m.status='active' AND t.status='active'`), userID, tenantID).Scan(&email, &name, &emailVerifiedAt, &role) != nil { return nil, errors.New("inactive account") } agent, _ := agentID.(string) @@ -209,7 +210,7 @@ func (s *Service) issueOAuthTokensTx(ctx context.Context, tx *sql.Tx, key *oauth if scopeContains(scope, "openid") { idClaims := jwt.MapClaims{"iss": s.deps.PublicURL, "sub": userID, "aud": clientID, "iat": now.Unix(), "exp": now.Add(time.Hour).Unix(), "auth_time": now.Unix()} if scopeContains(scope, "email") { - idClaims["email"], idClaims["email_verified"] = email, true + idClaims["email"], idClaims["email_verified"] = email, emailVerifiedAt.Valid } if scopeContains(scope, "profile") { if name != "" { @@ -277,7 +278,7 @@ func (s *Service) userinfo(w http.ResponseWriter, r *http.Request) { return } var account models.User - if s.gdb(r.Context()).Select("email,name").Where("id = ? AND status = 'active'", subject).Take(&account).Error != nil { + if s.gdb(r.Context()).Select("email,name,email_verified_at").Where("id = ? AND status = 'active'", subject).Take(&account).Error != nil { oauthError(w, 401, "invalid_token", "User not found") return } @@ -285,7 +286,7 @@ func (s *Service) userinfo(w http.ResponseWriter, r *http.Request) { out := map[string]any{"sub": subject} scope, _ := c["scope"].(string) if scopeContains(scope, "email") || scopeContains(scope, "openid") || scopeContains(scope, "mcp") { - out["email"], out["email_verified"] = email, true + out["email"], out["email_verified"] = email, account.EmailVerifiedAt != nil } if scopeContains(scope, "profile") || scopeContains(scope, "openid") { if name != "" { diff --git a/apps/server/internal/platform/identity/routes.go b/apps/server/internal/platform/identity/routes.go index df079509..3a10378b 100644 --- a/apps/server/internal/platform/identity/routes.go +++ b/apps/server/internal/platform/identity/routes.go @@ -10,6 +10,7 @@ import ( "errors" "net" "net/http" + "net/netip" "net/url" "strconv" "strings" @@ -21,6 +22,7 @@ import ( "github.com/Moonrend/Zakura/apps/server/internal/platform/appdeps" "github.com/Moonrend/Zakura/apps/server/internal/platform/db/models" "github.com/Moonrend/Zakura/apps/server/internal/platform/emailtmpl" + "github.com/Moonrend/Zakura/apps/server/internal/platform/emailverify" "github.com/Moonrend/Zakura/apps/server/internal/platform/httpx" ) @@ -163,7 +165,7 @@ func setupHandler(s *Service, deps *appdeps.Dependencies) http.HandlerFunc { httpx.Error(w, 400, "invalid request") return } - res, err := s.Setup(r.Context(), b.AdminEmail, b.AdminPassword, b.AdminName, b.TenantName, requestIP(r), r.UserAgent()) + res, err := s.Setup(r.Context(), b.AdminEmail, b.AdminPassword, b.AdminName, b.TenantName, s.requestIP(r), r.UserAgent()) if err != nil { httpx.Error(w, 400, err.Error()) return @@ -190,12 +192,21 @@ func loginHandler(s *Service, deps *appdeps.Dependencies) http.HandlerFunc { httpx.JSON(w, 403, map[string]any{"error": "This account requires company SSO", "code": "sso_required"}) return } - ip := requestIP(r) - res, err := s.Login(r.Context(), b.Email, b.Password, b.TenantSlug, requestIP(r), r.UserAgent()) + ip := s.requestIP(r) + allowed, err := s.reserveLoginAttempt(r.Context(), b.Email) + if err != nil { + httpx.Error(w, 503, "Login temporarily unavailable") + return + } + if !allowed { + httpx.Error(w, 429, "Too many login attempts; try again later") + return + } + res, err := s.Login(r.Context(), b.Email, b.Password, b.TenantSlug, ip, r.UserAgent()) if err != nil { var mfa *MFARequiredError if errors.As(err, &mfa) { - s.clearLoginFailures(r.Context(), b.Email, ip) + s.clearLoginFailures(r.Context(), b.Email) if mfa.Enrollment { httpx.JSON(w, 200, map[string]any{"mfaEnrollmentRequired": true, "mfaEnrollmentTicket": mfa.Ticket, "methods": mfa.Methods, "code": "mfa_enrollment_required"}) } else { @@ -203,14 +214,10 @@ func loginHandler(s *Service, deps *appdeps.Dependencies) http.HandlerFunc { } return } - if s.recordLoginFailure(r.Context(), b.Email, ip) { - httpx.Error(w, 429, "Too many login attempts; try again later") - return - } httpx.Error(w, 401, "Invalid credentials") return } - s.clearLoginFailures(r.Context(), b.Email, ip) + s.clearLoginFailures(r.Context(), b.Email) httpx.JSON(w, 200, map[string]any{"session": res.Session, "user": res.User, "tenant": res.Tenant, "role": res.Role, "multiTenant": deps.MultiTenant, "edition": deps.Edition}) } } @@ -243,7 +250,7 @@ func registerHandler(s *Service, deps *appdeps.Dependencies) http.HandlerFunc { if join.action == "auto_join" { joinTarget = &join } - res, err := s.Register(r.Context(), b.Email, b.Password, b.Name, b.TenantName, requestIP(r), r.UserAgent(), joinTarget) + res, err := s.Register(r.Context(), b.Email, b.Password, b.Name, b.TenantName, s.requestIP(r), r.UserAgent(), joinTarget) if err != nil { status := 400 if strings.Contains(err.Error(), "registered") { @@ -255,7 +262,7 @@ func registerHandler(s *Service, deps *appdeps.Dependencies) http.HandlerFunc { httpx.Error(w, status, err.Error()) return } - _, _ = s.sendVerificationEmail(r.Context(), res.User.ID, res.User.Email) + _, _ = s.sendVerificationEmail(r.Context(), res.User.ID) httpx.JSON(w, 201, map[string]any{"session": res.Session, "user": res.User, "tenant": res.Tenant, "next": "/onboarding"}) } } @@ -474,7 +481,7 @@ func createTenantHandler(s *Service) http.HandlerFunc { httpx.Error(w, 400, "invalid request") return } - res, err := s.CreateTenant(r.Context(), p, b.Name, b.Slug, requestIP(r), r.UserAgent()) + res, err := s.CreateTenant(r.Context(), p, b.Name, b.Slug, s.requestIP(r), r.UserAgent()) if err != nil { httpx.Error(w, 400, err.Error()) return @@ -499,7 +506,7 @@ func switchTenantHandler(s *Service) http.HandlerFunc { httpx.Error(w, 400, "tenantId required") return } - res, err := s.SwitchTenant(r.Context(), p, b.TenantID, requestIP(r), r.UserAgent()) + res, err := s.SwitchTenant(r.Context(), p, b.TenantID, s.requestIP(r), r.UserAgent()) if err != nil { httpx.Error(w, 403, err.Error()) return @@ -590,7 +597,7 @@ func deleteTenantHandler(s *Service) http.HandlerFunc { // Issue the replacement session before deleting the current tenant, just as // the TypeScript service does, so a successful response can immediately be // used by the preserved frontend. - switched, err := s.SwitchTenant(r.Context(), p, next.ID, requestIP(r), r.UserAgent()) + switched, err := s.SwitchTenant(r.Context(), p, next.ID, s.requestIP(r), r.UserAgent()) if err != nil { httpx.Error(w, 500, "Could not switch teams") return @@ -1024,7 +1031,7 @@ func acceptInviteHandler(s *Service, deps *appdeps.Dependencies) http.HandlerFun httpx.Error(w, 409, err.Error()) return } - res, err := s.SwitchTenant(r.Context(), p, tenantID, requestIP(r), r.UserAgent()) + res, err := s.SwitchTenant(r.Context(), p, tenantID, s.requestIP(r), r.UserAgent()) if err != nil { httpx.Error(w, 500, "session issue failed") return @@ -1181,14 +1188,34 @@ func forgotPasswordHandler(s *Service) http.HandlerFunc { httpx.Error(w, 400, "invalid request") return } + email := strings.ToLower(strings.TrimSpace(b.Email)) + if !s.allowPasswordReset(r.Context(), email, s.requestIP(r)) { + httpx.JSON(w, 200, map[string]any{"sent": true}) + return + } var dbUser models.User - if s.gdb(r.Context()).Where("email = ? AND status = 'active'", strings.ToLower(strings.TrimSpace(b.Email))).Take(&dbUser).Error == nil { - userID, email := derefString(dbUser.ID), dbUser.Email - token, _ := randomToken(32) + if s.gdb(r.Context()).Where("email = ? AND status = 'active'", email).Take(&dbUser).Error == nil { + userID, destination := derefString(dbUser.ID), dbUser.Email + token, tokenErr := randomToken(32) + if tokenErr != nil { + httpx.JSON(w, 200, map[string]any{"sent": true}) + return + } h := sha256.Sum256([]byte(token)) tokenID := s.deps.NewID() - _ = s.gdb(r.Context()).Create(&models.AuthToken{ID: &tokenID, UserID: &userID, Kind: "password_reset", TokenHash: hex.EncodeToString(h[:]), ExpiresAt: s.deps.Clock().UTC().Add(time.Hour).Format(time.RFC3339Nano), CreatedAt: s.now()}).Error - if s.deps.SendTransactionalEmail != nil { + now := s.now() + expires := s.deps.Clock().UTC().Add(time.Hour).Format(time.RFC3339Nano) + createErr := appdeps.InTx(r.Context(), s.deps.DB, func(tx *sql.Tx) error { + if _, err := tx.ExecContext(r.Context(), s.q(`DELETE FROM auth_tokens WHERE kind='password_reset' AND expires_at<=?`), now); err != nil { + return err + } + if _, err := tx.ExecContext(r.Context(), s.q(`DELETE FROM auth_tokens WHERE kind='password_reset' AND user_id=?`), userID); err != nil { + return err + } + _, err := tx.ExecContext(r.Context(), s.q(`INSERT INTO auth_tokens(id,user_id,kind,token_hash,expires_at,created_at) VALUES(?,?,'password_reset',?,?,?)`), tokenID, userID, hex.EncodeToString(h[:]), expires, now) + return err + }) + if createErr == nil && s.deps.SendTransactionalEmail != nil { resetURL := s.deps.WebURL + "/reset-password?token=" + url.QueryEscape(token) setPassword := derefString(dbUser.PasswordHash) == "" htmlBody, textBody, renderErr := emailtmpl.Render(emailtmpl.ResetPassword, emailtmpl.ResetPasswordData{ResetURL: resetURL, SetPassword: setPassword}) @@ -1197,7 +1224,7 @@ func forgotPasswordHandler(s *Service) http.HandlerFunc { if setPassword { subject = "设置 Zakura 密码" } - _ = s.deps.SendTransactionalEmail(r.Context(), email, subject, htmlBody, textBody) + _ = s.deps.SendTransactionalEmail(r.Context(), destination, subject, htmlBody, textBody) } } } @@ -1205,17 +1232,18 @@ func forgotPasswordHandler(s *Service) http.HandlerFunc { } } -func (s *Service) sendVerificationEmail(ctx context.Context, userID, email string) (bool, error) { +func (s *Service) sendVerificationEmail(ctx context.Context, userID string) (bool, error) { if s.deps.SendTransactionalEmail == nil { return false, nil } var account models.User - if err := s.gdb(ctx).Select("email_verified_at").Where("id = ? AND status = 'active'", userID).Take(&account).Error; err != nil { + if err := s.gdb(ctx).Select("email,email_version,email_verified_at").Where("id = ? AND status = 'active'", userID).Take(&account).Error; err != nil { return false, err } if account.EmailVerifiedAt != nil { return true, nil } + email := emailverify.Normalize(account.Email) token, err := randomToken(32) if err != nil { return false, err @@ -1223,7 +1251,7 @@ func (s *Service) sendVerificationEmail(ctx context.Context, userID, email strin digest := sha256.Sum256([]byte(token)) tokenID := s.deps.NewID() uid := userID - if err = s.gdb(ctx).Create(&models.AuthToken{ID: &tokenID, UserID: &uid, Kind: "email_verify", TokenHash: hex.EncodeToString(digest[:]), ExpiresAt: s.deps.Clock().UTC().Add(24 * time.Hour).Format(time.RFC3339Nano), CreatedAt: s.now()}).Error; err != nil { + if err = s.gdb(ctx).Create(&models.AuthToken{ID: &tokenID, UserID: &uid, Kind: "email_verify", TokenHash: hex.EncodeToString(digest[:]), MetaJSON: emailverify.Encode(email, account.EmailVersion), ExpiresAt: s.deps.Clock().UTC().Add(24 * time.Hour).Format(time.RFC3339Nano), CreatedAt: s.now()}).Error; err != nil { return false, err } verifyURL := s.deps.WebURL + "/verify-email?token=" + url.QueryEscape(token) @@ -1268,6 +1296,9 @@ func resetPasswordHandler(s *Service) http.HandlerFunc { if _, e = tx.ExecContext(r.Context(), s.q(`UPDATE users SET password_hash=?,updated_at=? WHERE id=?`), string(hash), s.now(), uid); e != nil { return e } + if _, e = tx.ExecContext(r.Context(), s.q(`UPDATE oauth_refresh_tokens SET revoked_at=? WHERE user_id=? AND revoked_at IS NULL`), s.now(), uid); e != nil { + return e + } _, e = tx.ExecContext(r.Context(), s.q(`UPDATE user_sessions SET revoked_at=? WHERE user_id=? AND revoked_at IS NULL`), s.now(), uid) return e }) @@ -1288,10 +1319,13 @@ func verifyEmailTokenHandler(s *Service) http.HandlerFunc { return } h := sha256.Sum256([]byte(b.Token)) - var verifiedUserID string err := appdeps.InTx(r.Context(), s.deps.DB, func(tx *sql.Tx) error { - var id, uid string - if e := tx.QueryRowContext(r.Context(), s.q(`SELECT id,user_id FROM auth_tokens WHERE token_hash=? AND kind='email_verify' AND consumed_at IS NULL AND expires_at>?`), hex.EncodeToString(h[:]), s.now()).Scan(&id, &uid); e != nil { + var id, uid, metaRaw string + if e := tx.QueryRowContext(r.Context(), s.q(`SELECT id,user_id,meta_json FROM auth_tokens WHERE token_hash=? AND kind='email_verify' AND consumed_at IS NULL AND expires_at>?`), hex.EncodeToString(h[:]), s.now()).Scan(&id, &uid, &metaRaw); e != nil { + return errors.New("invalid or expired token") + } + binding, e := emailverify.Decode(metaRaw) + if e != nil { return errors.New("invalid or expired token") } res, e := tx.ExecContext(r.Context(), s.q(`UPDATE auth_tokens SET consumed_at=? WHERE id=? AND consumed_at IS NULL`), s.now(), id) @@ -1302,38 +1336,52 @@ func verifyEmailTokenHandler(s *Service) http.HandlerFunc { if n != 1 { return errors.New("token already used") } - verifiedUserID = uid - _, e = tx.ExecContext(r.Context(), s.q(`UPDATE users SET email_verified_at=?,updated_at=? WHERE id=?`), s.now(), s.now(), uid) - return e + now := s.now() + res, e = tx.ExecContext(r.Context(), s.q(`UPDATE users SET email_verified_at=?,updated_at=? WHERE id=? AND LOWER(TRIM(email))=? AND email_version=? AND status='active'`), now, now, uid, binding.TargetEmail, binding.EmailVersion) + if e != nil { + return e + } + n, _ = res.RowsAffected() + if n != 1 { + return errors.New("invalid or expired token") + } + return s.maybeAutoJoinTenantTx(r.Context(), tx, uid, binding.TargetEmail) }) if err != nil { httpx.Error(w, 400, err.Error()) return } - if verifiedUserID != "" { - var account models.User - if s.gdb(r.Context()).Select("email").Where("id = ?", verifiedUserID).Take(&account).Error == nil { - _ = s.maybeAutoJoinTenant(r.Context(), verifiedUserID, account.Email) - } - } httpx.JSON(w, 200, map[string]any{"ok": true}) } } -func requestIP(r *http.Request) string { - for _, key := range []string{"CF-Connecting-IP", "X-Real-IP"} { - if v := strings.TrimSpace(r.Header.Get(key)); v != "" { - return v +func (s *Service) requestIP(r *http.Request) string { + peer, ok := parseRemoteIP(r.RemoteAddr) + if !ok { + return r.RemoteAddr + } + for _, prefix := range s.deps.TrustedProxyCIDRs { + if !prefix.Contains(peer) { + continue } + forwarded, err := netip.ParseAddr(strings.TrimSpace(r.Header.Get("X-Real-IP"))) + if err == nil { + return forwarded.Unmap().String() + } + break } - if v := strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0]); v != "" { - return v + return peer.String() +} +func parseRemoteIP(remote string) (netip.Addr, bool) { + host, _, err := net.SplitHostPort(remote) + if err != nil { + host = remote } - host, _, err := net.SplitHostPort(r.RemoteAddr) - if err == nil { - return host + address, err := netip.ParseAddr(strings.Trim(strings.TrimSpace(host), "[]")) + if err != nil { + return netip.Addr{}, false } - return r.RemoteAddr + return address.Unmap(), true } func nullString(v sql.NullString) any { if v.Valid { diff --git a/apps/server/internal/platform/identity/routes_test.go b/apps/server/internal/platform/identity/routes_test.go index f25a8c03..f0f6a30b 100644 --- a/apps/server/internal/platform/identity/routes_test.go +++ b/apps/server/internal/platform/identity/routes_test.go @@ -238,22 +238,37 @@ func TestConcurrentSetupCreatesExactlyOnePlatformAdmin(t *testing.T) { func TestLoginThrottleIsDurableAndClearsOnSuccess(t *testing.T) { deps := testDeps(t) + now := deps.Clock() + deps.Clock = func() time.Time { return now } r := chi.NewRouter() identity.RegisterRoutes(r, deps) setupUser(t, r, "throttle@example.com", "Throttle") - for i := 0; i < 8; i++ { + for i := 0; i < 3; i++ { failed := call(t, r, http.MethodPost, "/api/auth/login", map[string]any{"email": "throttle@example.com", "password": "wrong-password"}, "") + if failed.Code != http.StatusUnauthorized { + t.Fatalf("initial failure %d status=%d body=%s", i+1, failed.Code, failed.Body.String()) + } + } + success := call(t, r, http.MethodPost, "/api/auth/login", map[string]any{"email": "throttle@example.com", "password": "setup-password-123"}, "") + if success.Code != http.StatusOK { + t.Fatalf("valid login before limit: %d %s", success.Code, success.Body.String()) + } + for i := 0; i < 8; i++ { + forwarded := fmt.Sprintf("203.0.113.%d", i+1) + remote := fmt.Sprintf("198.51.100.%d:42000", i+1) + failed := callFrom(t, r, http.MethodPost, "/api/auth/login", map[string]any{"email": "throttle@example.com", "password": "wrong-password"}, "", remote, map[string]string{"CF-Connecting-IP": forwarded, "X-Real-IP": forwarded, "X-Forwarded-For": forwarded}) if failed.Code != http.StatusUnauthorized { t.Fatalf("failure %d status=%d body=%s", i+1, failed.Code, failed.Body.String()) } } - blocked := call(t, r, http.MethodPost, "/api/auth/login", map[string]any{"email": "throttle@example.com", "password": "wrong-password"}, "") + blocked := callFrom(t, r, http.MethodPost, "/api/auth/login", map[string]any{"email": "throttle@example.com", "password": "setup-password-123"}, "", "198.51.100.20:42000", map[string]string{"CF-Connecting-IP": "192.0.2.10", "X-Real-IP": "192.0.2.11", "X-Forwarded-For": "192.0.2.12"}) if blocked.Code != http.StatusTooManyRequests { - t.Fatalf("ninth failure status=%d body=%s", blocked.Code, blocked.Body.String()) + t.Fatalf("rotated headers bypassed throttle: status=%d body=%s", blocked.Code, blocked.Body.String()) } - success := call(t, r, http.MethodPost, "/api/auth/login", map[string]any{"email": "throttle@example.com", "password": "setup-password-123"}, "") - if success.Code != http.StatusOK { - t.Fatalf("valid login after failures: %d %s", success.Code, success.Body.String()) + now = now.Add(16 * time.Minute) + recovered := call(t, r, http.MethodPost, "/api/auth/login", map[string]any{"email": "throttle@example.com", "password": "setup-password-123"}, "") + if recovered.Code != http.StatusOK { + t.Fatalf("valid login after reset: %d %s", recovered.Code, recovered.Body.String()) } again := call(t, r, http.MethodPost, "/api/auth/login", map[string]any{"email": "throttle@example.com", "password": "wrong-password"}, "") if again.Code != http.StatusUnauthorized { @@ -375,6 +390,14 @@ func TestOAuthCodeAndRefreshAreSingleUse(t *testing.T) { if tokenBody.AccessToken == "" || tokenBody.IDToken == "" || !strings.HasPrefix(tokenBody.RefreshToken, "rcr_") { t.Fatalf("pinned OAuth token response missing fields: %+v", tokenBody) } + idToken, _, err := jwt.NewParser().ParseUnverified(tokenBody.IDToken, jwt.MapClaims{}) + if err != nil { + t.Fatalf("parse ID token claims: %v", err) + } + idClaims, claimsOK := idToken.Claims.(jwt.MapClaims) + if !claimsOK || idClaims["email"] != "oauth@example.com" || idClaims["email_verified"] != false { + t.Fatalf("unverified email ID token claims: %#v", idToken.Claims) + } unverified, _, err := jwt.NewParser().ParseUnverified(tokenBody.AccessToken, jwt.MapClaims{}) if err != nil || unverified == nil || unverified.Method.Alg() != "RS256" || unverified.Header["typ"] != "at+jwt" { header := map[string]any(nil) @@ -384,9 +407,17 @@ func TestOAuthCodeAndRefreshAreSingleUse(t *testing.T) { t.Fatalf("access token is not pinned RS256 at+jwt: header=%#v err=%v", header, err) } userinfo := call(t, r, http.MethodGet, "/userinfo", nil, tokenBody.AccessToken) - if userinfo.Code != http.StatusOK || !strings.Contains(userinfo.Body.String(), "oauth@example.com") { + if userinfo.Code != http.StatusOK { t.Fatalf("userinfo with issued token: %d %s", userinfo.Code, userinfo.Body.String()) } + var userinfoBody struct { + Email string `json:"email"` + EmailVerified *bool `json:"email_verified"` + } + decode(t, userinfo, &userinfoBody) + if userinfoBody.Email != "oauth@example.com" || userinfoBody.EmailVerified == nil || *userinfoBody.EmailVerified { + t.Fatalf("unverified email userinfo claims: %+v", userinfoBody) + } oauthMe := call(t, r, http.MethodGet, "/api/me", nil, tokenBody.AccessToken) if oauthMe.Code != http.StatusOK { t.Fatalf("RS256 OAuth token did not authenticate API request: %d %s", oauthMe.Code, oauthMe.Body.String()) @@ -395,6 +426,17 @@ func TestOAuthCodeAndRefreshAreSingleUse(t *testing.T) { if jwks.Code != http.StatusOK || !strings.Contains(jwks.Body.String(), `"kty":"RSA"`) || !strings.Contains(jwks.Body.String(), `"alg":"RS256"`) { t.Fatalf("RS256 JWKS: %d %s", jwks.Code, jwks.Body.String()) } + if _, err := deps.DB.Exec(`UPDATE users SET email_verified_at=? WHERE email=?`, deps.Clock().Format(time.RFC3339Nano), "oauth@example.com"); err != nil { + t.Fatal(err) + } + verifiedUserinfo := call(t, r, http.MethodGet, "/userinfo", nil, tokenBody.AccessToken) + if verifiedUserinfo.Code != http.StatusOK { + t.Fatalf("verified userinfo with issued token: %d %s", verifiedUserinfo.Code, verifiedUserinfo.Body.String()) + } + decode(t, verifiedUserinfo, &userinfoBody) + if userinfoBody.Email != "oauth@example.com" || userinfoBody.EmailVerified == nil || !*userinfoBody.EmailVerified { + t.Fatalf("verified email userinfo claims: %+v", userinfoBody) + } refresh := url.Values{"grant_type": {"refresh_token"}, "client_id": {client.ClientID}, "refresh_token": {tokenBody.RefreshToken}} wg.Add(2) for i := 0; i < 2; i++ { @@ -402,9 +444,14 @@ func TestOAuthCodeAndRefreshAreSingleUse(t *testing.T) { } wg.Wait() ok, bad = 0, 0 + var refreshedTokenBody struct { + AccessToken string `json:"access_token"` + IDToken string `json:"id_token"` + } for _, rr := range results { if rr.Code == 200 { ok++ + decode(t, rr, &refreshedTokenBody) } else if rr.Code == 400 { bad++ } @@ -412,6 +459,14 @@ func TestOAuthCodeAndRefreshAreSingleUse(t *testing.T) { if ok != 1 || bad != 1 { t.Fatalf("refresh replay statuses %d,%d", results[0].Code, results[1].Code) } + refreshedIDToken, _, err := jwt.NewParser().ParseUnverified(refreshedTokenBody.IDToken, jwt.MapClaims{}) + if err != nil { + t.Fatalf("parse refreshed ID token claims: %v", err) + } + refreshedIDClaims, claimsOK := refreshedIDToken.Claims.(jwt.MapClaims) + if !claimsOK || refreshedIDClaims["email"] != "oauth@example.com" || refreshedIDClaims["email_verified"] != true { + t.Fatalf("verified email ID token claims: %#v", refreshedIDToken.Claims) + } } type identityRoundTripFunc func(*http.Request) (*http.Response, error) @@ -850,6 +905,99 @@ func TestForgotPasswordForPasswordlessAccount(t *testing.T) { } } +func TestForgotPasswordAccountCooldownCoalescesTokens(t *testing.T) { + deps := testDeps(t) + var emails int + deps.SendTransactionalEmail = func(context.Context, string, string, string, string) error { + emails++ + return nil + } + r := chi.NewRouter() + identity.RegisterRoutes(r, deps) + setupUser(t, r, "owner@example.com", "Owner Team") + var userID string + if err := deps.DB.QueryRow(`SELECT id FROM users WHERE email='owner@example.com'`).Scan(&userID); err != nil { + t.Fatal(err) + } + now := deps.Clock().UTC() + if _, err := deps.DB.Exec(`INSERT INTO auth_tokens(id,user_id,kind,token_hash,expires_at,created_at) VALUES(?,?,'password_reset','older-reset-token',?,?)`, deps.NewID(), userID, now.Add(30*time.Minute).Format(time.RFC3339Nano), now.Add(-time.Minute).Format(time.RFC3339Nano)); err != nil { + t.Fatal(err) + } + if _, err := deps.DB.Exec(`INSERT INTO auth_tokens(id,user_id,kind,token_hash,expires_at,created_at) VALUES(?,NULL,'password_reset','expired-reset-token',?,?)`, deps.NewID(), now.Add(-time.Minute).Format(time.RFC3339Nano), now.Add(-time.Hour).Format(time.RFC3339Nano)); err != nil { + t.Fatal(err) + } + + first := forgotPasswordCall(t, r, "owner@example.com", "192.0.2.10") + second := forgotPasswordCall(t, r, " OWNER@EXAMPLE.COM ", "198.51.100.10") + if first.Code != http.StatusOK || second.Code != http.StatusOK || !strings.Contains(second.Body.String(), `"sent":true`) { + t.Fatalf("generic forgot-password response changed: first=%d second=%d body=%s", first.Code, second.Code, second.Body.String()) + } + var tokens, expired int + if err := deps.DB.QueryRow(`SELECT COUNT(*) FROM auth_tokens t JOIN users u ON u.id=t.user_id WHERE t.kind='password_reset' AND u.email='owner@example.com'`).Scan(&tokens); err != nil { + t.Fatal(err) + } + if err := deps.DB.QueryRow(`SELECT COUNT(*) FROM auth_tokens WHERE token_hash='expired-reset-token'`).Scan(&expired); err != nil { + t.Fatal(err) + } + if tokens != 1 || expired != 0 || emails != 1 { + t.Fatalf("account cooldown did not coalesce work: tokens=%d expired=%d emails=%d", tokens, expired, emails) + } +} + +func TestForgotPasswordNetworkAndGlobalLimits(t *testing.T) { + t.Run("network", func(t *testing.T) { + deps := testDeps(t) + var emails int + deps.SendTransactionalEmail = func(context.Context, string, string, string, string) error { + emails++ + return nil + } + r := chi.NewRouter() + identity.RegisterRoutes(r, deps) + setupUser(t, r, "owner@example.com", "Owner Team") + for i := 0; i < 20; i++ { + response := forgotPasswordCall(t, r, fmt.Sprintf("unknown-%d@example.com", i), "192.0.2.20") + if response.Code != http.StatusOK { + t.Fatalf("unknown request %d status=%d", i, response.Code) + } + } + blocked := forgotPasswordCall(t, r, "owner@example.com", "192.0.2.20") + allowed := forgotPasswordCall(t, r, "owner@example.com", "198.51.100.20") + if blocked.Code != http.StatusOK || allowed.Code != http.StatusOK || emails != 1 { + t.Fatalf("network limit: blocked=%d allowed=%d emails=%d", blocked.Code, allowed.Code, emails) + } + }) + + t.Run("global", func(t *testing.T) { + deps := testDeps(t) + now := deps.Clock() + deps.Clock = func() time.Time { return now } + var emails int + deps.SendTransactionalEmail = func(context.Context, string, string, string, string) error { + emails++ + return nil + } + r := chi.NewRouter() + identity.RegisterRoutes(r, deps) + setupUser(t, r, "owner@example.com", "Owner Team") + for i := 0; i < 100; i++ { + response := forgotPasswordCall(t, r, fmt.Sprintf("unknown-%d@example.com", i), fmt.Sprintf("198.51.100.%d", i+1)) + if response.Code != http.StatusOK { + t.Fatalf("unknown request %d status=%d", i, response.Code) + } + } + blocked := forgotPasswordCall(t, r, "owner@example.com", "203.0.113.10") + if blocked.Code != http.StatusOK || emails != 0 { + t.Fatalf("global limit did not suppress delivery: status=%d emails=%d", blocked.Code, emails) + } + now = now.Add(16 * time.Minute) + allowed := forgotPasswordCall(t, r, "owner@example.com", "203.0.113.10") + if allowed.Code != http.StatusOK || emails != 1 { + t.Fatalf("global window did not reopen: status=%d emails=%d", allowed.Code, emails) + } + }) +} + func TestResetPasswordMessages(t *testing.T) { deps := testDeps(t) r := chi.NewRouter() @@ -868,6 +1016,89 @@ func TestResetPasswordMessages(t *testing.T) { } } +func TestResetPasswordRevokesOAuthRefreshTokens(t *testing.T) { + deps := testDeps(t) + deps.Edition = "saas" + r := chi.NewRouter() + identity.RegisterRoutes(r, deps) + oldSession := setupUser(t, r, "reset@example.com", "Reset Team") + other := call(t, r, http.MethodPost, "/api/auth/register", map[string]any{"email": "other@example.com", "password": "other-password-123", "tenantName": "Other Team"}, "") + if other.Code != http.StatusCreated { + t.Fatalf("register other user: %d %s", other.Code, other.Body.String()) + } + clientResponse := call(t, r, http.MethodPost, "/oauth/register", map[string]any{"redirect_uris": []string{"http://localhost/callback"}, "token_endpoint_auth_method": "none"}, "") + if clientResponse.Code != http.StatusCreated { + t.Fatalf("register client: %d %s", clientResponse.Code, clientResponse.Body.String()) + } + var client struct { + ID string `json:"client_id"` + } + decode(t, clientResponse, &client) + + var userID, tenantID, otherUserID, otherTenantID string + if err := deps.DB.QueryRow(`SELECT u.id,m.tenant_id FROM users u JOIN tenant_memberships m ON m.user_id=u.id WHERE u.email='reset@example.com'`).Scan(&userID, &tenantID); err != nil { + t.Fatal(err) + } + if err := deps.DB.QueryRow(`SELECT u.id,m.tenant_id FROM users u JOIN tenant_memberships m ON m.user_id=u.id WHERE u.email='other@example.com'`).Scan(&otherUserID, &otherTenantID); err != nil { + t.Fatal(err) + } + now := deps.Clock().UTC() + nowText := now.Format(time.RFC3339Nano) + resetToken := "known-password-reset-token" + resetHash := sha256.Sum256([]byte(resetToken)) + if _, err := deps.DB.Exec(`INSERT INTO auth_tokens(id,user_id,kind,token_hash,expires_at,created_at) VALUES(?,?,?,?,?,?)`, "reset-token", userID, "password_reset", hex.EncodeToString(resetHash[:]), now.Add(time.Hour).Format(time.RFC3339Nano), nowText); err != nil { + t.Fatal(err) + } + type refreshFixture struct { + id, family, raw, user, tenant string + consumed any + } + refreshes := []refreshFixture{ + {id: "consumed-parent", family: "rotated-family", raw: "rcr_consumed_parent", user: userID, tenant: tenantID, consumed: nowText}, + {id: "rotated-descendant", family: "rotated-family", raw: "rcr_rotated_descendant", user: userID, tenant: tenantID}, + {id: "second-family", family: "second-family", raw: "rcr_second_family", user: userID, tenant: tenantID}, + {id: "other-user-token", family: "other-family", raw: "rcr_other_user", user: otherUserID, tenant: otherTenantID}, + } + for _, refresh := range refreshes { + digest := sha256.Sum256([]byte(refresh.raw)) + if _, err := deps.DB.Exec(`INSERT INTO oauth_refresh_tokens(id,family_id,token_hash,client_id,user_id,tenant_id,scope,expires_at,consumed_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)`, refresh.id, refresh.family, hex.EncodeToString(digest[:]), client.ID, refresh.user, refresh.tenant, "mcp", now.Add(24*time.Hour).Format(time.RFC3339Nano), refresh.consumed, nowText); err != nil { + t.Fatal(err) + } + } + + reset := call(t, r, http.MethodPost, "/api/auth/reset-password", map[string]any{"token": resetToken, "password": "replacement-password-123"}, "") + if reset.Code != http.StatusOK { + t.Fatalf("reset password: %d %s", reset.Code, reset.Body.String()) + } + var revoked int + if err := deps.DB.QueryRow(`SELECT COUNT(*) FROM oauth_refresh_tokens WHERE user_id=? AND revoked_at IS NOT NULL`, userID).Scan(&revoked); err != nil { + t.Fatal(err) + } + if revoked != 3 { + t.Fatalf("reset user refresh tokens revoked=%d", revoked) + } + var otherRevoked sql.NullString + if err := deps.DB.QueryRow(`SELECT revoked_at FROM oauth_refresh_tokens WHERE id='other-user-token'`).Scan(&otherRevoked); err != nil { + t.Fatal(err) + } + if otherRevoked.Valid { + t.Fatalf("other user's refresh token was revoked at %s", otherRevoked.String) + } + for _, raw := range []string{"rcr_rotated_descendant", "rcr_second_family"} { + response := callForm(r, "/token", url.Values{"grant_type": {"refresh_token"}, "client_id": {client.ID}, "refresh_token": {raw}}) + if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "invalid_grant") { + t.Fatalf("refresh token remained usable: %d %s", response.Code, response.Body.String()) + } + } + if current := call(t, r, http.MethodGet, "/api/me", nil, oldSession); current.Code != http.StatusUnauthorized { + t.Fatalf("old session remained usable: %d %s", current.Code, current.Body.String()) + } + login := call(t, r, http.MethodPost, "/api/auth/login", map[string]any{"email": "reset@example.com", "password": "replacement-password-123"}, "") + if login.Code != http.StatusOK { + t.Fatalf("new password login: %d %s", login.Code, login.Body.String()) + } +} + func TestOIDCSSOWithDeterministicFakeIdP(t *testing.T) { deps := testDeps(t) deps.Edition = "saas" @@ -1066,6 +1297,14 @@ func TestSocialOAuthWithDeterministicFakeProvider(t *testing.T) { deps := testDeps(t) deps.Edition = "saas" var tokenCalls atomic.Int64 + var providerSubject atomic.Value + var profileEmail atomic.Value + var githubEmail atomic.Value + var providerVerified atomic.Bool + providerSubject.Store("12345") + profileEmail.Store("") + githubEmail.Store("social@example.com") + providerVerified.Store(true) idp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/token": @@ -1080,13 +1319,13 @@ func TestSocialOAuthWithDeterministicFakeProvider(t *testing.T) { http.Error(w, "bad token", http.StatusUnauthorized) return } - _ = json.NewEncoder(w).Encode(map[string]any{"id": 12345, "email": nil, "name": "Social User"}) + _ = json.NewEncoder(w).Encode(map[string]any{"id": providerSubject.Load(), "sub": providerSubject.Load(), "email": profileEmail.Load(), "email_verified": providerVerified.Load(), "name": "Social User"}) case "/userinfo/emails": if r.Header.Get("Authorization") != "Bearer fake-access" { http.Error(w, "bad token", http.StatusUnauthorized) return } - _ = json.NewEncoder(w).Encode([]map[string]any{{"email": "social@example.com", "primary": true, "verified": true}}) + _ = json.NewEncoder(w).Encode([]map[string]any{{"email": githubEmail.Load(), "primary": true, "verified": providerVerified.Load()}}) default: http.NotFound(w, r) } @@ -1160,6 +1399,54 @@ func TestSocialOAuthWithDeterministicFakeProvider(t *testing.T) { if replay.Code != http.StatusBadRequest || tokenCalls.Load() != 1 { t.Fatalf("state replay was not rejected before provider exchange: %d %s", replay.Code, replay.Body.String()) } + + githubLogin := func(subject string, verified bool) *httptest.ResponseRecorder { + t.Helper() + providerSubject.Store(subject) + profileEmail.Store("owner@example.com") + githubEmail.Store("owner@example.com") + providerVerified.Store(verified) + start := call(t, r, http.MethodPost, "/api/auth/oauth/github/start", map[string]any{}, "") + if start.Code != http.StatusOK { + t.Fatalf("start GitHub login: %d %s", start.Code, start.Body.String()) + } + var started struct { + AuthorizeURL string `json:"authorizeUrl"` + } + decode(t, start, &started) + authorizeURL, err := url.Parse(started.AuthorizeURL) + if err != nil || authorizeURL.Query().Get("state") == "" { + t.Fatalf("invalid GitHub authorize URL: %q err=%v", started.AuthorizeURL, err) + } + return call(t, r, http.MethodPost, "/api/auth/oauth/github/callback", map[string]any{"code": "provider-code", "state": authorizeURL.Query().Get("state")}, "") + } + unverifiedGitHub := githubLogin("github-attacker", false) + if unverifiedGitHub.Code != http.StatusForbidden || !strings.Contains(unverifiedGitHub.Body.String(), "did not verify") { + t.Fatalf("unverified GitHub email linked an existing account: %d %s", unverifiedGitHub.Code, unverifiedGitHub.Body.String()) + } + var unverifiedGitHubBindings int + if err := deps.DB.QueryRow(`SELECT COUNT(*) FROM oauth_identities WHERE provider='github' AND provider_user_id='github-attacker'`).Scan(&unverifiedGitHubBindings); err != nil || unverifiedGitHubBindings != 0 { + t.Fatalf("unverified GitHub identity was persisted: bindings=%d err=%v", unverifiedGitHubBindings, err) + } + + verifiedGitHub := githubLogin("github-owner", true) + if verifiedGitHub.Code != http.StatusOK { + t.Fatalf("verified GitHub email did not link: %d %s", verifiedGitHub.Code, verifiedGitHub.Body.String()) + } + var verifiedResult struct { + Session string `json:"session"` + User struct { + Email string `json:"email"` + } `json:"user"` + } + decode(t, verifiedGitHub, &verifiedResult) + if verifiedResult.Session == "" || verifiedResult.User.Email != "owner@example.com" { + t.Fatalf("verified GitHub result mismatch: %+v", verifiedResult) + } + var verifiedGitHubBindings int + if err := deps.DB.QueryRow(`SELECT COUNT(*) FROM oauth_identities WHERE provider='github' AND provider_user_id='github-owner'`).Scan(&verifiedGitHubBindings); err != nil || verifiedGitHubBindings != 1 { + t.Fatalf("verified GitHub identity binding missing: bindings=%d err=%v", verifiedGitHubBindings, err) + } } func TestSCIMMappedUsersGroupsAndLifecycle(t *testing.T) { @@ -1337,15 +1624,25 @@ func testDeps(t *testing.T) *appdeps.Dependencies { t.Fatal(err) } var seq atomic.Int64 - return &appdeps.Dependencies{DB: c.DB, Gorm: gormDB, Dialect: c.Dialect, Rebind: c.Rebind, Clock: func() time.Time { return time.Date(2026, 10, 3, 12, 0, 0, 0, time.UTC) }, NewID: func() string { return fmt.Sprintf("%026d", seq.Add(1)) }, Secret: []byte("0123456789abcdef0123456789abcdef"), PublicURL: "http://api.test", WebURL: "http://web.test", Edition: "self-hosted", MultiTenant: true} + now := time.Now().UTC() + return &appdeps.Dependencies{DB: c.DB, Gorm: gormDB, Dialect: c.Dialect, Rebind: c.Rebind, Clock: func() time.Time { return now }, NewID: func() string { return fmt.Sprintf("%026d", seq.Add(1)) }, Secret: []byte("0123456789abcdef0123456789abcdef"), PublicURL: "http://api.test", WebURL: "http://web.test", Edition: "self-hosted", MultiTenant: true} } func call(t *testing.T, h http.Handler, method, path string, body any, token string) *httptest.ResponseRecorder { + return callFrom(t, h, method, path, body, token, "", nil) +} +func callFrom(t *testing.T, h http.Handler, method, path string, body any, token, remoteAddr string, headers map[string]string) *httptest.ResponseRecorder { t.Helper() var raw []byte if body != nil { raw, _ = json.Marshal(body) } req := httptest.NewRequest(method, path, bytes.NewReader(raw)) + if remoteAddr != "" { + req.RemoteAddr = remoteAddr + } + for key, value := range headers { + req.Header.Set(key, value) + } if body != nil { req.Header.Set("Content-Type", "application/json") } @@ -1356,6 +1653,16 @@ func call(t *testing.T, h http.Handler, method, path string, body any, token str h.ServeHTTP(rr, req) return rr } +func forgotPasswordCall(t *testing.T, h http.Handler, email, ip string) *httptest.ResponseRecorder { + t.Helper() + raw, _ := json.Marshal(map[string]any{"email": email}) + req := httptest.NewRequest(http.MethodPost, "/api/auth/forgot-password", bytes.NewReader(raw)) + req.Header.Set("Content-Type", "application/json") + req.RemoteAddr = net.JoinHostPort(ip, "12345") + rr := httptest.NewRecorder() + h.ServeHTTP(rr, req) + return rr +} func decode(t *testing.T, rr *httptest.ResponseRecorder, dst any) { t.Helper() if err := json.Unmarshal(rr.Body.Bytes(), dst); err != nil { diff --git a/apps/server/internal/platform/identity/service.go b/apps/server/internal/platform/identity/service.go index b0c45ff3..3fba8263 100644 --- a/apps/server/internal/platform/identity/service.go +++ b/apps/server/internal/platform/identity/service.go @@ -32,7 +32,16 @@ type Service struct { cimdCache map[string]cimdCacheEntry } -const passwordBcryptCost = 12 +const ( + passwordBcryptCost = 12 + passwordResetAccountLimit = 1 + passwordResetNetworkLimit = 20 + passwordResetGlobalLimit = 100 + passwordResetAccountWindow = 15 * time.Minute + passwordResetNetworkWindow = 15 * time.Minute + passwordResetGlobalWindow = time.Minute + maxPasswordLoginAttempts = 8 +) func New(deps *appdeps.Dependencies) *Service { return &Service{deps: deps, cimdCache: map[string]cimdCacheEntry{}} @@ -268,27 +277,26 @@ func (s *Service) recordLoginUsage(ctx context.Context, tenantID, userID, method } func (s *Service) maybeAutoJoinTenant(ctx context.Context, userID, email string) error { + return appdeps.InTx(ctx, s.deps.DB, func(tx *sql.Tx) error { + return s.maybeAutoJoinTenantTx(ctx, tx, userID, email) + }) +} + +func (s *Service) maybeAutoJoinTenantTx(ctx context.Context, tx *sql.Tx, userID, email string) error { parts := strings.SplitN(strings.ToLower(strings.TrimSpace(email)), "@", 2) if len(parts) != 2 { return nil } - var row struct { - TenantID string `gorm:"column:tenant_id"` - } - err := s.gdb(ctx).Table("tenant_domains AS d"). - Select("d.tenant_id AS tenant_id"). - Joins("JOIN tenants t ON t.id = d.tenant_id"). - Where("d.domain = ? AND d.verified_at IS NOT NULL AND d.join_mode = 'auto_join' AND t.status = 'active'", parts[1]). - Take(&row).Error - if errors.Is(err, gorm.ErrRecordNotFound) { + var tenantID string + err := tx.QueryRowContext(ctx, s.q(`SELECT d.tenant_id FROM tenant_domains d JOIN tenants t ON t.id=d.tenant_id WHERE d.domain=? AND d.verified_at IS NOT NULL AND d.join_mode='auto_join' AND t.status='active' LIMIT 1`), parts[1]).Scan(&tenantID) + if errors.Is(err, sql.ErrNoRows) { return nil } if err != nil { return err } - tenantID := row.TenantID now := s.now() - err = s.gdb(ctx).Exec(`INSERT INTO tenant_memberships(id,tenant_id,user_id,role,status,created_at,updated_at) VALUES(?,?,?,'member','active',?,?) ON CONFLICT(tenant_id,user_id) DO NOTHING`, s.deps.NewID(), tenantID, userID, now, now).Error + _, err = tx.ExecContext(ctx, s.q(`INSERT INTO tenant_memberships(id,tenant_id,user_id,role,status,created_at,updated_at) VALUES(?,?,?,'member','active',?,?) ON CONFLICT(tenant_id,user_id) DO NOTHING`), s.deps.NewID(), tenantID, userID, now, now) return err } @@ -458,19 +466,48 @@ func (s *Service) resolveRegistrationJoin(ctx context.Context, email string) (re } } -func (s *Service) recordLoginFailure(ctx context.Context, email, ip string) bool { - key := sha256.Sum256([]byte(strings.ToLower(strings.TrimSpace(email)) + "|" + ip)) +func (s *Service) reserveLoginAttempt(ctx context.Context, email string) (bool, error) { + key := loginFailureKey(email) now := s.deps.Clock().UTC() _ = s.gdb(ctx).Where("reset_at <= ?", now.Format(time.RFC3339Nano)).Delete(&models.AuthLoginFailure{}).Error reset := now.Add(15 * time.Minute).Format(time.RFC3339Nano) var count int err := s.gdb(ctx).Raw(`INSERT INTO auth_login_failures(key_hash,count,reset_at,updated_at) VALUES(?,1,?,?) ON CONFLICT(key_hash) DO UPDATE SET count=CASE WHEN auth_login_failures.reset_at<=excluded.updated_at THEN 1 ELSE auth_login_failures.count+1 END,reset_at=CASE WHEN auth_login_failures.reset_at<=excluded.updated_at THEN excluded.reset_at ELSE auth_login_failures.reset_at END,updated_at=excluded.updated_at RETURNING count`, hex.EncodeToString(key[:]), reset, now.Format(time.RFC3339Nano)).Scan(&count).Error - return err == nil && count > 8 + return count <= maxPasswordLoginAttempts, err } -func (s *Service) clearLoginFailures(ctx context.Context, email, ip string) { - key := sha256.Sum256([]byte(strings.ToLower(strings.TrimSpace(email)) + "|" + ip)) +func (s *Service) clearLoginFailures(ctx context.Context, email string) { + key := loginFailureKey(email) _ = s.gdb(ctx).Where("key_hash = ?", hex.EncodeToString(key[:])).Delete(&models.AuthLoginFailure{}).Error } +func (s *Service) allowPasswordReset(ctx context.Context, email, ip string) bool { + now := s.deps.Clock().UTC() + if err := s.gdb(ctx).Where("reset_at <= ?", now.Format(time.RFC3339Nano)).Delete(&models.AuthLoginFailure{}).Error; err != nil { + return false + } + limits := []struct { + key string + limit int + window time.Duration + }{ + {key: "password-reset:global", limit: passwordResetGlobalLimit, window: passwordResetGlobalWindow}, + {key: "password-reset:network:" + ip, limit: passwordResetNetworkLimit, window: passwordResetNetworkWindow}, + {key: "password-reset:account:" + strings.ToLower(strings.TrimSpace(email)), limit: passwordResetAccountLimit, window: passwordResetAccountWindow}, + } + for _, rate := range limits { + key := sha256.Sum256([]byte(rate.key)) + reset := now.Add(rate.window).Format(time.RFC3339Nano) + var count int + err := s.gdb(ctx).Raw(`INSERT INTO auth_login_failures(key_hash,count,reset_at,updated_at) VALUES(?,1,?,?) ON CONFLICT(key_hash) DO UPDATE SET count=CASE WHEN auth_login_failures.reset_at<=excluded.updated_at THEN 1 ELSE auth_login_failures.count+1 END,reset_at=CASE WHEN auth_login_failures.reset_at<=excluded.updated_at THEN excluded.reset_at ELSE auth_login_failures.reset_at END,updated_at=excluded.updated_at RETURNING count`, hex.EncodeToString(key[:]), reset, now.Format(time.RFC3339Nano)).Scan(&count).Error + if err != nil || count > rate.limit { + return false + } + } + return true +} + +func loginFailureKey(email string) [sha256.Size]byte { + return sha256.Sum256([]byte("account|" + strings.ToLower(strings.TrimSpace(email)))) +} func (s *Service) appendAuditTx(ctx context.Context, tx *sql.Tx, tenantID, action, actorID, targetType, targetID string, detail map[string]any) error { _, err := tx.ExecContext(ctx, s.q(`INSERT INTO security_audit_logs(id,tenant_id,action,actor_type,actor_id,target_type,target_id,detail_json,created_at) VALUES(?,?,?,'user',?,?,?,?,?)`), s.deps.NewID(), tenantID, action, actorID, targetType, targetID, encodeJSON(detail), s.now()) return err diff --git a/apps/server/internal/platform/identity/social_oauth.go b/apps/server/internal/platform/identity/social_oauth.go index fb73e7eb..5e006104 100644 --- a/apps/server/internal/platform/identity/social_oauth.go +++ b/apps/server/internal/platform/identity/social_oauth.go @@ -213,7 +213,7 @@ func (s *Service) completeOAuthLogin(w http.ResponseWriter, r *http.Request) { httpx.Error(w, 403, err.Error()) return } - result, err := s.socialAuthResult(r.Context(), user, tenant, role, requestIP(r), r.UserAgent()) + result, err := s.socialAuthResult(r.Context(), user, tenant, role, s.requestIP(r), r.UserAgent()) if err != nil { httpx.Error(w, 500, err.Error()) return @@ -301,7 +301,6 @@ func fetchGitHubEmail(ctx context.Context, client *http.Client, userinfoURL, tok for _, preference := range []func(emailRecord) bool{ func(item emailRecord) bool { return item.Primary && item.Verified }, func(item emailRecord) bool { return item.Verified }, - func(emailRecord) bool { return true }, } { for _, item := range list { email := strings.ToLower(strings.TrimSpace(item.Email)) @@ -318,10 +317,17 @@ func (s *Service) linkSocialIdentity(ctx context.Context, provider, subject, ema var identity models.OauthIdentity err := s.gdb(ctx).Select("user_id").Where("provider = ? AND provider_user_id = ?", provider, subject).Take(&identity).Error if errors.Is(err, gorm.ErrRecordNotFound) { - if !isSyntheticEmail(email) { + syntheticEmail := isSyntheticEmail(email) + if !syntheticEmail && !verified { + return User{}, Tenant{}, "", errors.New("OAuth provider did not verify the email address") + } + if !syntheticEmail { var existing models.User - if s.gdb(ctx).Select("id").Where("email = ?", email).Take(&existing).Error == nil { + lookupErr := s.gdb(ctx).Select("id").Where("email = ?", email).Take(&existing).Error + if lookupErr == nil { uid = derefString(existing.ID) + } else if !errors.Is(lookupErr, gorm.ErrRecordNotFound) { + return User{}, Tenant{}, "", lookupErr } } if uid == "" { diff --git a/apps/server/internal/platform/identity/sso.go b/apps/server/internal/platform/identity/sso.go index 5a2d95c4..ef277783 100644 --- a/apps/server/internal/platform/identity/sso.go +++ b/apps/server/internal/platform/identity/sso.go @@ -474,7 +474,7 @@ func (s *Service) verifyOIDCToken(ctx context.Context, cfg ssoConfig, raw, nonce return claims, nil } func (s *Service) finishSSOLogin(w http.ResponseWriter, r *http.Request, cfg ssoConfig, identity enterpriseSSOIdentity, email, name, protocol string) { - result, err := s.ssoLoginResult(r.Context(), cfg, identity, email, name, requestIP(r), r.UserAgent(), protocol) + result, err := s.ssoLoginResult(r.Context(), cfg, identity, email, name, s.requestIP(r), r.UserAgent(), protocol) if err != nil { status := http.StatusBadRequest if strings.Contains(err.Error(), "suspended") || strings.Contains(err.Error(), "not provisioned") || strings.Contains(err.Error(), "not linked") || strings.Contains(err.Error(), "not verified") { @@ -695,7 +695,7 @@ func (s *Service) samlACS(w http.ResponseWriter, r *http.Request) { s.samlFailure(w, r, err) return } - result, err := s.ssoLoginResult(r.Context(), cfg, identity, strings.ToLower(strings.TrimSpace(email)), name, requestIP(r), r.UserAgent(), "saml") + result, err := s.ssoLoginResult(r.Context(), cfg, identity, strings.ToLower(strings.TrimSpace(email)), name, s.requestIP(r), r.UserAgent(), "saml") if err != nil { s.samlFailure(w, r, err) return diff --git a/apps/server/internal/platform/identity/webauthn.go b/apps/server/internal/platform/identity/webauthn.go index fe5963e7..a3c71dec 100644 --- a/apps/server/internal/platform/identity/webauthn.go +++ b/apps/server/internal/platform/identity/webauthn.go @@ -467,13 +467,13 @@ func (s *Service) issuePasswordlessSession(w http.ResponseWriter, r *http.Reques } u := User{ID: derefString(dbUser.ID), Email: dbUser.Email, Name: derefString(dbUser.Name), IsPlatformAdmin: dbUser.IsPlatformAdmin, HasPassword: dbUser.PasswordHash != nil && *dbUser.PasswordHash != ""} u.EmailVerified = dbUser.EmailVerifiedAt != nil - token, err := s.issueSession(r.Context(), u, t, role, requestIP(r), r.UserAgent()) + token, err := s.issueSession(r.Context(), u, t, role, s.requestIP(r), r.UserAgent()) if err != nil { return err } now := s.now() _ = s.gdb(r.Context()).Model(&models.User{}).Where("id = ?", userID).Updates(map[string]any{"last_login_at": now, "updated_at": now}).Error - _ = s.Audit(r.Context(), t.ID, "auth.login", userID, "user", userID, map[string]any{"method": "passkey", "ip": requestIP(r)}) + _ = s.Audit(r.Context(), t.ID, "auth.login", userID, "user", userID, map[string]any{"method": "passkey", "ip": s.requestIP(r)}) s.recordLoginUsage(r.Context(), t.ID, userID, "passkey") httpx.JSON(w, 200, map[string]any{"session": token, "user": u, "tenant": t, "role": role, "multiTenant": s.deps.MultiTenant, "edition": s.deps.Edition}) return nil diff --git a/apps/server/internal/platform/migrations/migrate.go b/apps/server/internal/platform/migrations/migrate.go index a3f18ca4..dd222e2a 100644 --- a/apps/server/internal/platform/migrations/migrate.go +++ b/apps/server/internal/platform/migrations/migrate.go @@ -99,6 +99,9 @@ var workspaceAuthTargetsSQL string //go:embed sql/0029_workspace_node_removal.sql var workspaceNodeRemovalSQL string +//go:embed sql/0030_connector_oauth_states.sql +var connectorOAuthStatesSQL string + // postgres replaces sql on PostgreSQL when the dialects need different // statements rather than the textual type substitutions of postgresSchema. type migration struct { @@ -136,6 +139,7 @@ var ordered = []migration{ {27, "node_installations", nodeInstallationsSQL, ""}, {28, "workspace_auth_targets", workspaceAuthTargetsSQL, ""}, {29, "workspace_node_removal", workspaceNodeRemovalSQL, ""}, + {30, "connector_oauth_states", connectorOAuthStatesSQL, ""}, } func Apply(ctx context.Context, db *sql.DB, dialect string, rebind func(string) string) error { @@ -198,7 +202,7 @@ func ensureAdditiveCompatibility(ctx context.Context, db *sql.DB, dialect string } specs := []columnSpec{ {"platform_meta", "singleton", "INTEGER", "INTEGER"}, {"platform_meta", "settings_json", "TEXT NOT NULL DEFAULT '{}'", "TEXT NOT NULL DEFAULT '{}'"}, - {"users", "status", "TEXT NOT NULL DEFAULT 'active'", "TEXT NOT NULL DEFAULT 'active'"}, {"users", "avatar_mime", "TEXT", "TEXT"}, {"users", "avatar_data", "BLOB", "BYTEA"}, {"users", "totp_secret", "TEXT", "TEXT"}, {"users", "totp_pending_secret", "TEXT", "TEXT"}, {"users", "recovery_codes_json", "TEXT NOT NULL DEFAULT '[]'", "TEXT NOT NULL DEFAULT '[]'"}, {"users", "mfa_enabled", "INTEGER NOT NULL DEFAULT 0", "BOOLEAN NOT NULL DEFAULT FALSE"}, {"users", "email_mfa_enabled_at", "TIMESTAMP", "TIMESTAMPTZ"}, {"users", "suspended_reason", "TEXT", "TEXT"}, {"users", "suspended_by_user_id", "TEXT", "TEXT"}, + {"users", "status", "TEXT NOT NULL DEFAULT 'active'", "TEXT NOT NULL DEFAULT 'active'"}, {"users", "avatar_mime", "TEXT", "TEXT"}, {"users", "avatar_data", "BLOB", "BYTEA"}, {"users", "email_version", "INTEGER NOT NULL DEFAULT 1", "INTEGER NOT NULL DEFAULT 1"}, {"users", "totp_secret", "TEXT", "TEXT"}, {"users", "totp_pending_secret", "TEXT", "TEXT"}, {"users", "recovery_codes_json", "TEXT NOT NULL DEFAULT '[]'", "TEXT NOT NULL DEFAULT '[]'"}, {"users", "mfa_enabled", "INTEGER NOT NULL DEFAULT 0", "BOOLEAN NOT NULL DEFAULT FALSE"}, {"users", "email_mfa_enabled_at", "TIMESTAMP", "TIMESTAMPTZ"}, {"users", "suspended_reason", "TEXT", "TEXT"}, {"users", "suspended_by_user_id", "TEXT", "TEXT"}, {"tenants", "status", "TEXT NOT NULL DEFAULT 'active'", "TEXT NOT NULL DEFAULT 'active'"}, {"tenants", "mfa_policy", "TEXT NOT NULL DEFAULT 'optional'", "TEXT NOT NULL DEFAULT 'optional'"}, {"tenants", "audit_retention_days", "INTEGER NOT NULL DEFAULT 365", "INTEGER NOT NULL DEFAULT 365"}, {"tenants", "settings_json", "TEXT NOT NULL DEFAULT '{}'", "TEXT NOT NULL DEFAULT '{}'"}, {"tenants", "suspended_reason", "TEXT", "TEXT"}, {"tenants", "suspended_by_user_id", "TEXT", "TEXT"}, {"user_sessions", "token_hash", "TEXT", "TEXT"}, {"user_sessions", "last_seen_at", "TEXT", "TEXT"}, {"agents", "avatar_color", "TEXT", "TEXT"}, {"agents", "avatar_shape", "TEXT", "TEXT"}, {"agents", "avatar_url", "TEXT", "TEXT"}, diff --git a/apps/server/internal/platform/migrations/migrate_test.go b/apps/server/internal/platform/migrations/migrate_test.go index dac27a18..a40d0d5e 100644 --- a/apps/server/internal/platform/migrations/migrate_test.go +++ b/apps/server/internal/platform/migrations/migrate_test.go @@ -36,7 +36,7 @@ func TestApplyExtendsPinnedLegacyIdentityTables(t *testing.T) { } for table, columns := range map[string][]string{ "platform_meta": {"singleton", "settings_json"}, - "users": {"status", "avatar_data", "totp_secret"}, + "users": {"status", "avatar_data", "email_version", "totp_secret"}, "tenants": {"status", "mfa_policy", "audit_retention_days"}, "user_sessions": {"token_hash", "last_seen_at"}, "component_instances": {"agent_id", "component_type", "component_ref", "config_json", "secret_json"}, diff --git a/apps/server/internal/platform/migrations/sql/0001_platform.sql b/apps/server/internal/platform/migrations/sql/0001_platform.sql index 1890b18a..d57f8868 100644 --- a/apps/server/internal/platform/migrations/sql/0001_platform.sql +++ b/apps/server/internal/platform/migrations/sql/0001_platform.sql @@ -19,6 +19,7 @@ CREATE TABLE IF NOT EXISTS users ( avatar_data BLOB, avatar_updated_at TEXT, email_verified_at TEXT, + email_version INTEGER NOT NULL DEFAULT 1, totp_secret TEXT, totp_pending_secret TEXT, totp_enabled_at TEXT, diff --git a/apps/server/internal/platform/migrations/sql/0030_connector_oauth_states.sql b/apps/server/internal/platform/migrations/sql/0030_connector_oauth_states.sql new file mode 100644 index 00000000..449aa96e --- /dev/null +++ b/apps/server/internal/platform/migrations/sql/0030_connector_oauth_states.sql @@ -0,0 +1,12 @@ +CREATE TABLE connector_oauth_states ( + id TEXT PRIMARY KEY, + tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, + source_scope TEXT NOT NULL, + source_profile_id TEXT NOT NULL, + destination_scope TEXT NOT NULL, + destination_profile_id TEXT NOT NULL, + expires_at BIGINT NOT NULL, + created_at TEXT NOT NULL +); +-- statement-breakpoint +CREATE INDEX connector_oauth_states_expires_idx ON connector_oauth_states(expires_at); diff --git a/apps/server/internal/platform/server/router.go b/apps/server/internal/platform/server/router.go index 3f69db4a..3b2de657 100644 --- a/apps/server/internal/platform/server/router.go +++ b/apps/server/internal/platform/server/router.go @@ -63,7 +63,7 @@ func Router(cfg config.Config, d *appdeps.Dependencies, log *slog.Logger) http.H } func NewDependencies(cfg config.Config, db *sql.DB, dialect string, rebind func(string) string, gormDB *gorm.DB) *appdeps.Dependencies { - d := &appdeps.Dependencies{DB: db, Gorm: gormDB, Dialect: dialect, Rebind: rebind, Clock: time.Now, NewID: newID, Secret: []byte(cfg.Secret), PublicURL: cfg.PublicURL, WebURL: cfg.WebURL, DataDir: cfg.DataDir, Edition: cfg.Edition, MultiTenant: cfg.MultiTenant, VerifyDomain: VerifyDNSDomain} + d := &appdeps.Dependencies{DB: db, Gorm: gormDB, Dialect: dialect, Rebind: rebind, Clock: time.Now, NewID: newID, Secret: []byte(cfg.Secret), PublicURL: cfg.PublicURL, WebURL: cfg.WebURL, DataDir: cfg.DataDir, Edition: cfg.Edition, MultiTenant: cfg.MultiTenant, VerifyDomain: VerifyDNSDomain, TrustedProxyCIDRs: cfg.TrustedProxyCIDRs} d.OnTenantCreated = func(ctx context.Context, tenantID string) { _ = admin.SyncManagedWebDefaultsForTenant(ctx, d, tenantID) } diff --git a/apps/server/internal/platform/server/router_space_integrations_test.go b/apps/server/internal/platform/server/router_space_integrations_test.go index 2fb0da36..16e0d00d 100644 --- a/apps/server/internal/platform/server/router_space_integrations_test.go +++ b/apps/server/internal/platform/server/router_space_integrations_test.go @@ -44,7 +44,7 @@ func TestRouterZeroAgentConnectionUsesRegisteredRuntimeLifecycle(t *testing.T) { var sequence atomic.Int32 d := &appdeps.Dependencies{Context: ctx, DB: db, Gorm: gdb, Dialect: "sqlite", Rebind: appdeps.IdentityRebind, Clock: time.Now, NewID: func() string { return "router-" + time.Now().Format("150405.000000000") + string(rune(sequence.Add(1)+64)) - }, Secret: bytes.Repeat([]byte("k"), 32), PublicURL: "http://local.test"} + }, Secret: bytes.Repeat([]byte("k"), 32), PublicURL: "http://local.test", ProviderTestPrivate: true} now := time.Now().Format(time.RFC3339Nano) if _, e = db.Exec(`INSERT INTO tenants(id,slug,name,created_at,updated_at) VALUES('owner','owner','Owner',?,?)`, now, now); e != nil { t.Fatal(e) diff --git a/apps/server/internal/platform/system/routes.go b/apps/server/internal/platform/system/routes.go index 5266be1d..5580401f 100644 --- a/apps/server/internal/platform/system/routes.go +++ b/apps/server/internal/platform/system/routes.go @@ -23,6 +23,7 @@ import ( "github.com/Moonrend/Zakura/apps/server/internal/platform/appdeps" "github.com/Moonrend/Zakura/apps/server/internal/platform/db/models" "github.com/Moonrend/Zakura/apps/server/internal/platform/emailtmpl" + "github.com/Moonrend/Zakura/apps/server/internal/platform/emailverify" "github.com/Moonrend/Zakura/apps/server/internal/platform/httpx" "github.com/go-chi/chi/v5" "golang.org/x/crypto/scrypt" @@ -377,7 +378,7 @@ func (h *routes) requestVerifyEmail(w http.ResponseWriter, r *http.Request) { return } var user models.User - if err := h.d.Gorm.WithContext(r.Context()).Select("email,email_verified_at").Where("id=? AND status='active'", p.UserID).Take(&user).Error; err != nil { + if err := h.d.Gorm.WithContext(r.Context()).Select("email,email_version,email_verified_at").Where("id=? AND status='active'", p.UserID).Take(&user).Error; err != nil { httpx.Error(w, 404, "not found") return } @@ -389,7 +390,8 @@ func (h *routes) requestVerifyEmail(w http.ResponseWriter, r *http.Request) { sum := sha256.Sum256([]byte(raw)) id := h.d.NewID() userID := p.UserID - err := h.d.Gorm.WithContext(r.Context()).Create(&models.AuthToken{ID: &id, UserID: &userID, Kind: "email_verify", TokenHash: hex.EncodeToString(sum[:]), MetaJSON: "{}", ExpiresAt: h.d.Clock().UTC().Add(24 * time.Hour).Format(time.RFC3339Nano), CreatedAt: h.now()}).Error + email := emailverify.Normalize(user.Email) + err := h.d.Gorm.WithContext(r.Context()).Create(&models.AuthToken{ID: &id, UserID: &userID, Kind: "email_verify", TokenHash: hex.EncodeToString(sum[:]), MetaJSON: emailverify.Encode(email, user.EmailVersion), ExpiresAt: h.d.Clock().UTC().Add(24 * time.Hour).Format(time.RFC3339Nano), CreatedAt: h.now()}).Error if err != nil { httpx.Error(w, 500, "request failed") return @@ -399,7 +401,7 @@ func (h *routes) requestVerifyEmail(w http.ResponseWriter, r *http.Request) { verifyURL := h.d.WebURL + "/verify-email?token=" + url.QueryEscape(raw) htmlBody, textBody, renderErr := emailtmpl.Render(emailtmpl.VerifyEmail, emailtmpl.VerifyEmailData{VerifyURL: verifyURL}) if renderErr == nil { - sent = h.d.SendTransactionalEmail(r.Context(), user.Email, "验证你的 Zakura 邮箱", htmlBody, textBody) == nil + sent = h.d.SendTransactionalEmail(r.Context(), email, "验证你的 Zakura 邮箱", htmlBody, textBody) == nil } } httpx.JSON(w, 200, map[string]any{"sent": sent}) diff --git a/apps/server/internal/runtime/acp_runtime.go b/apps/server/internal/runtime/acp_runtime.go index 731a643a..6aefe881 100644 --- a/apps/server/internal/runtime/acp_runtime.go +++ b/apps/server/internal/runtime/acp_runtime.go @@ -441,6 +441,10 @@ func (m *acpRuntimeManager) start(ctx context.Context, tenantID, agentID, sid, p } startMethod, writeMethod, closeMethod = "docker.exec.start", "docker.exec.write", "docker.exec.close" params = map[string]any{"id": workspaceID, "command": argv, "workingDir": workingDir, "env": env} + } else { + // Legacy ACP startup is a trusted control-plane path. Interactive + // workspace terminals never receive this host-execution opt-in. + params["allowHostWorkspace"] = true } } var started struct { diff --git a/apps/server/internal/runtime/agent_loop.go b/apps/server/internal/runtime/agent_loop.go index 10f0876a..86f88502 100644 --- a/apps/server/internal/runtime/agent_loop.go +++ b/apps/server/internal/runtime/agent_loop.go @@ -569,8 +569,8 @@ func (s *Service) readModelRound(ctx context.Context, tenant, model string, payl } defer resp.Body.Close() if resp.Status < 200 || resp.Status >= 300 { - body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) - return modelRoundResult{}, &providerError{Status: resp.Status, Message: string(body), Retryable: resp.Status == 429 || resp.Status >= 500} + body, _ := io.ReadAll(io.LimitReader(resp.Body, maxProviderErrorResponse)) + return modelRoundResult{}, &providerError{Status: resp.Status, Message: gwTruncate(string(body), 1000), Retryable: resp.Status == 429 || resp.Status >= 500} } reader := bufio.NewReader(resp.Body) prefix, _ := reader.Peek(1) diff --git a/apps/server/internal/runtime/agent_tool_runners_web.go b/apps/server/internal/runtime/agent_tool_runners_web.go index d5f773e4..ea396540 100644 --- a/apps/server/internal/runtime/agent_tool_runners_web.go +++ b/apps/server/internal/runtime/agent_tool_runners_web.go @@ -12,6 +12,7 @@ import ( "io" "net" "net/http" + "net/netip" "net/url" "regexp" "strconv" @@ -32,11 +33,47 @@ const ( ) var ( - webSearchHTTPClient = &http.Client{Timeout: webSearchTimeout} - webFetchHTTPClient = &http.Client{Timeout: webFetchTimeout} - webSearchEngineIDs = []string{"tavily", "serper", "brave", "jina", "bing", "searxng"} + webSearchHTTPClient = &http.Client{Timeout: webSearchTimeout} + webFetchHTTPClient = &http.Client{Timeout: webFetchTimeout} + webFetchPublicHTTPClient = newPublicWebFetchHTTPClient( + net.DefaultResolver.LookupIPAddr, + (&net.Dialer{Timeout: webFetchTimeout, KeepAlive: 30 * time.Second}).DialContext, + ) + webSearchEngineIDs = []string{"tavily", "serper", "brave", "jina", "bing", "searxng"} + + errWebFetchPrivateAddress = errors.New("fetching private addresses is not allowed") + webFetchIPv6GlobalPrefix = netip.MustParsePrefix("2000::/3") + webFetchNAT64Prefix = netip.MustParsePrefix("64:ff9b::/96") + webFetchNonPublicPrefixes = []netip.Prefix{ + netip.MustParsePrefix("0.0.0.0/8"), + netip.MustParsePrefix("10.0.0.0/8"), + netip.MustParsePrefix("100.64.0.0/10"), + netip.MustParsePrefix("127.0.0.0/8"), + netip.MustParsePrefix("169.254.0.0/16"), + netip.MustParsePrefix("172.16.0.0/12"), + netip.MustParsePrefix("192.0.0.0/24"), + netip.MustParsePrefix("192.0.2.0/24"), + netip.MustParsePrefix("192.88.99.0/24"), + netip.MustParsePrefix("192.168.0.0/16"), + netip.MustParsePrefix("198.18.0.0/15"), + netip.MustParsePrefix("198.51.100.0/24"), + netip.MustParsePrefix("203.0.113.0/24"), + netip.MustParsePrefix("224.0.0.0/4"), + netip.MustParsePrefix("240.0.0.0/4"), + netip.MustParsePrefix("2001::/32"), + netip.MustParsePrefix("2001:2::/48"), + netip.MustParsePrefix("2001:10::/28"), + netip.MustParsePrefix("2001:20::/28"), + netip.MustParsePrefix("2001:db8::/32"), + netip.MustParsePrefix("2002::/16"), + netip.MustParsePrefix("3fff::/20"), + netip.MustParsePrefix("fec0::/10"), + } ) +type webFetchLookupIPAddr func(context.Context, string) ([]net.IPAddr, error) +type webFetchDialContext func(context.Context, string, string) (net.Conn, error) + type webSearchEngine struct { ID string APIKey string @@ -480,15 +517,10 @@ func (h *handler) runWebFetch(ctx context.Context, tenant, agent string, args js if err != nil { return nil, err } - if backend.ID == "native" && !backend.AllowPrivateHosts { - if err := rejectPrivateHost(parsedURL.Hostname()); err != nil { - return nil, err - } - } var content string switch backend.ID { case "native": - content, err = fetchNative(ctx, parsedURL, maxBytes) + content, err = fetchNative(ctx, parsedURL, maxBytes, backend.AllowPrivateHosts) case "jina-reader": content, err = fetchJinaReader(ctx, backend, rawURL) case "firecrawl": @@ -503,22 +535,96 @@ func (h *handler) runWebFetch(ctx context.Context, tenant, agent string, args js return json.RawMessage(text), nil } -func rejectPrivateHost(host string) error { - name := strings.ToLower(strings.Trim(strings.TrimSpace(host), "[]")) +func publicWebFetchIP(ip net.IP) bool { + address, ok := netip.AddrFromSlice(ip) + if !ok { + return false + } + address = address.Unmap() + if !address.IsGlobalUnicast() || address.IsPrivate() { + return false + } + if webFetchNAT64Prefix.Contains(address) { + bytes := address.As16() + return publicWebFetchIP(net.IPv4(bytes[12], bytes[13], bytes[14], bytes[15])) + } + if address.Is6() && !webFetchIPv6GlobalPrefix.Contains(address) { + return false + } + for _, prefix := range webFetchNonPublicPrefixes { + if prefix.Contains(address) { + return false + } + } + return true +} + +func resolvePublicWebFetchHost(ctx context.Context, host string, lookup webFetchLookupIPAddr) ([]net.IPAddr, error) { + name := strings.TrimSuffix(strings.ToLower(strings.Trim(strings.TrimSpace(host), "[]")), ".") if name == "" || name == "localhost" || strings.HasSuffix(name, ".localhost") { - return errors.New("fetching private addresses is not allowed") + return nil, errWebFetchPrivateAddress } - ip := net.ParseIP(name) - if ip == nil { - return nil + if ip := net.ParseIP(name); ip != nil { + if !publicWebFetchIP(ip) { + return nil, errWebFetchPrivateAddress + } + return []net.IPAddr{{IP: ip}}, nil } - if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsUnspecified() || ip.IsMulticast() { - return errors.New("fetching private addresses is not allowed") + addresses, err := lookup(ctx, name) + if err != nil { + return nil, fmt.Errorf("resolving web fetch host %q: %w", name, err) } - if v4 := ip.To4(); v4 != nil && v4[0] == 100 && v4[1] >= 64 && v4[1] <= 127 { - return errors.New("fetching private addresses is not allowed") + if len(addresses) == 0 { + return nil, fmt.Errorf("web fetch host %q did not resolve to an address", name) + } + for _, address := range addresses { + if !publicWebFetchIP(address.IP) { + return nil, errWebFetchPrivateAddress + } + } + return addresses, nil +} + +func newPublicWebFetchDialContext(lookup webFetchLookupIPAddr, dial webFetchDialContext) webFetchDialContext { + return func(ctx context.Context, network, address string) (net.Conn, error) { + host, port, err := net.SplitHostPort(address) + if err != nil { + return nil, fmt.Errorf("invalid web fetch address: %w", err) + } + addresses, err := resolvePublicWebFetchHost(ctx, host, lookup) + if err != nil { + return nil, err + } + var dialErr error + for _, resolved := range addresses { + connection, err := dial(ctx, network, net.JoinHostPort(resolved.IP.String(), port)) + if err == nil { + return connection, nil + } + dialErr = err + } + return nil, dialErr + } +} + +func newPublicWebFetchHTTPClient(lookup webFetchLookupIPAddr, dial webFetchDialContext) *http.Client { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + transport.Dial = nil + transport.DialContext = newPublicWebFetchDialContext(lookup, dial) + transport.DialTLS = nil + transport.DialTLSContext = nil + return &http.Client{ + Transport: transport, + Timeout: webFetchTimeout, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return errors.New("stopped after 10 redirects") + } + _, err := resolvePublicWebFetchHost(req.Context(), req.URL.Hostname(), lookup) + return err + }, } - return nil } var ( @@ -543,14 +649,18 @@ func htmlToText(input string) string { return strings.TrimSpace(text) } -func fetchNative(ctx context.Context, target *url.URL, maxBytes int) (string, error) { +func fetchNative(ctx context.Context, target *url.URL, maxBytes int, allowPrivateHosts bool) (string, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil) if err != nil { return "", err } req.Header.Set("User-Agent", webFetchUserAgent) req.Header.Set("Accept", "text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5") - resp, err := webFetchHTTPClient.Do(req) + client := webFetchPublicHTTPClient + if allowPrivateHosts { + client = webFetchHTTPClient + } + resp, err := client.Do(req) if err != nil { return "", err } diff --git a/apps/server/internal/runtime/agent_tool_runners_web_test.go b/apps/server/internal/runtime/agent_tool_runners_web_test.go index 20fc80d9..04b906f9 100644 --- a/apps/server/internal/runtime/agent_tool_runners_web_test.go +++ b/apps/server/internal/runtime/agent_tool_runners_web_test.go @@ -5,7 +5,9 @@ import ( "context" "encoding/base64" "encoding/json" + "errors" "fmt" + "net" "net/http" "net/http/httptest" "strings" @@ -310,19 +312,98 @@ func TestRunWebFetchNative(t *testing.T) { func TestRunWebFetchSSRF(t *testing.T) { h, agentID := newWebHandler(t) - for _, target := range []string{"http://127.0.0.1/x", "http://192.168.1.1/x", "http://localhost/x", "http://10.0.0.5/x", "http://169.254.1.1/x", "http://[::1]/x"} { + for _, target := range []string{"http://127.0.0.1/x", "http://192.168.1.1/x", "http://localhost/x", "http://10.0.0.5/x", "http://169.254.1.1/x", "http://[::1]/x", "http://[::ffff:127.0.0.1]/x"} { _, err := h.runWebFetch(context.Background(), "tenant", agentID, json.RawMessage(`{"url":"`+target+`"}`)) if err == nil || !strings.Contains(err.Error(), "private addresses is not allowed") { t.Fatalf("expected SSRF rejection for %s, got %v", target, err) } } - for _, host := range []string{"example.com", "8.8.8.8"} { - if err := rejectPrivateHost(host); err != nil { - t.Fatalf("public host %s should pass: %v", host, err) + for address, wantPublic := range map[string]bool{ + "8.8.8.8": true, + "2606:4700:4700::1111": true, + "10.0.0.5": false, + "100.64.0.1": false, + "192.0.2.1": false, + "198.18.0.1": false, + "224.0.0.1": false, + "fc00::1": false, + "2001:db8::1": false, + "2002:7f00:1::": false, + } { + if got := publicWebFetchIP(net.ParseIP(address)); got != wantPublic { + t.Fatalf("publicWebFetchIP(%s) = %v, want %v", address, got, wantPublic) } } } +func TestPublicWebFetchDialPinsResolvedAddress(t *testing.T) { + lookup := func(context.Context, string) ([]net.IPAddr, error) { + return []net.IPAddr{{IP: net.ParseIP("93.184.216.34")}}, nil + } + var dialedAddress string + var peer net.Conn + dial := newPublicWebFetchDialContext(lookup, func(_ context.Context, _ string, address string) (net.Conn, error) { + dialedAddress = address + connection, other := net.Pipe() + peer = other + return connection, nil + }) + connection, err := dial(context.Background(), "tcp", "example.com:443") + if err != nil { + t.Fatal(err) + } + defer connection.Close() + defer peer.Close() + if dialedAddress != "93.184.216.34:443" { + t.Fatalf("dialed address = %q", dialedAddress) + } +} + +func TestPublicWebFetchDialRejectsMixedDNS(t *testing.T) { + lookup := func(context.Context, string) ([]net.IPAddr, error) { + return []net.IPAddr{{IP: net.ParseIP("93.184.216.34")}, {IP: net.ParseIP("127.0.0.1")}}, nil + } + dialed := false + dial := newPublicWebFetchDialContext(lookup, func(context.Context, string, string) (net.Conn, error) { + dialed = true + return nil, errors.New("unexpected dial") + }) + _, err := dial(context.Background(), "tcp", "mixed.example:80") + if !errors.Is(err, errWebFetchPrivateAddress) || dialed { + t.Fatalf("mixed DNS answer was not rejected before dial: err=%v dialed=%v", err, dialed) + } +} + +func TestPublicWebFetchClientRevalidatesRedirects(t *testing.T) { + lookup := func(_ context.Context, host string) ([]net.IPAddr, error) { + if host == "redirect.example" { + return []net.IPAddr{{IP: net.ParseIP("10.0.0.5")}}, nil + } + return []net.IPAddr{{IP: net.ParseIP("93.184.216.34")}}, nil + } + client := newPublicWebFetchHTTPClient(lookup, func(context.Context, string, string) (net.Conn, error) { + return nil, errors.New("not used") + }) + redirect, err := http.NewRequest(http.MethodGet, "https://redirect.example/private", nil) + if err != nil { + t.Fatal(err) + } + if err = client.CheckRedirect(redirect, []*http.Request{{}}); !errors.Is(err, errWebFetchPrivateAddress) { + t.Fatalf("private redirect was not rejected: %v", err) + } + publicRedirect, err := http.NewRequest(http.MethodGet, "https://public.example/page", nil) + if err != nil { + t.Fatal(err) + } + if err = client.CheckRedirect(publicRedirect, []*http.Request{{}}); err != nil { + t.Fatalf("public redirect was rejected: %v", err) + } + transport, ok := client.Transport.(*http.Transport) + if !ok || transport.Proxy != nil || transport.Dial != nil || transport.DialContext == nil || transport.DialTLS != nil || transport.DialTLSContext != nil { + t.Fatalf("public web fetch transport permits proxy bypass: %#v", client.Transport) + } +} + func TestRunWebFetchJinaReader(t *testing.T) { h, agentID := newWebHandler(t) var gotPath string diff --git a/apps/server/internal/runtime/authz.go b/apps/server/internal/runtime/authz.go index bd349f73..8c39edaa 100644 --- a/apps/server/internal/runtime/authz.go +++ b/apps/server/internal/runtime/authz.go @@ -51,3 +51,15 @@ func RequireAPIScope(next http.Handler) http.Handler { func gatewayPrincipalAllowed(p httpx.Principal) bool { return p.APIKey && p.SpaceID != "" && apiKeyScopeAllows(p, "gateway", "gateway:models", "gateway:chat") } + +func providerAdminAllowed(p httpx.Principal) bool { + return !p.APIKey && (p.IsPlatformAdmin || p.Role == "owner" || p.Role == "admin") +} + +func requireProviderAdmin(w http.ResponseWriter, r *http.Request) bool { + if providerAdminAllowed(principal(r)) { + return true + } + httpx.Error(w, http.StatusForbidden, "Provider administration requires an owner or administrator") + return false +} diff --git a/apps/server/internal/runtime/builtins/skills/deliver-artifacts/SKILL.md b/apps/server/internal/runtime/builtins/skills/deliver-artifacts/SKILL.md index 3842d84a..ea6be8fa 100644 --- a/apps/server/internal/runtime/builtins/skills/deliver-artifacts/SKILL.md +++ b/apps/server/internal/runtime/builtins/skills/deliver-artifacts/SKILL.md @@ -10,11 +10,11 @@ description: 把工作区里的成果交到用户手上:生成文件下载链 ## 文件:临时下载链接 ``` -re_get_file_url path=/outputs/report.pdf ttl_minutes=1440 disposition=inline +re_get_file_url path=/outputs/chart.png ttl_minutes=1440 disposition=inline → https://… (持链接者可下载,到期或撤销后失效) ``` -- `disposition=inline`——图片、PDF 在浏览器里直接预览 +- `disposition=inline`——纯文本和 PNG、JPEG、GIF、WebP 等光栅图片可在浏览器里直接预览;HTML、SVG、PDF 等其他格式会强制下载 - `disposition=attachment`(默认)——触发下载 - `ttl_minutes`——默认 60 分钟,最长 7 天。按用户实际需要给,别一律给最长 - 上限 32MB;更大的文件先压缩,或改用端口暴露提供服务 diff --git a/apps/server/internal/runtime/codemode.go b/apps/server/internal/runtime/codemode.go index befefc6d..56faaa19 100644 --- a/apps/server/internal/runtime/codemode.go +++ b/apps/server/internal/runtime/codemode.go @@ -171,6 +171,11 @@ func (h *handler) runCodemodeTool(ctx context.Context, tenant, agent, session, t command := []string{"node", ".zakura/codemode/harness.mjs"} startMethod, writeMethod, closeMethod := "host.pty.start", "host.pty.write", "host.pty.close" params := map[string]any{"spaceId": remote.spaceID, "command": command, "workingDir": "/", "env": map[string]string{}, "cols": 120, "rows": 40} + if target.space.WorkspaceKind == "host" { + // Legacy code mode is a trusted control-plane path. Interactive + // workspace terminals never receive this host-execution opt-in. + params["allowHostWorkspace"] = true + } if target.container != "" { startMethod, writeMethod, closeMethod = "docker.exec.start", "docker.exec.write", "docker.exec.close" params = map[string]any{"id": target.container, "command": command, "workingDir": "/workspace", "env": map[string]string{}} diff --git a/apps/server/internal/runtime/computer_server_http.go b/apps/server/internal/runtime/computer_server_http.go index d942eee8..28374f6b 100644 --- a/apps/server/internal/runtime/computer_server_http.go +++ b/apps/server/internal/runtime/computer_server_http.go @@ -258,7 +258,7 @@ type workspaceRunnerError struct{ error } func (h *handler) serverComputerLifecycleError(w http.ResponseWriter, err error) { var runnerErr workspaceRunnerError switch { - case errors.Is(err, errWorkspaceNodeRequired), errors.Is(err, errWorkspaceStarting), errors.Is(err, errWorkspaceLeaseLost), errors.Is(err, workspaces.ErrConflict), errors.Is(err, workspaces.ErrTargetRevoked), errors.Is(err, workspaces.ErrUnverified): + case errors.Is(err, errWorkspaceNodeRequired), errors.Is(err, errWorkspaceStarting), errors.Is(err, errWorkspaceLeaseLost), errors.Is(err, errLegacyHostWorkspace), errors.Is(err, workspaces.ErrConflict), errors.Is(err, workspaces.ErrTargetRevoked), errors.Is(err, workspaces.ErrUnverified): httpx.Error(w, http.StatusConflict, err.Error()) case errors.As(err, &runnerErr): httpx.Error(w, http.StatusBadGateway, err.Error()) diff --git a/apps/server/internal/runtime/container_allocation_authorization_test.go b/apps/server/internal/runtime/container_allocation_authorization_test.go new file mode 100644 index 00000000..ba0787b6 --- /dev/null +++ b/apps/server/internal/runtime/container_allocation_authorization_test.go @@ -0,0 +1,45 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +package runtime + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Moonrend/Zakura/apps/server/internal/platform/httpx" + "github.com/go-chi/chi/v5" +) + +func TestContainerAllocationRequiresPlatformAdmin(t *testing.T) { + h := &handler{} + router := chi.NewRouter() + h.registerInstances(router) + h.registerWorkspace(router) + + request := func(path, body string, actor httpx.Principal) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req = req.WithContext(httpx.WithPrincipal(req.Context(), actor)) + response := httptest.NewRecorder() + router.ServeHTTP(response, req) + return response + } + + for _, path := range []string{ + "/containers/allocate", + "/runtime-nodes/node/containers/allocate", + } { + t.Run(path, func(t *testing.T) { + member := request(path, `{"image":"attacker/image","command":["sleep","infinity"]}`, httpx.Principal{TenantID: "tenant", Role: "member"}) + if member.Code != http.StatusForbidden { + t.Fatalf("member allocation status = %d, want %d", member.Code, http.StatusForbidden) + } + + admin := request(path, `{}`, httpx.Principal{TenantID: "tenant", Role: "owner", IsPlatformAdmin: true}) + if admin.Code != http.StatusBadRequest { + t.Fatalf("platform admin validation status = %d, want %d", admin.Code, http.StatusBadRequest) + } + }) + } +} diff --git a/apps/server/internal/runtime/file_share.go b/apps/server/internal/runtime/file_share.go index 31fd9a03..09a83252 100644 --- a/apps/server/internal/runtime/file_share.go +++ b/apps/server/internal/runtime/file_share.go @@ -7,6 +7,7 @@ import ( "encoding/base64" "encoding/hex" "errors" + "mime" "net/http" "os" "path/filepath" @@ -19,6 +20,39 @@ import ( "gorm.io/gorm" ) +func fileShareResponsePolicy(mimeType, disposition string) (string, string) { + mediaType, params, err := mime.ParseMediaType(mimeType) + if err != nil || mediaType == "" { + return "application/octet-stream", "attachment" + } + mediaType = strings.ToLower(mediaType) + normalized := mime.FormatMediaType(mediaType, params) + if normalized == "" { + return "application/octet-stream", "attachment" + } + if disposition != "inline" { + return normalized, "attachment" + } + switch mediaType { + case "image/avif", "image/bmp", "image/gif", "image/jpeg", "image/png", "image/webp", "image/x-icon", "text/plain": + return normalized, "inline" + default: + return normalized, "attachment" + } +} + +func setFileShareResponseHeaders(w http.ResponseWriter, mimeType, disposition, fileName string, size int64) string { + mimeType, disposition = fileShareResponsePolicy(mimeType, disposition) + safeName := strings.NewReplacer("\"", "_", "\r", "_", "\n", "_").Replace(fileName) + w.Header().Set("Content-Type", mimeType) + w.Header().Set("Content-Disposition", disposition+`; filename="`+safeName+`"`) + w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) + w.Header().Set("Cache-Control", "private, max-age=60") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Content-Security-Policy", "default-src 'none'; sandbox") + return safeName +} + func newShareToken() (string, string, error) { raw := make([]byte, 32) if _, e := rand.Read(raw); e != nil { @@ -44,9 +78,7 @@ func (h *handler) createFileShare(w http.ResponseWriter, r *http.Request) { httpx.Error(w, 400, "ttlMinutes exceeds 7 days") return } - if b.Disposition != "inline" { - b.Disposition = "attachment" - } + b.MimeType, b.Disposition = fileShareResponsePolicy(b.MimeType, b.Disposition) f, ok := h.fs(w, r) if !ok { return @@ -139,10 +171,6 @@ func (h *handler) downloadSharedFile(w http.ResponseWriter, r *http.Request) { return } _ = h.deps.Gorm.WithContext(r.Context()).Table("file_shares").Where("id = ?", row.ID).Updates(map[string]any{"download_count": gorm.Expr("download_count+1"), "updated_at": runtimeTimeString(h.store.now())}) - safe := strings.NewReplacer("\"", "_", "\r", "_", "\n", "_").Replace(row.Name) - w.Header().Set("Content-Type", row.Mime) - w.Header().Set("Content-Disposition", row.Disposition+`; filename="`+safe+`"`) - w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10)) - w.Header().Set("Cache-Control", "private, max-age=60") + safe := setFileShareResponseHeaders(w, row.Mime, row.Disposition, row.Name, info.Size()) http.ServeContent(w, r, safe, info.ModTime(), file) } diff --git a/apps/server/internal/runtime/gateway.go b/apps/server/internal/runtime/gateway.go index 531d31ed..7d6e35a1 100644 --- a/apps/server/internal/runtime/gateway.go +++ b/apps/server/internal/runtime/gateway.go @@ -9,23 +9,26 @@ import ( "errors" "fmt" "io" - "net" "net/http" "net/url" - "path" "strings" "sync" "time" ) -const maxProviderResponse = 64 << 20 +const ( + maxProviderResponse = 64 << 20 + maxProviderErrorResponse = 4 << 10 +) type Gateway struct { - store *Store - client *http.Client - captureSlots chan struct{} - captureMu sync.Mutex - captureTails map[*gatewayCapture]gatewayCaptureKey + store *Store + client *http.Client + providerClient *http.Client + allowPrivate bool + captureSlots chan struct{} + captureMu sync.Mutex + captureTails map[*gatewayCapture]gatewayCaptureKey } func NewGateway(store *Store) *Gateway { @@ -33,7 +36,8 @@ func NewGateway(store *Store) *Gateway { transport.MaxIdleConns = 256 transport.MaxIdleConnsPerHost = 64 transport.ResponseHeaderTimeout = 90 * time.Second - return &Gateway{store: store, client: &http.Client{Transport: transport}, captureSlots: make(chan struct{}, gatewayCaptureSlots)} + allowPrivate := store.deps.ProviderTestPrivate + return &Gateway{store: store, client: &http.Client{Transport: transport}, providerClient: newProviderHTTPClient(allowPrivate), allowPrivate: allowPrivate, captureSlots: make(chan struct{}, gatewayCaptureSlots)} } type upstreamConfig struct { @@ -149,25 +153,15 @@ func clientWithTimeout(client *http.Client, timeoutMs int) *http.Client { return &clone } -func safeProviderURL(baseURL, endpoint string) (*url.URL, error) { - u, err := url.Parse(baseURL) - if err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") { - return nil, errors.New("upstream baseUrl must be an absolute http(s) URL") - } - if u.User != nil { - return nil, errors.New("credentials in upstream URL are not allowed") - } - host := strings.Trim(u.Hostname(), "[]") - if ip := net.ParseIP(host); ip != nil && (ip.IsUnspecified() || ip.IsMulticast() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()) { - return nil, errors.New("unsafe upstream address") - } - basePath := strings.TrimSuffix(u.Path, "/") - if strings.HasPrefix(endpoint, "/v1/") && strings.HasSuffix(basePath, "/v1") { - endpoint = strings.TrimPrefix(endpoint, "/v1") +func (g *Gateway) providerURL(baseURL, endpoint string) (*url.URL, error) { + return providerURL(baseURL, endpoint, g.allowPrivate) +} + +func (g *Gateway) providerHTTPClient() *http.Client { + if g.providerClient != nil { + return g.providerClient } - u.Path = path.Join(basePath, endpoint) - u.RawPath = "" - return u, nil + return newProviderHTTPClient(false) } // endpointFor maps a client operation onto the upstream's native endpoint. The @@ -265,7 +259,7 @@ func (g *Gateway) doCandidate(ctx context.Context, tenant, operation string, ori if cfg.BaseURL == "" { return nil, errors.New("upstream baseUrl is not configured") } - u, err := safeProviderURL(cfg.BaseURL, endpointFor(upstream.Protocol, operation)) + u, err := g.providerURL(cfg.BaseURL, endpointFor(upstream.Protocol, operation)) if err != nil { return nil, err } @@ -273,7 +267,7 @@ func (g *Gateway) doCandidate(ctx context.Context, tenant, operation string, ori if err != nil { return nil, err } - client := clientWithTimeout(g.client, cfg.Timeout) + client := clientWithTimeout(g.providerHTTPClient(), cfg.Timeout) forwarded, _ := ctx.Value(gatewayClientHeadersKey{}).(http.Header) var lastErr error for attempt := 0; attempt < 3; attempt++ { diff --git a/apps/server/internal/runtime/gateway_http.go b/apps/server/internal/runtime/gateway_http.go index efebdd3a..6f98e0f2 100644 --- a/apps/server/internal/runtime/gateway_http.go +++ b/apps/server/internal/runtime/gateway_http.go @@ -51,12 +51,12 @@ func copyProviderResponse(w http.ResponseWriter, resp *ProviderResponse) error { } } if resp.Status < 200 || resp.Status >= 300 { - body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + body, err := io.ReadAll(io.LimitReader(resp.Body, maxProviderErrorResponse)) if err != nil { writeGatewayError(w, resp.Operation, http.StatusBadGateway, err.Error(), "upstream_error") return err } - message := gwOr(gwErrorMessage(body), http.StatusText(resp.Status)) + message := gwTruncate(gwOr(gwErrorMessage(body), http.StatusText(resp.Status)), 1000) if stream, ok := w.(*gatewayStreamWriter); ok { return stream.writeError(resp.Operation, resp.Status, message, "upstream_error") } @@ -137,7 +137,7 @@ func writeGatewayFailure(w http.ResponseWriter, operation string, err error) { var routeErr *gatewayRouteError if errors.As(err, &routeErr) && routeErr.Status > 0 { status = routeErr.Status - message = gwOr(gwErrorMessage(routeErr.Body), err.Error()) + message = gwTruncate(gwOr(gwErrorMessage(routeErr.Body), err.Error()), 1000) if routeErr.RetryAfter != "" { w.Header().Set("Retry-After", routeErr.RetryAfter) } diff --git a/apps/server/internal/runtime/gateway_perf_test.go b/apps/server/internal/runtime/gateway_perf_test.go index 4e2cb859..2d43a5c7 100644 --- a/apps/server/internal/runtime/gateway_perf_test.go +++ b/apps/server/internal/runtime/gateway_perf_test.go @@ -29,7 +29,7 @@ func BenchmarkGatewayCandidatePayload(b *testing.B) { })) defer upstream.Close() gateway := NewGateway(NewStore(testDepsTB(b))) - defer gateway.client.CloseIdleConnections() + defer gateway.providerHTTPClient().CloseIdleConnections() config := Upstream{Protocol: "openai", Config: raw(map[string]any{"baseUrl": upstream.URL})} route := ModelRoute{Model: "actual-model"} payload := []byte(`{"model":"alias","messages":[{"role":"user","content":"` + strings.Repeat("hello ", 10000) + `"}],"metadata":{"id":9007199254740993}}`) diff --git a/apps/server/internal/runtime/gateway_regression_test.go b/apps/server/internal/runtime/gateway_regression_test.go index feb6a04f..7728e11c 100644 --- a/apps/server/internal/runtime/gateway_regression_test.go +++ b/apps/server/internal/runtime/gateway_regression_test.go @@ -74,7 +74,7 @@ func TestGatewayHTTPStreamFlushesBeforeUpstreamFinishes(t *testing.T) { t.Fatal(err) } h := &handler{deps: d, store: store, service: NewService(store)} - defer h.service.gateway.client.CloseIdleConnections() + defer h.service.gateway.providerHTTPClient().CloseIdleConnections() proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r = r.WithContext(httpx.WithPrincipal(r.Context(), httpx.Principal{TenantID: "tenant", APIKey: true, SpaceID: space.ID, APIKeyScopes: `["gateway"]`})) h.gateway("chat", "chat")(w, r) @@ -171,7 +171,7 @@ func TestGatewayTransportRetryCancellation(t *testing.T) { defer cancel() var calls atomic.Int32 called := make(chan struct{}) - gateway := &Gateway{store: NewStore(testDeps(t)), client: &http.Client{Transport: gatewayRoundTripFunc(func(r *http.Request) (*http.Response, error) { + gateway := &Gateway{store: NewStore(testDeps(t)), providerClient: &http.Client{Transport: gatewayRoundTripFunc(func(r *http.Request) (*http.Response, error) { calls.Add(1) close(called) return nil, errors.New("dial failed") @@ -213,7 +213,7 @@ func TestGatewayFailedResponseDoesNotWaitForBody(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() gateway := NewGateway(store) - defer gateway.client.CloseIdleConnections() + defer gateway.providerHTTPClient().CloseIdleConnections() _, err = gateway.Do(ctx, "tenant", "chat", "chat", "m", []byte(`{}`)) if err == nil || ctx.Err() != nil || !strings.Contains(err.Error(), "HTTP 500") { t.Fatalf("blocked reading error body: %v", err) @@ -302,7 +302,7 @@ func TestGatewayHTTPResponseReadFailures(t *testing.T) { } h := &handler{deps: d, store: store, service: NewService(store)} var calls atomic.Int32 - h.service.gateway.client = &http.Client{Transport: gatewayRoundTripFunc(func(*http.Request) (*http.Response, error) { + h.service.gateway.providerClient = &http.Client{Transport: gatewayRoundTripFunc(func(*http.Request) (*http.Response, error) { calls.Add(1) contentType, prefix := "application/json", `{"partial":` if stream { diff --git a/apps/server/internal/runtime/gateway_transport.go b/apps/server/internal/runtime/gateway_transport.go index cc66eed4..642fd2df 100644 --- a/apps/server/internal/runtime/gateway_transport.go +++ b/apps/server/internal/runtime/gateway_transport.go @@ -100,7 +100,7 @@ func copyProviderStream(w http.ResponseWriter, body io.Reader) error { func readGatewayErrorBody(ctx context.Context, body io.ReadCloser) []byte { done := make(chan []byte, 1) go func() { - data, _ := io.ReadAll(io.LimitReader(body, 1<<20)) + data, _ := io.ReadAll(io.LimitReader(body, maxProviderErrorResponse)) done <- data }() timer := time.NewTimer(100 * time.Millisecond) diff --git a/apps/server/internal/runtime/http.go b/apps/server/internal/runtime/http.go index c761126b..fba92fed 100644 --- a/apps/server/internal/runtime/http.go +++ b/apps/server/internal/runtime/http.go @@ -42,10 +42,11 @@ type handler struct { loadedToolCache map[string]cachedLoaded trigramMu sync.Mutex trigramStates map[string]string + otelLimits *otelLimiter } func RegisterRoutes(r chi.Router, deps *appdeps.Dependencies) MCPInstanceLifecycle { - h := &handler{deps: deps, store: NewStore(deps), mcpSessions: map[string]spaceMCPSession{}} + h := &handler{deps: deps, store: NewStore(deps), mcpSessions: map[string]spaceMCPSession{}, otelLimits: newOTelLimiter()} if err := h.store.protectStoredAgentApprovals(deps.RunContext()); err != nil { panic(fmt.Errorf("initialize tool approval protection: %w", err)) } @@ -91,7 +92,7 @@ func RegisterRoutes(r chi.Router, deps *appdeps.Dependencies) MCPInstanceLifecyc r.Get("/api/runtime-nodes/{id}/install.ps1", h.runtimeInstallPS) r.Get("/api/runtime-nodes/{id}/bootstrap.sh", h.runtimeBootstrapSh) r.Get("/api/otel/config", h.getOTelConfig) - r.Post("/api/otel/v1/logs", h.ingestOTelLogs) + r.With(httpx.Auth(deps), RequireAPIScope).Post("/api/otel/v1/logs", h.ingestOTelLogs) r.Get("/api/zakurabot/ws", h.zakuraBotWS) r.Get("/api/agents/{id}/desktop-proxy", h.desktopProxy) r.Get("/api/agents/{id}/terminal-proxy", h.terminalProxy) @@ -235,7 +236,7 @@ func decodeMap(r *http.Request) (map[string]any, error) { } func statusErr(w http.ResponseWriter, e error) { switch { - case errors.Is(e, errLocalRunnerForbidden): + case errors.Is(e, errLocalRunnerForbidden), errors.Is(e, errStdioOCIPlatformAdminRequired): httpx.Error(w, 403, e.Error()) case errors.Is(e, ErrNotFound): httpx.Error(w, 404, "Not found") @@ -1209,6 +1210,9 @@ func (h *handler) listUpstreams(w http.ResponseWriter, r *http.Request) { httpx.JSON(w, 200, map[string]any{"upstreams": x}) } func (h *handler) createUpstream(w http.ResponseWriter, r *http.Request) { + if !requireProviderAdmin(w, r) { + return + } var in Upstream if httpx.DecodeJSON(r, &in) != nil { httpx.Error(w, 400, "invalid JSON") diff --git a/apps/server/internal/runtime/instances.go b/apps/server/internal/runtime/instances.go index 2b82d862..b4ec5830 100644 --- a/apps/server/internal/runtime/instances.go +++ b/apps/server/internal/runtime/instances.go @@ -275,6 +275,22 @@ func (h *handler) createInstance(w http.ResponseWriter, r *http.Request) { if body.Type == "mcp" { configValues := map[string]any{} _ = json.Unmarshal([]byte(configPlain), &configValues) + command, packageManager, _, hasCommand, controlErr := stdioConfigControls(json.RawMessage(configPlain)) + if controlErr != nil { + httpx.Error(w, http.StatusBadRequest, controlErr.Error()) + return + } + delete(configValues, stdioOCIApprovalKey) + if hasCommand && command != "" { + approved, approvalErr := authorizeStdioOCI(p, command, packageManager) + if approvalErr != nil { + statusErr(w, approvalErr) + return + } + if approved { + configValues[stdioOCIApprovalKey] = true + } + } if configured, _ := configValues["ownerSpaceId"].(string); configured != "" { if owner != "" && owner != configured { httpx.Error(w, 400, "conflicting Space ownership") @@ -390,7 +406,7 @@ func (h *handler) patchInstance(w http.ResponseWriter, r *http.Request) { statusErr(w, e) return } - config, secret, e := h.PatchMCPConfig(r.Context(), p.TenantID, id, raw) + config, secret, e := h.patchMCPConfig(r.Context(), p.TenantID, id, raw, p) if e != nil { statusErr(w, e) return @@ -1187,6 +1203,11 @@ func (h *handler) listContainers(w http.ResponseWriter, r *http.Request) { httpx.JSON(w, http.StatusOK, out) } func (h *handler) allocateContainer(w http.ResponseWriter, r *http.Request) { + p := principal(r) + if !p.IsPlatformAdmin { + httpx.Error(w, http.StatusForbidden, "platform admin required") + return + } var b struct { InstanceID, SpaceID, AgentID *string RuntimeNodeID *string `json:"runtimeNodeId"` @@ -1207,7 +1228,6 @@ func (h *handler) allocateContainer(w http.ResponseWriter, r *http.Request) { httpx.Error(w, 400, "invalid container name") return } - p := principal(r) if b.RuntimeNodeID == nil || *b.RuntimeNodeID == "" { var nodeRow struct { NodeID *string `gorm:"column:runtime_node_id"` diff --git a/apps/server/internal/runtime/jev_evaluation.go b/apps/server/internal/runtime/jev_evaluation.go index 7c9224bb..c6b79c18 100644 --- a/apps/server/internal/runtime/jev_evaluation.go +++ b/apps/server/internal/runtime/jev_evaluation.go @@ -71,7 +71,7 @@ func (g *Gateway) evaluateApproval(ctx context.Context, tenant, selected string, if cfg.APIKey == "" { return nil, errors.New("Jev credential is not configured") } - target, err := safeProviderURL(firstNonEmpty(cfg.BaseURL, jevDefaultBaseURL), "/v1/systemone") + target, err := g.providerURL(firstNonEmpty(cfg.BaseURL, jevDefaultBaseURL), "/v1/systemone") if err != nil { return nil, err } @@ -114,7 +114,7 @@ func (g *Gateway) evaluateApproval(ctx context.Context, tenant, selected string, timeout = 30000 } started := time.Now() - resp, err := clientWithTimeout(g.client, timeout).Do(req) + resp, err := clientWithTimeout(g.providerHTTPClient(), timeout).Do(req) if err != nil { if ctx.Err() != nil { return nil, ctx.Err() diff --git a/apps/server/internal/runtime/jev_evaluation_test.go b/apps/server/internal/runtime/jev_evaluation_test.go index 5d7c3694..45fce026 100644 --- a/apps/server/internal/runtime/jev_evaluation_test.go +++ b/apps/server/internal/runtime/jev_evaluation_test.go @@ -253,7 +253,7 @@ func TestJevEvaluationCancellation(t *testing.T) { func TestJevHTTPProviderCredentialContract(t *testing.T) { d := testDeps(t) - token := seedTenant(t, d, "tenant") + token := seedProviderAdmin(t, d, "tenant") router := chi.NewRouter() RegisterRoutes(router, d) server := httptest.NewServer(router) diff --git a/apps/server/internal/runtime/mcp.go b/apps/server/internal/runtime/mcp.go index e20301b4..e7489b5a 100644 --- a/apps/server/internal/runtime/mcp.go +++ b/apps/server/internal/runtime/mcp.go @@ -9,10 +9,13 @@ import ( "errors" "fmt" "io" + "net" "net/http" + "net/netip" "net/url" "os" "slices" + "strconv" "strings" "time" @@ -36,6 +39,34 @@ type rpcEnvelope struct { Params any `json:"params,omitempty"` } +const ( + maxMCPResponseBytes = 16 << 20 + maxMCPErrorBytes = 4 << 10 + maxMCPErrorText = 512 +) + +func boundedMCPErrorDetail(raw []byte) string { + detail := strings.Join(strings.Fields(string(raw)), " ") + return gwTruncate(detail, maxMCPErrorText) +} + +func sanitizeMCPProbeHeaders(headers map[string]string) (map[string]string, error) { + clean := make(map[string]string, len(headers)) + for key, value := range headers { + canonical := http.CanonicalHeaderKey(strings.TrimSpace(key)) + switch canonical { + case "Authorization", "Api-Key", "X-Api-Key": + default: + return nil, fmt.Errorf("probe header %q is not allowed", key) + } + if strings.ContainsAny(value, "\r\n") { + return nil, fmt.Errorf("probe header %q has an invalid value", key) + } + clean[canonical] = value + } + return clean, nil +} + func (h *handler) protectMCPConfig(id string, raw json.RawMessage) (string, string, error) { config := map[string]any{} if len(raw) > 0 && json.Unmarshal(raw, &config) != nil { @@ -177,6 +208,9 @@ func (h *handler) getMCPInstance(ctx context.Context, tenant, id string) (mcpIns return x, e } func (h *handler) mcpRPC(ctx context.Context, inst mcpInstance, method string, params any) (json.RawMessage, error) { + if err := requireStdioOCIConfigApproval(inst.Config); err != nil { + return nil, err + } var cfg struct { URL string `json:"url"` RuntimeNodeID string `json:"runtimeNodeId"` @@ -227,13 +261,11 @@ func (h *handler) mcpRPC(ctx context.Context, inst mcpInstance, method string, p return nil, errors.New("invalid MCP credential payload") } } - u, e := url.Parse(cfg.URL) - if e != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") { - return nil, errors.New("invalid MCP URL") - } var safe *url.URL + client := h.service.gateway.providerHTTPClient() + var e error if cfg.RuntimeNodeID == "" { - safe, e = safeProviderURL(cfg.URL, "") + safe, e = h.providerURL(cfg.URL, "") if e != nil { return nil, e } @@ -255,10 +287,18 @@ func (h *handler) mcpRPC(ctx context.Context, inst mcpInstance, method string, p _ = json.Unmarshal([]byte(hostInfo), &reported) primary, _ := reported["primaryIp"].(string) hostname, _ := reported["hostname"].(string) - if !strings.EqualFold(u.Hostname(), primary) && !strings.EqualFold(u.Hostname(), hostname) { + safe, e = providerURL(cfg.URL, "", true) + if e != nil { + return nil, errors.New("invalid runtime MCP URL") + } + if !strings.EqualFold(safe.Hostname(), primary) && !strings.EqualFold(safe.Hostname(), hostname) { return nil, errors.New("MCP URL does not match its runtime node") } - safe = u + primaryIP, parseErr := netip.ParseAddr(strings.Trim(strings.TrimSpace(primary), "[]")) + if parseErr != nil || primaryIP.Zone() != "" || !primaryIP.IsValid() || primaryIP.IsUnspecified() || primaryIP.IsMulticast() { + return nil, errors.New("MCP runtime node has no usable primary address") + } + client = newPinnedProviderHTTPClient(primaryIP) } type callResult struct { result json.RawMessage @@ -306,18 +346,31 @@ func (h *handler) mcpRPC(ctx context.Context, inst mcpInstance, method string, p if token != "" { req.Header.Set("Authorization", "Bearer "+token) } - resp, err := h.service.gateway.client.Do(req) + resp, err := client.Do(req) if err != nil { return callResult{}, err } - raw, readErr := io.ReadAll(io.LimitReader(resp.Body, 16<<20)) + limit := int64(maxMCPResponseBytes) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + limit = maxMCPErrorBytes + } + raw, readErr := io.ReadAll(io.LimitReader(resp.Body, limit+1)) _ = resp.Body.Close() + if int64(len(raw)) > limit { + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + return callResult{}, errors.New("MCP response exceeds size limit") + } + raw = raw[:limit] + } result := callResult{sid: resp.Header.Get("Mcp-Session-Id"), status: resp.StatusCode, body: raw} if readErr != nil { return result, readErr } if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return result, fmt.Errorf("MCP status %d: %s", resp.StatusCode, string(raw)) + if detail := boundedMCPErrorDetail(raw); detail != "" { + return result, fmt.Errorf("MCP status %d: %s", resp.StatusCode, detail) + } + return result, fmt.Errorf("MCP status %d", resp.StatusCode) } if notification || len(bytes.TrimSpace(raw)) == 0 { return result, nil @@ -341,7 +394,7 @@ func (h *handler) mcpRPC(ctx context.Context, inst mcpInstance, method string, p return result, errors.New("invalid MCP JSON-RPC response") } if out.Error != nil { - return result, fmt.Errorf("MCP %d: %s", out.Error.Code, out.Error.Message) + return result, fmt.Errorf("MCP %d: %s", out.Error.Code, boundedMCPErrorDetail([]byte(out.Error.Message))) } result.result = out.Result return result, nil @@ -385,7 +438,7 @@ func (h *handler) mcpRPC(ctx context.Context, inst mcpInstance, method string, p if token != "" { req.Header.Set("Authorization", "Bearer "+token) } - if resp, err := h.service.gateway.client.Do(req); err == nil { + if resp, err := client.Do(req); err == nil { _ = resp.Body.Close() } }() @@ -568,6 +621,9 @@ func (h *handler) deleteMCPPolicy(w http.ResponseWriter, r *http.Request) { httpx.JSON(w, 200, map[string]any{"ok": true}) } func (h *handler) probeMCP(w http.ResponseWriter, r *http.Request) { + if !requireProviderAdmin(w, r) { + return + } var b struct { URL string `json:"url"` Headers map[string]string `json:"headers"` @@ -576,7 +632,12 @@ func (h *handler) probeMCP(w http.ResponseWriter, r *http.Request) { httpx.Error(w, 400, "url required") return } - cfg, _ := json.Marshal(map[string]any{"url": b.URL, "headers": b.Headers}) + headers, err := sanitizeMCPProbeHeaders(b.Headers) + if err != nil { + httpx.Error(w, http.StatusBadRequest, err.Error()) + return + } + cfg, _ := json.Marshal(map[string]any{"url": b.URL, "headers": headers}) result, e := h.mcpRPC(r.Context(), mcpInstance{ID: "probe", Config: cfg, Secret: json.RawMessage(`{}`)}, "initialize", map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{}, "clientInfo": map[string]any{"name": "zakura", "version": "go-rewrite"}}) if e != nil { statusErr(w, e) @@ -603,9 +664,98 @@ type stdioImportBody struct { Headers map[string]string `json:"headers"` Args []string `json:"args"` Env map[string]string `json:"env"` + OCIPlatformApproved bool `json:"-"` +} + +const stdioOCIApprovalKey = "ociPlatformApproved" + +var errStdioOCIPlatformAdminRequired = errors.New("OCI stdio MCP requires platform administrator approval") + +var stdioConfigControlKeys = []string{"command", "args", "env", "workingDir", "packageManager", "bridgeImage", stdioOCIApprovalKey} + +func stdioPackageManager(command, configured string) string { + packageManager := strings.ToLower(strings.TrimSpace(configured)) + if packageManager == "" { + if command == "docker" || command == "podman" { + return "oci" + } + return "npm" + } + return packageManager +} + +func authorizeStdioOCI(p httpx.Principal, command, packageManager string) (bool, error) { + if stdioPackageManager(command, packageManager) != "oci" { + return false, nil + } + if !p.IsPlatformAdmin { + return false, errStdioOCIPlatformAdminRequired + } + return true, nil +} + +func requireStdioOCIApproval(body stdioImportBody) error { + if stdioPackageManager(body.Command, body.PackageManager) == "oci" && !body.OCIPlatformApproved { + return errStdioOCIPlatformAdminRequired + } + return nil +} + +func validateStdioConfigControlKeys(cfg map[string]any) error { + for key := range cfg { + for _, canonical := range stdioConfigControlKeys { + if key != canonical && strings.EqualFold(key, canonical) { + return fmt.Errorf("stdio config field %s must use its canonical name", canonical) + } + } + } + return nil +} + +func stdioConfigControls(raw json.RawMessage) (command, packageManager string, approved, hasCommand bool, err error) { + var cfg map[string]any + if json.Unmarshal(raw, &cfg) != nil { + return "", "", false, false, errors.New("invalid MCP config") + } + if err = validateStdioConfigControlKeys(cfg); err != nil { + return "", "", false, false, err + } + commandValue, hasCommand := cfg["command"] + if !hasCommand { + return "", "", false, false, nil + } + command, valid := commandValue.(string) + if !valid { + return "", "", false, true, errors.New("invalid stdio MCP command") + } + if value, ok := cfg["packageManager"]; ok && value != nil { + packageManager, valid = value.(string) + if !valid { + return "", "", false, true, errors.New("invalid stdio MCP packageManager") + } + } + if value, ok := cfg[stdioOCIApprovalKey]; ok { + approved, valid = value.(bool) + if !valid { + return "", "", false, true, errors.New("invalid OCI platform approval") + } + } + return command, packageManager, approved, true, nil +} + +func requireStdioOCIConfigApproval(raw json.RawMessage) error { + command, packageManager, approved, hasCommand, err := stdioConfigControls(raw) + if err != nil || !hasCommand || command == "" { + return err + } + return requireStdioOCIApproval(stdioImportBody{Command: command, PackageManager: packageManager, OCIPlatformApproved: approved}) } func stdioBodyFromConfig(raw json.RawMessage) (stdioImportBody, bool) { + command, packageManager, approved, hasCommand, err := stdioConfigControls(raw) + if err != nil || !hasCommand || command == "" { + return stdioImportBody{}, false + } var cfg struct { Command string `json:"command"` Args []string `json:"args"` @@ -615,11 +765,11 @@ func stdioBodyFromConfig(raw json.RawMessage) (stdioImportBody, bool) { RuntimeNodeID string `json:"runtimeNodeId"` BridgeImage string `json:"bridgeImage"` } - if json.Unmarshal(raw, &cfg) != nil || cfg.Command == "" { + if json.Unmarshal(raw, &cfg) != nil { return stdioImportBody{}, false } node := cfg.RuntimeNodeID - return stdioImportBody{Command: cfg.Command, Args: cfg.Args, Env: cfg.Env, WorkingDir: cfg.WorkingDir, PackageManager: cfg.PackageManager, RuntimeNodeID: &node, Image: cfg.BridgeImage}, true + return stdioImportBody{Command: command, Args: cfg.Args, Env: cfg.Env, WorkingDir: cfg.WorkingDir, PackageManager: packageManager, RuntimeNodeID: &node, Image: cfg.BridgeImage, OCIPlatformApproved: approved}, true } func (h *handler) stdioBodyForInstance(instance mcpInstance) (stdioImportBody, bool, error) { @@ -688,6 +838,13 @@ func (h *handler) installMCP(ctx context.Context, p httpx.Principal, body stdioI if body.Command != "" && body.URL != "" { return nil, errors.New("choose command or url, not both") } + if body.Command != "" { + approved, err := authorizeStdioOCI(p, body.Command, body.PackageManager) + if err != nil { + return nil, err + } + body.OCIPlatformApproved = approved + } if body.Command != "" && body.Image != "" && !p.IsPlatformAdmin && p.Role != "owner" && p.Role != "admin" { return nil, errors.New("custom stdio images require an administrator") } @@ -729,7 +886,7 @@ func (h *handler) installMCP(ctx context.Context, p httpx.Principal, body stdioI return nil, errors.New("stdio MCP requires exactly one owning Space") } if body.URL != "" { - if _, err := safeProviderURL(body.URL, ""); err != nil { + if _, err := h.providerURL(body.URL, ""); err != nil { return nil, err } } @@ -756,6 +913,9 @@ func (h *handler) installMCP(ctx context.Context, p httpx.Principal, body stdioI return nil, errors.New("stdio runtime node must be the owning Space server computer") } cfg = map[string]any{"ownerSpaceId": spaces[0], "serverComputerId": exec.computer.ID, "command": body.Command, "args": body.Args, "workingDir": body.WorkingDir, "packageManager": body.PackageManager, "bridgeImage": body.Image} + if body.OCIPlatformApproved { + cfg[stdioOCIApprovalKey] = true + } } envKeys := make([]string, 0, len(body.Env)) for key := range body.Env { @@ -863,13 +1023,9 @@ func (h *handler) provisionStdioMCPWithLease(ctx context.Context, tenant, instan return err } remote := h.executionRemote(runner, exec) - packageManager := strings.ToLower(strings.TrimSpace(body.PackageManager)) - if packageManager == "" { - if body.Command == "docker" || body.Command == "podman" { - packageManager = "oci" - } else { - packageManager = "npm" - } + packageManager := stdioPackageManager(body.Command, body.PackageManager) + if err = requireStdioOCIApproval(body); err != nil { + return err } if exec.workspace != nil && packageManager == "oci" { return errors.New("OCI stdio MCP is unavailable on managed disks because nested Docker writers are not tracked") @@ -1005,15 +1161,13 @@ func (h *handler) provisionStdioMCPWithLease(ctx context.Context, tenant, instan if port == 0 { return cleanup(errors.New("runner did not publish stdio bridge port")) } - hostname, _ := host["primaryIp"].(string) - if hostname == "" { - hostname, _ = host["hostname"].(string) + primary, _ := host["primaryIp"].(string) + primaryIP, parseErr := netip.ParseAddr(strings.Trim(strings.TrimSpace(primary), "[]")) + if parseErr != nil || primaryIP.Zone() != "" || !primaryIP.IsValid() || primaryIP.IsUnspecified() || primaryIP.IsMulticast() { + return cleanup(errors.New("runtime node did not report a usable primary address")) } - if hostname == "" { - return cleanup(errors.New("runtime node did not report an address")) - } - endpoint := fmt.Sprintf("http://%s:%d/mcp", hostname, port) - if err = h.probeStdioBridge(ctx, endpoint); err != nil { + endpoint := "http://" + net.JoinHostPort(primaryIP.Unmap().String(), strconv.Itoa(port)) + "/mcp" + if err = h.probeStdioBridge(ctx, endpoint, newPinnedProviderHTTPClient(primaryIP)); err != nil { return cleanup(fmt.Errorf("stdio bridge readiness failed: %w", err)) } envKeys := make([]string, 0, len(body.Env)) @@ -1022,6 +1176,9 @@ func (h *handler) provisionStdioMCPWithLease(ctx context.Context, tenant, instan } slices.Sort(envKeys) config := map[string]any{"url": endpoint, "ownerSpaceId": owner, "serverComputerId": exec.computer.ID, "runtimeNodeId": nodeID, "dataSpaceId": dataSpaceID, "dataPath": dataPath, "command": body.Command, "args": body.Args, "environmentVariables": envKeys, "workingDir": body.WorkingDir, "packageManager": packageManager, "bridgeImage": image} + if body.OCIPlatformApproved { + config[stdioOCIApprovalKey] = true + } if exec.workspace != nil { config["workspaceTarget"] = exec.workspace.Target } @@ -1045,7 +1202,7 @@ func (h *handler) provisionStdioMCPWithLease(ctx context.Context, tenant, instan return nil } -func (h *handler) probeStdioBridge(ctx context.Context, endpoint string) error { +func (h *handler) probeStdioBridge(ctx context.Context, endpoint string, client *http.Client) error { base := strings.TrimSuffix(endpoint, "/mcp") var last error for attempt := 0; attempt < 20; attempt++ { @@ -1058,7 +1215,7 @@ func (h *handler) probeStdioBridge(ctx context.Context, endpoint string) error { } callCtx, cancel := context.WithTimeout(ctx, 2*time.Second) req, _ := http.NewRequestWithContext(callCtx, http.MethodGet, base+"/health", nil) - resp, err := h.service.gateway.client.Do(req) + resp, err := client.Do(req) if err == nil { _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20)) _ = resp.Body.Close() @@ -1088,7 +1245,7 @@ func (h *handler) probeStdioBridge(ctx context.Context, endpoint string) error { if sid != "" { req.Header.Set("Mcp-Session-Id", sid) } - resp, err := h.service.gateway.client.Do(req) + resp, err := client.Do(req) if err != nil { return nil, nil, err } @@ -1124,7 +1281,7 @@ func (h *handler) probeStdioBridge(ctx context.Context, endpoint string) error { defer cancel() req, _ := http.NewRequestWithContext(cleanupCtx, http.MethodDelete, endpoint, nil) req.Header.Set("Mcp-Session-Id", sid) - if resp, err := h.service.gateway.client.Do(req); err == nil { + if resp, err := client.Do(req); err == nil { _ = resp.Body.Close() } }() diff --git a/apps/server/internal/runtime/mcp_extra.go b/apps/server/internal/runtime/mcp_extra.go index 20c1aa68..94ebe13b 100644 --- a/apps/server/internal/runtime/mcp_extra.go +++ b/apps/server/internal/runtime/mcp_extra.go @@ -207,13 +207,13 @@ func (h *handler) syncMCPStore(w http.ResponseWriter, r *http.Request) { synced := 0 failed := map[string]string{} for _, s := range sources { - target, e := safeProviderURL(s.URL, "") + target, e := h.providerURL(s.URL, "") if e != nil { failed[s.ID] = e.Error() continue } req, _ := http.NewRequestWithContext(r.Context(), http.MethodGet, target.String(), nil) - resp, e := h.service.gateway.client.Do(req) + resp, e := h.service.gateway.providerHTTPClient().Do(req) if e != nil { failed[s.ID] = e.Error() continue @@ -312,7 +312,7 @@ func (h *handler) mcpOAuthStart(w http.ResponseWriter, r *http.Request) { return } } - mcpURL, e := safeProviderURL(b.MCPURL, "") + mcpURL, e := h.providerURL(b.MCPURL, "") if e != nil { statusErr(w, e) return @@ -321,7 +321,7 @@ func (h *handler) mcpOAuthStart(w http.ResponseWriter, r *http.Request) { u, _ := url.Parse(mcpURL.String()) metadataURL := u.Scheme + "://" + u.Host + "/.well-known/oauth-authorization-server" req, _ := http.NewRequestWithContext(r.Context(), http.MethodGet, metadataURL, nil) - resp, e := h.service.gateway.client.Do(req) + resp, e := h.service.gateway.providerHTTPClient().Do(req) if e != nil { httpx.Error(w, 502, e.Error()) return @@ -377,15 +377,19 @@ func (h *handler) mcpOAuthCallback(w http.ResponseWriter, r *http.Request) { } req, _ := http.NewRequestWithContext(r.Context(), http.MethodPost, state.TokenEndpoint, strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, e := h.service.gateway.client.Do(req) + resp, e := h.service.gateway.providerHTTPClient().Do(req) if e != nil { httpx.Error(w, 502, e.Error()) return } - raw, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20)) + limit := int64(2 << 20) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + limit = maxMCPErrorBytes + } + raw, _ := io.ReadAll(io.LimitReader(resp.Body, limit)) resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { - httpx.Error(w, 502, string(raw)) + httpx.Error(w, 502, boundedMCPErrorDetail(raw)) return } var token map[string]any diff --git a/apps/server/internal/runtime/mcp_space_policy.go b/apps/server/internal/runtime/mcp_space_policy.go index 450da510..18bd50f6 100644 --- a/apps/server/internal/runtime/mcp_space_policy.go +++ b/apps/server/internal/runtime/mcp_space_policy.go @@ -69,6 +69,10 @@ func validateMCPPolicy(raw json.RawMessage) error { // PatchMCPConfig preserves the encrypted credential envelope and forbids API // callers from rewriting the canonical owner or provisioning provenance. func (h *handler) PatchMCPConfig(ctx context.Context, tenant, id string, patch json.RawMessage) (string, string, error) { + return h.patchMCPConfig(ctx, tenant, id, patch, httpx.Principal{}) +} + +func (h *handler) patchMCPConfig(ctx context.Context, tenant, id string, patch json.RawMessage, actor httpx.Principal) (string, string, error) { inst, err := h.getMCPInstance(ctx, tenant, id) if err != nil { return "", "", err @@ -78,6 +82,12 @@ func (h *handler) PatchMCPConfig(ctx context.Context, tenant, id string, patch j if json.Unmarshal(inst.Config, ¤t) != nil || json.Unmarshal(patch, &next) != nil { return "", "", errors.New("invalid MCP config") } + if err = validateStdioConfigControlKeys(next); err != nil { + return "", "", err + } + if _, ok := next[stdioOCIApprovalKey]; ok { + return "", "", errors.New("OCI platform approval is server-managed") + } if value, ok := next["exposure"]; ok { exposure, valid := value.(string) if !valid || !mcpExposureValue(exposure) { @@ -105,6 +115,46 @@ func (h *handler) PatchMCPConfig(ctx context.Context, tenant, id string, patch j } } } + ociExecutionChanged := false + for _, key := range []string{"command", "args", "env", "workingDir", "packageManager", "bridgeImage"} { + if value, ok := next[key]; ok { + switch key { + case "command", "workingDir", "packageManager", "bridgeImage": + if _, valid := value.(string); !valid { + return "", "", errors.New("stdio execution fields must use their declared types") + } + case "args": + items, valid := value.([]any) + if !valid { + return "", "", errors.New("stdio args must be a string array") + } + for _, item := range items { + if _, valid = item.(string); !valid { + return "", "", errors.New("stdio args must be a string array") + } + } + case "env": + values, valid := value.(map[string]any) + if !valid { + return "", "", errors.New("stdio env must be a string map") + } + for _, item := range values { + if _, valid = item.(string); !valid { + return "", "", errors.New("stdio env must be a string map") + } + } + } + a, _ := json.Marshal(value) + b, _ := json.Marshal(current[key]) + if string(a) != string(b) { + ociExecutionChanged = true + } + } + } + ociApproved, _ := current[stdioOCIApprovalKey].(bool) + currentCommand, _ := current["command"].(string) + currentPackageManager, _ := current["packageManager"].(string) + currentOCI := currentCommand != "" && stdioPackageManager(currentCommand, currentPackageManager) == "oci" var envelope struct { Enc string `json:"enc"` } @@ -122,6 +172,23 @@ func (h *handler) PatchMCPConfig(ctx context.Context, tenant, id string, patch j for key, value := range next { current[key] = value } + command, _ := current["command"].(string) + packageManager, _ := current["packageManager"].(string) + candidateOCI := command != "" && stdioPackageManager(command, packageManager) == "oci" + if currentOCI && ociExecutionChanged && !actor.IsPlatformAdmin { + return "", "", errStdioOCIPlatformAdminRequired + } + if candidateOCI { + if !ociApproved || ociExecutionChanged { + ociApproved, err = authorizeStdioOCI(actor, command, packageManager) + if err != nil { + return "", "", err + } + } + current[stdioOCIApprovalKey] = ociApproved + } else { + delete(current, stdioOCIApprovalKey) + } for _, key := range []string{"token", "apiKey", "accessToken", "access_token", "headers", "credentials", "secret", "env", "clientSecret"} { if value, ok := current[key]; ok { secret[key] = value diff --git a/apps/server/internal/runtime/mcp_space_test.go b/apps/server/internal/runtime/mcp_space_test.go index 46cdf58e..b0db4e20 100644 --- a/apps/server/internal/runtime/mcp_space_test.go +++ b/apps/server/internal/runtime/mcp_space_test.go @@ -5,6 +5,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" @@ -301,4 +302,10 @@ func TestMCPStoreSharesProvisioningAndLegacyOwnership(t *testing.T) { if _, _, err = h.PatchMCPConfig(context.Background(), "tenant", id, json.RawMessage(`{"ownerSpaceId":"other"}`)); err == nil { t.Fatal("owner changed via generic config patch") } + if _, _, err = h.PatchMCPConfig(context.Background(), "tenant", id, json.RawMessage(`{"packageManager":"oci"}`)); !errors.Is(err, errStdioOCIPlatformAdminRequired) { + t.Fatalf("OCI enabled without platform approval: %v", err) + } + if _, _, err = h.PatchMCPConfig(context.Background(), "tenant", id, json.RawMessage(`{"packageManager":"oci","ociPlatformApproved":true}`)); err == nil { + t.Fatal("OCI approval forged via generic config patch") + } } diff --git a/apps/server/internal/runtime/mcp_stdio_test.go b/apps/server/internal/runtime/mcp_stdio_test.go index 054056f7..90283112 100644 --- a/apps/server/internal/runtime/mcp_stdio_test.go +++ b/apps/server/internal/runtime/mcp_stdio_test.go @@ -8,6 +8,7 @@ import ( "encoding/binary" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net" @@ -20,9 +21,95 @@ import ( "testing" "time" + "github.com/Moonrend/Zakura/apps/server/internal/platform/appdeps" + "github.com/Moonrend/Zakura/apps/server/internal/platform/httpx" "github.com/go-chi/chi/v5" + "github.com/golang-jwt/jwt/v5" ) +func stdioPlatformAdminSession(t *testing.T, d *appdeps.Dependencies, tenant string) string { + t.Helper() + nowTime := d.Clock() + now := nowTime.Format(time.RFC3339Nano) + userID, email, sessionID := "stdio-admin", "stdio-admin@example.test", "stdio-admin-session" + if _, err := d.DB.Exec(`INSERT INTO users(id,email,name,password_hash,is_platform_admin,status,created_at,updated_at) VALUES(?,?,?,'unused',TRUE,'active',?,?)`, userID, email, "Stdio Admin", now, now); err != nil { + t.Fatal(err) + } + if _, err := d.DB.Exec(`INSERT INTO tenant_memberships(id,tenant_id,user_id,role,status,created_at,updated_at) VALUES('stdio-admin-membership',?,?,'owner','active',?,?)`, tenant, userID, now, now); err != nil { + t.Fatal(err) + } + token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{"sub": userID, "tenantId": tenant, "email": email, "role": "owner", "sid": sessionID, "isPlatformAdmin": true, "iat": nowTime.Unix(), "exp": nowTime.Add(time.Hour).Unix()}) + raw, err := token.SignedString(d.Secret) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256([]byte(raw)) + if _, err = d.DB.Exec(`INSERT INTO user_sessions(id,user_id,tenant_id,email,role,is_platform_admin,token_hash,expires_at,last_seen_at,created_at) VALUES(?,?,?,?,'owner',TRUE,?,?,?,?)`, sessionID, userID, tenant, email, hex.EncodeToString(sum[:]), nowTime.Add(time.Hour).Format(time.RFC3339Nano), now, now); err != nil { + t.Fatal(err) + } + return raw +} + +func TestStdioOCIAuthorizationRequiresPlatformAdmin(t *testing.T) { + for _, tc := range []struct { + name, role, command, packageManager string + platformAdmin bool + wantApproved, wantDenied bool + }{ + {name: "member explicit OCI", role: "member", command: "npx", packageManager: "oci", wantDenied: true}, + {name: "tenant owner explicit OCI", role: "owner", command: "npx", packageManager: " OCI ", wantDenied: true}, + {name: "member inferred Docker", command: "docker", wantDenied: true}, + {name: "member inferred Podman", command: "podman", wantDenied: true}, + {name: "platform admin explicit OCI", command: "npx", packageManager: "oci", platformAdmin: true, wantApproved: true}, + {name: "platform admin inferred Docker", command: "docker", platformAdmin: true, wantApproved: true}, + {name: "ordinary npm", command: "npx"}, + {name: "ordinary binary", command: "server", packageManager: "binary"}, + } { + t.Run(tc.name, func(t *testing.T) { + approved, err := authorizeStdioOCI(httpx.Principal{Role: tc.role, IsPlatformAdmin: tc.platformAdmin}, tc.command, tc.packageManager) + if approved != tc.wantApproved || errors.Is(err, errStdioOCIPlatformAdminRequired) != tc.wantDenied { + t.Fatalf("approved=%v err=%v", approved, err) + } + }) + } +} + +func TestStdioOCIStoredApprovalRequired(t *testing.T) { + for _, tc := range []struct { + name, config string + wantDenied bool + }{ + {name: "legacy explicit OCI", config: `{"command":"npx","packageManager":"oci"}`, wantDenied: true}, + {name: "legacy inferred Docker", config: `{"command":"docker"}`, wantDenied: true}, + {name: "legacy inferred Podman", config: `{"command":"podman"}`, wantDenied: true}, + {name: "approved OCI", config: `{"command":"docker","ociPlatformApproved":true}`}, + {name: "ordinary npm", config: `{"command":"npx"}`}, + } { + t.Run(tc.name, func(t *testing.T) { + body, ok := stdioBodyFromConfig(json.RawMessage(tc.config)) + if !ok { + t.Fatal("stdio config was not recognized") + } + if err := requireStdioOCIApproval(body); errors.Is(err, errStdioOCIPlatformAdminRequired) != tc.wantDenied { + t.Fatalf("approval error=%v", err) + } + }) + } +} + +func TestStdioOCIControlAliasesAreRejected(t *testing.T) { + for _, config := range []string{ + `{"command":"npx","PackageManager":"oci","OCIPlatformApproved":true}`, + `{"Command":"docker","ociPlatformApproved":true}`, + `{"command":"npx","packageManager":["oci"]}`, + `{"command":"docker","ociPlatformApproved":"true"}`, + } { + if err := requireStdioOCIConfigApproval(json.RawMessage(config)); err == nil { + t.Fatalf("non-canonical OCI control accepted: %s", config) + } + } +} + func readRunnerServerText(r *bufio.Reader) (string, error) { var head [2]byte if _, err := io.ReadFull(r, head[:]); err != nil { @@ -127,7 +214,8 @@ func TestImportStdioProvisionsNativeBridgeOnRunner(t *testing.T) { bridgeURL, _ := url.Parse(bridgeServer.URL) bridgePort, _ := strconv.Atoi(bridgeURL.Port()) d := testDeps(t) - token := seedTenant(t, d, "tenant") + memberToken := seedTenant(t, d, "tenant") + token := stdioPlatformAdminSession(t, d, "tenant") runnerToken := "rnr_stdio-runner-token" hash := sha256.Sum256([]byte(runnerToken)) now := d.Clock() @@ -265,17 +353,20 @@ func TestImportStdioProvisionsNativeBridgeOnRunner(t *testing.T) { } var config, status string expectedEndpoint := `"url":"` + bridgeServer.URL + `/mcp"` - if err = d.DB.QueryRow(`SELECT config_json,status FROM component_instances WHERE tenant_id='tenant'`).Scan(&config, &status); err != nil || status != "running" || !strings.Contains(config, expectedEndpoint) || !strings.Contains(config, `"runtimeNodeId":"node"`) || !strings.Contains(config, `"packageManager":"oci"`) { + if err = d.DB.QueryRow(`SELECT config_json,status FROM component_instances WHERE tenant_id='tenant'`).Scan(&config, &status); err != nil || status != "running" || !strings.Contains(config, expectedEndpoint) || !strings.Contains(config, `"runtimeNodeId":"node"`) || !strings.Contains(config, `"packageManager":"oci"`) || !strings.Contains(config, `"ociPlatformApproved":true`) { t.Fatalf("persisted component config/status: err=%v status=%q config=%s", err, status, config) } + instance := out["instance"].(map[string]any) + instanceID := instance["id"].(string) + if code, denied := doJSON(t, server.Client(), "PATCH", server.URL+"/api/instances/"+instanceID, memberToken, map[string]any{"config": map[string]any{"args": []string{"run", "--privileged", "server"}}}); code != http.StatusForbidden { + t.Fatalf("tenant changed approved OCI execution: %d %#v", code, denied) + } if bridgeInit.Load() != 1 || bridgeList.Load() != 1 || bridgeDelete.Load() != 1 { t.Fatalf("bridge MCP warmup: initialize=%d list=%d delete=%d", bridgeInit.Load(), bridgeList.Load(), bridgeDelete.Load()) } if strings.Contains(config, `"env"`) || strings.Contains(config, `"DEMO":"yes"`) { t.Fatalf("stdio environment leaked into config_json: %s", config) } - instance := out["instance"].(map[string]any) - instanceID := instance["id"].(string) var secretStored string if err = d.DB.QueryRow(`SELECT secret_json FROM component_instances WHERE id=?`, instanceID).Scan(&secretStored); err != nil || strings.Contains(secretStored, "yes") { t.Fatalf("stdio secret storage leak: %s err=%v", secretStored, err) diff --git a/apps/server/internal/runtime/memory_embedding.go b/apps/server/internal/runtime/memory_embedding.go index d246d7a5..9dbc2518 100644 --- a/apps/server/internal/runtime/memory_embedding.go +++ b/apps/server/internal/runtime/memory_embedding.go @@ -122,15 +122,19 @@ func (h *handler) embedMemoryText(ctx context.Context, tenant string, cfg *memor return nil, "", err } defer resp.Body.Close() - raw, err = io.ReadAll(io.LimitReader(resp.Body, 8<<20)) + limit := int64(8 << 20) + if resp.Status < 200 || resp.Status >= 300 { + limit = maxProviderErrorResponse + } + raw, err = io.ReadAll(io.LimitReader(resp.Body, limit)) if err != nil { return nil, "", err } if resp.Status < 200 || resp.Status >= 300 { - return nil, "", fmt.Errorf("embedding failed HTTP %d: %s", resp.Status, string(raw)) + return nil, "", fmt.Errorf("embedding failed HTTP %d: %s", resp.Status, gwTruncate(strings.Join(strings.Fields(string(raw)), " "), 1000)) } } else { - u, err := safeProviderURL(strings.TrimRight(cfg.BaseURL, "/"), "embeddings") + u, err := h.providerURL(strings.TrimRight(cfg.BaseURL, "/"), "embeddings") if err != nil { return nil, "", err } @@ -140,17 +144,21 @@ func (h *handler) embedMemoryText(ctx context.Context, tenant string, cfg *memor if cfg.APIKey != "" { req.Header.Set("Authorization", "Bearer "+cfg.APIKey) } - resp, err := h.service.gateway.client.Do(req) + resp, err := h.service.gateway.providerHTTPClient().Do(req) if err != nil { return nil, "", err } defer resp.Body.Close() - raw, err = io.ReadAll(io.LimitReader(resp.Body, 8<<20)) + limit := int64(8 << 20) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + limit = maxProviderErrorResponse + } + raw, err = io.ReadAll(io.LimitReader(resp.Body, limit)) if err != nil { return nil, "", err } if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return nil, "", fmt.Errorf("embedding failed HTTP %d: %s", resp.StatusCode, string(raw)) + return nil, "", fmt.Errorf("embedding failed HTTP %d: %s", resp.StatusCode, gwTruncate(strings.Join(strings.Fields(string(raw)), " "), 1000)) } } var decoded struct { diff --git a/apps/server/internal/runtime/misc_routes.go b/apps/server/internal/runtime/misc_routes.go index 3c7cc74a..ce65c699 100644 --- a/apps/server/internal/runtime/misc_routes.go +++ b/apps/server/internal/runtime/misc_routes.go @@ -30,16 +30,115 @@ type modelAuthLogin struct { ExpiresAt time.Time } -var otelRateBuckets = struct { - sync.Mutex - values map[string]struct { - count int - resetAt time.Time - } -}{values: map[string]struct { +const ( + otelRateWindow = time.Minute + otelClientRequestLimit = 60 + otelGlobalRequestLimit = 600 + otelGlobalByteLimit = 64 << 20 + otelMaxRateBuckets = 512 + otelMaxBodyBytes = 8 << 20 + otelMaxConcurrentIngest = 8 + otelMaxConcurrentForwards = 4 +) + +var errOTelByteBudget = errors.New("OTel global byte budget exceeded") + +type otelRateBucket struct { count int resetAt time.Time -}{}} +} + +type otelGlobalBucket struct { + count int + bytes int64 + resetAt time.Time +} + +type otelLimiter struct { + sync.Mutex + clients map[string]otelRateBucket + global otelGlobalBucket + ingestSlots chan struct{} + forwardSlots chan struct{} +} + +func newOTelLimiter() *otelLimiter { + return &otelLimiter{ + clients: make(map[string]otelRateBucket), + ingestSlots: make(chan struct{}, otelMaxConcurrentIngest), + forwardSlots: make(chan struct{}, otelMaxConcurrentForwards), + } +} + +func (l *otelLimiter) resetGlobal(now time.Time) { + if !now.Before(l.global.resetAt) { + l.global = otelGlobalBucket{resetAt: now.Add(otelRateWindow)} + } +} + +func (l *otelLimiter) rateLimited(key string, now time.Time) bool { + l.Lock() + defer l.Unlock() + + for existingKey, bucket := range l.clients { + if !now.Before(bucket.resetAt) { + delete(l.clients, existingKey) + } + } + l.resetGlobal(now) + if l.global.count >= otelGlobalRequestLimit { + return true + } + + bucket, ok := l.clients[key] + if !ok { + if len(l.clients) >= otelMaxRateBuckets { + return true + } + bucket.resetAt = now.Add(otelRateWindow) + } + if bucket.count >= otelClientRequestLimit { + return true + } + bucket.count++ + l.clients[key] = bucket + l.global.count++ + return false +} + +func (l *otelLimiter) bytesLimited(size int64, now time.Time) bool { + l.Lock() + defer l.Unlock() + l.resetGlobal(now) + if size < 0 || size > otelGlobalByteLimit-l.global.bytes { + return true + } + l.global.bytes += size + return false +} + +type otelByteBudgetReader struct { + reader io.Reader + limits *otelLimiter + now func() time.Time +} + +func (r *otelByteBudgetReader) Read(p []byte) (int, error) { + n, err := r.reader.Read(p) + if n > 0 && r.limits.bytesLimited(int64(n), r.now()) { + return 0, errOTelByteBudget + } + return n, err +} + +func acquireOTelSlot(slots chan struct{}) bool { + select { + case slots <- struct{}{}: + return true + default: + return false + } +} func (h *handler) registerMisc(r chi.Router) { r.Get("/capabilities", h.capabilities) @@ -170,7 +269,7 @@ func (h *handler) putCapability(w http.ResponseWriter, r *http.Request, key stri return } if endpoint, ok := cfg["endpoint"].(string); ok && endpoint != "" { - if _, e := safeProviderURL(endpoint, ""); e != nil { + if _, e := serviceURL(endpoint, ""); e != nil { statusErr(w, e) return } @@ -322,15 +421,19 @@ func (h *handler) modelAuthStart(w http.ResponseWriter, r *http.Request) { } req, _ := http.NewRequestWithContext(r.Context(), http.MethodPost, deviceURL, strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, e := h.service.gateway.client.Do(req) + resp, e := h.service.gateway.providerHTTPClient().Do(req) if e != nil { httpx.Error(w, 502, e.Error()) return } defer resp.Body.Close() - raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + limit := int64(1 << 20) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + limit = maxProviderErrorResponse + } + raw, _ := io.ReadAll(io.LimitReader(resp.Body, limit)) if resp.StatusCode < 200 || resp.StatusCode >= 300 { - httpx.Error(w, 502, string(raw)) + httpx.Error(w, 502, gwTruncate(strings.Join(strings.Fields(string(raw)), " "), 1000)) return } var device struct { @@ -397,7 +500,7 @@ func (h *handler) modelAuthPoll(w http.ResponseWriter, r *http.Request) { form := url.Values{"grant_type": []string{"urn:ietf:params:oauth:grant-type:device_code"}, "device_code": []string{login.DeviceCode}, "client_id": []string{clientID}} req, _ := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, e := h.service.gateway.client.Do(req) + resp, e := h.service.gateway.providerHTTPClient().Do(req) if e != nil { if errors.Is(e, context.Canceled) { httpx.Error(w, 409, "poll cancelled") @@ -540,22 +643,32 @@ func (h *handler) getOTelConfig(w http.ResponseWriter, r *http.Request) { }) } func (h *handler) ingestOTelLogs(w http.ResponseWriter, r *http.Request) { - actor := httpx.Principal{UserID: "0", TenantID: "0"} - if token := strings.TrimSpace(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")); token != "" { - if authenticated, err := h.authenticateRealtime(r.Context(), token); err == nil { - actor = authenticated - } + actor, ok := httpx.PrincipalFrom(r.Context()) + if !ok || actor.UserID == "" || actor.TenantID == "" { + httpx.Error(w, http.StatusUnauthorized, "unauthorized") + return } - remote := strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0]) - if remote == "" { - remote = r.RemoteAddr + if h.otelLimits.rateLimited(otelRateIdentity(actor), h.store.now()) { + w.WriteHeader(http.StatusTooManyRequests) + return } - if otelRateLimited(actor.UserID + ":" + actor.TenantID + ":" + remote) { + if !acquireOTelSlot(h.otelLimits.ingestSlots) { w.WriteHeader(http.StatusTooManyRequests) return } - raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20)) + defer func() { <-h.otelLimits.ingestSlots }() + + body := &otelByteBudgetReader{ + reader: http.MaxBytesReader(w, r.Body, otelMaxBodyBytes), + limits: h.otelLimits, + now: h.store.now, + } + raw, err := io.ReadAll(body) if err != nil { + if errors.Is(err, errOTelByteBudget) { + w.WriteHeader(http.StatusTooManyRequests) + return + } httpx.Error(w, 413, "payload too large") return } @@ -571,26 +684,21 @@ func (h *handler) ingestOTelLogs(w http.ResponseWriter, r *http.Request) { endpoint := strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT")) if endpoint != "" { stamped, _ := json.Marshal(payload) - go h.forwardOTel(endpoint, stamped) + if acquireOTelSlot(h.otelLimits.forwardSlots) { + go func() { + defer func() { <-h.otelLimits.forwardSlots }() + h.forwardOTel(endpoint, stamped) + }() + } } w.WriteHeader(http.StatusAccepted) } -func otelRateLimited(key string) bool { - now := time.Now() - otelRateBuckets.Lock() - defer otelRateBuckets.Unlock() - bucket, ok := otelRateBuckets.values[key] - if !ok || !now.Before(bucket.resetAt) { - otelRateBuckets.values[key] = struct { - count int - resetAt time.Time - }{count: 1, resetAt: now.Add(time.Minute)} - return false +func otelRateIdentity(actor httpx.Principal) string { + if actor.APIKey { + return "api-key\x00" + actor.TenantID + "\x00" + actor.APIKeyID } - bucket.count++ - otelRateBuckets.values[key] = bucket - return bucket.count > 60 + return "user\x00" + actor.TenantID + "\x00" + actor.UserID } func filterAndStampOTel(payload map[string]any, userID, tenantID string) bool { diff --git a/apps/server/internal/runtime/model_inventory.go b/apps/server/internal/runtime/model_inventory.go index 29ba971c..74eef066 100644 --- a/apps/server/internal/runtime/model_inventory.go +++ b/apps/server/internal/runtime/model_inventory.go @@ -75,7 +75,7 @@ func (h *handler) fetchUpstreamModelList(ctx context.Context, tenant string, u U if cfg.BaseURL == "" { return nil, errors.New("baseUrl not configured") } - target, e := safeProviderURL(cfg.BaseURL, "/v1/models") + target, e := h.providerURL(cfg.BaseURL, "/v1/models") if e != nil { return nil, e } @@ -96,7 +96,7 @@ func (h *handler) fetchUpstreamModelList(ctx context.Context, tenant string, u U req.Header.Set(k, v) } } - client := h.service.gateway.client + client := h.service.gateway.providerHTTPClient() if cfg.Timeout > 0 { clone := *client clone.Timeout = time.Duration(cfg.Timeout) * time.Millisecond @@ -107,7 +107,11 @@ func (h *handler) fetchUpstreamModelList(ctx context.Context, tenant string, u U return nil, e } defer resp.Body.Close() - raw, e := io.ReadAll(io.LimitReader(resp.Body, 16<<20)) + limit := int64(16 << 20) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + limit = maxProviderErrorResponse + } + raw, e := io.ReadAll(io.LimitReader(resp.Body, limit)) if e != nil { return nil, e } diff --git a/apps/server/internal/runtime/model_inventory_test.go b/apps/server/internal/runtime/model_inventory_test.go index bcccf929..7a534e84 100644 --- a/apps/server/internal/runtime/model_inventory_test.go +++ b/apps/server/internal/runtime/model_inventory_test.go @@ -64,7 +64,7 @@ func TestFetchUpstreamModelListParsing(t *testing.T) { func TestSyncModelsRespectsSelectionAndNeverDeletes(t *testing.T) { d := testDeps(t) - tok := seedTenant(t, d, "tenant-a") + tok := seedProviderAdmin(t, d, "tenant-a") provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "Bearer test-key" { t.Errorf("missing decrypted model credential: %q", r.Header.Get("Authorization")) @@ -133,7 +133,7 @@ func TestSyncModelsRespectsSelectionAndNeverDeletes(t *testing.T) { func TestPatchUpstreamModelCheckNoDelete(t *testing.T) { d := testDeps(t) - tok := seedTenant(t, d, "tenant-a") + tok := seedProviderAdmin(t, d, "tenant-a") provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "Bearer test-key" { t.Errorf("missing decrypted model credential: %q", r.Header.Get("Authorization")) @@ -176,7 +176,7 @@ func TestPatchUpstreamModelCheckNoDelete(t *testing.T) { func TestPatchUpstreamCredentialMerge(t *testing.T) { d := testDeps(t) - tok := seedTenant(t, d, "tenant-a") + tok := seedProviderAdmin(t, d, "tenant-a") var mu sync.Mutex lastAuth := "" provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -265,7 +265,7 @@ func TestGroupUpstreamModels(t *testing.T) { func TestListUpstreamModelsGroupedShape(t *testing.T) { d := testDeps(t) - tok := seedTenant(t, d, "tenant-a") + tok := seedProviderAdmin(t, d, "tenant-a") router := chi.NewRouter() RegisterRoutes(router, d) server := httptest.NewServer(router) @@ -344,7 +344,7 @@ func findRouteByAlias(routes []any, alias string) map[string]any { func TestSyncAutoProvisionsRoutes(t *testing.T) { d := testDeps(t) - tok := seedTenant(t, d, "tenant-a") + tok := seedProviderAdmin(t, d, "tenant-a") provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"id": "A"}, map[string]any{"id": "B"}}}) @@ -392,7 +392,7 @@ func TestSyncAutoProvisionsRoutes(t *testing.T) { func TestSyncPreservesExistingRoute(t *testing.T) { d := testDeps(t) - tok := seedTenant(t, d, "tenant-a") + tok := seedProviderAdmin(t, d, "tenant-a") provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"id": "A"}, map[string]any{"id": "B"}}}) @@ -432,7 +432,7 @@ func TestSyncPreservesExistingRoute(t *testing.T) { func TestSetDefaultModelRoute(t *testing.T) { d := testDeps(t) - tok := seedTenant(t, d, "tenant-a") + tok := seedProviderAdmin(t, d, "tenant-a") provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"id": "A"}, map[string]any{"id": "B"}}}) @@ -495,7 +495,7 @@ func TestSetDefaultModelRoute(t *testing.T) { func TestDeleteUpstreamModelRemovesRoutes(t *testing.T) { d := testDeps(t) - tok := seedTenant(t, d, "tenant-a") + tok := seedProviderAdmin(t, d, "tenant-a") provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"id": "A"}, map[string]any{"id": "B"}}}) @@ -532,7 +532,7 @@ func TestDeleteUpstreamModelRemovesRoutes(t *testing.T) { func TestDeleteUpstreamRemovesRoutes(t *testing.T) { d := testDeps(t) - tok := seedTenant(t, d, "tenant-a") + tok := seedProviderAdmin(t, d, "tenant-a") provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"id": "A"}, map[string]any{"id": "B"}}}) @@ -568,7 +568,7 @@ func TestDeleteUpstreamRemovesRoutes(t *testing.T) { func TestResolveCandidatesFindsAutoRoutes(t *testing.T) { d := testDeps(t) - tok := seedTenant(t, d, "tenant-a") + tok := seedProviderAdmin(t, d, "tenant-a") provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"id": "A"}, map[string]any{"id": "B"}}}) diff --git a/apps/server/internal/runtime/models_extra.go b/apps/server/internal/runtime/models_extra.go index 0f253e5d..c704e23e 100644 --- a/apps/server/internal/runtime/models_extra.go +++ b/apps/server/internal/runtime/models_extra.go @@ -24,6 +24,9 @@ func validModelCapability(capability string) bool { } func (h *handler) patchUpstream(w http.ResponseWriter, r *http.Request) { + if !requireProviderAdmin(w, r) { + return + } m, e := decodeMap(r) if e != nil { httpx.Error(w, 400, "invalid JSON") diff --git a/apps/server/internal/runtime/network.go b/apps/server/internal/runtime/network.go index 8c6dc385..d694033b 100644 --- a/apps/server/internal/runtime/network.go +++ b/apps/server/internal/runtime/network.go @@ -283,7 +283,7 @@ func (h *handler) testExposureProvider(w http.ResponseWriter, r *http.Request) { var ok bool var message string if endpoint != "" { - u, e := safeProviderURL(endpoint, "") + u, e := serviceURL(endpoint, "") if e != nil { statusErr(w, e) return @@ -475,7 +475,7 @@ func (h *handler) createExposure(w http.ResponseWriter, r *http.Request) { httpx.Error(w, 400, "provider controlUrl required") return } - u, e := safeProviderURL(control, "") + u, e := serviceURL(control, "") if e != nil { statusErr(w, e) return @@ -751,7 +751,7 @@ func (h *handler) putPlatformHeadscale(w http.ResponseWriter, r *http.Request) { stored.URL = strings.TrimRight(strings.TrimSpace(*b.URL), "/") } if b.URL != nil && stored.URL != "" { - if _, e := safeProviderURL(stored.URL, ""); e != nil { + if _, e := serviceURL(stored.URL, ""); e != nil { statusErr(w, e) return } @@ -1208,7 +1208,7 @@ func (h *handler) ensureMeshACL(w http.ResponseWriter, r *http.Request) { return } raw, _ := json.Marshal(policy) - u, e := safeProviderURL(strings.TrimRight(base, "/")+"/api/v1/policy", "") + u, e := serviceURL(strings.TrimRight(base, "/")+"/api/v1/policy", "") if e != nil { statusErr(w, e) return diff --git a/apps/server/internal/runtime/node_installation.go b/apps/server/internal/runtime/node_installation.go index 9eeba8b1..5ff2f5cf 100644 --- a/apps/server/internal/runtime/node_installation.go +++ b/apps/server/internal/runtime/node_installation.go @@ -69,13 +69,14 @@ func (h *handler) enrollComposeNode(w http.ResponseWriter, r *http.Request) { httpx.JSON(w, http.StatusOK, credential) } -// Compose credentials never enter the manual-install token cache or UI. +// Compose credentials never enter the manual-install token cache or UI. Manual +// enrollment tokens enter the cache only when their node is created; presenting +// a node credential must never restore installation material after enrollment. func (h *handler) cacheRuntimeNodeToken(ctx context.Context, nodeID, token string) (string, error) { var incarnation string var revoked bool err := h.deps.DB.QueryRowContext(ctx, h.deps.Rebind(`SELECT node_incarnation,revoked FROM node_installations WHERE node_id=?`), nodeID).Scan(&incarnation, &revoked) if errors.Is(err, sql.ErrNoRows) { - runnerTokenCache.Store(nodeID, token) return "", nil } runnerTokenCache.Delete(nodeID) diff --git a/apps/server/internal/runtime/platform_services.go b/apps/server/internal/runtime/platform_services.go index 3615c429..f00f3c2e 100644 --- a/apps/server/internal/runtime/platform_services.go +++ b/apps/server/internal/runtime/platform_services.go @@ -335,7 +335,7 @@ func (h *handler) patchPlatformService(w http.ResponseWriter, r *http.Request) { return } if b.EndpointURL != "" { - if _, e := safeProviderURL(b.EndpointURL, ""); e != nil { + if _, e := serviceURL(b.EndpointURL, ""); e != nil { statusErr(w, e) return } @@ -641,7 +641,7 @@ func (h *handler) connectPlatformService(w http.ResponseWriter, r *http.Request) httpx.Error(w, 400, "endpointUrl required") return } - u, e := safeProviderURL(b.EndpointURL, "") + u, e := serviceURL(b.EndpointURL, "") if e != nil { statusErr(w, e) return diff --git a/apps/server/internal/runtime/provider_egress.go b/apps/server/internal/runtime/provider_egress.go new file mode 100644 index 00000000..44564b57 --- /dev/null +++ b/apps/server/internal/runtime/provider_egress.go @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +package runtime + +import ( + "context" + "errors" + "fmt" + "net" + "net/http" + "net/netip" + "net/url" + "path" + "strings" + "time" +) + +type providerLookup func(context.Context, string) ([]netip.Addr, error) +type providerDial func(context.Context, string, string) (net.Conn, error) + +var nonPublicProviderPrefixes = []netip.Prefix{ + netip.MustParsePrefix("0.0.0.0/8"), + netip.MustParsePrefix("100.64.0.0/10"), + netip.MustParsePrefix("192.0.0.0/24"), + netip.MustParsePrefix("192.0.2.0/24"), + netip.MustParsePrefix("192.88.99.0/24"), + netip.MustParsePrefix("198.18.0.0/15"), + netip.MustParsePrefix("198.51.100.0/24"), + netip.MustParsePrefix("203.0.113.0/24"), + netip.MustParsePrefix("240.0.0.0/4"), + netip.MustParsePrefix("::/96"), + netip.MustParsePrefix("64:ff9b::/96"), + netip.MustParsePrefix("64:ff9b:1::/48"), + netip.MustParsePrefix("100::/64"), + netip.MustParsePrefix("2001::/32"), + netip.MustParsePrefix("2001:2::/48"), + netip.MustParsePrefix("2001:db8::/32"), + netip.MustParsePrefix("2001:10::/28"), + netip.MustParsePrefix("2001:20::/28"), + netip.MustParsePrefix("2002::/16"), + netip.MustParsePrefix("3fff::/20"), + netip.MustParsePrefix("5f00::/16"), + netip.MustParsePrefix("fec0::/10"), +} + +func publicProviderIP(addr netip.Addr) bool { + if !addr.IsValid() || addr.Zone() != "" { + return false + } + addr = addr.Unmap() + if !addr.IsGlobalUnicast() || addr.IsPrivate() || addr.IsLoopback() || addr.IsLinkLocalUnicast() || addr.IsMulticast() || addr.IsUnspecified() { + return false + } + for _, prefix := range nonPublicProviderPrefixes { + if prefix.Contains(addr) { + return false + } + } + return true +} + +func validateProviderURL(u *url.URL, allowPrivate bool) error { + if u == nil || u.Host == "" || u.Hostname() == "" || (u.Scheme != "https" && u.Scheme != "http") { + return errors.New("upstream baseUrl must be an absolute http(s) URL") + } + if u.User != nil { + return errors.New("credentials in upstream URL are not allowed") + } + host := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(u.Hostname())), ".") + if host == "" { + return errors.New("upstream baseUrl must include a host") + } + if !allowPrivate && (host == "localhost" || strings.HasSuffix(host, ".localhost") || strings.HasSuffix(host, ".local") || strings.HasSuffix(host, ".internal")) { + return errors.New("unsafe upstream address") + } + if addr, err := netip.ParseAddr(host); err == nil && !allowPrivate && !publicProviderIP(addr) { + return errors.New("unsafe upstream address") + } + return nil +} + +func providerURL(baseURL, endpoint string, allowPrivate bool) (*url.URL, error) { + u, err := url.Parse(baseURL) + if err != nil { + return nil, err + } + if err = validateProviderURL(u, allowPrivate); err != nil { + return nil, err + } + basePath := strings.TrimSuffix(u.Path, "/") + if strings.HasPrefix(endpoint, "/v1/") && strings.HasSuffix(basePath, "/v1") { + endpoint = strings.TrimPrefix(endpoint, "/v1") + } + u.Path = path.Join(basePath, endpoint) + u.RawPath = "" + u.Fragment = "" + return u, nil +} + +func safeProviderURL(baseURL, endpoint string) (*url.URL, error) { + return providerURL(baseURL, endpoint, false) +} + +func serviceURL(baseURL, endpoint string) (*url.URL, error) { + u, err := providerURL(baseURL, endpoint, true) + if err != nil { + return nil, err + } + if ip := net.ParseIP(strings.Trim(u.Hostname(), "[]")); ip != nil && (ip.IsUnspecified() || ip.IsMulticast() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()) { + return nil, errors.New("unsafe upstream address") + } + return u, nil +} + +func (h *handler) providerURL(baseURL, endpoint string) (*url.URL, error) { + if h != nil && h.service != nil && h.service.gateway != nil { + return h.service.gateway.providerURL(baseURL, endpoint) + } + return providerURL(baseURL, endpoint, false) +} + +func resolveProviderIPs(ctx context.Context, host string, lookup providerLookup, allowPrivate bool) ([]netip.Addr, error) { + if addr, err := netip.ParseAddr(strings.Trim(host, "[]")); err == nil { + if !allowPrivate && !publicProviderIP(addr) { + return nil, errors.New("unsafe upstream address") + } + return []netip.Addr{addr.Unmap()}, nil + } + addrs, err := lookup(ctx, host) + if err != nil || len(addrs) == 0 { + return nil, errors.New("upstream host could not be resolved") + } + for _, addr := range addrs { + if !allowPrivate && !publicProviderIP(addr) { + return nil, errors.New("upstream host resolved to a non-public address") + } + } + return addrs, nil +} + +func providerDialContext(lookup providerLookup, dial providerDial, allowPrivate bool) func(context.Context, string, string) (net.Conn, error) { + return func(ctx context.Context, network, address string) (net.Conn, error) { + host, port, err := net.SplitHostPort(address) + if err != nil { + return nil, errors.New("invalid upstream address") + } + addrs, err := resolveProviderIPs(ctx, host, lookup, allowPrivate) + if err != nil { + return nil, err + } + var lastErr error + for _, addr := range addrs { + conn, dialErr := dial(ctx, network, net.JoinHostPort(addr.Unmap().String(), port)) + if dialErr == nil { + return conn, nil + } + lastErr = dialErr + } + return nil, fmt.Errorf("upstream connection failed: %w", lastErr) + } +} + +func sameProviderRedirectHost(current, previous *url.URL) bool { + if current == nil || previous == nil { + return false + } + currentHost := strings.TrimSuffix(strings.ToLower(current.Hostname()), ".") + previousHost := strings.TrimSuffix(strings.ToLower(previous.Hostname()), ".") + return currentHost != "" && currentHost == previousHost +} + +func providerRedirectPolicy(allowPrivate bool) func(*http.Request, []*http.Request) error { + return func(req *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return errors.New("too many upstream redirects") + } + if err := validateProviderURL(req.URL, allowPrivate); err != nil { + return err + } + if len(via) > 0 { + previous := via[len(via)-1].URL + if !sameProviderRedirectHost(req.URL, previous) || previous.Scheme == "https" && req.URL.Scheme != "https" { + return errors.New("cross-origin upstream redirect is not allowed") + } + } + return nil + } +} + +func providerTransport(dialContext func(context.Context, string, string) (net.Conn, error)) *http.Transport { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + transport.DialContext = dialContext + transport.DialTLSContext = nil + transport.MaxIdleConns = 256 + transport.MaxIdleConnsPerHost = 64 + transport.ResponseHeaderTimeout = 90 * time.Second + return transport +} + +func newProviderHTTPClient(allowPrivate bool) *http.Client { + dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second} + lookup := func(ctx context.Context, host string) ([]netip.Addr, error) { + return net.DefaultResolver.LookupNetIP(ctx, "ip", host) + } + return &http.Client{ + Transport: providerTransport(providerDialContext(lookup, dialer.DialContext, allowPrivate)), + CheckRedirect: providerRedirectPolicy(allowPrivate), + } +} + +func newPinnedProviderHTTPClient(addr netip.Addr) *http.Client { + dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second} + dialContext := func(ctx context.Context, network, address string) (net.Conn, error) { + _, port, err := net.SplitHostPort(address) + if err != nil { + return nil, errors.New("invalid runtime MCP address") + } + return dialer.DialContext(ctx, network, net.JoinHostPort(addr.Unmap().String(), port)) + } + return &http.Client{ + Transport: providerTransport(dialContext), + CheckRedirect: func(*http.Request, []*http.Request) error { + return errors.New("runtime MCP redirects are not allowed") + }, + } +} diff --git a/apps/server/internal/runtime/provider_egress_test.go b/apps/server/internal/runtime/provider_egress_test.go new file mode 100644 index 00000000..677dca67 --- /dev/null +++ b/apps/server/internal/runtime/provider_egress_test.go @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +package runtime + +import ( + "context" + "errors" + "net" + "net/http" + "net/netip" + "net/url" + "strings" + "testing" + + "github.com/Moonrend/Zakura/apps/server/internal/platform/httpx" +) + +func TestPublicProviderURLRejectsPrivateDestinations(t *testing.T) { + blocked := []string{ + "http://127.0.0.1/v1", + "http://10.0.0.1/v1", + "http://172.16.0.1/v1", + "http://192.168.0.1/v1", + "http://100.64.0.1/v1", + "http://169.254.169.254/latest/meta-data", + "http://[::1]/v1", + "http://[fc00::1]/v1", + "http://[64:ff9b::7f00:1]/v1", + "http://[2002:7f00:1::1]/v1", + "http://localhost/v1", + "http://service.internal/v1", + } + for _, target := range blocked { + if _, err := providerURL(target, "", false); err == nil { + t.Fatalf("accepted non-public provider URL %q", target) + } + } + if _, err := safeProviderURL("http://127.0.0.1/v1", ""); err == nil { + t.Fatal("safeProviderURL accepted loopback") + } + got, err := providerURL("https://api.example.com/v1", "/v1/models", false) + if err != nil || got.String() != "https://api.example.com/v1/models" { + t.Fatalf("public provider URL changed: %v %v", got, err) + } + if _, err = serviceURL("http://127.0.0.1/v1", ""); err != nil { + t.Fatalf("intentional internal service URL rejected loopback: %v", err) + } +} + +func TestProviderDialRejectsPrivateDNSAnswers(t *testing.T) { + for _, answers := range [][]netip.Addr{ + {netip.MustParseAddr("10.0.0.7")}, + {netip.MustParseAddr("93.184.216.34"), netip.MustParseAddr("127.0.0.1")}, + {netip.MustParseAddr("::ffff:192.168.1.2")}, + } { + dialed := false + lookup := func(context.Context, string) ([]netip.Addr, error) { return answers, nil } + dial := func(context.Context, string, string) (net.Conn, error) { + dialed = true + return nil, errors.New("unexpected dial") + } + if _, err := providerDialContext(lookup, dial, false)(context.Background(), "tcp", "provider.example:443"); err == nil { + t.Fatalf("accepted DNS answers %#v", answers) + } + if dialed { + t.Fatalf("dialed before validating every DNS answer %#v", answers) + } + } +} + +func TestProviderDialPinsValidatedAddress(t *testing.T) { + const publicIP = "93.184.216.34" + var dialed string + lookupCalls := 0 + lookup := func(context.Context, string) ([]netip.Addr, error) { + lookupCalls++ + return []netip.Addr{netip.MustParseAddr(publicIP)}, nil + } + dial := func(_ context.Context, _ string, address string) (net.Conn, error) { + dialed = address + return nil, errors.New("fixture stop") + } + _, _ = providerDialContext(lookup, dial, false)(context.Background(), "tcp", "provider.example:443") + if lookupCalls != 1 || dialed != publicIP+":443" { + t.Fatalf("lookupCalls=%d dialed=%q", lookupCalls, dialed) + } +} + +func TestProviderRedirectPolicyRevalidatesTarget(t *testing.T) { + policy := providerRedirectPolicy(false) + previous := &http.Request{URL: &url.URL{Scheme: "https", Host: "api.example.com", Path: "/v1"}} + allowed := &http.Request{URL: &url.URL{Scheme: "https", Host: "api.example.com", Path: "/v2"}} + if err := policy(allowed, []*http.Request{previous}); err != nil { + t.Fatalf("same-host HTTPS redirect rejected: %v", err) + } + for _, target := range []*http.Request{ + {URL: &url.URL{Scheme: "https", Host: "other.example.com"}}, + {URL: &url.URL{Scheme: "http", Host: "api.example.com"}}, + {URL: &url.URL{Scheme: "http", Host: "127.0.0.1"}}, + } { + if err := policy(target, []*http.Request{previous}); err == nil { + t.Fatalf("accepted unsafe redirect to %s", target.URL) + } + } + client := newProviderHTTPClient(false) + transport, ok := client.Transport.(*http.Transport) + if !ok || transport.Proxy != nil || transport.DialContext == nil || client.CheckRedirect == nil { + t.Fatal("provider client lost direct pinned transport or redirect validation") + } +} + +func TestMCPProbeHeaderAllowlist(t *testing.T) { + headers, err := sanitizeMCPProbeHeaders(map[string]string{"authorization": "Bearer token", "x-api-key": "secret"}) + if err != nil || headers["Authorization"] != "Bearer token" || headers["X-Api-Key"] != "secret" { + t.Fatalf("probe authentication headers changed: %#v %v", headers, err) + } + for _, key := range []string{"Host", "Cookie", "X-Forwarded-For", "Proxy-Authorization"} { + if _, err = sanitizeMCPProbeHeaders(map[string]string{key: "value"}); err == nil { + t.Fatalf("accepted probe header %q", key) + } + } +} + +func TestProviderAdministrationBoundary(t *testing.T) { + for _, principal := range []httpx.Principal{{Role: "owner"}, {Role: "admin"}, {IsPlatformAdmin: true}} { + if !providerAdminAllowed(principal) { + t.Fatalf("administrator rejected: %#v", principal) + } + } + for _, principal := range []httpx.Principal{{Role: "member"}, {Role: "owner", APIKey: true}, {APIKey: true, APIKeyScopes: `["*"]`}} { + if providerAdminAllowed(principal) { + t.Fatalf("ordinary principal accepted: %#v", principal) + } + } +} + +func TestMCPErrorReflectionIsBounded(t *testing.T) { + detail := boundedMCPErrorDetail([]byte(strings.Repeat("sensitive ", maxMCPErrorText))) + if len(detail) > maxMCPErrorText+3 || !strings.HasSuffix(detail, "…") { + t.Fatalf("unbounded MCP error detail length=%d", len(detail)) + } +} diff --git a/apps/server/internal/runtime/public_protocols_test.go b/apps/server/internal/runtime/public_protocols_test.go index f591c3e0..f7073ff0 100644 --- a/apps/server/internal/runtime/public_protocols_test.go +++ b/apps/server/internal/runtime/public_protocols_test.go @@ -9,6 +9,7 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net" @@ -23,7 +24,7 @@ import ( "github.com/golang-jwt/jwt/v5" ) -func TestPublicOTelContractAndFiltering(t *testing.T) { +func TestAuthenticatedOTelContractAndFiltering(t *testing.T) { forwarded := make(chan map[string]any, 1) collector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var body map[string]any @@ -34,6 +35,7 @@ func TestPublicOTelContractAndFiltering(t *testing.T) { defer collector.Close() t.Setenv("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", collector.URL+"/v1/logs") d := testDeps(t) + token := seedTenant(t, d, "tenant") router := chi.NewRouter() RegisterRoutes(router, d) server := httptest.NewServer(router) @@ -65,19 +67,30 @@ func TestPublicOTelContractAndFiltering(t *testing.T) { }, } } - post := func(body any) int { + post := func(body any, token, forwardedFor string) int { raw, _ := json.Marshal(body) - resp, err := http.Post(server.URL+"/api/otel/v1/logs", "application/json", bytes.NewReader(raw)) + req, _ := http.NewRequest(http.MethodPost, server.URL+"/api/otel/v1/logs", bytes.NewReader(raw)) + req.Header.Set("Content-Type", "application/json") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + if forwardedFor != "" { + req.Header.Set("X-Forwarded-For", forwardedFor) + } + resp, err := server.Client().Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() return resp.StatusCode } - if status := post(payload(9)); status != http.StatusNoContent { + if status := post(payload(9), "", "198.51.100.10"); status != http.StatusUnauthorized { + t.Fatalf("unauthenticated status %d", status) + } + if status := post(payload(9), token, "198.51.100.11"); status != http.StatusNoContent { t.Fatalf("info status %d", status) } - if status := post(payload(17)); status != http.StatusAccepted { + if status := post(payload(17), token, "198.51.100.12"); status != http.StatusAccepted { t.Fatalf("error status %d", status) } select { @@ -91,6 +104,83 @@ func TestPublicOTelContractAndFiltering(t *testing.T) { } } +func TestOTelLimiterBoundsAndExpiresIdentityBuckets(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + limits := newOTelLimiter() + for i := 0; i < otelMaxRateBuckets; i++ { + if limits.rateLimited(fmt.Sprintf("actor-%d", i), now) { + t.Fatalf("actor %d was rejected before the bucket cap", i) + } + } + if !limits.rateLimited("overflow", now) { + t.Fatal("new identity was accepted beyond the bucket cap") + } + if len(limits.clients) != otelMaxRateBuckets { + t.Fatalf("bucket count %d exceeds fixed cap %d", len(limits.clients), otelMaxRateBuckets) + } + if limits.rateLimited("fresh", now.Add(otelRateWindow)) { + t.Fatal("fresh identity was rejected after stale buckets expired") + } + if len(limits.clients) != 1 { + t.Fatalf("expired buckets were not evicted: %d remain", len(limits.clients)) + } +} + +func TestOTelLimiterAppliesGlobalResourceCaps(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + clientLimits := newOTelLimiter() + for request := 0; request < otelClientRequestLimit; request++ { + if clientLimits.rateLimited("same-actor", now) { + t.Fatalf("request %d was rejected before the per-client cap", request) + } + } + if !clientLimits.rateLimited("same-actor", now) { + t.Fatal("request was accepted beyond the per-client cap") + } + + limits := newOTelLimiter() + for actor := 0; actor < otelGlobalRequestLimit/otelClientRequestLimit; actor++ { + for request := 0; request < otelClientRequestLimit; request++ { + if limits.rateLimited(fmt.Sprintf("actor-%d", actor), now) { + t.Fatalf("request %d for actor %d was rejected before the global cap", request, actor) + } + } + } + if !limits.rateLimited("global-overflow", now) { + t.Fatal("request was accepted beyond the global cap") + } + + byteLimits := newOTelLimiter() + if byteLimits.bytesLimited(otelGlobalByteLimit-1, now) || !byteLimits.bytesLimited(2, now) { + t.Fatal("global byte budget did not reject overflow") + } + byteLimits = newOTelLimiter() + byteLimits.global = otelGlobalBucket{bytes: otelGlobalByteLimit - 1, resetAt: now.Add(otelRateWindow)} + reader := &otelByteBudgetReader{reader: strings.NewReader("xx"), limits: byteLimits, now: func() time.Time { return now }} + if _, err := io.ReadAll(reader); !errors.Is(err, errOTelByteBudget) { + t.Fatalf("body reader did not enforce the global byte budget: %v", err) + } + for i := 0; i < otelMaxConcurrentIngest; i++ { + if !acquireOTelSlot(byteLimits.ingestSlots) { + t.Fatalf("ingest slot %d was rejected before the concurrency cap", i) + } + } + if acquireOTelSlot(byteLimits.ingestSlots) { + t.Fatal("ingest was accepted beyond the concurrency cap") + } + for i := 0; i < otelMaxConcurrentIngest; i++ { + <-byteLimits.ingestSlots + } + for i := 0; i < otelMaxConcurrentForwards; i++ { + if !acquireOTelSlot(byteLimits.forwardSlots) { + t.Fatalf("forward slot %d was rejected before the concurrency cap", i) + } + } + if acquireOTelSlot(byteLimits.forwardSlots) { + t.Fatal("forward was accepted beyond the concurrency cap") + } +} + func TestPublicRunnerTokenRoutes(t *testing.T) { d := testDeps(t) seedTenant(t, d, "tenant") diff --git a/apps/server/internal/runtime/runner_hub.go b/apps/server/internal/runtime/runner_hub.go index 7053fe32..d0e81f65 100644 --- a/apps/server/internal/runtime/runner_hub.go +++ b/apps/server/internal/runtime/runner_hub.go @@ -202,6 +202,9 @@ func (h *handler) runnerHubHTTP(w http.ResponseWriter, r *http.Request) { if err != nil { return } + // The credential remains node authentication material, but it is no longer + // retained as retrievable installation material after successful enrollment. + runnerTokenCache.Delete(nodeID) ticker := time.NewTicker(20 * time.Second) defer ticker.Stop() for { diff --git a/apps/server/internal/runtime/runtime_node_install_authorization_test.go b/apps/server/internal/runtime/runtime_node_install_authorization_test.go new file mode 100644 index 00000000..446997f8 --- /dev/null +++ b/apps/server/internal/runtime/runtime_node_install_authorization_test.go @@ -0,0 +1,114 @@ +package runtime + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Moonrend/Zakura/apps/server/internal/platform/db/models" + "github.com/Moonrend/Zakura/apps/server/internal/platform/httpx" + "github.com/go-chi/chi/v5" +) + +func TestSharedRuntimeNodeInstallMaterialRequiresOwningPlatformAdmin(t *testing.T) { + d := testDeps(t) + seedTenant(t, d, "owner-tenant") + seedTenant(t, d, "other-tenant") + now := runtimeTimeString(d.Clock()) + id := "shared-node" + node := models.RuntimeNode{ID: &id, TenantID: "owner-tenant", Name: "Shared", Slug: "shared", Kind: "computer", Status: "offline", CapabilitiesJSON: "{}", HostInfoJSON: "{}", StorageRoot: "/var/lib/zakura", LabelsJSON: "{}", IsShared: true, CreatedAt: now, UpdatedAt: now} + if err := d.Gorm.Create(&node).Error; err != nil { + t.Fatal(err) + } + h := &handler{deps: d, store: NewStore(d), hub: newRunnerHub(d)} + const token = "rnr_shared-install-secret" + runnerTokenCache.Store(id, token) + t.Cleanup(func() { runnerTokenCache.Delete(id) }) + router := chi.NewRouter() + router.Get("/runtime-nodes/{id}/install", h.runtimeInstallInfo) + router.Get("/runtime-nodes/{id}/detail", h.runtimeNodeDetail) + request := func(path string, actor httpx.Principal) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodGet, path, nil) + router.ServeHTTP(w, r.WithContext(httpx.WithPrincipal(context.Background(), actor))) + return w + } + + foreign := httpx.Principal{TenantID: "other-tenant", Role: "owner", IsPlatformAdmin: true} + if w := request("/runtime-nodes/shared-node/install", foreign); w.Code != http.StatusNotFound || strings.Contains(w.Body.String(), token) { + t.Fatalf("foreign shared install response: %d %s", w.Code, w.Body.String()) + } + w := request("/runtime-nodes/shared-node/detail", foreign) + if w.Code != http.StatusOK || strings.Contains(w.Body.String(), token) { + t.Fatalf("foreign shared detail response: %d %s", w.Code, w.Body.String()) + } + var detail struct { + Node struct { + Access string `json:"access"` + } `json:"node"` + Install any `json:"install"` + InstallTailscale any `json:"installTailscale"` + } + if err := json.Unmarshal(w.Body.Bytes(), &detail); err != nil || detail.Node.Access != "shared" || detail.Install != nil || detail.InstallTailscale != nil { + t.Fatalf("shared detail contains installation material: %#v, %v", detail, err) + } + + owner := httpx.Principal{TenantID: "owner-tenant", Role: "owner", IsPlatformAdmin: true} + w = request("/runtime-nodes/shared-node/install", owner) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), token) || w.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("owning platform admin install response: %d %s", w.Code, w.Body.String()) + } + owner.IsPlatformAdmin = false + if w := request("/runtime-nodes/shared-node/install", owner); w.Code != http.StatusForbidden || strings.Contains(w.Body.String(), token) { + t.Fatalf("non-platform shared install response: %d %s", w.Code, w.Body.String()) + } +} + +func TestRuntimeNodeInstallAuthorizationRejectsUntrustedPrincipals(t *testing.T) { + d := testDeps(t) + seedTenant(t, d, "tenant") + now := runtimeTimeString(d.Clock()) + id := "owned-node" + node := models.RuntimeNode{ID: &id, TenantID: "tenant", Name: "Owned", Slug: "owned", Kind: "computer", Status: "offline", CapabilitiesJSON: "{}", HostInfoJSON: "{}", StorageRoot: "/var/lib/zakura", LabelsJSON: "{}", CreatedAt: now, UpdatedAt: now} + if err := d.Gorm.Create(&node).Error; err != nil { + t.Fatal(err) + } + h := &handler{deps: d} + for _, actor := range []httpx.Principal{ + {TenantID: "tenant", Role: "member"}, + {TenantID: "tenant", Role: "owner", APIKey: true}, + {TenantID: "tenant", Role: "owner", SpaceID: "space"}, + {TenantID: "tenant", Role: "owner", AgentID: "agent"}, + } { + if err := h.authorizeRuntimeNodeInstall(context.Background(), actor, id); !errors.Is(err, errRuntimeNodeInstallForbidden) { + t.Fatalf("untrusted principal authorization error = %v", err) + } + } + if err := h.authorizeRuntimeNodeInstall(context.Background(), httpx.Principal{TenantID: "tenant", Role: "admin"}, id); err != nil { + t.Fatalf("tenant admin authorization error = %v", err) + } +} + +func TestManualNodeAuthenticationDoesNotRestoreInstallMaterial(t *testing.T) { + d := testDeps(t) + seedTenant(t, d, "tenant") + now := runtimeTimeString(d.Clock()) + id := "manual-node" + node := models.RuntimeNode{ID: &id, TenantID: "tenant", Name: "Manual", Slug: "manual", Kind: "computer", Status: "offline", CapabilitiesJSON: "{}", HostInfoJSON: "{}", StorageRoot: "/var/lib/zakura", LabelsJSON: "{}", CreatedAt: now, UpdatedAt: now} + if err := d.Gorm.Create(&node).Error; err != nil { + t.Fatal(err) + } + runnerTokenCache.Delete(id) + h := &handler{deps: d} + incarnation, err := h.cacheRuntimeNodeToken(context.Background(), id, "rnr_runtime-credential") + if err != nil || incarnation != "" { + t.Fatalf("manual node authentication failed: %q %v", incarnation, err) + } + if _, ok := runnerTokenCache.Load(id); ok { + t.Fatal("manual node authentication restored installation material") + } +} diff --git a/apps/server/internal/runtime/runtime_nodes_extra.go b/apps/server/internal/runtime/runtime_nodes_extra.go index 8ed7fd19..6632528f 100644 --- a/apps/server/internal/runtime/runtime_nodes_extra.go +++ b/apps/server/internal/runtime/runtime_nodes_extra.go @@ -27,6 +27,7 @@ import ( "github.com/Moonrend/Zakura/apps/server/internal/platform/db/models" "github.com/Moonrend/Zakura/apps/server/internal/platform/httpx" "github.com/go-chi/chi/v5" + "gorm.io/gorm" ) var runnerTokenCache sync.Map @@ -106,6 +107,7 @@ func (h *handler) registerRuntimeNode(w http.ResponseWriter, r *http.Request) { statusErr(w, e) return } + runnerTokenCache.Delete(nodeID) node, e := scanRuntimeNode(h.deps.Gorm.WithContext(r.Context()).Raw(`SELECT id,name,slug,kind,status,endpoint,capabilities_json,host_info_json,storage_root,agent_version,last_seen_at,labels_json,is_shared,created_at,updated_at FROM runtime_nodes WHERE id=?`, nodeID).Row()) if e != nil { statusErr(w, e) @@ -164,26 +166,36 @@ func (h *handler) runtimeAgentBinary(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, file) } func (h *handler) runtimeInstallInfo(w http.ResponseWriter, r *http.Request) { + if err := h.authorizeRuntimeNodeInstall(r.Context(), principal(r), chi.URLParam(r, "id")); err != nil { + if errors.Is(err, errRuntimeNodeInstallForbidden) { + httpx.Error(w, http.StatusForbidden, err.Error()) + } else { + statusErr(w, err) + } + return + } node, e := h.getRuntimeNodeMap(r) if e != nil { statusErr(w, e) return } - token, _ := runnerTokenCache.Load(chi.URLParam(r, "id")) - if token == nil { + cached, ok := runnerTokenCache.Load(chi.URLParam(r, "id")) + token, ok := cached.(string) + if !ok { httpx.Error(w, http.StatusBadRequest, "registration token is no longer available; recreate the node") return } loginServer, tsAvailable := h.runnerTailscaleMeta(r.Context(), principal(r).TenantID) - install := h.runnerInstallPackage(node, token.(string), "") + install := h.runnerInstallPackage(node, token, "") installTailscale := any(nil) if tsAvailable { - installTailscale = h.runnerInstallPackage(node, token.(string), loginServer) + installTailscale = h.runnerInstallPackage(node, token, loginServer) } var meshProvider any if tsAvailable { meshProvider = "headscale-platform" } + w.Header().Set("Cache-Control", "no-store") httpx.JSON(w, http.StatusOK, map[string]any{"node": node, "install": install, "installTailscale": installTailscale, "meshConnected": tsAvailable, "hostJoinsTailscale": tsAvailable, "meshProvider": meshProvider, "tokenHint": "rnr_…"}) } @@ -200,16 +212,22 @@ func (h *handler) runtimeNodeDetail(w http.ResponseWriter, r *http.Request) { } loginServer, tsAvailable := h.runnerTailscaleMeta(r.Context(), principal(r).TenantID) var install, installTailscale any - if token, ok := runnerTokenCache.Load(chi.URLParam(r, "id")); ok { - install = h.runnerInstallPackage(node, token.(string), "") - if tsAvailable { - installTailscale = h.runnerInstallPackage(node, token.(string), loginServer) + shared, _ := node["isShared"].(bool) + if !shared && h.authorizeRuntimeNodeInstall(r.Context(), principal(r), chi.URLParam(r, "id")) == nil { + if cached, ok := runnerTokenCache.Load(chi.URLParam(r, "id")); ok { + if token, ok := cached.(string); ok { + install = h.runnerInstallPackage(node, token, "") + if tsAvailable { + installTailscale = h.runnerInstallPackage(node, token, loginServer) + } + } } } var meshProvider any if tsAvailable { meshProvider = "headscale-platform" } + w.Header().Set("Cache-Control", "no-store") httpx.JSON(w, http.StatusOK, map[string]any{"node": node, "containers": containers, "install": install, "installTailscale": installTailscale, "meshConnected": tsAvailable, "hostJoinsTailscale": tsAvailable, "meshProvider": meshProvider, "tailscaleError": nil, "tokenHint": nil}) } @@ -337,6 +355,27 @@ func runnerShellInstaller(server, token, kind, prelude string) string { func shellQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'" } var errRuntimeNodeUpdateForbidden = errors.New("platform admin required") +var errRuntimeNodeInstallForbidden = errors.New("node installation permission required") + +func (h *handler) authorizeRuntimeNodeInstall(ctx context.Context, actor httpx.Principal, nodeID string) error { + if actor.APIKey || actor.SpaceID != "" || actor.AgentID != "" || !actor.IsPlatformAdmin && actor.Role != "owner" && actor.Role != "admin" { + return errRuntimeNodeInstallForbidden + } + var node struct { + IsShared bool `gorm:"column:is_shared"` + } + err := h.deps.Gorm.WithContext(ctx).Table("runtime_nodes").Select("is_shared").Where("tenant_id=? AND id=? AND kind<>'local'", actor.TenantID, nodeID).Take(&node).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return ErrNotFound + } + if err != nil { + return err + } + if node.IsShared && !actor.IsPlatformAdmin { + return errRuntimeNodeInstallForbidden + } + return nil +} func (h *handler) authorizeRuntimeNodeUpdate(ctx context.Context, actor httpx.Principal, nodeID string) error { if !actor.IsPlatformAdmin { @@ -355,6 +394,11 @@ func (h *handler) authorizeRuntimeNodeUpdate(ctx context.Context, actor httpx.Pr func (h *handler) getRuntimeNodeMap(r *http.Request) (map[string]any, error) { node, err := scanRuntimeNode(h.deps.Gorm.WithContext(r.Context()).Raw(`SELECT id,name,slug,kind,status,endpoint,capabilities_json,host_info_json,storage_root,agent_version,last_seen_at,labels_json,is_shared,created_at,updated_at FROM runtime_nodes WHERE (tenant_id=? OR is_shared=true) AND id=?`, principal(r).TenantID, chi.URLParam(r, "id")).Row()) if err == nil { + if shared, _ := node["isShared"].(bool); shared { + node["access"] = "shared" + } else { + node["access"] = "owned" + } h.projectRuntimeNode(node) } return node, err @@ -376,6 +420,7 @@ func (h *handler) runtimeInstallSh(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("tailscale") == "1" { tailscalePrelude = h.runnerTailscalePrelude(r.Context(), chi.URLParam(r, "id")) } + w.Header().Set("Cache-Control", "no-store") w.Header().Set("Content-Type", "text/x-shellscript; charset=utf-8") _, _ = io.WriteString(w, runnerShellInstaller(strings.TrimRight(h.deps.PublicURL, "/"), token, kind, tailscalePrelude)) } @@ -392,6 +437,7 @@ func (h *handler) runtimeInstallPS(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("kind") == "server" { kind = "server" } + w.Header().Set("Cache-Control", "no-store") w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("X-Content-Type-Options", "nosniff") fmt.Fprintf(w, "$env:ZAKURA_AGENT_SERVER = '%s'\n$env:ZAKURA_AGENT_TOKEN = '%s'\n$env:ZAKURA_AGENT_KIND = '%s'\n", strings.ReplaceAll(strings.TrimRight(h.deps.PublicURL, "/"), "'", "''"), strings.ReplaceAll(token, "'", "''"), kind) @@ -404,6 +450,7 @@ func (h *handler) runtimeBootstrapSh(w http.ResponseWriter, r *http.Request) { return } target := "/api/runtime-nodes/" + url.PathEscape(chi.URLParam(r, "id")) + "/install.sh?" + r.URL.Query().Encode() + w.Header().Set("Cache-Control", "no-store") http.Redirect(w, r, target, http.StatusFound) } @@ -560,6 +607,14 @@ func (h *handler) runRunnerUpdate(ctx context.Context, session *runnerSession, j }) } func (h *handler) refreshWorkspaceImage(w http.ResponseWriter, r *http.Request) { + if err := h.authorizeRuntimeNodeUpdate(r.Context(), principal(r), chi.URLParam(r, "id")); err != nil { + if errors.Is(err, errRuntimeNodeUpdateForbidden) { + httpx.Error(w, http.StatusForbidden, err.Error()) + } else { + statusErr(w, err) + } + return + } var body struct { Image string `json:"image"` RecreateRunning *bool `json:"recreateRunning"` diff --git a/apps/server/internal/runtime/runtime_test.go b/apps/server/internal/runtime/runtime_test.go index f2f28391..9c782aa1 100644 --- a/apps/server/internal/runtime/runtime_test.go +++ b/apps/server/internal/runtime/runtime_test.go @@ -22,6 +22,7 @@ import ( "github.com/Moonrend/Zakura/apps/server/internal/platform/appdeps" "github.com/Moonrend/Zakura/apps/server/internal/platform/migrations" "github.com/go-chi/chi/v5" + "github.com/golang-jwt/jwt/v5" _ "github.com/mattn/go-sqlite3" "gorm.io/driver/sqlite" "gorm.io/gorm" @@ -51,7 +52,7 @@ func testDepsTB(t testing.TB) *appdeps.Dependencies { if gerr != nil { t.Fatal(gerr) } - return &appdeps.Dependencies{Context: ctx, DB: db, Gorm: gdb, Dialect: "sqlite", Rebind: appdeps.IdentityRebind, Clock: func() time.Time { return time.Now().UTC() }, NewID: func() string { return fmt.Sprintf("id-%06d", n.Add(1)) }, Secret: bytes.Repeat([]byte("s"), 32), PublicURL: "http://example.test"} + return &appdeps.Dependencies{Context: ctx, DB: db, Gorm: gdb, Dialect: "sqlite", Rebind: appdeps.IdentityRebind, Clock: func() time.Time { return time.Now().UTC() }, NewID: func() string { return fmt.Sprintf("id-%06d", n.Add(1)) }, Secret: bytes.Repeat([]byte("s"), 32), PublicURL: "http://example.test", ProviderTestPrivate: true} } func seedTenant(t testing.TB, d *appdeps.Dependencies, id string) string { t.Helper() @@ -66,6 +67,31 @@ func seedTenant(t testing.TB, d *appdeps.Dependencies, id string) string { } return token } + +func seedProviderAdmin(t testing.TB, d *appdeps.Dependencies, tenant string) string { + t.Helper() + seedTenant(t, d, tenant) + now := d.Clock().UTC() + expires := now.Add(time.Hour) + userID := "provider-admin-" + tenant + sessionID := "provider-session-" + tenant + email := "provider-admin-" + tenant + "@example.test" + if _, err := d.DB.Exec(d.Rebind(`INSERT INTO users(id,email,password_hash,name,status,is_platform_admin,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?)`), userID, email, "unused", "Provider Admin", "active", false, now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano)); err != nil { + t.Fatal(err) + } + if _, err := d.DB.Exec(d.Rebind(`INSERT INTO tenant_memberships(id,tenant_id,user_id,role,status,created_at,updated_at) VALUES(?,?,?,?,?,?,?)`), "provider-membership-"+tenant, tenant, userID, "owner", "active", now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano)); err != nil { + t.Fatal(err) + } + token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{"sub": userID, "tenantId": tenant, "email": email, "role": "owner", "sid": sessionID, "isPlatformAdmin": false, "iat": now.Unix(), "exp": expires.Unix()}).SignedString(d.Secret) + if err != nil { + t.Fatal(err) + } + sum := sha256.Sum256([]byte(token)) + if _, err = d.DB.Exec(d.Rebind(`INSERT INTO user_sessions(id,user_id,tenant_id,email,role,is_platform_admin,token_hash,expires_at,last_seen_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)`), sessionID, userID, tenant, email, "owner", false, hex.EncodeToString(sum[:]), expires.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano)); err != nil { + t.Fatal(err) + } + return token +} func doJSON(t *testing.T, c *http.Client, method, url, token string, body any) (int, map[string]any) { t.Helper() var raw []byte @@ -100,7 +126,7 @@ func doArray(t *testing.T, c *http.Client, method, url, token string) (int, []an func TestHTTPDurabilityTenantIsolationAndQueue(t *testing.T) { d := testDeps(t) - tok1, tok2 := seedTenant(t, d, "tenant-a"), seedTenant(t, d, "tenant-b") + tok1, tok2 := seedProviderAdmin(t, d, "tenant-a"), seedTenant(t, d, "tenant-b") entered := make(chan struct{}, 2) release := make(chan struct{}) provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -258,6 +284,53 @@ func TestRunCancellationAndPathJail(t *testing.T) { } } +func TestFileShareResponsePolicy(t *testing.T) { + tests := []struct { + name string + mimeType string + disposition string + wantMIME string + wantDisposition string + }{ + {name: "raster image remains inline", mimeType: "image/png", disposition: "inline", wantMIME: "image/png", wantDisposition: "inline"}, + {name: "plain text remains inline", mimeType: "text/plain; charset=utf-8", disposition: "inline", wantMIME: "text/plain; charset=utf-8", wantDisposition: "inline"}, + {name: "html becomes attachment", mimeType: "text/html; charset=utf-8", disposition: "inline", wantMIME: "text/html; charset=utf-8", wantDisposition: "attachment"}, + {name: "svg becomes attachment", mimeType: "image/svg+xml", disposition: "inline", wantMIME: "image/svg+xml", wantDisposition: "attachment"}, + {name: "pdf becomes attachment", mimeType: "application/pdf", disposition: "inline", wantMIME: "application/pdf", wantDisposition: "attachment"}, + {name: "malformed mime becomes download", mimeType: "text/plain\r\nContent-Type: text/html", disposition: "inline", wantMIME: "application/octet-stream", wantDisposition: "attachment"}, + {name: "missing mime becomes download", disposition: "inline", wantMIME: "application/octet-stream", wantDisposition: "attachment"}, + {name: "requested attachment remains download", mimeType: "image/png", disposition: "attachment", wantMIME: "image/png", wantDisposition: "attachment"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + gotMIME, gotDisposition := fileShareResponsePolicy(test.mimeType, test.disposition) + if gotMIME != test.wantMIME || gotDisposition != test.wantDisposition { + t.Fatalf("policy(%q, %q) = (%q, %q), want (%q, %q)", test.mimeType, test.disposition, gotMIME, gotDisposition, test.wantMIME, test.wantDisposition) + } + }) + } +} + +func TestFileShareResponseHeadersRevalidateStoredPolicy(t *testing.T) { + response := httptest.NewRecorder() + name := setFileShareResponseHeaders(response, "text/html", "inline", "attack.html", 42) + if name != "attack.html" { + t.Fatalf("response filename: %q", name) + } + if got := response.Header().Get("Content-Disposition"); got != `attachment; filename="attack.html"` { + t.Fatalf("stored active content disposition: %q", got) + } + if got := response.Header().Get("Content-Type"); got != "text/html" { + t.Fatalf("response content type: %q", got) + } + if got := response.Header().Get("Content-Security-Policy"); got != "default-src 'none'; sandbox" { + t.Fatalf("response CSP: %q", got) + } + if got := response.Header().Get("X-Content-Type-Options"); got != "nosniff" { + t.Fatalf("response content type protection: %q", got) + } +} + func TestRunnerEnrollmentAndFileShare(t *testing.T) { d := testDeps(t) token := seedTenant(t, d, "tenant") @@ -343,11 +416,15 @@ func TestRunnerEnrollmentAndFileShare(t *testing.T) { if code != 409 { t.Fatalf("expected revision conflict, got %d", code) } - code, out = doJSON(t, client, "POST", server.URL+"/api/agents/"+agent+"/fs/share", token, map[string]any{"path": "report.txt", "ttlMinutes": 5}) + code, out = doJSON(t, client, "POST", server.URL+"/api/agents/"+agent+"/fs/share", token, map[string]any{"path": "report.txt", "mimeType": "text/html", "disposition": "inline", "ttlMinutes": 5}) if code != 201 { t.Fatalf("share: %d %#v", code, out) } - shareURL := out["share"].(map[string]any)["url"].(string) + share := out["share"].(map[string]any) + if share["disposition"] != "attachment" { + t.Fatalf("active content disposition: %#v", share) + } + shareURL := share["url"].(string) shareURL = strings.Replace(shareURL, d.PublicURL, server.URL, 1) resp, e := client.Get(shareURL) if e != nil { @@ -358,4 +435,13 @@ func TestRunnerEnrollmentAndFileShare(t *testing.T) { if resp.StatusCode != 200 || string(body) != "durable report" { t.Fatalf("download: %d %q", resp.StatusCode, body) } + if got := resp.Header.Get("Content-Disposition"); !strings.HasPrefix(got, "attachment;") { + t.Fatalf("active content served inline: %q", got) + } + if got := resp.Header.Get("Content-Security-Policy"); got != "default-src 'none'; sandbox" { + t.Fatalf("share CSP: %q", got) + } + if got := resp.Header.Get("X-Content-Type-Options"); got != "nosniff" { + t.Fatalf("share content type protection: %q", got) + } } diff --git a/apps/server/internal/runtime/runtime_update_authorization_test.go b/apps/server/internal/runtime/runtime_update_authorization_test.go index 24254950..c62125e1 100644 --- a/apps/server/internal/runtime/runtime_update_authorization_test.go +++ b/apps/server/internal/runtime/runtime_update_authorization_test.go @@ -4,10 +4,14 @@ package runtime import ( "context" "errors" + "net/http" + "net/http/httptest" + "strings" "testing" "github.com/Moonrend/Zakura/apps/server/internal/platform/db/models" "github.com/Moonrend/Zakura/apps/server/internal/platform/httpx" + "github.com/go-chi/chi/v5" ) func TestRuntimeNodeUpdateAuthorizationRequiresPlatformAdminOwnership(t *testing.T) { @@ -46,3 +50,47 @@ func TestRuntimeNodeUpdateAuthorizationRequiresPlatformAdminOwnership(t *testing }) } } + +func TestRefreshWorkspaceImageAuthorizesBeforeNodeSideEffects(t *testing.T) { + d := testDeps(t) + seedTenant(t, d, "tenant-a") + seedTenant(t, d, "tenant-b") + now := runtimeTimeString(d.Clock()) + node := func(id, tenant string, shared bool) models.RuntimeNode { + return models.RuntimeNode{ID: &id, TenantID: tenant, Name: id, Slug: id, Kind: "computer", Status: "online", CapabilitiesJSON: "{}", HostInfoJSON: "{}", StorageRoot: "/var/lib/zakura", LabelsJSON: "{}", IsShared: shared, CreatedAt: now, UpdatedAt: now} + } + for _, candidate := range []models.RuntimeNode{ + node("owned", "tenant-a", false), + node("foreign-shared", "tenant-b", true), + } { + if err := d.Gorm.Create(&candidate).Error; err != nil { + t.Fatal(err) + } + } + + h := &handler{deps: d} + for _, tc := range []struct { + name string + actor httpx.Principal + nodeID string + status int + }{ + {name: "member cannot refresh owned node", actor: httpx.Principal{TenantID: "tenant-a", Role: "member"}, nodeID: "owned", status: http.StatusForbidden}, + {name: "admin cannot refresh foreign shared node", actor: httpx.Principal{TenantID: "tenant-a", Role: "owner", IsPlatformAdmin: true}, nodeID: "foreign-shared", status: http.StatusNotFound}, + } { + t.Run(tc.name, func(t *testing.T) { + request := httptest.NewRequest(http.MethodPost, "/api/runtime-nodes/"+tc.nodeID+"/refresh-workspace-image", strings.NewReader(`{"image":"example.invalid/workspace:latest"}`)) + route := chi.NewRouteContext() + route.URLParams.Add("id", tc.nodeID) + ctx := context.WithValue(httpx.WithPrincipal(request.Context(), tc.actor), chi.RouteCtxKey, route) + request = request.WithContext(ctx) + + // The nil hub is intentional: denied requests must return before any Docker RPC. + response := httptest.NewRecorder() + h.refreshWorkspaceImage(response, request) + if response.Code != tc.status { + t.Fatalf("refreshWorkspaceImage() status = %d, want %d", response.Code, tc.status) + } + }) + } +} diff --git a/apps/server/internal/runtime/skills.go b/apps/server/internal/runtime/skills.go index 9d187e9e..b5dcacd9 100644 --- a/apps/server/internal/runtime/skills.go +++ b/apps/server/internal/runtime/skills.go @@ -851,7 +851,7 @@ func (h *handler) healthMemoryProvider(w http.ResponseWriter, r *http.Request) { httpx.JSON(w, http.StatusOK, map[string]any{"status": "unhealthy", "message": "baseUrl required"}) return } - u, e := safeProviderURL(baseURL, func() string { + u, e := h.providerURL(baseURL, func() string { if kind == "openviking" { return "health" } @@ -862,7 +862,7 @@ func (h *handler) healthMemoryProvider(w http.ResponseWriter, r *http.Request) { return } req, _ := http.NewRequestWithContext(r.Context(), http.MethodGet, u.String(), nil) - resp, e := h.service.gateway.client.Do(req) + resp, e := h.service.gateway.providerHTTPClient().Do(req) if e != nil { httpx.JSON(w, http.StatusOK, map[string]any{"status": "unhealthy", "message": e.Error()}) return diff --git a/apps/server/internal/runtime/space_workspace_proxy.go b/apps/server/internal/runtime/space_workspace_proxy.go index 63ee01cc..c37a607d 100644 --- a/apps/server/internal/runtime/space_workspace_proxy.go +++ b/apps/server/internal/runtime/space_workspace_proxy.go @@ -27,6 +27,8 @@ type spaceWorkspaceTarget struct { remote *remoteWorkspace } +var errLegacyHostWorkspace = errors.New("legacy host workspace requires migration to container mode") + // Resolve the canonical workspace, never a selected execution computer or the // first container matching a label. A server computer has no provider runtime. func (h *handler) resolveSpaceWorkspaceTarget(ctx context.Context, tenant, space, kind string) (*spaceWorkspaceTarget, error) { @@ -80,6 +82,17 @@ func (h *handler) resolveSpaceWorkspaceTarget(ctx context.Context, tenant, space return &spaceWorkspaceTarget{space: s, runner: runner, container: container, remote: remote, ticket: acpLoginTicket{Tenant: tenant, Space: space, Profile: "workspace-" + kind, Node: exec.nodeID, Computer: exec.computer.ID, ConfigHash: acpLoginDigest(raw)}}, nil } +func (h *handler) resolveSpaceWorkspaceConnectionTarget(ctx context.Context, tenant, space, kind string) (*spaceWorkspaceTarget, error) { + target, err := h.resolveSpaceWorkspaceTarget(ctx, tenant, space, kind) + if err != nil { + return nil, err + } + if target.space.WorkspaceKind == "host" { + return nil, errLegacyHostWorkspace + } + return target, nil +} + func (h *handler) workspaceTicketPrincipal(ctx context.Context, identity, tenant, space string) (httpx.Principal, error) { p := httpx.Principal{TenantID: tenant} if err := h.validateACPLoginPrincipal(ctx, identity, tenant, space); err != nil { @@ -173,7 +186,7 @@ func (h *handler) issueSpaceWorkspaceTicket(w http.ResponseWriter, r *http.Reque } defer lease.release() ctx = context.WithValue(ctx, workspaceRequestTargetKey{}, lease.Space) - target, err := h.resolveSpaceWorkspaceTarget(ctx, p.TenantID, space, kind) + target, err := h.resolveSpaceWorkspaceConnectionTarget(ctx, p.TenantID, space, kind) if err != nil { h.serverComputerLifecycleError(w, err) return @@ -238,7 +251,7 @@ func (h *handler) consumeSpaceWorkspaceTicket(ctx context.Context, token, space, return nil, nil, ctx, invalid } ctx = context.WithValue(ctx, workspaceRequestTargetKey{}, lease.Space) - target, err := h.resolveSpaceWorkspaceTarget(ctx, ticket.Tenant, space, kind) + target, err := h.resolveSpaceWorkspaceConnectionTarget(ctx, ticket.Tenant, space, kind) if err != nil || target.ticket.Node != ticket.Node || target.ticket.Computer != ticket.Computer || target.ticket.ConfigHash != ticket.ConfigHash { return fail() } @@ -270,7 +283,7 @@ func (h *handler) recheckSpaceWorkspaceConnection(ctx context.Context, target *s if err := h.requireSpaceInfrastructureAvailable(ctx, target.ticket.Tenant, target.ticket.Space); err != nil { return err } - current, err := h.resolveSpaceWorkspaceTarget(ctx, target.ticket.Tenant, target.ticket.Space, kind) + current, err := h.resolveSpaceWorkspaceConnectionTarget(ctx, target.ticket.Tenant, target.ticket.Space, kind) if err != nil { return err } diff --git a/apps/server/internal/runtime/space_workspace_proxy_test.go b/apps/server/internal/runtime/space_workspace_proxy_test.go index 0dfb330e..f9060ab0 100644 --- a/apps/server/internal/runtime/space_workspace_proxy_test.go +++ b/apps/server/internal/runtime/space_workspace_proxy_test.go @@ -104,6 +104,52 @@ func (rig *workspaceProxyRig) issueAs(t *testing.T, kind string, actor httpx.Pri return response.Ticket } +func TestSpaceWorkspaceTicketRejectsLegacyHostWorkspace(t *testing.T) { + rig := newWorkspaceProxyRig(t) + if err := rig.h.deps.Gorm.Table("spaces").Where("id=?", rig.space.ID).Update("workspace_kind", "host").Error; err != nil { + t.Fatal(err) + } + router := chi.NewRouter() + router.Post("/spaces/{id}/ticket", func(w http.ResponseWriter, r *http.Request) { rig.h.issueSpaceWorkspaceTicket(w, r, "terminal") }) + req := httptest.NewRequest(http.MethodPost, "/spaces/"+rig.space.ID+"/ticket", nil) + req = req.WithContext(httpx.WithPrincipal(req.Context(), acpLoginPrincipal())) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), "migration") { + t.Fatalf("legacy host ticket: %d %s", w.Code, w.Body) + } + var tickets int64 + if err := rig.h.deps.Gorm.Table("runtime_connection_tickets").Count(&tickets).Error; err != nil || tickets != 0 { + t.Fatalf("legacy host ticket persisted: %d %v", tickets, err) + } + rig.mu.Lock() + defer rig.mu.Unlock() + for _, call := range rig.calls { + if strings.HasPrefix(call.method, "host.pty.") { + t.Fatalf("legacy host ticket reached runner method %s", call.method) + } + } +} + +func TestSpaceWorkspaceTicketRejectsHostModeAfterIssue(t *testing.T) { + rig := newWorkspaceProxyRig(t) + token := rig.issue(t, "terminal") + if err := rig.h.deps.Gorm.Table("spaces").Where("id=?", rig.space.ID).Update("workspace_kind", "host").Error; err != nil { + t.Fatal(err) + } + if _, lease, _, err := rig.h.consumeSpaceWorkspaceTicket(context.Background(), token, rig.space.ID, "terminal"); err == nil { + lease.release() + t.Fatal("terminal ticket survived migration to legacy host mode") + } + rig.mu.Lock() + defer rig.mu.Unlock() + for _, call := range rig.calls { + if strings.HasPrefix(call.method, "host.pty.") { + t.Fatalf("legacy host ticket reached runner method %s", call.method) + } + } +} + func TestSpaceWorkspaceTicketRevalidation(t *testing.T) { for _, scenario := range []string{"valid", "cross-space", "cross-kind", "tampered", "expired", "revoked-key", "changed-container", "changed-node", "migrating"} { t.Run(scenario, func(t *testing.T) { diff --git a/apps/server/internal/runtime/tool_approval_jev_execution_test.go b/apps/server/internal/runtime/tool_approval_jev_execution_test.go index a8607b8d..268b0071 100644 --- a/apps/server/internal/runtime/tool_approval_jev_execution_test.go +++ b/apps/server/internal/runtime/tool_approval_jev_execution_test.go @@ -53,11 +53,11 @@ func TestToolApprovalJevExecutionPaths(t *testing.T) { var releaseOnce sync.Once releaseEvaluation := func() { releaseOnce.Do(func() { close(release) }) } defer releaseEvaluation() - base := gateway.client.Transport + base := gateway.providerHTTPClient().Transport if base == nil { base = http.DefaultTransport } - gateway.client = &http.Client{Transport: approvalRoundTripper(func(req *http.Request) (*http.Response, error) { + gateway.providerClient = &http.Client{Transport: approvalRoundTripper(func(req *http.Request) (*http.Response, error) { response, err := base.RoundTrip(req) if err != nil { return nil, err diff --git a/apps/server/internal/runtime/tool_approval_jev_test.go b/apps/server/internal/runtime/tool_approval_jev_test.go index a7441baa..86aa78c5 100644 --- a/apps/server/internal/runtime/tool_approval_jev_test.go +++ b/apps/server/internal/runtime/tool_approval_jev_test.go @@ -112,11 +112,11 @@ func TestToolApprovalJevPolicyChangeDuringEvaluation(t *testing.T) { } // Change the persisted policy after the provider has returned but before the // shared gate can authorize execution. No external side effect lives in CAS. - base := gateway.client.Transport + base := gateway.providerHTTPClient().Transport if base == nil { base = http.DefaultTransport } - gateway.client = &http.Client{Transport: approvalRoundTripper(func(req *http.Request) (*http.Response, error) { + gateway.providerClient = &http.Client{Transport: approvalRoundTripper(func(req *http.Request) (*http.Response, error) { response, err := base.RoundTrip(req) if err != nil { return nil, err @@ -182,12 +182,12 @@ func TestToolApprovalJevReceivesBoundedContext(t *testing.T) { } args = json.RawMessage(`{"computerId":"attached","path":"/workspace/project/note","apiKey":"private-argument-sentinel"}`) } - base := gateway.client.Transport + base := gateway.providerHTTPClient().Transport if base == nil { base = http.DefaultTransport } var captured []byte - gateway.client = &http.Client{Transport: approvalRoundTripper(func(req *http.Request) (*http.Response, error) { + gateway.providerClient = &http.Client{Transport: approvalRoundTripper(func(req *http.Request) (*http.Response, error) { body, err := io.ReadAll(req.Body) if err != nil { return nil, err diff --git a/apps/server/internal/runtime/workspace.go b/apps/server/internal/runtime/workspace.go index bc4743d4..a1a3e6b9 100644 --- a/apps/server/internal/runtime/workspace.go +++ b/apps/server/internal/runtime/workspace.go @@ -973,6 +973,7 @@ func (h *handler) createRuntimeNode(w http.ResponseWriter, r *http.Request) { if tsAvailable { meshProvider = "headscale-platform" } + w.Header().Set("Cache-Control", "no-store") httpx.JSON(w, http.StatusCreated, map[string]any{"node": node, "token": token, "install": install, "installTailscale": installTailscale, "hostJoinsTailscale": tsAvailable, "meshProvider": meshProvider}) } func (h *handler) patchRuntimeNode(w http.ResponseWriter, r *http.Request) { diff --git a/apps/server/internal/runtime/workspace_host_terminal_test.go b/apps/server/internal/runtime/workspace_host_terminal_test.go index 3a767b3d..507b950a 100644 --- a/apps/server/internal/runtime/workspace_host_terminal_test.go +++ b/apps/server/internal/runtime/workspace_host_terminal_test.go @@ -6,71 +6,54 @@ import ( "context" "encoding/json" "net" - "reflect" "strings" "testing" "time" ) -func TestSpaceWorkspaceTerminalSelectsHostShell(t *testing.T) { - for _, platform := range []string{"windows", "linux", "legacy-windows"} { - t.Run(platform, func(t *testing.T) { - d := testDeps(t) - seedTenant(t, d, "tenant") - starts := make(chan map[string]any, 1) - h := builtinToolHarness(t, d, "rnr_host_shell", func(method string, params map[string]any) (any, error) { - switch method { - case "sys.info": - info := codemodeInfo() - if platform == "legacy-windows" { - info["hostInfo"] = map[string]any{"platform": "windows"} - } else { - info["goos"] = platform - } - return info, nil - case "host.pty.start": - starts <- params - return map[string]any{"id": "host-terminal"}, nil - default: - return map[string]any{"ok": true}, nil - } - }) - runner, err := h.hub.get("node") - if err != nil { - t.Fatal(err) - } - server, client := net.Pipe() - defer server.Close() - defer client.Close() - bridge := &workspaceBridge{conn: server, rw: bufio.NewReadWriter(bufio.NewReader(server), bufio.NewWriter(server))} - done := make(chan struct{}) - go func() { - defer close(done) - h.bridgeTerminalContainer(context.Background(), bridge, runner, "space", "host", "", "") - }() - _ = client.SetReadDeadline(time.Now().Add(2 * time.Second)) - raw, err := readRunnerServerText(bufio.NewReader(client)) - if err != nil { - t.Fatal(err) - } - var ready struct{ Type, Command string } - if err := json.Unmarshal([]byte(raw), &ready); err != nil || ready.Type != "ready" { - t.Fatalf("terminal ready=%s err=%v", raw, err) - } - want := []string{"bash", "-l"} - if platform != "linux" { - want = []string{"powershell.exe", "-NoLogo", "-NoProfile"} - } - params := <-starts - if !reflect.DeepEqual(stringSlice(params["command"]), want) || ready.Command != strings.Join(want, " ") || params["spaceId"] != "space" || params["workingDir"] != "/workspace" { - t.Fatalf("shell allocation=%#v ready=%+v want=%v", params, ready, want) - } - _ = client.Close() +func TestSpaceWorkspaceTerminalRejectsHostMode(t *testing.T) { + d := testDeps(t) + seedTenant(t, d, "tenant") + hostCalls := make(chan string, 1) + h := builtinToolHarness(t, d, "rnr_host_shell", func(method string, params map[string]any) (any, error) { + if strings.HasPrefix(method, "host.pty.") { select { - case <-done: - case <-time.After(time.Second): - t.Fatal("host terminal did not close") + case hostCalls <- method: + default: } - }) + } + return map[string]any{"ok": true}, nil + }) + runner, err := h.hub.get("node") + if err != nil { + t.Fatal(err) + } + server, client := net.Pipe() + defer server.Close() + defer client.Close() + bridge := &workspaceBridge{conn: server, rw: bufio.NewReadWriter(bufio.NewReader(server), bufio.NewWriter(server))} + done := make(chan struct{}) + go func() { + defer close(done) + h.bridgeTerminalContainer(context.Background(), bridge, runner, "space", "host", "", "") + }() + _ = client.SetReadDeadline(time.Now().Add(2 * time.Second)) + raw, err := readRunnerServerText(bufio.NewReader(client)) + if err != nil { + t.Fatal(err) + } + var response struct{ Type, Message string } + if err := json.Unmarshal([]byte(raw), &response); err != nil || response.Type != "error" || !strings.Contains(response.Message, "migration") { + t.Fatalf("host terminal response=%s err=%v", raw, err) + } + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("host terminal refusal did not complete") + } + select { + case method := <-hostCalls: + t.Fatalf("host terminal reached runner method %s", method) + default: } } diff --git a/apps/server/internal/runtime/workspace_proxy.go b/apps/server/internal/runtime/workspace_proxy.go index 9ba5bdf0..0deb0fca 100644 --- a/apps/server/internal/runtime/workspace_proxy.go +++ b/apps/server/internal/runtime/workspace_proxy.go @@ -248,34 +248,20 @@ func (h *handler) bridgeDesktopContainer(ctx context.Context, bridge *workspaceB } func (h *handler) bridgeTerminalContainer(ctx context.Context, bridge *workspaceBridge, session *runnerSession, spaceID, workspaceKind, adapterID, dockerID string) { - method, writeMethod, closeMethod := "host.pty.start", "host.pty.write", "host.pty.close" - command := []string{"bash", "-l"} if workspaceKind == "host" && adapterID == "" { - var info struct { - GOOS string `json:"goos"` - HostInfo struct { - Platform string `json:"platform"` - } `json:"hostInfo"` - } - if err := session.call(ctx, "sys.info", map[string]any{}, &info); err != nil { - bridge.cleanupErr = err - _ = bridge.write(0x1, []byte(`{"type":"error","message":"terminal unavailable"}`)) - return - } - if info.GOOS == "windows" || info.HostInfo.Platform == "windows" { - command = []string{"powershell.exe", "-NoLogo", "-NoProfile"} - } + bridge.cleanupErr = errLegacyHostWorkspace + raw, _ := json.Marshal(map[string]any{"type": "error", "message": errLegacyHostWorkspace.Error()}) + _ = bridge.write(0x1, raw) + return } - params := map[string]any{"spaceId": spaceID, "command": command, "workingDir": "/workspace", "cols": 120, "rows": 30} - if workspaceKind != "host" || adapterID != "" { - if dockerID == "" { - bridge.cleanupErr = errors.New("canonical workspace container is required") - _ = bridge.write(0x1, []byte(`{"type":"error","message":"workspace container is not running"}`)) - return - } - method, writeMethod, closeMethod = "docker.exec.start", "docker.exec.write", "docker.exec.close" - params = map[string]any{"id": dockerID, "command": []string{"bash", "-l"}, "workingDir": "/workspace", "tty": true, "cols": 120, "rows": 30} + if dockerID == "" { + bridge.cleanupErr = errors.New("canonical workspace container is required") + _ = bridge.write(0x1, []byte(`{"type":"error","message":"workspace container is not running"}`)) + return } + command := []string{"bash", "-l"} + method, writeMethod, closeMethod := "docker.exec.start", "docker.exec.write", "docker.exec.close" + params := map[string]any{"id": dockerID, "command": command, "workingDir": "/workspace", "tty": true, "cols": 120, "rows": 30} var started struct { ID string `json:"id"` } @@ -329,11 +315,7 @@ func (h *handler) bridgeTerminalContainer(ctx context.Context, bridge *workspace message.Type, message.Data = "input", string(payload) } if message.Type == "resize" { - resizeMethod := "host.pty.resize" - if method == "docker.exec.start" { - resizeMethod = "docker.exec.resize" - } - if err := bridge.call(ctx, session, resizeMethod, map[string]any{"id": started.ID, "cols": message.Cols, "rows": message.Rows}, nil); err != nil { + if err := bridge.call(ctx, session, "docker.exec.resize", map[string]any{"id": started.ID, "cols": message.Cols, "rows": message.Rows}, nil); err != nil { return } } else if message.Type == "input" { diff --git a/docker-compose.yml b/docker-compose.yml index cd90896f..35a8907f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,7 @@ # Zakura — OSS quickstart(server + web + 独立 node) # # 默认 SQLite(持久化到命名卷),完成管理员初始化后 node 自动登记: +# export ZAKURA_SECRET="$(openssl rand -hex 32)" # 将该值保存到受保护的部署配置 # docker compose up -d # # 使用 Postgres(内置 pgvector 服务,需把 DATABASE_URL 指过去): @@ -25,10 +26,12 @@ services: # 默认 SQLite;改用 Postgres:postgresql://zakura:zakura@postgres:5432/zakura DATABASE_URL: ${DATABASE_URL:-file:/data/zakura.db} DATA_DIR: /data - # 必填(>=32 字节);quickstart 用占位默认值,部署时务必覆盖 - ZAKURA_SECRET: ${ZAKURA_SECRET:-zakura-local-dev-secret-change-me-0123456789abcdef} + # 必填(>=32 字节);使用持久保存的唯一随机值,缺失时 Compose 拒绝启动 + ZAKURA_SECRET: ${ZAKURA_SECRET:?Set ZAKURA_SECRET to a unique value of at least 32 bytes} PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:8787} WEB_PUBLIC_URL: ${WEB_PUBLIC_URL:-http://localhost:3001} + # 仅在反向代理会覆盖 X-Real-IP 时配置信任的代理网段(逗号分隔 CIDR) + TRUSTED_PROXY_CIDRS: ${TRUSTED_PROXY_CIDRS:-} ZAKURA_EDITION: ${ZAKURA_EDITION:-oss} AUTO_MIGRATE: ${AUTO_MIGRATE:-true} ZAKURA_NODE_BOOTSTRAP_DIR: /node-bootstrap diff --git a/docker/nginx/proxy_locations.conf b/docker/nginx/proxy_locations.conf index 227d165e..415a989d 100644 --- a/docker/nginx/proxy_locations.conf +++ b/docker/nginx/proxy_locations.conf @@ -39,8 +39,9 @@ location = /api/zakurabot/ws { location /api/ { proxy_http_version 1.1; proxy_set_header Host $host; + proxy_set_header CF-Connecting-IP ""; proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Authorization $http_authorization; proxy_set_header X-Zakura-Session $http_x_zakura_session; From 81856096bb7edad38549dab65d4ce8c74df7a63e Mon Sep 17 00:00:00 2001 From: momo-mnsjtxy <122842784+momo-mnsjtxy@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:53:53 +0800 Subject: [PATCH 2/4] Fix the runtime terminal regression fixture --- apps/server/internal/runtime/workspace_host_terminal_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/server/internal/runtime/workspace_host_terminal_test.go b/apps/server/internal/runtime/workspace_host_terminal_test.go index 507b950a..2de6684d 100644 --- a/apps/server/internal/runtime/workspace_host_terminal_test.go +++ b/apps/server/internal/runtime/workspace_host_terminal_test.go @@ -16,6 +16,9 @@ func TestSpaceWorkspaceTerminalRejectsHostMode(t *testing.T) { seedTenant(t, d, "tenant") hostCalls := make(chan string, 1) h := builtinToolHarness(t, d, "rnr_host_shell", func(method string, params map[string]any) (any, error) { + if method == "sys.info" { + return map[string]any{"version": "test", "kind": "computer", "storageRoot": "/srv/zakura"}, nil + } if strings.HasPrefix(method, "host.pty.") { select { case hostCalls <- method: From 661c18d1d98bbbfe5216db846ae1f4d4f4059783 Mon Sep 17 00:00:00 2001 From: momo-mnsjtxy <122842784+momo-mnsjtxy@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:55:16 +0800 Subject: [PATCH 3/4] Keep frontend contract test sessions current --- apps/server/integration/frontend_contract_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/server/integration/frontend_contract_test.go b/apps/server/integration/frontend_contract_test.go index 6105ea28..2dc7824b 100644 --- a/apps/server/integration/frontend_contract_test.go +++ b/apps/server/integration/frontend_contract_test.go @@ -61,8 +61,9 @@ func TestPreservedFrontendCoreContracts(t *testing.T) { t.Fatal(err) } var seq atomic.Int64 + fixtureNow := time.Now().UTC() cfg := config.Config{WebURL: "http://web.test", PublicURL: "http://api.test", Edition: "saas", MultiTenant: true} - deps := &appdeps.Dependencies{DB: conn.DB, Gorm: gormDB, Dialect: conn.Dialect, Rebind: conn.Rebind, Clock: func() time.Time { return time.Date(2026, 10, 3, 12, 0, 0, 0, time.UTC) }, NewID: func() string { return fmt.Sprintf("%026d", seq.Add(1)) }, Secret: bytes.Repeat([]byte("z"), 32), PublicURL: cfg.PublicURL, WebURL: cfg.WebURL, DataDir: dataDir, Edition: cfg.Edition, MultiTenant: cfg.MultiTenant, VerifyDomain: func(context.Context, string, string) error { return nil }} + deps := &appdeps.Dependencies{DB: conn.DB, Gorm: gormDB, Dialect: conn.Dialect, Rebind: conn.Rebind, Clock: func() time.Time { return fixtureNow }, NewID: func() string { return fmt.Sprintf("%026d", seq.Add(1)) }, Secret: bytes.Repeat([]byte("z"), 32), PublicURL: cfg.PublicURL, WebURL: cfg.WebURL, DataDir: dataDir, Edition: cfg.Edition, MultiTenant: cfg.MultiTenant, VerifyDomain: func(context.Context, string, string) error { return nil }} router := platformserver.Router(cfg, deps, slog.New(slog.NewTextHandler(io.Discard, nil))) srv := httptest.NewServer(router) defer srv.Close() From ef86d078b0c145ec5e08fad80ad6dc9499de52bd Mon Sep 17 00:00:00 2001 From: momo-mnsjtxy <122842784+momo-mnsjtxy@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:58:06 +0800 Subject: [PATCH 4/4] Keep PostgreSQL workflow fixture sessions current --- apps/server/integration/postgres_integration_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/server/integration/postgres_integration_test.go b/apps/server/integration/postgres_integration_test.go index db8656e8..f8e27f17 100644 --- a/apps/server/integration/postgres_integration_test.go +++ b/apps/server/integration/postgres_integration_test.go @@ -48,10 +48,11 @@ func TestPostgresCoreWorkflow(t *testing.T) { } var seq int + fixtureNow := time.Now().UTC() cfg := config.Config{WebURL: "http://web.test", PublicURL: "http://api.test", Edition: "saas", MultiTenant: true} deps := &appdeps.Dependencies{ DB: conn.DB, Gorm: gormDB, Dialect: conn.Dialect, Rebind: conn.Rebind, - Clock: func() time.Time { return time.Date(2026, 10, 3, 12, 0, 0, 0, time.UTC) }, + Clock: func() time.Time { return fixtureNow }, NewID: func() string { seq++; return fmt.Sprintf("pg-%023d", seq) }, Secret: bytes.Repeat([]byte("p"), 32), PublicURL: cfg.PublicURL, WebURL: cfg.WebURL, Edition: cfg.Edition, MultiTenant: cfg.MultiTenant,