From aaa284586f064bbdc041e5caf0edcf1906091c13 Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:10:45 +0800 Subject: [PATCH] feat(plugin-hub): add plugin capability platform with embedded WebUI proxy and unified LLM gateway --- config.example.yaml | 30 + go.mod | 2 +- internal/app/app.go | 58 +- internal/app/plugin_auth_test.go | 78 ++ internal/config/config.go | 4 + internal/config/plugins.go | 205 ++++ internal/database/plugin_hub.go | 129 ++ internal/database/plugin_hub_test.go | 71 ++ internal/database/plugin_runtime.go | 411 +++++++ internal/database/plugin_services.go | 176 +++ internal/database/plugin_services_test.go | 68 ++ internal/database/rbac.go | 16 + internal/database/schemas/application.sql | 146 +++ internal/handler/plugins.go | 469 ++++++++ internal/handler/plugins_test.go | 222 ++++ internal/pluginhub/catalog/artex.yaml | 105 ++ internal/pluginhub/catalog/catalog.go | 50 + internal/pluginhub/catalog/catalog_test.go | 26 + internal/pluginhub/catalog/static-web.yaml | 19 + internal/pluginhub/e2e_test.go | 382 ++++++ internal/pluginhub/lifecycle.go | 344 ++++++ internal/pluginhub/llmgateway/gateway.go | 628 ++++++++++ internal/pluginhub/llmgateway/gateway_test.go | 267 +++++ internal/pluginhub/llmgateway/transport.go | 356 ++++++ internal/pluginhub/manager.go | 486 ++++++++ internal/pluginhub/manager_test.go | 378 ++++++ internal/pluginhub/manifest/declaration.go | 648 ++++++++++ internal/pluginhub/manifest/decode.go | 141 +++ internal/pluginhub/manifest/manifest_test.go | 137 +++ internal/pluginhub/manifest/plan.go | 120 ++ .../manifest/schemas/install-plan-v1.json | 212 ++++ .../manifest/schemas/manifest-v1.json | 1065 +++++++++++++++++ .../manifest/testdata/web-plugin.yaml | 132 ++ internal/pluginhub/planning.go | 254 ++++ internal/pluginhub/runner/archive.go | 141 +++ internal/pluginhub/runner/docker.go | 768 ++++++++++++ internal/pluginhub/runner/docker_test.go | 261 ++++ internal/pluginhub/runner/environment.go | 224 ++++ internal/pluginhub/runner/model_config.go | 196 +++ .../pluginhub/runner/model_config_test.go | 62 + internal/pluginhub/runner/native.go | 449 +++++++ internal/pluginhub/runner/native_test.go | 228 ++++ internal/pluginhub/runner/runner.go | 132 ++ internal/pluginhub/services.go | 182 +++ internal/pluginhub/snapshot.go | 108 ++ internal/pluginhub/source/egress.go | 149 +++ internal/pluginhub/source/github.go | 396 ++++++ internal/pluginhub/source/github_test.go | 102 ++ internal/pluginhub/source/locks.go | 247 ++++ internal/pluginhub/source/locks_test.go | 92 ++ internal/pluginhub/webproxy/proxy.go | 302 +++++ internal/pluginhub/webproxy/server.go | 501 ++++++++ internal/pluginhub/webproxy/server_test.go | 306 +++++ internal/security/auth_middleware.go | 22 +- internal/security/rbac.go | 3 + internal/security/rbac_middleware.go | 30 + web/frontend/src/lib/nav.js | 5 +- web/frontend/src/pages/plugin-hub/Drawers.jsx | 714 +++++++++++ .../src/pages/plugin-hub/WorkspaceView.jsx | 173 +++ web/frontend/src/pages/plugin-hub/api.js | 230 ++++ web/frontend/src/pages/plugin-hub/index.jsx | 513 ++++++++ web/frontend/src/pages/plugin-hub/page.css | 167 +++ web/frontend/src/pages/registry.js | 1 + ...Bits-RToEHLbz.js => AssetBits-DtqSAj0f.js} | 2 +- ...jQgJt8.js => AssetEditorModal-BRlVM7dg.js} | 4 +- ...oWtYg.js => agents-management-d131UeV3.js} | 2 +- ...-docs-B5EmdKmF.js => api-docs-D-52AArB.js} | 4 +- .../app/assets/asset-library-Be1fEX32.js | 3 - .../app/assets/asset-library-ChAmA5Ch.js | 3 + ...CJNzTj95.js => asset-overview-D3G_k7fn.js} | 2 +- web/static/app/assets/c2-events-BBXPOkip.js | 1 + web/static/app/assets/c2-events-DBkH1Ps2.js | 1 - ...s-D48uHMNt.js => c2-listeners-mznWKf39.js} | 2 +- web/static/app/assets/c2-payloads-BKak-gMx.js | 1 + web/static/app/assets/c2-payloads-DkiAq8H3.js | 1 - ...es-B9vlWJDM.js => c2-profiles-D57VOkSl.js} | 4 +- ...ns-B3T6vNBp.js => c2-sessions-Dzb2ExJE.js} | 2 +- ...ared-Bp5-se02.js => c2-shared-CtmcbePz.js} | 2 +- ...ared-CLxa-jXi.js => c2-shared-DNQvNHHd.js} | 2 +- ...tasks-BPlX1VSv.js => c2-tasks-bTc_K3I3.js} | 2 +- web/static/app/assets/chat-B6cOdvxB.js | 5 - web/static/app/assets/chat-Cq-XdIX7.js | 5 + web/static/app/assets/chat-files-C_do2wG4.js | 1 + web/static/app/assets/chat-files-DvYZqigo.js | 1 - web/static/app/assets/dashboard-Bw4z9UMz.js | 1 + web/static/app/assets/dashboard-C1bTnf9G.js | 1 - .../app/assets/deep-assessments-D9Eh-P7-.js | 2 - .../app/assets/deep-assessments-Ear0CRFf.js | 2 + ...-C3k12cpw.js => graph-parents-i1hc3RVG.js} | 2 +- web/static/app/assets/hitl-BXv08yGA.js | 7 - web/static/app/assets/hitl-BqElf4Dy.js | 7 + web/static/app/assets/index-CFmEgVyi.js | 64 - web/static/app/assets/index-D_JyAVdp.js | 64 + .../app/assets/info-collect-C0qW9x7x.js | 1 + .../app/assets/info-collect-Cz_FrKnl.js | 1 - .../assets/knowledge-management-BxQoJW22.js | 1 + .../assets/knowledge-management-C95HlQvj.js | 1 - ...s => knowledge-retrieval-logs-B2smCvdG.js} | 2 +- .../app/assets/mcp-management-D08mlkbU.js | 1 - .../app/assets/mcp-management-J5-UGLel.js | 1 + ...or-BktPgkRb.js => mcp-monitor-CYkF90E6.js} | 2 +- ...-CGyXELTK.js => platform-rbac-BENNKoJc.js} | 2 +- web/static/app/assets/plugin-hub-DXxb5SNn.js | 3 + web/static/app/assets/plugin-hub-Yl4AUy33.css | 1 + ...m-B7LOVrYq.js => project-form-XZEBxv0P.js} | 2 +- ...jects-CGHGDxFZ.js => projects-SuTBYp6J.js} | 6 +- .../app/assets/roles-management-5zmgJVPT.js | 1 + .../app/assets/roles-management-DHztKoq9.js | 1 - .../{semi-CHxO7u8f.js => semi-65W_4I1v.js} | 10 +- web/static/app/assets/settings-ClSXlHvg.js | 21 - web/static/app/assets/settings-DPQLaCt9.js | 21 + ...i0o-C.js => skills-management-CCkb0p77.js} | 2 +- ...DDzWiLjF.js => skills-monitor-rnLJQpb-.js} | 2 +- web/static/app/assets/tasks-CMXgkYzg.js | 2 - web/static/app/assets/tasks-ChAtqbZl.js | 2 + web/static/app/assets/tool-guard-QZ-UJFtd.js | 1 + web/static/app/assets/tool-guard-YZfmNQZ9.js | 1 - .../app/assets/vulnerabilities-CLjF5w8M.js | 2 - .../app/assets/vulnerabilities-D_rM4qkt.js | 2 + ...shell-CIHejtP-.js => webshell-BCjmG7pY.js} | 4 +- web/static/app/assets/workflows-D0hIK8-5.js | 1 - web/static/app/assets/workflows-g37AHSUA.js | 1 + web/static/app/index.html | 4 +- web/static/i18n/ar-SA.json | 158 ++- web/static/i18n/en-US.json | 156 ++- web/static/i18n/ru-RU.json | 156 ++- web/static/i18n/zh-CN.json | 156 ++- 127 files changed, 15299 insertions(+), 168 deletions(-) create mode 100644 internal/app/plugin_auth_test.go create mode 100644 internal/config/plugins.go create mode 100644 internal/database/plugin_hub.go create mode 100644 internal/database/plugin_hub_test.go create mode 100644 internal/database/plugin_runtime.go create mode 100644 internal/database/plugin_services.go create mode 100644 internal/database/plugin_services_test.go create mode 100644 internal/handler/plugins.go create mode 100644 internal/handler/plugins_test.go create mode 100644 internal/pluginhub/catalog/artex.yaml create mode 100644 internal/pluginhub/catalog/catalog.go create mode 100644 internal/pluginhub/catalog/catalog_test.go create mode 100644 internal/pluginhub/catalog/static-web.yaml create mode 100644 internal/pluginhub/e2e_test.go create mode 100644 internal/pluginhub/lifecycle.go create mode 100644 internal/pluginhub/llmgateway/gateway.go create mode 100644 internal/pluginhub/llmgateway/gateway_test.go create mode 100644 internal/pluginhub/llmgateway/transport.go create mode 100644 internal/pluginhub/manager.go create mode 100644 internal/pluginhub/manager_test.go create mode 100644 internal/pluginhub/manifest/declaration.go create mode 100644 internal/pluginhub/manifest/decode.go create mode 100644 internal/pluginhub/manifest/manifest_test.go create mode 100644 internal/pluginhub/manifest/plan.go create mode 100644 internal/pluginhub/manifest/schemas/install-plan-v1.json create mode 100644 internal/pluginhub/manifest/schemas/manifest-v1.json create mode 100644 internal/pluginhub/manifest/testdata/web-plugin.yaml create mode 100644 internal/pluginhub/planning.go create mode 100644 internal/pluginhub/runner/archive.go create mode 100644 internal/pluginhub/runner/docker.go create mode 100644 internal/pluginhub/runner/docker_test.go create mode 100644 internal/pluginhub/runner/environment.go create mode 100644 internal/pluginhub/runner/model_config.go create mode 100644 internal/pluginhub/runner/model_config_test.go create mode 100644 internal/pluginhub/runner/native.go create mode 100644 internal/pluginhub/runner/native_test.go create mode 100644 internal/pluginhub/runner/runner.go create mode 100644 internal/pluginhub/services.go create mode 100644 internal/pluginhub/snapshot.go create mode 100644 internal/pluginhub/source/egress.go create mode 100644 internal/pluginhub/source/github.go create mode 100644 internal/pluginhub/source/github_test.go create mode 100644 internal/pluginhub/source/locks.go create mode 100644 internal/pluginhub/source/locks_test.go create mode 100644 internal/pluginhub/webproxy/proxy.go create mode 100644 internal/pluginhub/webproxy/server.go create mode 100644 internal/pluginhub/webproxy/server_test.go create mode 100644 web/frontend/src/pages/plugin-hub/Drawers.jsx create mode 100644 web/frontend/src/pages/plugin-hub/WorkspaceView.jsx create mode 100644 web/frontend/src/pages/plugin-hub/api.js create mode 100644 web/frontend/src/pages/plugin-hub/index.jsx create mode 100644 web/frontend/src/pages/plugin-hub/page.css rename web/static/app/assets/{AssetBits-RToEHLbz.js => AssetBits-DtqSAj0f.js} (59%) rename web/static/app/assets/{AssetEditorModal-CqjQgJt8.js => AssetEditorModal-BRlVM7dg.js} (77%) rename web/static/app/assets/{agents-management-D1UoWtYg.js => agents-management-d131UeV3.js} (66%) rename web/static/app/assets/{api-docs-B5EmdKmF.js => api-docs-D-52AArB.js} (51%) delete mode 100644 web/static/app/assets/asset-library-Be1fEX32.js create mode 100644 web/static/app/assets/asset-library-ChAmA5Ch.js rename web/static/app/assets/{asset-overview-CJNzTj95.js => asset-overview-D3G_k7fn.js} (85%) create mode 100644 web/static/app/assets/c2-events-BBXPOkip.js delete mode 100644 web/static/app/assets/c2-events-DBkH1Ps2.js rename web/static/app/assets/{c2-listeners-D48uHMNt.js => c2-listeners-mznWKf39.js} (74%) create mode 100644 web/static/app/assets/c2-payloads-BKak-gMx.js delete mode 100644 web/static/app/assets/c2-payloads-DkiAq8H3.js rename web/static/app/assets/{c2-profiles-B9vlWJDM.js => c2-profiles-D57VOkSl.js} (59%) rename web/static/app/assets/{c2-sessions-B3T6vNBp.js => c2-sessions-Dzb2ExJE.js} (64%) rename web/static/app/assets/{c2-shared-Bp5-se02.js => c2-shared-CtmcbePz.js} (94%) rename web/static/app/assets/{c2-shared-CLxa-jXi.js => c2-shared-DNQvNHHd.js} (80%) rename web/static/app/assets/{c2-tasks-BPlX1VSv.js => c2-tasks-bTc_K3I3.js} (68%) delete mode 100644 web/static/app/assets/chat-B6cOdvxB.js create mode 100644 web/static/app/assets/chat-Cq-XdIX7.js create mode 100644 web/static/app/assets/chat-files-C_do2wG4.js delete mode 100644 web/static/app/assets/chat-files-DvYZqigo.js create mode 100644 web/static/app/assets/dashboard-Bw4z9UMz.js delete mode 100644 web/static/app/assets/dashboard-C1bTnf9G.js delete mode 100644 web/static/app/assets/deep-assessments-D9Eh-P7-.js create mode 100644 web/static/app/assets/deep-assessments-Ear0CRFf.js rename web/static/app/assets/{graph-parents-C3k12cpw.js => graph-parents-i1hc3RVG.js} (85%) delete mode 100644 web/static/app/assets/hitl-BXv08yGA.js create mode 100644 web/static/app/assets/hitl-BqElf4Dy.js delete mode 100644 web/static/app/assets/index-CFmEgVyi.js create mode 100644 web/static/app/assets/index-D_JyAVdp.js create mode 100644 web/static/app/assets/info-collect-C0qW9x7x.js delete mode 100644 web/static/app/assets/info-collect-Cz_FrKnl.js create mode 100644 web/static/app/assets/knowledge-management-BxQoJW22.js delete mode 100644 web/static/app/assets/knowledge-management-C95HlQvj.js rename web/static/app/assets/{knowledge-retrieval-logs-EGeeNq1a.js => knowledge-retrieval-logs-B2smCvdG.js} (70%) delete mode 100644 web/static/app/assets/mcp-management-D08mlkbU.js create mode 100644 web/static/app/assets/mcp-management-J5-UGLel.js rename web/static/app/assets/{mcp-monitor-BktPgkRb.js => mcp-monitor-CYkF90E6.js} (70%) rename web/static/app/assets/{platform-rbac-CGyXELTK.js => platform-rbac-BENNKoJc.js} (60%) create mode 100644 web/static/app/assets/plugin-hub-DXxb5SNn.js create mode 100644 web/static/app/assets/plugin-hub-Yl4AUy33.css rename web/static/app/assets/{project-form-B7LOVrYq.js => project-form-XZEBxv0P.js} (88%) rename web/static/app/assets/{projects-CGHGDxFZ.js => projects-SuTBYp6J.js} (60%) create mode 100644 web/static/app/assets/roles-management-5zmgJVPT.js delete mode 100644 web/static/app/assets/roles-management-DHztKoq9.js rename web/static/app/assets/{semi-CHxO7u8f.js => semi-65W_4I1v.js} (75%) delete mode 100644 web/static/app/assets/settings-ClSXlHvg.js create mode 100644 web/static/app/assets/settings-DPQLaCt9.js rename web/static/app/assets/{skills-management-D14i0o-C.js => skills-management-CCkb0p77.js} (62%) rename web/static/app/assets/{skills-monitor-DDzWiLjF.js => skills-monitor-rnLJQpb-.js} (75%) delete mode 100644 web/static/app/assets/tasks-CMXgkYzg.js create mode 100644 web/static/app/assets/tasks-ChAtqbZl.js create mode 100644 web/static/app/assets/tool-guard-QZ-UJFtd.js delete mode 100644 web/static/app/assets/tool-guard-YZfmNQZ9.js delete mode 100644 web/static/app/assets/vulnerabilities-CLjF5w8M.js create mode 100644 web/static/app/assets/vulnerabilities-D_rM4qkt.js rename web/static/app/assets/{webshell-CIHejtP-.js => webshell-BCjmG7pY.js} (69%) delete mode 100644 web/static/app/assets/workflows-D0hIK8-5.js create mode 100644 web/static/app/assets/workflows-g37AHSUA.js diff --git a/config.example.yaml b/config.example.yaml index 08c72aa5..8fc1f8a5 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -35,6 +35,36 @@ server: # tls_key_path: /path/to/privkey.pem # 方式 B(仅本地/测试):在配置目录的 data/tls/self-signed.pem 保存并复用自签证书和私钥(SAN 含 localhost / 127.0.0.1)。 tls_auto_self_sign: true +# 插件平台。默认每个 WebUI 使用独立端口并复用主站 TLS 策略。 +# 默认端口模式每个已安装插件占用一个代理端口,并复用主站的 TLS 配置。 +# VPS、防火墙或容器端口映射可预先放行这个闭区间。插件后端端口保持在私网。 +# plugins: +# directory: data/plugins # 相对配置文件目录 +# egress: +# proxy_mode: system # system / direct / fixed +# # proxy_url: http://proxy.example.com:3128 +# # github_token_env: CSAI_PLUGINS_GITHUB_TOKEN +# approval_policy: admin_confirm # 默认:全局插件管理员确认锁定计划,批准记录保存在 SQLite +# # 改为 host_config_only 时,由下方声明摘要与制品摘要列表授权执行。 +# # approved_artifacts: +# # "": [""] +# proxy: +# mode: port +# port_pool: +# start: 43100 +# end: 43131 +# # host_suffix: plugins.localhost # mode: host 使用 +# # bind_host: 127.0.0.1 # 端口模式,缺省继承主站监听 IP +# # public_origin: https://csai.example.com +# # external_ports: {43100: 44310} +# llm_gateway: +# listen_host: 127.0.0.1 # 也可绑定明确的私有 bridge IP +# listen_port: 0 # 0 表示分配可用端口 +# # container_host: host.docker.internal +# concurrency: 4 +# rpm: 30 +# token_budget: 200000 # 每实例每日 UTC 计费额度 + # 认证配置 auth: session_duration_hours: 12 # 登录有效期(小时),超时后需重新登录 diff --git a/go.mod b/go.mod index 7cb7764c..a4e5e8fc 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( github.com/creack/pty v1.1.24 github.com/disintegration/imaging v1.6.2 github.com/gin-gonic/gin v1.9.1 + github.com/google/jsonschema-go v0.4.2 github.com/google/uuid v1.6.0 github.com/gorilla/websocket v1.5.3 github.com/larksuite/oapi-sdk-go/v3 v3.4.22 @@ -44,7 +45,6 @@ require ( github.com/go-resty/resty/v2 v2.6.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/gogo/protobuf v1.3.2 // indirect - github.com/google/jsonschema-go v0.4.2 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.10 // indirect github.com/kr/pretty v0.3.1 // indirect diff --git a/internal/app/app.go b/internal/app/app.go index ad9ef21b..ba73d42c 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -29,6 +29,7 @@ import ( "cyberstrike-ai/internal/mcp" "cyberstrike-ai/internal/mcp/builtin" "cyberstrike-ai/internal/monitor" + "cyberstrike-ai/internal/pluginhub" "cyberstrike-ai/internal/robot" "cyberstrike-ai/internal/security" @@ -77,6 +78,7 @@ type App struct { c2Handler *handler.C2Handler // C2 REST(与 Manager 生命周期同步) storageHandler *handler.StorageHandler // 运行空间占用统计与垃圾清理 auditSvc *audit.Service + pluginHub *pluginhub.Manager } // New 创建新应用 @@ -525,7 +527,13 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st openAPIHandler := handler.NewOpenAPIHandler(db, log.Logger, conversationHandler, agentHandler) // 创建 App 实例(部分字段稍后填充) + pluginHub, err := pluginhub.New(db, cfg.Plugins, configDir, log.Logger) + if err != nil { + return nil, fmt.Errorf("initialize plugin runtime: %w", err) + } + pluginHub.ConfigureServices(authManager, configHandler.RuntimeConfigSnapshot) app := &App{ + pluginHub: pluginHub, config: cfg, configDir: configDir, logger: log, @@ -748,7 +756,25 @@ func (a *App) RunWithContext(ctx context.Context) error { return tlsErr } - srv := &http.Server{Addr: addr, Handler: a.router} + var mainHandler http.Handler = a.router + if a.pluginHub != nil { + var pluginTLS *tls.Config + if tlsMode != mainTLSOff { + pluginTLS, tlsErr = ensureMainTLSConfigCerts(tlsMode, tlsConf, certFile, keyFile) + if tlsErr != nil { + return fmt.Errorf("初始化插件监听证书: %w", tlsErr) + } + } + if err := a.pluginHub.StartServices(a.config.Server.Host, a.config.Server.Port, pluginTLS); err != nil { + a.logger.Warn("Plugin model gateway unavailable", zap.Error(err)) + } + defer a.pluginHub.CloseServices() + mainHandler = a.pluginHub.WebHandler(mainHandler) + if err := a.pluginHub.Start(ctx); err != nil { + a.logger.Warn("Plugin runtime unavailable", zap.Error(err)) + } + } + srv := &http.Server{Addr: addr, Handler: mainHandler} var mainMux *mainServerMux httpRedirect := config.ServerHTTPRedirectEnabled(&a.config.Server) if tlsMode != mainTLSOff { @@ -834,6 +860,13 @@ func (a *App) Shutdown() { } func (a *App) shutdown() { + if a.pluginHub != nil { + ctx, cancel := context.WithTimeout(context.Background(), 32*time.Second) + if err := a.pluginHub.Close(ctx); err != nil { + a.logger.Warn("Could not finish plugin runtime cleanup", zap.Error(err)) + } + cancel() + } if a.agentHandler != nil { a.agentHandler.ShutdownTasks() } @@ -956,6 +989,13 @@ func (a *App) RestartRobotConnections() { } // setupRoutes 设置路由 +func pluginAwarePlatformAuth(manager *security.AuthManager, proxy config.PluginProxyConfig) gin.HandlerFunc { + if proxy.Effective().Mode == "port" { + return security.AuthMiddlewareWithoutCookie(manager) + } + return security.AuthMiddleware(manager) +} + func setupRoutes( router *gin.Engine, authHandler *handler.AuthHandler, @@ -989,6 +1029,7 @@ func setupRoutes( openAPIHandler *handler.OpenAPIHandler, updateHandler *handler.UpdateHandler, ) { + platformAuth := pluginAwarePlatformAuth(authManager, app.config.Plugins.Proxy) // API路由 api := router.Group("/api") @@ -997,12 +1038,12 @@ func setupRoutes( loginRL := security.NewRateLimiter(10, 1*time.Minute) { authRoutes.POST("/login", security.RateLimitMiddleware(loginRL), authHandler.Login) - authRoutes.POST("/logout", security.AuthMiddleware(authManager), authHandler.Logout) - authRoutes.POST("/change-password", security.AuthMiddleware(authManager), security.RequirePermission("auth:self"), authHandler.ChangePassword) - authRoutes.GET("/validate", updateHandler.SetBootHeader, security.AuthMiddleware(authManager), authHandler.Validate) - authRoutes.POST("/robot-binding-code", security.AuthMiddleware(authManager), security.RequirePermission("auth:self"), robotHandler.CreateRobotBindingCode) - authRoutes.GET("/robot-bindings", security.AuthMiddleware(authManager), security.RequirePermission("auth:self"), robotHandler.ListMyRobotBindings) - authRoutes.DELETE("/robot-bindings/:id", security.AuthMiddleware(authManager), security.RequirePermission("auth:self"), robotHandler.DeleteMyRobotBinding) + authRoutes.POST("/logout", platformAuth, authHandler.Logout) + authRoutes.POST("/change-password", platformAuth, security.RequirePermission("auth:self"), authHandler.ChangePassword) + authRoutes.GET("/validate", updateHandler.SetBootHeader, platformAuth, authHandler.Validate) + authRoutes.POST("/robot-binding-code", platformAuth, security.RequirePermission("auth:self"), robotHandler.CreateRobotBindingCode) + authRoutes.GET("/robot-bindings", platformAuth, security.RequirePermission("auth:self"), robotHandler.ListMyRobotBindings) + authRoutes.DELETE("/robot-bindings/:id", platformAuth, security.RequirePermission("auth:self"), robotHandler.DeleteMyRobotBinding) } // 机器人回调(无需登录,供企业微信/钉钉/飞书服务器调用) @@ -1018,7 +1059,7 @@ func setupRoutes( } protected := api.Group("") - protected.Use(security.AuthMiddleware(authManager)) + protected.Use(platformAuth) protected.Use(security.RBACMiddlewareWithDenyHook(app.db, func(c *gin.Context, reason, permission string) { if auditSvc != nil { auditSvc.Record(c, audit.Entry{ @@ -1028,6 +1069,7 @@ func setupRoutes( }) } })) + handler.NewPluginHandler(app.db, auditSvc, app.pluginHub).Register(protected) { protected.GET("/rbac/me", rbacHandler.Me) protected.GET("/rbac/metadata", rbacHandler.Metadata) diff --git a/internal/app/plugin_auth_test.go b/internal/app/plugin_auth_test.go new file mode 100644 index 00000000..cfa93999 --- /dev/null +++ b/internal/app/plugin_auth_test.go @@ -0,0 +1,78 @@ +package app + +import ( + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/security" + + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +// Stub the post-authorization endpoint handler. This verifies the actual +// platform middleware and route permissions without starting terminal or C2 tasks. +func TestPluginPortModePreservesChatWebShellAndC2StreamingAuthentication(t *testing.T) { + db, err := database.NewDB(filepath.Join(t.TempDir(), "auth.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + auth := security.NewAuthManager(1) + password, err := auth.AttachRBACStore(db) + if err != nil { + t.Fatal(err) + } + token, _, err := auth.Authenticate("admin", password) + if err != nil { + t.Fatal(err) + } + r := gin.New() + api := r.Group("/api", pluginAwarePlatformAuth(auth, config.PluginProxyConfig{}), security.RBACMiddleware(db)) + ok := func(c *gin.Context) { c.Status(http.StatusNoContent) } + api.POST("/agent/stream", ok) + api.POST("/multi-agent/stream", ok) + api.POST("/webshell/exec", ok) + api.POST("/terminal/run/stream", ok) + api.GET("/terminal/ws", ok) + api.GET("/c2/events/stream", ok) + for _, tt := range []struct { + name, method, path, transport string + }{ + {"Chat SSE", "POST", "/api/agent/stream", "bearer"}, + {"Multi-agent SSE", "POST", "/api/multi-agent/stream", "bearer"}, + {"WebShell", "POST", "/api/webshell/exec", "bearer"}, + {"Terminal SSE", "POST", "/api/terminal/run/stream", "bearer"}, + {"Terminal WebSocket", "GET", "/api/terminal/ws", "ws"}, + {"C2 event SSE", "GET", "/api/c2/events/stream", "sse"}, + } { + t.Run(tt.name, func(t *testing.T) { + req := httptest.NewRequest(tt.method, tt.path, nil) + req.AddCookie(&http.Cookie{Name: "auth_token", Value: token}) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + if w.Code != http.StatusUnauthorized { + t.Fatalf("primary cookie authenticates on port mode: %d", w.Code) + } + switch tt.transport { + case "bearer": + req.Header.Set("Authorization", "Bearer "+token) + case "ws": + req.URL.RawQuery = "token=" + token + req.Header.Set("Upgrade", "websocket") + case "sse": + req.URL.RawQuery = "token=" + token + req.Header.Set("Accept", "text/event-stream") + } + w = httptest.NewRecorder() + r.ServeHTTP(w, req) + if w.Code != http.StatusNoContent { + t.Fatalf("authorized client rejected: %d %s", w.Code, w.Body.String()) + } + }) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index f3f521d0..04bb7ec7 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -21,6 +21,7 @@ import ( ) type Config struct { + Plugins PluginsConfig `yaml:"plugins,omitempty" json:"-"` Proxy ProxyConfig `yaml:"proxy,omitempty" json:"proxy"` Version string `yaml:"version,omitempty" json:"version,omitempty"` // 前端显示的版本号,如 v1.3.3 Server ServerConfig `yaml:"server"` @@ -1572,6 +1573,9 @@ func Load(path string) (*Config, error) { if err := cfg.Proxy.Validate(); err != nil { return nil, err } + if err := cfg.Plugins.Validate(); err != nil { + return nil, err + } if err := cfg.Agent.validateTaskTimeout(); err != nil { return nil, err } diff --git a/internal/config/plugins.go b/internal/config/plugins.go new file mode 100644 index 00000000..c7c286a9 --- /dev/null +++ b/internal/config/plugins.go @@ -0,0 +1,205 @@ +package config + +import ( + "fmt" + "net/netip" + "net/url" + "regexp" + "strings" +) + +const ( + PluginApprovalAdminConfirm = "admin_confirm" + PluginApprovalHostConfigOnly = "host_config_only" +) + +// PluginsConfig is read at startup. The approval policy controls how locked +// plans become eligible for execution. +type PluginsConfig struct { + ApprovalPolicy string `yaml:"approval_policy,omitempty" json:"-"` + Directory string `yaml:"directory,omitempty" json:"-"` + Egress PluginEgress `yaml:"egress,omitempty" json:"-"` + ApprovedArtifacts map[string][]string `yaml:"approved_artifacts,omitempty" json:"-"` + Proxy PluginProxyConfig `yaml:"proxy,omitempty" json:"-"` + LLMGateway PluginLLMGatewayConfig `yaml:"llm_gateway,omitempty" json:"-"` +} + +type PluginEgress struct { + ProxyMode string `yaml:"proxy_mode,omitempty"` + ProxyURL string `yaml:"proxy_url,omitempty"` + GitHubTokenEnv string `yaml:"github_token_env,omitempty"` + AdditionalHosts []string `yaml:"additional_hosts,omitempty"` +} + +var pluginSHA256 = regexp.MustCompile(`^[a-f0-9]{64}$`) +var pluginEnvName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,63}$`) +var pluginRemoteHost = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]+$`) + +func (p PluginsConfig) EffectiveApprovalPolicy() string { + if p.ApprovalPolicy == "" { + return PluginApprovalAdminConfirm + } + return p.ApprovalPolicy +} + +func (p PluginsConfig) Validate() error { + if err := p.Proxy.Validate(); err != nil { + return err + } + if err := p.LLMGateway.Validate(); err != nil { + return err + } + switch p.EffectiveApprovalPolicy() { + case PluginApprovalAdminConfirm, PluginApprovalHostConfigOnly: + default: + return fmt.Errorf("plugins.approval_policy must be admin_confirm or host_config_only") + } + switch p.Egress.ProxyMode { + case "", "system", "direct": + if p.Egress.ProxyURL != "" { + return fmt.Errorf("plugins.egress.proxy_url requires fixed mode") + } + case "fixed": + u, err := url.Parse(p.Egress.ProxyURL) + if err != nil || u.Host == "" || !strings.Contains("|http|https|socks5|", "|"+u.Scheme+"|") || + u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + return fmt.Errorf("invalid plugins.egress.proxy_url") + } + default: + return fmt.Errorf("plugins.egress.proxy_mode must be system, direct or fixed") + } + if p.Egress.GitHubTokenEnv != "" && !pluginEnvName.MatchString(p.Egress.GitHubTokenEnv) { + return fmt.Errorf("invalid plugins.egress.github_token_env") + } + for _, host := range p.Egress.AdditionalHosts { + if !pluginRemoteHost.MatchString(host) || !strings.Contains(host, ".") || strings.Contains(host, "..") { + return fmt.Errorf("invalid plugins.egress.additional_hosts entry") + } + } + for declaration, artifacts := range p.ApprovedArtifacts { + if !pluginSHA256.MatchString(declaration) || len(artifacts) == 0 { + return fmt.Errorf("plugins.approved_artifacts requires declaration and artifact SHA-256 digests") + } + for _, artifact := range artifacts { + if !pluginSHA256.MatchString(artifact) { + return fmt.Errorf("invalid plugins.approved_artifacts artifact digest") + } + } + } + return nil +} + +type PluginProxyConfig struct { + Mode string `yaml:"mode,omitempty"` + BindHost string `yaml:"bind_host,omitempty"` + PortPool PluginPortPool `yaml:"port_pool,omitempty"` + HostSuffix string `yaml:"host_suffix,omitempty"` + PublicOrigin string `yaml:"public_origin,omitempty"` + ExternalPorts map[int]int `yaml:"external_ports,omitempty"` +} + +type PluginPortPool struct { + Start int `yaml:"start,omitempty"` + End int `yaml:"end,omitempty"` +} + +func (p PluginProxyConfig) Effective() PluginProxyConfig { + if p.Mode == "" { + p.Mode = "port" + } + if p.PortPool == (PluginPortPool{}) { + p.PortPool = PluginPortPool{43100, 43131} + } + return p +} + +func (p PluginProxyConfig) Validate() error { + p = p.Effective() + if p.Mode != "port" && p.Mode != "host" { + return fmt.Errorf("plugins.proxy.mode must be port or host") + } + if p.Mode == "host" && (len(p.HostSuffix) > 180 || !pluginDNSHost.MatchString(p.HostSuffix) || netipAddr(p.HostSuffix)) { + return fmt.Errorf("plugins.proxy.host_suffix must be a DNS suffix in host mode") + } + if p.PortPool.Start < 1024 || p.PortPool.End > 65535 || p.PortPool.End < p.PortPool.Start || p.PortPool.End-p.PortPool.Start > 2047 { + return fmt.Errorf("invalid plugins.proxy.port_pool") + } + if p.BindHost != "" && strings.ContainsAny(p.BindHost, " /\\@#?[]") { + return fmt.Errorf("invalid plugins.proxy.bind_host") + } + ports := map[int]bool{} + for port := p.PortPool.Start; port <= p.PortPool.End; port++ { + mapped := port + if external, exists := p.ExternalPorts[port]; exists { + mapped = external + } + if mapped < 1 || mapped > 65535 || ports[mapped] { + return fmt.Errorf("invalid or duplicate plugins.proxy.external_ports value") + } + ports[mapped] = true + } + for port := range p.ExternalPorts { + if p.Mode != "port" || port < p.PortPool.Start || port > p.PortPool.End { + return fmt.Errorf("invalid plugins.proxy.external_ports key") + } + } + if p.PublicOrigin != "" { + u, err := url.Parse(p.PublicOrigin) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || + u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + return fmt.Errorf("plugins.proxy.public_origin must be an HTTP(S) origin") + } + } + return nil +} + +var pluginDNSHost = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$`) + +func netipAddr(host string) bool { + _, err := netip.ParseAddr(host) + return err == nil +} + +type PluginLLMGatewayConfig struct { + ListenHost string `yaml:"listen_host,omitempty"` + ListenPort int `yaml:"listen_port,omitempty"` + ContainerHost string `yaml:"container_host,omitempty"` + Concurrency int `yaml:"concurrency,omitempty"` + RPM int `yaml:"rpm,omitempty"` + TokenBudget int64 `yaml:"token_budget,omitempty"` +} + +func (g PluginLLMGatewayConfig) Effective() PluginLLMGatewayConfig { + if g.ListenHost == "" { + g.ListenHost = "127.0.0.1" + } + if g.Concurrency == 0 { + g.Concurrency = 4 + } + if g.RPM == 0 { + g.RPM = 30 + } + if g.TokenBudget == 0 { + g.TokenBudget = 200000 + } + return g +} + +func (g PluginLLMGatewayConfig) Validate() error { + g = g.Effective() + ip, err := netip.ParseAddr(g.ListenHost) + if err != nil || (!ip.IsLoopback() && !ip.IsPrivate()) || ip.Zone() != "" { + return fmt.Errorf("plugins.llm_gateway.listen_host must be a loopback or specific private IP") + } + if g.ContainerHost != "" { + address, addrErr := netip.ParseAddr(g.ContainerHost) + if g.ContainerHost != "host.docker.internal" && (addrErr != nil || !address.IsPrivate() || address.Zone() != "") { + return fmt.Errorf("plugins.llm_gateway.container_host must be host.docker.internal or a private IP") + } + } + if g.ListenPort < 0 || g.ListenPort > 65535 || g.Concurrency < 1 || g.Concurrency > 64 || + g.RPM < 1 || g.RPM > 1200 || g.TokenBudget < 1 || g.TokenBudget > 1000000000 { + return fmt.Errorf("invalid plugins.llm_gateway port or limits") + } + return nil +} diff --git a/internal/database/plugin_hub.go b/internal/database/plugin_hub.go new file mode 100644 index 00000000..47a0b333 --- /dev/null +++ b/internal/database/plugin_hub.go @@ -0,0 +1,129 @@ +package database + +import ( + "context" + "database/sql" + "time" +) + +func (db *DB) SavePluginInspection(ctx context.Context, id, actor, payload string, now, expires time.Time) error { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.ExecContext(ctx, "DELETE FROM plugin_import_inspections WHERE expires_at <= ?", now.UTC()); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `INSERT INTO plugin_import_inspections + (id, actor_user_id, inspection_json, created_at, expires_at) VALUES (?, ?, ?, ?, ?)`, + id, actor, payload, now.UTC(), expires.UTC()); err != nil { + return err + } + return tx.Commit() +} + +func (db *DB) GetPluginInspection(ctx context.Context, id, actor string, now time.Time) (string, error) { + var payload string + err := db.QueryRowContext(ctx, `SELECT inspection_json FROM plugin_import_inspections + WHERE id = ? AND actor_user_id = ? AND expires_at > ?`, id, actor, now.UTC()).Scan(&payload) + return payload, err +} + +type PluginPlanRecord struct { + ID string + InstallID string + InspectionID string + ActorUserID string + ManifestJSON string + ManifestDigest string + PolicyJSON string + PlanJSON string + PlanDigest string + ExpiresAt time.Time + ApprovedAt *time.Time +} + +func (db *DB) SavePluginPlan(ctx context.Context, record PluginPlanRecord, now time.Time) error { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.ExecContext(ctx, `DELETE FROM plugin_install_plans WHERE expires_at <= ? AND approved_at IS NULL`, now.UTC()); err != nil { + return err + } + result, err := tx.ExecContext(ctx, `INSERT INTO plugin_install_plans + (id, install_id, inspection_id, actor_user_id, manifest_json, manifest_digest, policy_json, plan_json, plan_digest, expires_at) + SELECT ?, ?, id, actor_user_id, ?, ?, ?, ?, ?, ? FROM plugin_import_inspections + WHERE id = ? AND actor_user_id = ? AND expires_at > ?`, + record.ID, record.InstallID, record.ManifestJSON, record.ManifestDigest, record.PolicyJSON, record.PlanJSON, + record.PlanDigest, record.ExpiresAt.UTC(), record.InspectionID, record.ActorUserID, now.UTC()) + if err != nil { + return err + } + inserted, err := result.RowsAffected() + if err != nil { + return err + } + if inserted != 1 { + return sql.ErrNoRows + } + return tx.Commit() +} + +func (db *DB) GetPluginPlan(ctx context.Context, id, actor string, now time.Time) (PluginPlanRecord, error) { + var record PluginPlanRecord + err := db.QueryRowContext(ctx, `SELECT id, install_id, inspection_id, actor_user_id, manifest_json, manifest_digest, + policy_json, plan_json, plan_digest, expires_at, approved_at + FROM plugin_install_plans WHERE id = ? AND actor_user_id = ? AND expires_at > ?`, id, actor, now.UTC()). + Scan(&record.ID, &record.InstallID, &record.InspectionID, &record.ActorUserID, &record.ManifestJSON, + &record.ManifestDigest, &record.PolicyJSON, &record.PlanJSON, &record.PlanDigest, &record.ExpiresAt, &record.ApprovedAt) + return record, err +} + +type PluginInstallSummary struct { + ID string `json:"id"` + PluginID string `json:"plugin_id"` + Title string `json:"title"` + Driver string `json:"driver"` + Desired string `json:"desired_state"` + Observed string `json:"observed_state"` + ErrorCode string `json:"last_error_code,omitempty"` + UpdatedAt time.Time `json:"updated_at"` +} + +const pluginInstallSummaryColumns = `id, plugin_id, title, driver, desired_state, observed_state, COALESCE(last_error_code, ''), updated_at` + +func scanPluginInstall(row interface{ Scan(...any) error }) (PluginInstallSummary, error) { + var install PluginInstallSummary + err := row.Scan(&install.ID, &install.PluginID, &install.Title, &install.Driver, &install.Desired, &install.Observed, &install.ErrorCode, &install.UpdatedAt) + return install, err +} + +func (db *DB) ListPluginInstalls(ctx context.Context, actor, scope string) ([]PluginInstallSummary, error) { + rows, err := db.QueryContext(ctx, `SELECT `+pluginInstallSummaryColumns+` FROM plugin_installs + WHERE observed_state <> 'removed' AND ( + ? = 'all' OR (? = 'own' AND owner_user_id = ?) OR + (? IN ('own', 'assigned') AND EXISTS (SELECT 1 FROM rbac_resource_assignments a + WHERE a.user_id = ? AND a.resource_type = 'plugin_install' AND a.resource_id = plugin_installs.id))) + ORDER BY updated_at DESC, id`, scope, scope, actor, scope, actor) + if err != nil { + return nil, err + } + defer rows.Close() + items := []PluginInstallSummary{} + for rows.Next() { + install, err := scanPluginInstall(rows) + if err != nil { + return nil, err + } + items = append(items, install) + } + return items, rows.Err() +} + +func (db *DB) GetPluginInstall(ctx context.Context, id string) (PluginInstallSummary, error) { + return scanPluginInstall(db.QueryRowContext(ctx, `SELECT `+pluginInstallSummaryColumns+` FROM plugin_installs + WHERE id = ? AND observed_state <> 'removed'`, id)) +} diff --git a/internal/database/plugin_hub_test.go b/internal/database/plugin_hub_test.go new file mode 100644 index 00000000..a7b9c408 --- /dev/null +++ b/internal/database/plugin_hub_test.go @@ -0,0 +1,71 @@ +package database + +import ( + "context" + "database/sql" + "errors" + "path/filepath" + "testing" + "time" + + "go.uber.org/zap" +) + +func TestPluginSchemaReconcilesExistingDatabase(t *testing.T) { + path := filepath.Join(t.TempDir(), "upgrade.db") + raw, err := sql.Open("sqlite3", path) + if err != nil { + t.Fatal(err) + } + if _, err := raw.Exec(`CREATE TABLE local_legacy (value TEXT); INSERT INTO local_legacy VALUES ('keep')`); err != nil { + t.Fatal(err) + } + if err := raw.Close(); err != nil { + t.Fatal(err) + } + db, err := NewDB(path, zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + var count int + if err := db.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN + ('plugin_import_inspections','plugin_install_plans','plugin_installs','plugin_versions','plugin_operations')`).Scan(&count); err != nil || count != 5 { + t.Fatalf("missing tables: %d, %v", count, err) + } + var retained string + if err := db.QueryRow(`SELECT value FROM local_legacy`).Scan(&retained); err != nil || retained != "keep" { + t.Fatalf("legacy row changed: %q %v", retained, err) + } + ctx := context.Background() + now := time.Now().UTC() + if err := db.SavePluginInspection(ctx, "inspection", "author", "{}", now, now.Add(time.Minute)); err != nil { + t.Fatal(err) + } + record := PluginPlanRecord{ + ID: "plan", InstallID: "instance", InspectionID: "inspection", ActorUserID: "other", + ManifestJSON: "{}", PlanJSON: "{}", PolicyJSON: "{}", ExpiresAt: now.Add(30 * time.Second), + } + if err := db.SavePluginPlan(ctx, record, now); !errors.Is(err, sql.ErrNoRows) { + t.Fatalf("foreign actor wrote a plan: %v", err) + } + record.ActorUserID = "author" + if err := db.SavePluginPlan(ctx, record, now); err != nil { + t.Fatal(err) + } + if _, err := db.GetPluginPlan(ctx, record.ID, "author", now.Add(time.Minute)); !errors.Is(err, sql.ErrNoRows) { + t.Fatalf("expired plan returned: %v", err) + } + if err := db.Close(); err != nil { + t.Fatal(err) + } + + reopened, err := NewDB(path, zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer reopened.Close() + if got, err := reopened.GetPluginPlan(ctx, record.ID, "author", now); err != nil || got.InspectionID != "inspection" { + t.Fatalf("plan was lost after reopening: %+v %v", got, err) + } +} diff --git a/internal/database/plugin_runtime.go b/internal/database/plugin_runtime.go new file mode 100644 index 00000000..eeca07bc --- /dev/null +++ b/internal/database/plugin_runtime.go @@ -0,0 +1,411 @@ +package database + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" +) + +var ErrPluginOperationConflict = errors.New("plugin operation conflicts with existing state") +var ErrPluginPlanUnavailable = errors.New("plugin plan expired or already consumed") + +type PluginRuntimeInstall struct { + ID, PluginID, Source, Title, Desired, Observed, Version, Driver string + Endpoint, ErrorCode string + Port int + Generation int64 +} + +type PluginVersion struct { + ID, InstallID, Version, Driver, Manifest, ManifestDigest string + Artifact, ArtifactDigest, Policy, Plan string +} + +type PluginOperation struct { + ID string `json:"id"` + InstallID string `json:"install_id"` + Actor string `json:"-"` + Kind string `json:"kind"` + Key string `json:"-"` + PlanDigest string `json:"plan_digest,omitempty"` + VersionID string `json:"-"` + RequestHash string `json:"-"` + PurgeData bool `json:"-"` + Status string `json:"status"` + ErrorCode string `json:"error_code,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +type pluginQueryRow interface{ Scan(...any) error } + +const runtimeInstallColumns = "id, plugin_id, source_identity, title, desired_state, observed_state, COALESCE(active_version_id,''), driver, COALESCE(endpoint_ref,''), COALESCE(last_error_code,''), COALESCE(observed_port,0), generation" +const pluginVersionColumns = "id, install_id, version, driver, manifest_json, manifest_digest, artifact_identity, artifact_digest, approval_json, plan_json" +const pluginOperationColumns = "id, install_id, actor_user_id, kind, idempotency_key, plan_digest, version_id, request_digest, purge_data, status, error_code, created_at, updated_at" + +func scanRuntimeInstall(row pluginQueryRow) (v PluginRuntimeInstall, err error) { + err = row.Scan(&v.ID, &v.PluginID, &v.Source, &v.Title, &v.Desired, &v.Observed, &v.Version, &v.Driver, &v.Endpoint, &v.ErrorCode, &v.Port, &v.Generation) + return v, err +} + +func scanPluginVersion(row pluginQueryRow) (v PluginVersion, err error) { + err = row.Scan(&v.ID, &v.InstallID, &v.Version, &v.Driver, &v.Manifest, &v.ManifestDigest, &v.Artifact, &v.ArtifactDigest, &v.Policy, &v.Plan) + return v, err +} + +func scanPluginOperation(row pluginQueryRow) (v PluginOperation, err error) { + err = row.Scan(&v.ID, &v.InstallID, &v.Actor, &v.Kind, &v.Key, &v.PlanDigest, &v.VersionID, &v.RequestHash, &v.PurgeData, + &v.Status, &v.ErrorCode, &v.CreatedAt, &v.UpdatedAt) + return v, err +} + +func (db *DB) RuntimePluginInstall(ctx context.Context, id string) (PluginRuntimeInstall, error) { + return scanRuntimeInstall(db.QueryRowContext(ctx, "SELECT "+runtimeInstallColumns+" FROM plugin_installs WHERE id = ?", id)) +} + +func (db *DB) RecoverablePluginInstalls(ctx context.Context) ([]PluginRuntimeInstall, error) { + rows, err := db.QueryContext(ctx, "SELECT "+runtimeInstallColumns+" FROM plugin_installs WHERE observed_state NOT IN ('stopped','removed') OR desired_state = 'running'") + if err != nil { + return nil, err + } + defer rows.Close() + var values []PluginRuntimeInstall + for rows.Next() { + item, err := scanRuntimeInstall(rows) + if err != nil { + return nil, err + } + values = append(values, item) + } + return values, rows.Err() +} + +func (db *DB) PluginVersion(ctx context.Context, installID, versionID string) (PluginVersion, error) { + return scanPluginVersion(db.QueryRowContext(ctx, "SELECT "+pluginVersionColumns+" FROM plugin_versions WHERE install_id = ? AND id = ?", installID, versionID)) +} + +func (db *DB) PluginVersions(ctx context.Context, installID string) ([]PluginVersion, error) { + rows, err := db.QueryContext(ctx, "SELECT "+pluginVersionColumns+" FROM plugin_versions WHERE install_id = ? ORDER BY created_at DESC", installID) + if err != nil { + return nil, err + } + defer rows.Close() + var values []PluginVersion + for rows.Next() { + value, err := scanPluginVersion(rows) + if err != nil { + return nil, err + } + values = append(values, value) + } + return values, rows.Err() +} + +func (db *DB) LastPluginOperation(ctx context.Context, installID string) (PluginOperation, error) { + return scanPluginOperation(db.QueryRowContext(ctx, "SELECT "+pluginOperationColumns+ + " FROM plugin_operations WHERE install_id = ? ORDER BY updated_at DESC, id DESC LIMIT 1", installID)) +} + +func (db *DB) GetPluginOperation(ctx context.Context, id string) (PluginOperation, error) { + return scanPluginOperation(db.QueryRowContext(ctx, "SELECT "+pluginOperationColumns+" FROM plugin_operations WHERE id = ?", id)) +} + +func (db *DB) PluginOperationByKey(ctx context.Context, installID, key string) (PluginOperation, error) { + return scanPluginOperation(db.QueryRowContext(ctx, "SELECT "+pluginOperationColumns+" FROM plugin_operations WHERE install_id = ? AND idempotency_key = ?", installID, key)) +} + +func (db *DB) GetPluginPlanForConfirmation(ctx context.Context, id, actor string) (PluginPlanRecord, error) { + var result PluginPlanRecord + err := db.QueryRowContext(ctx, `SELECT id,install_id,inspection_id,actor_user_id,manifest_json,manifest_digest,policy_json,plan_json,plan_digest,expires_at + FROM plugin_install_plans WHERE id=? AND actor_user_id=?`, id, actor).Scan(&result.ID, &result.InstallID, &result.InspectionID, + &result.ActorUserID, &result.ManifestJSON, &result.ManifestDigest, &result.PolicyJSON, &result.PlanJSON, &result.PlanDigest, &result.ExpiresAt) + return result, err +} + +func (db *DB) PluginPlanApproved(ctx context.Context, id, install, actor, digest string) (bool, error) { + var approved bool + err := db.QueryRowContext(ctx, `SELECT EXISTS (SELECT 1 FROM plugin_install_plans + WHERE id=? AND install_id=? AND actor_user_id=? AND plan_digest=? + AND approved_at IS NOT NULL AND consumed_at IS NOT NULL)`, id, install, actor, digest).Scan(&approved) + return approved, err +} + +type PluginQueueRequest struct { + Operation PluginOperation + Install PluginRuntimeInstall + Version PluginVersion + PlanID string + CatalogID string +} + +func (db *DB) QueuePluginOperation(ctx context.Context, request PluginQueueRequest, now time.Time) (PluginOperation, error) { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return PluginOperation{}, err + } + defer tx.Rollback() + op := request.Operation + previous, err := scanPluginOperation(tx.QueryRowContext(ctx, "SELECT "+pluginOperationColumns+" FROM plugin_operations WHERE install_id=? AND idempotency_key=?", op.InstallID, op.Key)) + if err == nil { + if previous.Actor == op.Actor && previous.RequestHash == op.RequestHash { + return previous, nil + } + return PluginOperation{}, ErrPluginOperationConflict + } + if !errors.Is(err, sql.ErrNoRows) { + return PluginOperation{}, err + } + current, err := scanRuntimeInstall(tx.QueryRowContext(ctx, "SELECT "+runtimeInstallColumns+" FROM plugin_installs WHERE id = ?", op.InstallID)) + if op.Kind == "install" { + if !errors.Is(err, sql.ErrNoRows) { + if err != nil { + return PluginOperation{}, err + } + return PluginOperation{}, ErrPluginOperationConflict + } + } else if err != nil || current.Observed == "removed" { + if err == nil { + err = sql.ErrNoRows + } + return PluginOperation{}, err + } + if op.Kind == "upgrade" && (current.Source != request.Install.Source || current.PluginID != request.Install.PluginID || current.Version == "") { + return PluginOperation{}, ErrPluginOperationConflict + } + var busy bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM plugin_operations WHERE install_id=? AND status IN ('queued','running'))`, op.InstallID).Scan(&busy); err != nil { + return PluginOperation{}, err + } + if busy { + return PluginOperation{}, ErrPluginOperationConflict + } + if request.PlanID != "" { + result, err := tx.ExecContext(ctx, `UPDATE plugin_install_plans SET approved_at=?,consumed_at=? + WHERE id=? AND install_id=? AND actor_user_id=? AND plan_digest=? AND expires_at>? AND consumed_at IS NULL`, + now, now, request.PlanID, op.InstallID, op.Actor, op.PlanDigest, now) + if err := changedExactlyOne(result, err, ErrPluginPlanUnavailable); err != nil { + return PluginOperation{}, err + } + } + if op.Kind == "install" { + record := request.Install + var duplicate bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM plugin_installs WHERE source_identity=? AND plugin_id=? AND observed_state<>'removed')`, record.Source, record.PluginID).Scan(&duplicate); err != nil { + return PluginOperation{}, err + } + if duplicate { + return PluginOperation{}, ErrPluginOperationConflict + } + _, err := tx.ExecContext(ctx, `INSERT INTO plugin_installs + (id,catalog_id,plugin_id,source_identity,title,owner_user_id,desired_state,observed_state,driver,created_at,updated_at) + VALUES(?,?,?,?,?,?,'running','installing',?,?,?)`, op.InstallID, request.CatalogID, record.PluginID, record.Source, record.Title, + op.Actor, request.Version.Driver, now, now) + if err != nil { + return PluginOperation{}, err + } + } + if v := request.Version; v.ID != "" { + var storedID string + err = tx.QueryRowContext(ctx, `SELECT id FROM plugin_versions WHERE install_id=? AND manifest_digest=? AND artifact_identity=? AND artifact_digest=? AND driver=?`, + op.InstallID, v.ManifestDigest, v.Artifact, v.ArtifactDigest, v.Driver).Scan(&storedID) + if errors.Is(err, sql.ErrNoRows) { + _, err = tx.ExecContext(ctx, `INSERT INTO plugin_versions + (id,install_id,version,manifest_json,manifest_digest,artifact_identity,artifact_digest,driver,storage_key,approval_json,plan_json,created_at) + VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`, v.ID, op.InstallID, v.Version, v.Manifest, v.ManifestDigest, + v.Artifact, v.ArtifactDigest, v.Driver, v.ID, v.Policy, v.Plan, now) + storedID = v.ID + } + if err != nil { + return PluginOperation{}, err + } + op.VersionID = storedID + } + op.Status, op.CreatedAt, op.UpdatedAt = "queued", now, now + _, err = tx.ExecContext(ctx, `INSERT INTO plugin_operations + (id,install_id,actor_user_id,kind,idempotency_key,plan_digest,version_id,request_digest,purge_data,status,created_at,updated_at) + VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`, op.ID, op.InstallID, op.Actor, op.Kind, op.Key, op.PlanDigest, op.VersionID, + op.RequestHash, op.PurgeData, op.Status, now, now) + if err != nil { + return PluginOperation{}, err + } + return op, tx.Commit() +} + +func (db *DB) ClaimPluginOperation(ctx context.Context, owner string, now time.Time) (PluginOperation, error) { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return PluginOperation{}, err + } + defer tx.Rollback() + var ownsLease bool + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM plugin_runtime_leases WHERE id=1 AND owner=? AND expires_at>?)`, owner, now).Scan(&ownsLease) + if err != nil || !ownsLease { + return PluginOperation{}, sql.ErrNoRows + } + op, err := scanPluginOperation(tx.QueryRowContext(ctx, "SELECT "+pluginOperationColumns+" FROM plugin_operations WHERE status='queued' ORDER BY created_at,id LIMIT 1")) + if err != nil { + return PluginOperation{}, err + } + result, err := tx.ExecContext(ctx, `UPDATE plugin_operations SET status='running',lease_owner=?,lease_until=(SELECT expires_at FROM plugin_runtime_leases WHERE id=1),updated_at=? WHERE id=? AND status='queued'`, owner, now, op.ID) + if err := changedExactlyOne(result, err, ErrPluginOperationConflict); err != nil { + return PluginOperation{}, err + } + op.Status, op.UpdatedAt = "running", now + return op, tx.Commit() +} + +type PluginObservation struct { + Desired, Observed, Version, Driver, Endpoint, ErrorCode string + Port int +} + +func (db *DB) FinishPluginOperation(ctx context.Context, owner string, op PluginOperation, observation PluginObservation, failed bool) error { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + status := "succeeded" + if failed { + status = "failed" + } + now := time.Now().UTC() + result, err := tx.ExecContext(ctx, `UPDATE plugin_operations SET status=?, error_code=?, updated_at=?, lease_owner=NULL, lease_until=NULL + WHERE id=? AND status='running' AND lease_owner=? AND EXISTS(SELECT 1 FROM plugin_runtime_leases WHERE id=1 AND owner=? AND expires_at>?)`, + status, observation.ErrorCode, now, op.ID, owner, owner, now) + if err := changedExactlyOne(result, err, ErrPluginOperationConflict); err != nil { + return err + } + if err := setPluginObservation(ctx, tx, op.InstallID, observation, now); err != nil { + return err + } + return tx.Commit() +} + +func (db *DB) SetPluginObservation(ctx context.Context, owner, id string, observation PluginObservation) error { + now := time.Now().UTC() + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var ownsLease bool + err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM plugin_runtime_leases WHERE id=1 AND owner=? AND expires_at>?)`, owner, now).Scan(&ownsLease) + if err != nil || !ownsLease { + return ErrPluginOperationConflict + } + if err := setPluginObservation(ctx, tx, id, observation, now); err != nil { + return err + } + return tx.Commit() +} + +func setPluginObservation(ctx context.Context, tx *sql.Tx, id string, o PluginObservation, now time.Time) error { + _, err := tx.ExecContext(ctx, `UPDATE plugin_installs SET desired_state=?, observed_state=?, active_version_id=NULLIF(?, ''), + driver=?, endpoint_ref=NULLIF(?, ''), observed_port=NULLIF(?, 0), last_error_code=NULLIF(?, ''), + updated_at=? WHERE id=?`, + o.Desired, o.Observed, o.Version, o.Driver, o.Endpoint, o.Port, o.ErrorCode, now, id) + return err +} + +func (db *DB) InterruptedPluginOperations(ctx context.Context) ([]PluginOperation, error) { + rows, err := db.QueryContext(ctx, "SELECT "+pluginOperationColumns+" FROM plugin_operations WHERE status='running'") + if err != nil { + return nil, err + } + defer rows.Close() + var values []PluginOperation + for rows.Next() { + op, err := scanPluginOperation(rows) + if err != nil { + return nil, err + } + values = append(values, op) + } + return values, rows.Err() +} + +func (db *DB) InterruptPluginOperation(ctx context.Context, owner, id string) error { + now := time.Now().UTC() + result, err := db.ExecContext(ctx, `UPDATE plugin_operations SET status='failed', error_code='plugin_operation_interrupted', + updated_at=?, lease_owner=NULL, lease_until=NULL WHERE id=? AND status='running' + AND EXISTS(SELECT 1 FROM plugin_runtime_leases WHERE id=1 AND owner=? AND expires_at>?)`, now, id, owner, now) + return changedExactlyOne(result, err, ErrPluginOperationConflict) +} + +func (db *DB) RenewPluginLease(ctx context.Context, owner string, now, expires time.Time) (bool, error) { + result, err := db.ExecContext(ctx, `INSERT INTO plugin_runtime_leases(id,owner,expires_at) VALUES(1,?,?) + ON CONFLICT(id) DO UPDATE SET owner=excluded.owner,expires_at=excluded.expires_at + WHERE plugin_runtime_leases.owner=excluded.owner OR plugin_runtime_leases.expires_at<=?`, owner, expires, now) + if err != nil { + return false, err + } + n, err := result.RowsAffected() + return n == 1, err +} + +func (db *DB) ReleasePluginLease(ctx context.Context, owner string) error { + _, err := db.ExecContext(ctx, "DELETE FROM plugin_runtime_leases WHERE owner=?", owner) + return err +} + +func changedExactlyOne(result sql.Result, err, conflict error) error { + if err != nil { + return err + } + count, err := result.RowsAffected() + if err != nil { + return err + } + if count != 1 { + return conflict + } + return nil +} + +type PluginLogEntry struct { + ID int64 `json:"id"` + Message string `json:"message"` + CreatedAt time.Time `json:"created_at"` +} + +func (db *DB) AppendPluginLog(ctx context.Context, id, message string) error { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + _, err = tx.ExecContext(ctx, `INSERT INTO plugin_runtime_logs(install_id,message,created_at) VALUES(?,?,?)`, id, message, time.Now().UTC()) + if err != nil { + return err + } + _, err = tx.ExecContext(ctx, `DELETE FROM plugin_runtime_logs WHERE install_id=? AND id <= COALESCE( + (SELECT id FROM plugin_runtime_logs WHERE install_id=? ORDER BY id DESC LIMIT 1 OFFSET 2000),-1)`, id, id) + if err != nil { + return err + } + return tx.Commit() +} + +func (db *DB) ReadPluginLogs(ctx context.Context, id string, after int64, limit int) ([]PluginLogEntry, error) { + if after < 0 || limit < 1 || limit > 200 { + return nil, fmt.Errorf("invalid plugin log cursor") + } + rows, err := db.QueryContext(ctx, `SELECT id,message,created_at FROM plugin_runtime_logs + WHERE install_id=? AND id>? ORDER BY id LIMIT ?`, id, after, limit) + if err != nil { + return nil, err + } + defer rows.Close() + entries := []PluginLogEntry{} + for rows.Next() { + var entry PluginLogEntry + if err := rows.Scan(&entry.ID, &entry.Message, &entry.CreatedAt); err != nil { + return nil, err + } + entries = append(entries, entry) + } + return entries, rows.Err() +} diff --git a/internal/database/plugin_services.go b/internal/database/plugin_services.go new file mode 100644 index 00000000..49136b81 --- /dev/null +++ b/internal/database/plugin_services.go @@ -0,0 +1,176 @@ +package database + +import ( + "context" + "errors" + "time" +) + +type PluginWebOrigin struct { + InstallID string + Mode string + Port int + Hostname string + Retired *time.Time +} + +func scanPluginOrigin(row pluginQueryRow) (v PluginWebOrigin, err error) { + err = row.Scan(&v.InstallID, &v.Mode, &v.Port, &v.Hostname, &v.Retired) + return v, err +} + +func (db *DB) PluginWebOrigin(ctx context.Context, installID string) (PluginWebOrigin, error) { + return scanPluginOrigin(db.QueryRowContext(ctx, `SELECT install_id,mode,listener_port,hostname,retired_at + FROM plugin_web_origins WHERE install_id=?`, installID)) +} + +func (db *DB) PluginWebOrigins(ctx context.Context) ([]PluginWebOrigin, error) { + rows, err := db.QueryContext(ctx, "SELECT install_id,mode,listener_port,hostname,retired_at FROM plugin_web_origins") + if err != nil { + return nil, err + } + defer rows.Close() + var result []PluginWebOrigin + for rows.Next() { + item, err := scanPluginOrigin(rows) + if err != nil { + return nil, err + } + result = append(result, item) + } + return result, rows.Err() +} + +func (db *DB) SavePluginWebOrigin(ctx context.Context, origin PluginWebOrigin) error { + result, err := db.ExecContext(ctx, `INSERT INTO plugin_web_origins(install_id,mode,listener_port,hostname,created_at) + SELECT id,?,?,?,? FROM plugin_installs WHERE id=? AND observed_state='healthy'`, + origin.Mode, origin.Port, origin.Hostname, time.Now().UTC(), origin.InstallID) + return changedExactlyOne(result, err, ErrPluginOperationConflict) +} + +func (db *DB) RetirePluginWebOrigin(ctx context.Context, id string) error { + _, err := db.ExecContext(ctx, "UPDATE plugin_web_origins SET retired_at=? WHERE install_id=? AND retired_at IS NULL", time.Now().UTC(), id) + return err +} + +func (db *DB) BlockPluginTraffic(ctx context.Context, owner, id string) error { + result, err := db.ExecContext(ctx, `UPDATE plugin_installs SET observed_state='stopping',endpoint_ref=NULL,observed_port=NULL + WHERE id=? AND observed_state<>'removed' + AND EXISTS (SELECT 1 FROM plugin_runtime_leases WHERE id=1 AND owner=? AND expires_at>?)`, id, owner, time.Now().UTC()) + return changedExactlyOne(result, err, ErrPluginOperationConflict) +} + +type PluginLLMBinding struct { + Protocol string `json:"protocol,omitempty"` + Mode string `json:"mode"` + ChannelID string `json:"channel_id,omitempty"` + Concurrency int `json:"concurrency"` + RPM int `json:"rpm"` + TokenBudget int64 `json:"token_budget"` +} + +func (db *DB) PluginLLMBindings(ctx context.Context, installID string) ([]PluginLLMBinding, error) { + rows, err := db.QueryContext(ctx, `SELECT protocol,mode,channel_id,concurrency,rpm,token_budget + FROM plugin_llm_bindings WHERE install_id=? ORDER BY protocol`, installID) + if err != nil { + return nil, err + } + defer rows.Close() + var result []PluginLLMBinding + for rows.Next() { + var b PluginLLMBinding + if err := rows.Scan(&b.Protocol, &b.Mode, &b.ChannelID, &b.Concurrency, &b.RPM, &b.TokenBudget); err != nil { + return nil, err + } + result = append(result, b) + } + return result, rows.Err() +} + +func (db *DB) SetPluginLLMBindings(ctx context.Context, installID string, values []PluginLLMBinding) error { + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.ExecContext(ctx, "DELETE FROM plugin_gateway_keys WHERE install_id=?", installID); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, "DELETE FROM plugin_llm_bindings WHERE install_id=?", installID); err != nil { + return err + } + for _, b := range values { + if _, err := tx.ExecContext(ctx, `INSERT INTO plugin_llm_bindings(install_id,protocol,mode,channel_id,concurrency,rpm,token_budget) + VALUES(?,?,?,?,?,?,?)`, installID, b.Protocol, b.Mode, b.ChannelID, b.Concurrency, b.RPM, b.TokenBudget); err != nil { + return err + } + } + return tx.Commit() +} + +type PluginGatewayKey struct { + InstallID string + Generation int64 + Binding PluginLLMBinding +} + +func (db *DB) SavePluginGatewayKey(ctx context.Context, id string, generation int64, protocol, digest string) error { + result, err := db.ExecContext(ctx, `INSERT INTO plugin_gateway_keys(digest,install_id,generation,protocol,created_at) + SELECT ?,i.id,i.generation,b.protocol,? + FROM plugin_installs i JOIN plugin_llm_bindings b ON b.install_id=i.id + WHERE i.id=? AND i.generation=? AND i.observed_state='starting' AND b.protocol=? AND b.mode<>'disabled'`, + digest, time.Now().UTC(), id, generation, protocol) + return changedExactlyOne(result, err, ErrPluginOperationConflict) +} + +func (db *DB) PluginGatewayKey(ctx context.Context, digest string) (PluginGatewayKey, error) { + var key PluginGatewayKey + err := db.QueryRowContext(ctx, `SELECT k.install_id,k.generation,k.protocol,b.mode,b.channel_id,b.concurrency,b.rpm,b.token_budget + FROM plugin_gateway_keys k JOIN plugin_installs i ON i.id=k.install_id AND i.generation=k.generation + JOIN plugin_llm_bindings b ON b.install_id=k.install_id AND b.protocol=k.protocol + WHERE k.digest=? AND i.observed_state IN ('starting','healthy') AND b.mode<>'disabled'`, digest). + Scan(&key.InstallID, &key.Generation, &key.Binding.Protocol, &key.Binding.Mode, &key.Binding.ChannelID, + &key.Binding.Concurrency, &key.Binding.RPM, &key.Binding.TokenBudget) + return key, err +} + +func (db *DB) RevokePluginGatewayKeys(ctx context.Context, id string) error { + _, err := db.ExecContext(ctx, "DELETE FROM plugin_gateway_keys WHERE install_id=?", id) + return err +} + +// BeginPluginLaunch reserves the next generation before credentials or a WebUI can +// be associated with it. The runtime lease fences out another supervisor. +func (db *DB) BeginPluginLaunch(ctx context.Context, owner, id string) (int64, error) { + var generation int64 + err := db.QueryRowContext(ctx, `UPDATE plugin_installs + SET generation=generation+1,observed_state='starting',endpoint_ref=NULL,observed_port=NULL + WHERE id=? AND observed_state<>'removed' + AND EXISTS (SELECT 1 FROM plugin_runtime_leases WHERE id=1 AND owner=? AND expires_at>?) + RETURNING generation`, id, owner, time.Now().UTC()).Scan(&generation) + return generation, err +} + +var ErrPluginModelBudget = errors.New("plugin model token budget exhausted") + +func (db *DB) ReservePluginModelUsage(ctx context.Context, id string, k PluginGatewayKey, channel string, charge int64) error { + now := time.Now().UTC() + day := now.Format(time.DateOnly) + result, err := db.ExecContext(ctx, `INSERT INTO plugin_model_usage + (id,install_id,generation,protocol,channel_id,day,charged_tokens,status,created_at) + SELECT ?,?,?,?,?,?,?,'reserved',? + WHERE COALESCE((SELECT SUM(charged_tokens) FROM plugin_model_usage WHERE install_id=? AND day=?),0)+? <= ?`, + id, k.InstallID, k.Generation, k.Binding.Protocol, channel, day, charge, now, k.InstallID, day, charge, k.Binding.TokenBudget) + return changedExactlyOne(result, err, ErrPluginModelBudget) +} + +func (db *DB) FinishPluginModelUsage(ctx context.Context, id, status string, input, output int64, metered bool) error { + if !metered { + _, err := db.ExecContext(ctx, "UPDATE plugin_model_usage SET status=?,finished_at=? WHERE id=?", + status, time.Now().UTC(), id) + return err + } + _, err := db.ExecContext(ctx, `UPDATE plugin_model_usage SET status=?,finished_at=?,input_tokens=?,output_tokens=?, + charged_tokens=? WHERE id=?`, status, time.Now().UTC(), input, output, input+output, id) + return err +} diff --git a/internal/database/plugin_services_test.go b/internal/database/plugin_services_test.go new file mode 100644 index 00000000..c6d1e5dd --- /dev/null +++ b/internal/database/plugin_services_test.go @@ -0,0 +1,68 @@ +package database + +import ( + "context" + "path/filepath" + "testing" + "time" + + "go.uber.org/zap" +) + +func TestPluginServicesSchemaUpgradeAndGenerationFence(t *testing.T) { + file := filepath.Join(t.TempDir(), "previous.db") + db, err := NewDB(file, zap.NewNop()) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + _, err = db.Exec(`DROP TABLE plugin_web_origins; DROP TABLE plugin_gateway_keys; DROP TABLE plugin_model_usage; DROP TABLE plugin_llm_bindings; + INSERT INTO plugin_installs(id,plugin_id,source_identity,title,driver,observed_state,created_at,updated_at) + VALUES('fixture','old','old','retained','release','healthy',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`) + if err != nil { + t.Fatal(err) + } + if err := db.Close(); err != nil { + t.Fatal(err) + } + db, err = NewDB(file, zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + i, err := db.RuntimePluginInstall(ctx, "fixture") + if err != nil || i.Title != "retained" { + t.Fatalf("existing install lost: %+v %v", i, err) + } + var tables int + if err := db.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE name IN ('plugin_web_origins','plugin_llm_bindings','plugin_gateway_keys','plugin_model_usage')`).Scan(&tables); err != nil || tables != 4 { + t.Fatalf("plugin service schema incomplete: %d %v", tables, err) + } + now := time.Now().UTC() + if ok, err := db.RenewPluginLease(ctx, "test-owner", now, now.Add(time.Minute)); err != nil || !ok { + t.Fatal(err) + } + gen, err := db.BeginPluginLaunch(ctx, "test-owner", "fixture") + if err != nil || gen != 1 { + t.Fatalf("generation %d %v", gen, err) + } + b := PluginLLMBinding{Protocol: "openai_chat", Mode: "channel", ChannelID: "fixture", Concurrency: 1, RPM: 2, TokenBudget: 500} + if err := db.SetPluginLLMBindings(ctx, "fixture", []PluginLLMBinding{b}); err != nil { + t.Fatal(err) + } + if err := db.SavePluginGatewayKey(ctx, "fixture", gen, b.Protocol, "fixture-digest"); err != nil { + t.Fatal(err) + } + if _, err := db.PluginGatewayKey(ctx, "fixture-digest"); err != nil { + t.Fatal(err) + } + if err := db.BlockPluginTraffic(ctx, "test-owner", "fixture"); err != nil { + t.Fatal(err) + } + if _, err := db.PluginGatewayKey(ctx, "fixture-digest"); err == nil { + t.Fatal("stopping instance still admitted model traffic") + } + if err := db.SavePluginWebOrigin(ctx, PluginWebOrigin{InstallID: "fixture", Mode: "port", Port: 43220}); err == nil { + t.Fatal("stopping instance allocated a browser port") + } +} diff --git a/internal/database/rbac.go b/internal/database/rbac.go index 5e37e888..64e0d936 100644 --- a/internal/database/rbac.go +++ b/internal/database/rbac.go @@ -31,6 +31,7 @@ var rbacAssignableResourceTables = map[string]string{ "webshell": "webshell_connections", "batch_task": "batch_task_queues", "deep_assessment": "deep_assessments", + "plugin_install": "plugin_installs", "c2_listener": "c2_listeners", } @@ -501,6 +502,8 @@ func (db *DB) userOwnsResource(userID, resourceType, resourceID string) bool { table = "webshell_connections" case "deep_assessment": table = "deep_assessments" + case "plugin_install": + table = "plugin_installs" case "batch_task": table = "batch_task_queues" case "c2_listener": @@ -532,6 +535,8 @@ func (db *DB) SetResourceOwner(resourceType, resourceID, userID string) error { table = "webshell_connections" case "deep_assessment": table = "deep_assessments" + case "plugin_install": + table = "plugin_installs" case "batch_task": table = "batch_task_queues" case "c2_listener": @@ -558,6 +563,8 @@ func (db *DB) GetResourceOwner(resourceType, resourceID string) string { table = "webshell_connections" case "deep_assessment": table = "deep_assessments" + case "plugin_install": + table = "plugin_installs" case "batch_task": table = "batch_task_queues" case "c2_listener": @@ -627,6 +634,10 @@ func (db *DB) ListAssignableRBACResourcesPage(resourceType, search string, limit ORDER BY created_at DESC LIMIT ? OFFSET ?` case "deep_assessment": query = `SELECT id,name,status FROM deep_assessments WHERE LOWER(name) LIKE ? ESCAPE '\' OR LOWER(id) LIKE ? ESCAPE '\' ORDER BY updated_at DESC LIMIT ? OFFSET ?` + case "plugin_install": + query = `SELECT id, title, observed_state FROM plugin_installs WHERE observed_state <> 'removed' + AND (LOWER(title) LIKE ? ESCAPE '\' OR LOWER(id) LIKE ? ESCAPE '\') + ORDER BY updated_at DESC, id LIMIT ? OFFSET ?` case "batch_task": query = `SELECT id, COALESCE(NULLIF(title, ''), id), status FROM batch_task_queues WHERE LOWER(COALESCE(NULLIF(title, ''), id)) LIKE ? ESCAPE '\' OR LOWER(id) LIKE ? ESCAPE '\' @@ -682,6 +693,9 @@ func (db *DB) CountAssignableRBACResources(resourceType, search string) (int, er query = `SELECT COUNT(*) FROM webshell_connections WHERE LOWER(COALESCE(NULLIF(remark, ''), url)) LIKE ? ESCAPE '\' OR LOWER(id) LIKE ? ESCAPE '\'` case "deep_assessment": query = `SELECT COUNT(*) FROM deep_assessments WHERE LOWER(name) LIKE ? ESCAPE '\' OR LOWER(id) LIKE ? ESCAPE '\'` + case "plugin_install": + query = `SELECT COUNT(*) FROM plugin_installs WHERE observed_state <> 'removed' + AND (LOWER(title) LIKE ? ESCAPE '\' OR LOWER(id) LIKE ? ESCAPE '\')` case "batch_task": query = `SELECT COUNT(*) FROM batch_task_queues WHERE LOWER(COALESCE(NULLIF(title, ''), id)) LIKE ? ESCAPE '\' OR LOWER(id) LIKE ? ESCAPE '\'` case "c2_listener": @@ -778,6 +792,8 @@ func (db *DB) lookupRBACResourceOptionsByIDs(resourceType string, ids []string) query = `SELECT id, COALESCE(NULLIF(remark, ''), url), type FROM webshell_connections WHERE id IN (` + placeholders + `)` case "deep_assessment": query = `SELECT id,name,status FROM deep_assessments WHERE id IN (` + placeholders + `)` + case "plugin_install": + query = `SELECT id, title, observed_state FROM plugin_installs WHERE id IN (` + placeholders + `)` case "batch_task": query = `SELECT id, COALESCE(NULLIF(title, ''), id), status FROM batch_task_queues WHERE id IN (` + placeholders + `)` case "c2_listener": diff --git a/internal/database/schemas/application.sql b/internal/database/schemas/application.sql index 6e9dee00..3d45366d 100644 --- a/internal/database/schemas/application.sql +++ b/internal/database/schemas/application.sql @@ -1141,3 +1141,149 @@ CREATE TABLE IF NOT EXISTS project_fact_receipts ( execution_id TEXT NOT NULL REFERENCES tool_executions(id) ON DELETE CASCADE, PRIMARY KEY(fact_id, execution_id) ); + +CREATE TABLE IF NOT EXISTS plugin_import_inspections ( + id TEXT PRIMARY KEY, + actor_user_id TEXT NOT NULL, + inspection_json TEXT NOT NULL, + created_at DATETIME NOT NULL, + expires_at DATETIME NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_plugin_import_inspections_expiry ON plugin_import_inspections(expires_at); + +CREATE TABLE IF NOT EXISTS plugin_install_plans ( + id TEXT PRIMARY KEY, + install_id TEXT NOT NULL, + inspection_id TEXT NOT NULL, + actor_user_id TEXT NOT NULL, + manifest_json TEXT NOT NULL, + manifest_digest TEXT NOT NULL, + policy_json TEXT NOT NULL, + plan_json TEXT NOT NULL, + plan_digest TEXT NOT NULL, + expires_at DATETIME NOT NULL, + approved_at DATETIME, + consumed_at DATETIME +); +CREATE INDEX IF NOT EXISTS idx_plugin_install_plans_actor ON plugin_install_plans(actor_user_id, expires_at); + +CREATE TABLE IF NOT EXISTS plugin_installs ( + id TEXT PRIMARY KEY, + catalog_id TEXT NOT NULL DEFAULT '', + plugin_id TEXT NOT NULL, + source_identity TEXT NOT NULL, + title TEXT NOT NULL, + owner_user_id TEXT, + desired_state TEXT NOT NULL DEFAULT 'stopped', + observed_state TEXT NOT NULL DEFAULT 'stopped', + active_version_id TEXT, + generation INTEGER NOT NULL DEFAULT 0, + driver TEXT NOT NULL, + endpoint_ref TEXT, + observed_port INTEGER, + last_error_code TEXT, + created_at DATETIME NOT NULL, + updated_at DATETIME NOT NULL +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_plugin_installs_active_source ON plugin_installs(source_identity, plugin_id) + WHERE observed_state <> 'removed'; + +CREATE TABLE IF NOT EXISTS plugin_versions ( + id TEXT PRIMARY KEY, + install_id TEXT NOT NULL REFERENCES plugin_installs(id) ON DELETE CASCADE, + version TEXT NOT NULL, + manifest_json TEXT NOT NULL, + manifest_digest TEXT NOT NULL, + artifact_identity TEXT NOT NULL, + artifact_digest TEXT NOT NULL, + driver TEXT NOT NULL, + storage_key TEXT NOT NULL, + approval_json TEXT NOT NULL, + plan_json TEXT NOT NULL DEFAULT '', + created_at DATETIME NOT NULL, + UNIQUE(install_id, manifest_digest, artifact_identity, artifact_digest, driver) +); + +CREATE TABLE IF NOT EXISTS plugin_operations ( + id TEXT PRIMARY KEY, + install_id TEXT NOT NULL REFERENCES plugin_installs(id) ON DELETE CASCADE, + actor_user_id TEXT NOT NULL, + kind TEXT NOT NULL, + idempotency_key TEXT NOT NULL, + plan_digest TEXT NOT NULL, + version_id TEXT NOT NULL DEFAULT '', + request_digest TEXT NOT NULL DEFAULT '', + purge_data INTEGER NOT NULL DEFAULT 0, + error_code TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL CHECK(status IN ('queued','running','succeeded','failed','canceled')), + checkpoint TEXT NOT NULL DEFAULT '', + lease_owner TEXT, + lease_until DATETIME, + log_key TEXT, + created_at DATETIME NOT NULL, + updated_at DATETIME NOT NULL, + UNIQUE(install_id, idempotency_key) +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_plugin_operations_active ON plugin_operations(install_id) + WHERE status IN ('queued', 'running'); + +CREATE TABLE IF NOT EXISTS plugin_runtime_leases ( + id INTEGER PRIMARY KEY CHECK(id = 1), + owner TEXT NOT NULL, + expires_at DATETIME NOT NULL +); + +CREATE TABLE IF NOT EXISTS plugin_runtime_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + install_id TEXT NOT NULL REFERENCES plugin_installs(id) ON DELETE CASCADE, + message TEXT NOT NULL, + created_at DATETIME NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_plugin_runtime_logs_cursor ON plugin_runtime_logs(install_id, id); + +CREATE TABLE IF NOT EXISTS plugin_web_origins ( + install_id TEXT PRIMARY KEY REFERENCES plugin_installs(id), + mode TEXT NOT NULL CHECK(mode IN ('port','host')), + listener_port INTEGER NOT NULL DEFAULT 0, + hostname TEXT NOT NULL DEFAULT '', + created_at DATETIME NOT NULL, + retired_at DATETIME +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_plugin_web_origin_port ON plugin_web_origins(listener_port) WHERE mode='port'; +CREATE UNIQUE INDEX IF NOT EXISTS idx_plugin_web_origin_host ON plugin_web_origins(hostname) WHERE mode='host'; + +CREATE TABLE IF NOT EXISTS plugin_llm_bindings ( + install_id TEXT NOT NULL REFERENCES plugin_installs(id) ON DELETE CASCADE, + protocol TEXT NOT NULL, + mode TEXT NOT NULL CHECK(mode IN ('follow_default','channel','disabled')), + channel_id TEXT NOT NULL DEFAULT '', + concurrency INTEGER NOT NULL, + rpm INTEGER NOT NULL, + token_budget INTEGER NOT NULL, + PRIMARY KEY(install_id, protocol) +); + +CREATE TABLE IF NOT EXISTS plugin_gateway_keys ( + digest TEXT PRIMARY KEY, + install_id TEXT NOT NULL REFERENCES plugin_installs(id) ON DELETE CASCADE, + generation INTEGER NOT NULL, + protocol TEXT NOT NULL, + created_at DATETIME NOT NULL, + UNIQUE(install_id,generation,protocol) +); + +CREATE TABLE IF NOT EXISTS plugin_model_usage ( + id TEXT PRIMARY KEY, + install_id TEXT NOT NULL REFERENCES plugin_installs(id) ON DELETE CASCADE, + generation INTEGER NOT NULL, + protocol TEXT NOT NULL, + channel_id TEXT NOT NULL, + day TEXT NOT NULL, + input_tokens INTEGER NOT NULL DEFAULT 0, + output_tokens INTEGER NOT NULL DEFAULT 0, + charged_tokens INTEGER NOT NULL, + status TEXT NOT NULL, + created_at DATETIME NOT NULL, + finished_at DATETIME +); +CREATE INDEX IF NOT EXISTS idx_plugin_model_usage_budget ON plugin_model_usage(install_id,day); diff --git a/internal/handler/plugins.go b/internal/handler/plugins.go new file mode 100644 index 00000000..023f8735 --- /dev/null +++ b/internal/handler/plugins.go @@ -0,0 +1,469 @@ +package handler + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "runtime" + "strconv" + "strings" + "time" + + "cyberstrike-ai/internal/audit" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/pluginhub" + "cyberstrike-ai/internal/pluginhub/catalog" + "cyberstrike-ai/internal/pluginhub/llmgateway" + "cyberstrike-ai/internal/pluginhub/manifest" + "cyberstrike-ai/internal/pluginhub/source" + "cyberstrike-ai/internal/pluginhub/webproxy" + "cyberstrike-ai/internal/security" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +const pluginInspectionTTL = 20 * time.Minute + +type pluginInspector interface { + Inspect(context.Context, string, string) (*source.Inspection, error) +} + +type PluginHandler struct { + db *database.DB + audit *audit.Service + inspector pluginInspector + hub *pluginhub.Manager +} + +func NewPluginHandler(db *database.DB, auditSvc *audit.Service, hub *pluginhub.Manager) *PluginHandler { + return &PluginHandler{db: db, audit: auditSvc, inspector: hub.Inspector(), hub: hub} +} + +func (h *PluginHandler) Register(group *gin.RouterGroup) { + group = group.Group("/plugins", func(c *gin.Context) { + scheme, token, _ := strings.Cut(c.GetHeader("Authorization"), " ") + if !strings.EqualFold(scheme, "Bearer") || strings.TrimSpace(token) == "" { + c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "plugin_bearer_required"}) + return + } + c.Next() + }) + group.GET("/catalog", h.listCatalog) + group.GET("/schemas/:name", h.schema) + group.GET("/llm/channels", h.listLLMChannels) + group.GET("/installs", h.listInstalls) + group.GET("/installs/:id", h.getInstall) + group.POST("/imports/inspect", h.inspect) + group.POST("/install-plans", h.createPlan) + group.GET("/install-plans/:id", h.getPlan) + group.GET("/runtime/probes", h.probes) + group.POST("/installs", h.install) + group.POST("/installs/:id/operations", h.operation) + group.GET("/operations/:id", h.getOperation) + group.GET("/installs/:id/logs", h.logs) + group.POST("/installs/:id/embed-sessions", h.embed) + group.PATCH("/installs/:id/llm", h.patchLLM) +} + +func (h *PluginHandler) embed(c *gin.Context) { + session, ok := security.CurrentSession(c) + if !ok { + pluginError(c, http.StatusUnauthorized, "plugin_session_required") + return + } + entry, err := h.hub.IssueEmbed(c.Request, c.Param("id"), session.Token, session.ExpiresAt) + switch { + case errors.Is(err, webproxy.ErrForbidden): + pluginError(c, http.StatusForbidden, "plugin_embed_origin_or_permission_rejected") + case err != nil: + pluginError(c, http.StatusServiceUnavailable, "plugin_web_unavailable") + default: + c.Header("Cache-Control", "no-store") + c.JSON(http.StatusCreated, entry) + } +} + +func (h *PluginHandler) patchLLM(c *gin.Context) { + var patch llmgateway.Patch + if !bindPluginRequest(c, &patch) { + return + } + bindings, restart, err := h.hub.PatchLLM(c.Request.Context(), c.Param("id"), patch) + switch { + case errors.Is(err, llmgateway.ErrBinding): + pluginError(c, http.StatusUnprocessableEntity, "plugin_llm_binding_invalid") + case errors.Is(err, llmgateway.ErrUnavailable): + pluginError(c, http.StatusServiceUnavailable, "plugin_llm_gateway_unavailable") + case err != nil: + pluginRecordError(c, err) + default: + if h.audit != nil { + h.audit.RecordOK(c, "plugins", "model_binding", "Plugin model binding updated", "plugin_install", c.Param("id"), + map[string]interface{}{"restart_required": restart}) + } + c.JSON(http.StatusOK, gin.H{"bindings": bindings, "restart_required": restart}) + } +} + +func (h *PluginHandler) listCatalog(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"items": catalog.Entries()}) +} + +func (h *PluginHandler) schema(c *gin.Context) { + raw, err := manifest.Schema(c.Param("name")) + if err != nil { + pluginError(c, http.StatusNotFound, "plugin_schema_not_found") + return + } + c.Data(http.StatusOK, "application/schema+json", raw) +} + +func (h *PluginHandler) listInstalls(c *gin.Context) { + session, _ := security.CurrentSession(c) + items, err := h.db.ListPluginInstalls(c.Request.Context(), session.UserID, session.ScopeFor("plugins:read")) + if err != nil { + pluginError(c, http.StatusInternalServerError, "plugin_storage_error") + return + } + c.JSON(http.StatusOK, gin.H{"items": items}) +} + +func (h *PluginHandler) listLLMChannels(c *gin.Context) { + defaultChannel, channels := h.hub.AvailableLLMChannels() + c.JSON(http.StatusOK, gin.H{"default_channel": defaultChannel, "channels": channels}) +} + +func (h *PluginHandler) getInstall(c *gin.Context) { + item, err := h.hub.InstallDetail(c.Request.Context(), c.Param("id")) + if err != nil { + pluginRecordError(c, err) + return + } + c.JSON(http.StatusOK, item) +} + +func (h *PluginHandler) inspect(c *gin.Context) { + var request struct { + Repository string `json:"repository"` + Revision string `json:"revision"` + } + if !bindPluginRequest(c, &request) { + return + } + result, err := h.inspector.Inspect(c.Request.Context(), request.Repository, request.Revision) + if err != nil { + var status int + var code string + switch { + case errors.Is(err, source.ErrInvalidSource), errors.Is(err, source.ErrInvalidRevision): + status, code = http.StatusUnprocessableEntity, "plugin_invalid_source" + case errors.Is(err, source.ErrAmbiguousRef): + status, code = http.StatusConflict, "plugin_ambiguous_git_ref" + case errors.Is(err, source.ErrSourceNotFound): + status, code = http.StatusNotFound, "plugin_source_not_found" + case errors.Is(err, source.ErrManifestInvalid): + status, code = http.StatusUnprocessableEntity, "plugin_invalid_manifest" + case errors.Is(err, source.ErrRateLimited): + status, code = http.StatusTooManyRequests, "plugin_github_rate_limited" + default: + status, code = http.StatusBadGateway, "plugin_source_unavailable" + } + if h.audit != nil { + h.audit.RecordFail(c, "plugins", "inspect", "Plugin import inspection failed", map[string]interface{}{"code": code}) + } + pluginError(c, status, code) + return + } + session, _ := security.CurrentSession(c) + now := time.Now().UTC() + expires := now.Add(pluginInspectionTTL) + id := uuid.NewString() + payload, err := json.Marshal(result) + if err != nil { + pluginError(c, http.StatusInternalServerError, "plugin_inspection_error") + return + } + if err := h.db.SavePluginInspection(c.Request.Context(), id, session.UserID, string(payload), now, expires); err != nil { + pluginError(c, http.StatusInternalServerError, "plugin_storage_error") + return + } + if h.audit != nil { + h.audit.RecordOK(c, "plugins", "inspect", "Plugin import inspected", "plugin_inspection", id, + map[string]interface{}{"repository": result.Repository, "commit": result.Commit}) + } + c.JSON(http.StatusCreated, gin.H{"id": id, "expires_at": expires, "inspection": result}) +} + +func (h *PluginHandler) createPlan(c *gin.Context) { + var request struct { + InspectionID string `json:"inspection_id"` + CatalogID string `json:"catalog_id"` + InstallID string `json:"install_id"` + Manifest json.RawMessage `json:"manifest"` + Driver string `json:"driver"` + Isolation string `json:"isolation"` + } + if !bindPluginRequest(c, &request) { + return + } + session, _ := security.CurrentSession(c) + result, err := h.hub.CreatePlan(c.Request.Context(), pluginhub.PlanRequest{ + Actor: session.UserID, InspectionID: request.InspectionID, CatalogID: request.CatalogID, + InstallID: request.InstallID, Manifest: request.Manifest, Driver: request.Driver, Isolation: request.Isolation, + }) + if err != nil { + pluginLifecycleError(c, err) + return + } + record := result.Record + if h.audit != nil { + h.audit.RecordOK(c, "plugins", "plan", "Plugin install plan prepared for review", "plugin_plan", record.ID, + map[string]interface{}{"plan_digest": record.PlanDigest}) + } + response := pluginPlanResponse(record) + response["artifact_digest"], response["host_approved"] = result.ArtifactDigest, result.HostApproved + response["approval_policy"] = h.hub.ApprovalPolicy() + response["can_confirm"] = h.hub.CanConfirm(record.ManifestDigest, result.ArtifactDigest) + c.JSON(http.StatusCreated, response) +} + +func (h *PluginHandler) getPlan(c *gin.Context) { + session, _ := security.CurrentSession(c) + record, err := h.db.GetPluginPlan(c.Request.Context(), c.Param("id"), session.UserID, time.Now()) + if err != nil { + pluginRecordError(c, err) + return + } + response := pluginPlanResponse(record) + response["approval_policy"] = h.hub.ApprovalPolicy() + if plan, err := manifest.DecodeInstallPlan([]byte(record.PlanJSON)); err == nil { + artifact := pluginhub.ArtifactDigest(plan.Artifact) + response["artifact_digest"] = artifact + response["can_confirm"] = record.ApprovedAt == nil && h.hub.CanConfirm(record.ManifestDigest, artifact) + if record.ApprovedAt != nil { + response["approved_at"] = record.ApprovedAt + } + } + c.JSON(http.StatusOK, response) +} + +func pluginPlanResponse(record database.PluginPlanRecord) gin.H { + return gin.H{"plan": json.RawMessage(record.PlanJSON), "plan_digest": record.PlanDigest, + "manifest": json.RawMessage(record.ManifestJSON), "policy": json.RawMessage(record.PolicyJSON)} +} + +func (h *PluginHandler) probes(c *gin.Context) { + isolation := c.DefaultQuery("isolation", "standard") + if isolation != "standard" && isolation != "strict" { + pluginError(c, http.StatusUnprocessableEntity, "plugin_invalid_isolation") + return + } + ctx, cancel := context.WithTimeout(c.Request.Context(), 10*time.Second) + defer cancel() + c.JSON(http.StatusOK, gin.H{"execution_enabled": h.hub.Ready(), "os": runtime.GOOS, "arch": runtime.GOARCH, + "drivers": h.hub.Probes(ctx, isolation)}) +} + +type pluginOperationRequest struct { + Kind string `json:"kind"` + PlanID string `json:"plan_id"` + PlanDigest string `json:"plan_digest"` + Key string `json:"idempotency_key"` + Purge bool `json:"purge_data"` + AutoBindLLM *bool `json:"auto_bind_llm,omitempty"` +} + +func (h *PluginHandler) install(c *gin.Context) { + var request pluginOperationRequest + if !bindPluginRequest(c, &request) { + return + } + if request.Kind != "" && request.Kind != "install" { + pluginError(c, http.StatusUnprocessableEntity, "plugin_invalid_operation") + return + } + request.Kind = "install" + h.queue(c, request) +} + +func (h *PluginHandler) operation(c *gin.Context) { + var request pluginOperationRequest + if !bindPluginRequest(c, &request) { + return + } + if request.Kind == "install" { + pluginError(c, http.StatusUnprocessableEntity, "plugin_invalid_operation") + return + } + h.queue(c, request) +} + +func (h *PluginHandler) queue(c *gin.Context, request pluginOperationRequest) { + if key := c.GetHeader("Idempotency-Key"); key != "" { + if request.Key != "" && request.Key != key { + pluginError(c, http.StatusUnprocessableEntity, "plugin_invalid_idempotency_key") + return + } + request.Key = key + } + session, _ := security.CurrentSession(c) + op, err := h.hub.Queue(c.Request.Context(), pluginhub.OperationRequest{ + Actor: session.UserID, Kind: request.Kind, InstallID: c.Param("id"), PlanID: request.PlanID, + PlanDigest: request.PlanDigest, Key: request.Key, Purge: request.Purge, AutoBindLLM: request.AutoBindLLM, + }) + if err != nil { + pluginLifecycleError(c, err) + return + } + if h.audit != nil { + h.audit.RecordOK(c, "plugins", "operation", "Plugin operation accepted", "plugin_operation", op.ID, + map[string]interface{}{"kind": op.Kind, "install_id": op.InstallID, "plan_digest": op.PlanDigest}) + } + c.Header("Location", "/api/plugins/operations/"+op.ID) + c.JSON(http.StatusAccepted, op) +} + +func (h *PluginHandler) getOperation(c *gin.Context) { + item, err := h.db.GetPluginOperation(c.Request.Context(), c.Param("id")) + if err != nil { + pluginRecordError(c, err) + return + } + c.JSON(http.StatusOK, item) +} + +func (h *PluginHandler) logs(c *gin.Context) { + id := c.Param("id") + if _, err := h.db.RuntimePluginInstall(c.Request.Context(), id); err != nil { + pluginRecordError(c, err) + return + } + cursor := c.DefaultQuery("after", "0") + if value := c.GetHeader("Last-Event-ID"); value != "" && !c.Request.URL.Query().Has("after") { + cursor = value + } + after, cursorErr := strconv.ParseInt(cursor, 10, 64) + limit, limitErr := strconv.Atoi(c.DefaultQuery("limit", "100")) + if cursorErr != nil || after < 0 || limitErr != nil || limit < 1 || limit > 200 { + pluginError(c, http.StatusUnprocessableEntity, "plugin_invalid_log_cursor") + return + } + if strings.Contains(c.GetHeader("Accept"), "text/event-stream") { + h.streamLogs(c, id, after, limit) + return + } + entries, err := h.db.ReadPluginLogs(c.Request.Context(), id, after, limit) + if err != nil { + pluginRecordError(c, err) + return + } + if len(entries) != 0 { + after = entries[len(entries)-1].ID + } + c.JSON(http.StatusOK, gin.H{"items": entries, "next_cursor": after}) +} + +func (h *PluginHandler) streamLogs(c *gin.Context, id string, after int64, limit int) { + ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Minute) + defer cancel() + c.Header("Content-Type", "text/event-stream") + c.Header("Cache-Control", "no-store") + c.Header("X-Accel-Buffering", "no") + c.Status(http.StatusOK) + _, _ = io.WriteString(c.Writer, ": connected\n\n") + c.Writer.Flush() + poll := time.NewTicker(400 * time.Millisecond) + defer poll.Stop() + heartbeat := time.NewTicker(15 * time.Second) + defer heartbeat.Stop() + for { + entries, err := h.db.ReadPluginLogs(ctx, id, after, limit) + if err != nil { + return + } + for _, entry := range entries { + raw, _ := json.Marshal(entry) + if _, err := fmt.Fprintf(c.Writer, "id: %d\nevent: log\ndata: %s\n\n", entry.ID, raw); err != nil { + return + } + after = entry.ID + } + if len(entries) != 0 { + c.Writer.Flush() + } + select { + case <-ctx.Done(): + return + case <-poll.C: + case <-heartbeat.C: + if _, err := io.WriteString(c.Writer, ": heartbeat\n\n"); err != nil { + return + } + c.Writer.Flush() + } + } +} + +func pluginLifecycleError(c *gin.Context, err error) { + switch { + case errors.Is(err, pluginhub.ErrInvalidRequest): + pluginError(c, http.StatusUnprocessableEntity, "plugin_invalid_request") + case errors.Is(err, pluginhub.ErrManifestRequired), errors.Is(err, pluginhub.ErrCatalogManifest): + pluginError(c, http.StatusUnprocessableEntity, "plugin_manifest_required") + case errors.Is(err, pluginhub.ErrInvalidManifest): + pluginError(c, http.StatusUnprocessableEntity, "plugin_invalid_manifest") + case errors.Is(err, pluginhub.ErrSourceMismatch): + pluginError(c, http.StatusConflict, "plugin_manifest_source_mismatch") + case errors.Is(err, pluginhub.ErrUnapprovedArtifact): + pluginError(c, http.StatusForbidden, "plugin_artifact_not_approved") + case errors.Is(err, database.ErrPluginOperationConflict): + pluginError(c, http.StatusConflict, "plugin_operation_conflict") + case errors.Is(err, pluginhub.ErrStalePlan), errors.Is(err, database.ErrPluginPlanUnavailable): + pluginError(c, http.StatusConflict, "plugin_plan_stale") + case errors.Is(err, pluginhub.ErrRuntimeUnavailable): + pluginError(c, http.StatusServiceUnavailable, "plugin_runtime_unavailable") + case errors.Is(err, source.ErrArtifactUnavailable): + pluginError(c, http.StatusUnprocessableEntity, "plugin_artifact_unavailable") + case errors.Is(err, sql.ErrNoRows): + pluginError(c, http.StatusNotFound, "plugin_record_not_found") + default: + pluginError(c, http.StatusBadGateway, "plugin_operation_unavailable") + } +} + +func bindPluginRequest(c *gin.Context, value any) bool { + reader := http.MaxBytesReader(c.Writer, c.Request.Body, manifest.MaxDocumentBytes) + decoder := json.NewDecoder(reader) + decoder.DisallowUnknownFields() + if err := decoder.Decode(value); err != nil { + pluginError(c, http.StatusBadRequest, "plugin_invalid_request") + return false + } + var extra any + if err := decoder.Decode(&extra); err != io.EOF { + pluginError(c, http.StatusBadRequest, "plugin_invalid_request") + return false + } + return true +} + +func pluginRecordError(c *gin.Context, err error) { + if errors.Is(err, sql.ErrNoRows) { + pluginError(c, http.StatusNotFound, "plugin_record_not_found") + return + } + pluginError(c, http.StatusInternalServerError, "plugin_storage_error") +} + +func pluginRuntimeUnavailable(c *gin.Context) { + pluginError(c, http.StatusNotImplemented, "plugin_runtime_unavailable") +} + +func pluginError(c *gin.Context, status int, code string) { + c.JSON(status, gin.H{"error": code}) +} diff --git a/internal/handler/plugins_test.go b/internal/handler/plugins_test.go new file mode 100644 index 00000000..37eedddc --- /dev/null +++ b/internal/handler/plugins_test.go @@ -0,0 +1,222 @@ +package handler + +import ( + "bufio" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/pluginhub" + "cyberstrike-ai/internal/pluginhub/manifest" + "cyberstrike-ai/internal/pluginhub/source" + "cyberstrike-ai/internal/security" + + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +type pluginInspectorFunc func(context.Context, string, string) (*source.Inspection, error) + +func (f pluginInspectorFunc) Inspect(ctx context.Context, repository, revision string) (*source.Inspection, error) { + return f(ctx, repository, revision) +} + +func TestPluginManagementPreviewAndRBAC(t *testing.T) { + db, err := database.NewDB(filepath.Join(t.TempDir(), "plugins.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + auth := security.NewAuthManager(2) + password, err := auth.AttachRBACStore(db) + if err != nil { + t.Fatal(err) + } + admin, _, err := auth.Authenticate("admin", password) + if err != nil { + t.Fatal(err) + } + addUser := func(username, scope string, permissions ...string) (string, string) { + t.Helper() + role, err := db.UpsertRBACRole("", username, "", scope, permissions) + if err != nil { + t.Fatal(err) + } + hash, err := security.HashPassword(password) + if err != nil { + t.Fatal(err) + } + user, err := db.CreateRBACUser(username, username, hash, true, []string{role.ID}) + if err != nil { + t.Fatal(err) + } + token, _, err := auth.Authenticate(username, password) + if err != nil { + t.Fatal(err) + } + return user.ID, token + } + readerID, reader := addUser("plugin-reader", database.RBACScopeAssigned, "plugins:read") + _, scopedManager := addUser("plugin-scoped-manager", database.RBACScopeOwn, "plugins:manage") + _, otherManager := addUser("plugin-other-manager", database.RBACScopeAll, "plugins:manage") + _, userWithoutPlugins := addUser("plugin-other", database.RBACScopeAll, "auth:self") + + raw, err := os.ReadFile("../pluginhub/manifest/testdata/web-plugin.yaml") + if err != nil { + t.Fatal(err) + } + raw = []byte(strings.ReplaceAll(string(raw), "https://git.example.org/examples/log-review-demo.git", "https://github.com/example/review")) + commit := strings.Repeat("a", 40) + manager, err := pluginhub.New(db, config.PluginsConfig{}, t.TempDir(), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + handler := NewPluginHandler(db, nil, manager) + inspections := 0 + handler.inspector = pluginInspectorFunc(func(_ context.Context, repository, revision string) (*source.Inspection, error) { + inspections++ + if repository != "https://github.com/example/review" || (revision != "v1.0.0" && revision != "draft") { + t.Fatalf("bad inspector inputs: %s %s", repository, revision) + } + inspection := &source.Inspection{ + Repository: repository, RequestedRef: revision, ResolvedRef: "refs/tags/v1.0.0", + Commit: commit, Candidates: []string{"git"}, + } + if revision != "draft" { + declaration, err := manifest.DecodeDeclaration(raw) + if err != nil { + t.Fatal(err) + } + inspection.Manifest = declaration.Canonical + } + return inspection, nil + }) + router := gin.New() + group := router.Group("/api", security.AuthMiddleware(auth), security.RBACMiddleware(db)) + handler.Register(group) + + request := func(method, path, token, body string, expected int) []byte { + t.Helper() + req := httptest.NewRequest(method, "/api/plugins"+path, strings.NewReader(body)) + if strings.HasPrefix(token, "cookie:") { + req.AddCookie(&http.Cookie{Name: "auth_token", Value: strings.TrimPrefix(token, "cookie:")}) + } else if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + res := httptest.NewRecorder() + router.ServeHTTP(res, req) + if res.Code != expected { + t.Fatalf("%s %s: status %d, expected %d: %s", method, path, res.Code, expected, res.Body) + } + return res.Body.Bytes() + } + + request(http.MethodGet, "/catalog", "", "", http.StatusUnauthorized) + request(http.MethodGet, "/catalog", "cookie:"+admin, "", http.StatusUnauthorized) + request(http.MethodGet, "/catalog", reader, "", http.StatusOK) + request(http.MethodGet, "/catalog", userWithoutPlugins, "", http.StatusForbidden) + request(http.MethodGet, "/schemas/manifest-v1", reader, "", http.StatusOK) + body := `{"repository":"https://github.com/example/review","revision":"v1.0.0"}` + request(http.MethodPost, "/imports/inspect", reader, body, http.StatusForbidden) + request(http.MethodPost, "/imports/inspect", scopedManager, body, http.StatusForbidden) + var inspection struct{ ID string } + if err := json.Unmarshal(request(http.MethodPost, "/imports/inspect", admin, body, http.StatusCreated), &inspection); err != nil || inspection.ID == "" { + t.Fatalf("missing inspection ID: %v", err) + } + if inspections != 1 { + t.Fatalf("unapproved inspection ran: %d calls", inspections) + } + planRequest := `{"inspection_id":"` + inspection.ID + `","isolation":"standard","driver":"git"}` + request(http.MethodPost, "/install-plans", otherManager, planRequest, http.StatusNotFound) + var response struct { + Plan json.RawMessage `json:"plan"` + Digest string `json:"plan_digest"` + } + if err := json.Unmarshal(request(http.MethodPost, "/install-plans", admin, planRequest, http.StatusCreated), &response); err != nil { + t.Fatal(err) + } + plan, err := manifest.DecodeInstallPlan(response.Plan) + if err != nil || plan.Artifact.Commit != commit || plan.Isolation != "standard" || manifest.Digest(plan.Canonical) != response.Digest { + t.Fatalf("plan %+v: %v; digest %s", plan, err, response.Digest) + } + request(http.MethodGet, "/install-plans/"+plan.ID, otherManager, "", http.StatusNotFound) + request(http.MethodGet, "/install-plans/"+plan.ID, admin, "", http.StatusOK) + confirmation := `{"plan_id":"` + plan.ID + `","plan_digest":"` + response.Digest + `","idempotency_key":"approve"}` + request(http.MethodPost, "/installs", scopedManager, confirmation, http.StatusForbidden) + request(http.MethodPost, "/installs", admin, `{}`, http.StatusUnprocessableEntity) + draftRequest := `{"repository":"https://github.com/example/review","revision":"draft"}` + var draftInspection struct{ ID string } + if err := json.Unmarshal(request(http.MethodPost, "/imports/inspect", admin, draftRequest, http.StatusCreated), &draftInspection); err != nil { + t.Fatal(err) + } + draftPlan := `{"inspection_id":"` + draftInspection.ID + `"}` + request(http.MethodPost, "/install-plans", admin, draftPlan, http.StatusUnprocessableEntity) + edited, err := manifest.DecodeDeclaration(raw) + if err != nil { + t.Fatal(err) + } + draftPlan = `{"inspection_id":"` + draftInspection.ID + `","driver":"git","manifest":` + string(edited.Canonical) + `}` + request(http.MethodPost, "/install-plans", admin, strings.ReplaceAll(draftPlan, "example/review", "another/review"), http.StatusConflict) + request(http.MethodPost, "/install-plans", admin, draftPlan, http.StatusCreated) + item, err := db.Exec(`INSERT INTO plugin_installs + (id, plugin_id, source_identity, title, owner_user_id, driver, created_at, updated_at) + VALUES ('plugin-a','review','source-a','Review','admin','git',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`) + if err != nil { + t.Fatal(err) + } + if n, _ := item.RowsAffected(); n != 1 { + t.Fatalf("unexpected rows affected: %d", n) + } + request(http.MethodGet, "/installs/plugin-a", reader, "", http.StatusForbidden) + if err := db.AssignResourceToUser(readerID, "plugin_install", "plugin-a"); err != nil { + t.Fatal(err) + } + request(http.MethodGet, "/installs/plugin-a", reader, "", http.StatusOK) + list := request(http.MethodGet, "/installs", reader, "", http.StatusOK) + if !strings.Contains(string(list), "plugin-a") || strings.Contains(string(list), "source-a") { + t.Fatalf("unexpected install summary: %s", list) + } + request(http.MethodPost, "/installs/plugin-a/embed-sessions", reader, `{}`, http.StatusForbidden) + request(http.MethodPost, "/installs/plugin-a/embed-sessions", admin, `{}`, http.StatusForbidden) + request(http.MethodGet, "/installs/plugin-a/logs", reader, "", http.StatusForbidden) + if err := db.AppendPluginLog(context.Background(), "plugin-a", "fixture log line"); err != nil { + t.Fatal(err) + } + page := request(http.MethodGet, "/installs/plugin-a/logs?limit=1", admin, "", http.StatusOK) + if !strings.Contains(string(page), "fixture log line") || !strings.Contains(string(page), "next_cursor") { + t.Fatalf("unexpected log page: %s", page) + } + server := httptest.NewServer(router) + defer server.Close() + streamCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(streamCtx, http.MethodGet, server.URL+"/api/plugins/installs/plugin-a/logs", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Accept", "text/event-stream") + req.Header.Set("Authorization", "Bearer "+admin) + res, err := server.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK || res.Header.Get("Content-Type") != "text/event-stream" { + t.Fatalf("unexpected stream response: %s", res.Status) + } + scanner := bufio.NewScanner(res.Body) + for scanner.Scan() { + if strings.HasPrefix(scanner.Text(), "data: ") && strings.Contains(scanner.Text(), "fixture log line") { + return + } + } + t.Fatalf("log stream did not emit a fixture entry: %v", scanner.Err()) +} diff --git a/internal/pluginhub/catalog/artex.yaml b/internal/pluginhub/catalog/artex.yaml new file mode 100644 index 00000000..48c4fe84 --- /dev/null +++ b/internal/pluginhub/catalog/artex.yaml @@ -0,0 +1,105 @@ +apiVersion: plugins.csai.io/v1 +kind: WebPlugin +metadata: + id: artex + title: ARTEX + summary: AI 自主渗透测试平台(Go 后端 + Next.js 前端 + PostgreSQL),支持直接复用 CSAI 模型通道。 + version: "1.0.0" + repository: https://github.com/RuoJi6/ARTEX + license: AGPL-3.0 +distribution: + - type: container + mode: compose + services: + - name: artex + role: web + image: ruoji6/artex:latest + containerPort: 8787 + staticEnv: + TZ: Asia/Shanghai + ARTEX_EVENT_BUS: memory + secretEnv: + ARTEX_PG_DSN: + kind: connection_uri + secretRef: db-password + scheme: postgres + service: postgres + username: artex + database: artex + options: + sslmode: disable + depends_on: + postgres: service_healthy + resources: + memoryMiB: 4096 + pids: 512 + dataVolumes: + - name: app-data + mountPath: /app/data + - name: postgres + role: dependency + image: postgres:16-alpine + containerPort: 5432 + staticEnv: + POSTGRES_USER: artex + POSTGRES_DB: artex + secretEnv: + POSTGRES_PASSWORD: + kind: value + secretRef: db-password + healthcheck: + kind: exec + argv: [pg_isready, -U, artex, -d, artex] + intervalSeconds: 5 + timeoutSeconds: 3 + retries: 10 + resources: + memoryMiB: 512 + pids: 128 + dataVolumes: + - name: pgdata + mountPath: /var/lib/postgresql/data +secrets: + db-password: + generator: random_base64url + bytes: 32 +web: + route: root + entryPath: / + healthPath: / + allowHealthRedirect: true + sse: true + websocket: true +access: + mode: plugin_login + applicationBearer: + - /api +llm: + selection: single_active + bindings: + - protocol: openai_chat + providerValue: openai + env: + OPENAI_API_KEY: gateway_token + ARTEX_LLM_PROVIDER: provider + ARTEX_LLM_MODEL: model_alias + ARTEX_LLM_BASE_URL: gateway_v1_url + - protocol: anthropic_messages + providerValue: anthropic + env: + ANTHROPIC_API_KEY: gateway_token + ARTEX_LLM_PROVIDER: provider + ARTEX_LLM_MODEL: model_alias + ARTEX_LLM_BASE_URL: gateway_root_url +permissions: + persistentData: true + modelGateway: true + egress: + - managed_dependency + - managed_model_gateway +extensions: + capabilities: + - id: artex-mcp + transport: mcp_http + path: /mcp + resource: "io.artex:mcp" diff --git a/internal/pluginhub/catalog/catalog.go b/internal/pluginhub/catalog/catalog.go new file mode 100644 index 00000000..cebf33b9 --- /dev/null +++ b/internal/pluginhub/catalog/catalog.go @@ -0,0 +1,50 @@ +// Package catalog contains curated metadata for the read-only discovery UI. +package catalog + +import _ "embed" + +//go:embed static-web.yaml +var staticWeb []byte + +//go:embed artex.yaml +var artex []byte + +type Entry struct { + ID string `json:"id"` + Title string `json:"title"` + Repository string `json:"repository"` + Revision string `json:"revision"` + Summary string `json:"summary"` + Availability string `json:"availability"` +} + +func Entries() []Entry { + return []Entry{ + { + ID: "artex", + Title: "ARTEX", + Repository: "https://github.com/RuoJi6/ARTEX", + Summary: "AI autonomous penetration testing platform (Go + Next.js + PostgreSQL) with CSAI LLM gateway reuse.", + Availability: "plan_available", + }, + {ID: "static-web", Title: "Static Web Runtime Check", Repository: "https://github.com/nginx/docker-nginx-unprivileged", + Summary: "Unprivileged static WebUI for lifecycle verification.", Availability: "plan_available"}, + { + ID: "librechat", Title: "LibreChat", Repository: "https://github.com/LibreChat-AI/LibreChat", + Revision: "566e20b613389600a7975fd8f7c1bffbe54f06c8", + Summary: "Self-hosted chat WebUI used for plugin platform interoperability verification.", + Availability: "inspection_only", + }, + } +} + +func Manifest(id string) ([]byte, bool) { + switch id { + case "artex": + return append([]byte(nil), artex...), true + case "static-web": + return append([]byte(nil), staticWeb...), true + default: + return nil, false + } +} diff --git a/internal/pluginhub/catalog/catalog_test.go b/internal/pluginhub/catalog/catalog_test.go new file mode 100644 index 00000000..907576a8 --- /dev/null +++ b/internal/pluginhub/catalog/catalog_test.go @@ -0,0 +1,26 @@ +package catalog + +import ( + "testing" + + "cyberstrike-ai/internal/pluginhub/manifest" +) + +func TestEmbeddedManifestsValidate(t *testing.T) { + for _, entry := range Entries() { + if entry.Availability != "plan_available" { + continue + } + raw, ok := Manifest(entry.ID) + if !ok { + t.Fatalf("catalog entry %q advertises plan_available without embedded manifest", entry.ID) + } + decl, err := manifest.DecodeDeclaration(raw) + if err != nil { + t.Fatalf("catalog manifest %q failed validation: %v", entry.ID, err) + } + if decl.Metadata.ID != entry.ID { + t.Fatalf("catalog manifest %q declares metadata.id=%q", entry.ID, decl.Metadata.ID) + } + } +} diff --git a/internal/pluginhub/catalog/static-web.yaml b/internal/pluginhub/catalog/static-web.yaml new file mode 100644 index 00000000..9aafa0e8 --- /dev/null +++ b/internal/pluginhub/catalog/static-web.yaml @@ -0,0 +1,19 @@ +apiVersion: plugins.csai.io/v1 +kind: WebPlugin +metadata: + id: static-web + title: Static Web Runtime Check + version: "1.0.0" + repository: https://github.com/nginx/docker-nginx-unprivileged +distribution: + - type: container + mode: docker + services: + - name: web + role: web + image: nginxinc/nginx-unprivileged:stable-alpine + containerPort: 8080 + resources: {memoryMiB: 128, pids: 64} +web: {route: root, entryPath: "/", healthPath: "/"} +access: {mode: platform} +permissions: {persistentData: false, modelGateway: false, egress: []} diff --git a/internal/pluginhub/e2e_test.go b/internal/pluginhub/e2e_test.go new file mode 100644 index 00000000..7540251f --- /dev/null +++ b/internal/pluginhub/e2e_test.go @@ -0,0 +1,382 @@ +package pluginhub + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/pluginhub/manifest" + "cyberstrike-ai/internal/pluginhub/runner" + "cyberstrike-ai/internal/pluginhub/source" + "cyberstrike-ai/internal/pluginhub/webproxy" + "cyberstrike-ai/internal/security" + + "go.uber.org/zap" +) + +type e2eFakeDriver struct { + srv *httptest.Server +} + +func (d *e2eFakeDriver) Probe(context.Context, string) runner.Probe { + return runner.Probe{Available: true} +} + +func (d *e2eFakeDriver) Prepare(context.Context, runner.Spec) error { return nil } + +func (d *e2eFakeDriver) Start(_ context.Context, spec runner.Spec) (runner.State, error) { + if spec.Model == nil || spec.Model.Env["PLUGIN_LLM_BASE_URL"] == "" || spec.Model.Env["PLUGIN_LLM_TOKEN"] == "" { + return runner.State{}, ErrRuntimeUnavailable + } + baseURL := spec.Model.Env["PLUGIN_LLM_BASE_URL"] + token := spec.Model.Env["PLUGIN_LLM_TOKEN"] + model := spec.Model.Env["PLUGIN_LLM_MODEL"] + d.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/healthz": + w.WriteHeader(http.StatusOK) + case "/": + w.Header().Set("Content-Type", "text/html") + _, _ = w.Write([]byte("

Embedded Plugin OK

")) + case "/api/run-tool": + // Simulate the plugin calling CSAI's LLM gateway with OpenAI tool_calls (and without explicit max_tokens). + payload := map[string]any{ + "model": model, + "tools": []map[string]any{{ + "type": "function", + "function": map[string]any{ + "name": "ping_target", + "parameters": map[string]any{"type": "object"}, + }, + }}, + "messages": []map[string]any{ + {"role": "user", "content": "check target"}, + {"role": "assistant", "tool_calls": []map[string]any{{ + "id": "call_1", "type": "function", + "function": map[string]any{"name": "ping_target", "arguments": "{}"}, + }}}, + {"role": "tool", "tool_call_id": "call_1", "content": "alive"}, + }, + } + body, _ := json.Marshal(payload) + req, _ := http.NewRequestWithContext(r.Context(), http.MethodPost, baseURL+"/chat/completions", bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + defer resp.Body.Close() + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(resp.StatusCode) + _, _ = io.Copy(w, resp.Body) + default: + http.NotFound(w, r) + } + })) + u, _ := url.Parse(d.srv.URL) + var port int + _, _ = json.Marshal(u.Port()) + return runner.State{Running: true, Endpoint: d.srv.URL, Port: port}, nil +} + +func (d *e2eFakeDriver) Inspect(context.Context, runner.Spec) (runner.State, error) { + if d.srv == nil { + return runner.State{}, nil + } + return runner.State{Running: true, Endpoint: d.srv.URL}, nil +} + +func (d *e2eFakeDriver) Stop(context.Context, runner.Spec) error { + if d.srv != nil { + d.srv.Close() + d.srv = nil + } + return nil +} + +func (d *e2eFakeDriver) Remove(ctx context.Context, spec runner.Spec) error { + return d.Stop(ctx, spec) +} + +func TestEndToEndInstallAutoBindEmbedProxyAndToolCalling(t *testing.T) { + var upstreamSawMaxTokens bool + var upstreamSawMaxCompletion bool + var upstreamSawTools bool + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer upstream-secret-key" { + http.Error(w, "bad key", http.StatusUnauthorized) + return + } + var fields map[string]json.RawMessage + if err := json.NewDecoder(r.Body).Decode(&fields); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + upstreamSawMaxTokens = fields["max_tokens"] != nil + upstreamSawMaxCompletion = fields["max_completion_tokens"] != nil + upstreamSawTools = fields["tools"] != nil + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"chatcmpl-1","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"tool roundtrip ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":12,"completion_tokens":8}}`)) + })) + defer upstream.Close() + + db, err := database.NewDB(filepath.Join(t.TempDir(), "e2e.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + + auth := security.NewAuthManager(2) + pw, err := auth.AttachRBACStore(db) + if err != nil { + t.Fatal(err) + } + adminToken, adminExp, err := auth.Authenticate("admin", pw) + if err != nil { + t.Fatal(err) + } + + cfg := config.PluginsConfig{ + Directory: filepath.Join(t.TempDir(), "plugins"), + Proxy: config.PluginProxyConfig{ + Mode: "port", + BindHost: "127.0.0.1", + PortPool: config.PluginPortPool{Start: 44100, End: 44120}, + }, + } + mgr, err := New(db, cfg, t.TempDir(), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + drv := &e2eFakeDriver{} + mgr.drivers["git"] = drv + mgr.ConfigureServices(auth, func() (*config.Config, error) { + return &config.Config{ + AI: config.AIConfig{ + DefaultChannel: "primary", + Channels: map[string]config.AIChannelConfig{ + "primary": { + Name: "Primary OpenAI", + Provider: "openai", + APIKey: "upstream-secret-key", + BaseURL: upstream.URL + "/v1", + Model: "gpt-test", + }, + }, + }, + }, nil + }) + if err := mgr.StartServices("127.0.0.1", 8080, nil); err != nil { + t.Fatal(err) + } + defer mgr.CloseServices() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if err := mgr.Start(ctx); err != nil { + t.Fatal(err) + } + defer func() { + stopCtx, stopCancel := context.WithTimeout(context.Background(), 5*time.Second) + defer stopCancel() + _ = mgr.Close(stopCtx) + }() + for deadline := time.Now().Add(3 * time.Second); !mgr.Ready() && time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { + } + + // Verify sanitized channel listing works without leaking API key. + defaultCh, channels := mgr.AvailableLLMChannels() + if defaultCh != "primary" || len(channels) != 1 || channels[0].Protocol != manifest.OpenAI { + t.Fatalf("unexpected channels: default=%q list=%+v", defaultCh, channels) + } + + commit := strings.Repeat("b", 40) + manifestYAML := ` +apiVersion: plugins.csai.io/v1 +kind: WebPlugin +metadata: + id: e2e-tool + title: E2E Tool + summary: End-to-end verification plugin + version: "1.0.0" + repository: https://github.com/example/e2e-tool + license: MIT +distribution: + - type: git + url: https://github.com/example/e2e-tool + revision: main + dependencies: [{name: go, minVersion: "1.22"}] + build: [{program: go, args: [build, .]}] +launch: + entrypoint: e2e-tool + env: + PORT: listen_port +web: + route: root + entryPath: / + healthPath: /healthz +access: + mode: platform +llm: + selection: single_active + bindings: + - protocol: openai_chat + providerValue: openai + env: + PLUGIN_LLM_BASE_URL: gateway_v1_url + PLUGIN_LLM_TOKEN: gateway_token + PLUGIN_LLM_MODEL: model_alias + PLUGIN_LLM_PROVIDER: provider +permissions: + persistentData: false + modelGateway: true + egress: [managed_model_gateway] +` + decl, err := manifest.DecodeDeclaration([]byte(manifestYAML)) + if err != nil { + t.Fatal(err) + } + inspBytes, _ := json.Marshal(source.Inspection{ + Repository: "https://github.com/example/e2e-tool", + ResolvedRef: "refs/heads/main", + Commit: commit, + Manifest: decl.Canonical, + Candidates: []string{"git"}, + }) + now := time.Now().UTC() + if err := db.SavePluginInspection(ctx, "insp-e2e", "admin", string(inspBytes), now, now.Add(5*time.Minute)); err != nil { + t.Fatal(err) + } + planRes, err := mgr.CreatePlan(ctx, PlanRequest{ + Actor: "admin", + InspectionID: "insp-e2e", + Driver: "git", + Isolation: "standard", + }) + if err != nil { + t.Fatal(err) + } + + // Queue install with default AutoBindLLM (nil => auto-bind default channel). + op, err := mgr.Queue(ctx, OperationRequest{ + Actor: "admin", + Kind: "install", + PlanID: planRes.Record.ID, + PlanDigest: planRes.Record.PlanDigest, + Key: "install-e2e-1", + }) + if err != nil { + t.Fatal(err) + } + waitOp := func(opID string) database.PluginOperation { + t.Helper() + for deadline := time.Now().Add(8 * time.Second); time.Now().Before(deadline); time.Sleep(40 * time.Millisecond) { + got, err := db.GetPluginOperation(ctx, opID) + if err == nil && got.Status != "queued" && got.Status != "running" { + return got + } + } + t.Fatalf("operation %s timed out", opID) + return database.PluginOperation{} + } + if got := waitOp(op.ID); got.Status != "succeeded" { + t.Fatalf("install failed: %+v (os=%s/%s)", got, runtime.GOOS, runtime.GOARCH) + } + + detail, err := mgr.InstallDetail(ctx, op.InstallID) + if err != nil { + t.Fatal(err) + } + if detail.Observed != "healthy" || len(detail.LLMBindings) != 1 || detail.LLMBindings[0].Mode != "follow_default" { + t.Fatalf("unexpected detail after auto-bind install: %+v", detail) + } + + // Issue embed ticket and exchange it for an isolated browser session cookie. + issueReq := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/plugins/installs/"+op.InstallID+"/embed-sessions", nil) + issueReq.Host = "127.0.0.1:8080" + issueReq.Header.Set("Origin", "http://127.0.0.1:8080") + embed, err := mgr.IssueEmbed(issueReq, op.InstallID, adminToken, adminExp) + if err != nil { + t.Fatal(err) + } + + noRedirect := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + form := url.Values{"ticket": {embed.Ticket}} + exReq, _ := http.NewRequest(http.MethodPost, embed.Action, strings.NewReader(form.Encode())) + exReq.Header.Set("Content-Type", "application/x-www-form-urlencoded") + exReq.Header.Set("Origin", "http://127.0.0.1:8080") + exResp, err := noRedirect.Do(exReq) + if err != nil { + t.Fatal(err) + } + defer exResp.Body.Close() + if exResp.StatusCode != http.StatusSeeOther || len(exResp.Cookies()) != 1 { + t.Fatalf("ticket exchange failed: status=%d cookies=%d", exResp.StatusCode, len(exResp.Cookies())) + } + sessionCookie := exResp.Cookies()[0] + if sessionCookie.MaxAge != int((2 * time.Hour).Seconds()) { + t.Fatalf("expected 2h session cookie, got MaxAge=%d", sessionCookie.MaxAge) + } + + // Proxy GET / through isolated origin. + pageReq, _ := http.NewRequest(http.MethodGet, embed.Origin+"/", nil) + pageReq.AddCookie(sessionCookie) + pageResp, err := noRedirect.Do(pageReq) + if err != nil { + t.Fatal(err) + } + pageBody, _ := io.ReadAll(pageResp.Body) + pageResp.Body.Close() + if pageResp.StatusCode != http.StatusOK || !strings.Contains(string(pageBody), "Embedded Plugin OK") { + t.Fatalf("proxy page failed: status=%d body=%q", pageResp.StatusCode, string(pageBody)) + } + + // Proxy POST /api/run-tool -> plugin calls CSAI LLM gateway -> mock OpenAI upstream with tools + default max_tokens. + toolReq, _ := http.NewRequest(http.MethodPost, embed.Origin+"/api/run-tool", nil) + toolReq.Header.Set("Origin", embed.Origin) + toolReq.AddCookie(sessionCookie) + toolResp, err := noRedirect.Do(toolReq) + if err != nil { + t.Fatal(err) + } + toolBody, _ := io.ReadAll(toolResp.Body) + toolResp.Body.Close() + if toolResp.StatusCode != http.StatusOK || !strings.Contains(string(toolBody), "tool roundtrip ok") { + t.Fatalf("proxied tool roundtrip failed: status=%d body=%q", toolResp.StatusCode, string(toolBody)) + } + if !upstreamSawTools || !upstreamSawMaxTokens || upstreamSawMaxCompletion { + t.Fatalf("unexpected upstream request flags: tools=%v max_tokens=%v max_completion_tokens=%v", + upstreamSawTools, upstreamSawMaxTokens, upstreamSawMaxCompletion) + } + + // Uninstall and verify clean teardown + origin retirement. + unOp, err := mgr.Queue(ctx, OperationRequest{ + Actor: "admin", + Kind: "uninstall", + InstallID: op.InstallID, + Key: "uninstall-e2e-1", + Purge: true, + }) + if err != nil { + t.Fatal(err) + } + if got := waitOp(unOp.ID); got.Status != "succeeded" { + t.Fatalf("uninstall failed: %+v", got) + } + if _, err := mgr.IssueEmbed(issueReq, op.InstallID, adminToken, adminExp); err != webproxy.ErrUnavailable { + t.Fatalf("expected unavailable after uninstall, got %v", err) + } +} diff --git a/internal/pluginhub/lifecycle.go b/internal/pluginhub/lifecycle.go new file mode 100644 index 00000000..8663e44f --- /dev/null +++ b/internal/pluginhub/lifecycle.go @@ -0,0 +1,344 @@ +package pluginhub + +import ( + "context" + "fmt" + "os" + "path/filepath" + "time" + + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/pluginhub/runner" + + "go.uber.org/zap" +) + +func (m *Manager) execute(ctx context.Context, install database.PluginRuntimeInstall, op database.PluginOperation) (database.PluginObservation, error) { + result := observation(install) + switch op.Kind { + case "install", "start", "restart": + version := install.Version + if op.Kind == "install" { + version = op.VersionID + } + spec, driver, err := m.spec(ctx, install.ID, version) + if err != nil { + return result, err + } + if err := m.assertApproved(ctx, spec); err != nil { + return result, err + } + result.Version = version + if op.Kind == "restart" || install.Observed == "cleanup_pending" { + if err := m.stopTraffic(ctx, install.ID); err != nil { + return result, err + } + if err := driver.Stop(ctx, spec); err != nil { + result.Observed = "cleanup_pending" + return result, err + } + } + if op.Kind == "start" && install.Observed == "healthy" { + state, err := driver.Inspect(ctx, spec) + if err == nil && state.Running { + return markRunning(result, state, spec), nil + } + } + if err := driver.Prepare(ctx, spec); err != nil { + result.Observed = "failed" + return result, err + } + if op.Kind == "install" && !m.consumeSkipAutoBind(install.ID) && spec.Declaration.LLM != nil { + if bound, bindErr := m.gateway.EnsureDefaultBinding(ctx, install.ID, spec.Declaration.LLM); bindErr != nil { + spec.Log("Default LLM channel auto-bind skipped: " + bindErr.Error()) + } else if bound { + spec.Log("Auto-bound CSAI default LLM channel") + } + } + state, err := m.startPlugin(ctx, driver, spec) + if err != nil { + result.Observed, result.Desired = "failed", "stopped" + if err := stopAfterFailure(driver, spec); err != nil { + result.Observed = "cleanup_pending" + } + return result, err + } + return markRunning(result, state, spec), nil + case "stop": + result.Desired = "stopped" + if err := m.stopVersions(ctx, install.ID, false); err != nil { + result.Observed = "cleanup_pending" + return result, err + } + result.Observed = "stopped" + return result, nil + case "upgrade": + return m.upgrade(ctx, install, op) + case "uninstall": + result.Desired = "stopped" + if err := m.stopVersions(ctx, install.ID, true); err != nil { + result.Observed = "cleanup_pending" + return result, err + } + if op.PurgeData { + if err := os.RemoveAll(filepath.Join(m.root, install.ID)); err != nil { + result.Observed = "cleanup_pending" + return result, err + } + } + if err := m.web.Retire(ctx, install.ID); err != nil { + result.Observed = "cleanup_pending" + return result, err + } + result.Observed, result.Version = "removed", "" + return result, nil + default: + return result, ErrInvalidRequest + } +} + +func (m *Manager) upgrade(ctx context.Context, install database.PluginRuntimeInstall, op database.PluginOperation) (database.PluginObservation, error) { + result := observation(install) + old, oldDriver, err := m.spec(ctx, install.ID, install.Version) + if err != nil { + return result, err + } + next, nextDriver, err := m.spec(ctx, install.ID, op.VersionID) + if err != nil { + return result, err + } + if err := m.assertApproved(ctx, next); err != nil { + return result, err + } + if old.VersionID == next.VersionID { + state, err := oldDriver.Inspect(ctx, old) + if err == nil && state.Running { + result = markRunning(result, state, old) + } + return result, err + } + // Stage the new artifact before stopping the current process. The old active + // pointer stays committed until the replacement passes readiness. + if err := nextDriver.Prepare(ctx, next); err != nil { + state, inspectErr := oldDriver.Inspect(ctx, old) + if inspectErr == nil && state.Running { + result = markRunning(result, state, old) + } + return result, err + } + if err := m.stopTraffic(ctx, install.ID); err != nil { + return result, err + } + if err := oldDriver.Stop(ctx, old); err != nil { + result.Observed = "cleanup_pending" + return result, err + } + if err := snapshotData(ctx, next); err != nil { + return m.restorePrevious(result, old, oldDriver, err) + } + if install.Desired != "running" { + result.Version, result.Driver, result.Observed = next.VersionID, next.Plan.Artifact.Driver, "stopped" + return result, nil + } + state, err := m.startPlugin(ctx, nextDriver, next) + if err == nil { + return markRunning(result, state, next), nil + } + if cleanupErr := stopAfterFailure(nextDriver, next); cleanupErr != nil { + result.Observed = "cleanup_pending" + return result, cleanupErr + } + if restoreErr := restoreData(next); restoreErr != nil { + result.Observed = "cleanup_pending" + return result, restoreErr + } + return m.restorePrevious(result, old, oldDriver, err) +} + +func (m *Manager) restorePrevious(result database.PluginObservation, old runner.Spec, driver runner.Driver, failure error) (database.PluginObservation, error) { + result.Observed = "stopped" + if result.Desired != "running" { + return result, failure + } + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + if err := m.assertApproved(ctx, old); err != nil { + return result, failure + } + state, err := m.startPlugin(ctx, driver, old) + if err != nil { + result.Observed = "cleanup_pending" + return result, failure + } + old.Log("Previous version restored") + return markRunning(result, state, old), failure +} + +func stopAfterFailure(driver runner.Driver, spec runner.Spec) error { + ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) + defer cancel() + return driver.Stop(ctx, spec) +} + +func (m *Manager) stopVersions(ctx context.Context, id string, remove bool) error { + if err := m.stopTraffic(ctx, id); err != nil { + return err + } + versions, err := m.db.PluginVersions(ctx, id) + if err != nil { + return err + } + for _, version := range versions { + spec, driver, err := m.spec(ctx, id, version.ID) + if err != nil { + return err + } + if remove { + err = driver.Remove(ctx, spec) + } else { + err = driver.Stop(ctx, spec) + } + if err != nil { + return err + } + } + return nil +} + +func (m *Manager) reconcile(ctx context.Context, start bool) { + interrupted, err := m.db.InterruptedPluginOperations(ctx) + if err != nil { + m.logger.Warn("Could not read interrupted plugin operations", zap.Error(err)) + return + } + byInstall := map[string]database.PluginOperation{} + for _, op := range interrupted { + byInstall[op.InstallID] = op + } + installs, err := m.db.RecoverablePluginInstalls(ctx) + if err != nil { + m.logger.Warn("Could not read plugin recovery state", zap.Error(err)) + return + } + seen := map[string]bool{} + for _, install := range installs { + seen[install.ID] = true + m.reconcileInstance(ctx, install, byInstall[install.ID], start) + } + for _, op := range interrupted { + if seen[op.InstallID] { + continue + } + if install, err := m.db.RuntimePluginInstall(ctx, op.InstallID); err == nil { + m.reconcileInstance(ctx, install, op, start) + } + } +} + +func (m *Manager) reconcileInstance(ctx context.Context, install database.PluginRuntimeInstall, interrupted database.PluginOperation, start bool) { + result := observation(install) + if err := m.stopVersions(ctx, install.ID, false); err != nil { + result.Observed, result.ErrorCode = "cleanup_pending", "plugin_cleanup_pending" + result.Endpoint, result.Port = "", 0 + _ = m.db.SetPluginObservation(ctx, m.owner, install.ID, result) + return + } + rollback := interrupted + if rollback.ID == "" && install.Observed == "cleanup_pending" { + prior, err := m.db.LastPluginOperation(ctx, install.ID) + if err == nil && prior.Status == "failed" && prior.VersionID != install.Version { + rollback = prior + } + } + if rollback.Kind == "upgrade" { + next, _, err := m.spec(ctx, install.ID, rollback.VersionID) + if err != nil || restoreData(next) != nil { + result.Observed, result.ErrorCode = "cleanup_pending", "plugin_cleanup_pending" + result.Endpoint, result.Port = "", 0 + _ = m.db.SetPluginObservation(ctx, m.owner, install.ID, result) + return + } + } + if interrupted.ID != "" { + _ = m.db.InterruptPluginOperation(ctx, m.owner, interrupted.ID) + } + result.Observed, result.Endpoint, result.Port = "stopped", "", 0 + if result.Version == "" { + result.Desired = "stopped" + if interrupted.Kind == "install" { + // The approved version remains available for an explicit retry. + result.Version = interrupted.VersionID + } + } + if start && result.Desired == "running" && result.Version != "" { + spec, driver, err := m.spec(ctx, install.ID, result.Version) + if err == nil { + err = m.assertApproved(ctx, spec) + } + if err == nil { + err = driver.Prepare(ctx, spec) + } + if err == nil { + var state runner.State + state, err = m.startPlugin(ctx, driver, spec) + if err == nil { + result = markRunning(result, state, spec) + } else { + result.Observed, result.ErrorCode = "failed", "plugin_recovery_failed" + if cleanup := stopAfterFailure(driver, spec); cleanup != nil { + result.Observed = "cleanup_pending" + } + } + } else { + result.ErrorCode = "plugin_recovery_unavailable" + } + } + if err := m.db.SetPluginObservation(ctx, m.owner, install.ID, result); err != nil && ctx.Err() == nil { + m.logger.Warn("Could not persist plugin reconciliation", zap.Error(err)) + } +} + +func (m *Manager) observe(ctx context.Context) { + installs, err := m.db.RecoverablePluginInstalls(ctx) + if err != nil { + return + } + for _, i := range installs { + if i.Observed == "cleanup_pending" { + interrupted, err := m.db.InterruptedPluginOperations(ctx) + if err != nil { + continue + } + var active database.PluginOperation + for _, op := range interrupted { + if op.InstallID == i.ID { + active = op + break + } + } + m.reconcileInstance(ctx, i, active, false) + continue + } + if i.Observed != "healthy" { + continue + } + spec, driver, err := m.spec(ctx, i.ID, i.Version) + if err != nil { + continue + } + state, err := driver.Inspect(ctx, spec) + if err != nil || state.CheckHealth(ctx, spec.Declaration.Web) != nil { + result := observation(i) + result.Observed, result.ErrorCode = "degraded", "plugin_runtime_unhealthy" + result.Endpoint, result.Port = "", 0 + _ = m.db.SetPluginObservation(ctx, m.owner, i.ID, result) + } + } +} + +func validSnapshotVersion(spec runner.Spec) error { + if spec.Root == "" || spec.VersionID == "" { + return fmt.Errorf("plugin snapshot lacks owned instance identity") + } + return nil +} diff --git a/internal/pluginhub/llmgateway/gateway.go b/internal/pluginhub/llmgateway/gateway.go new file mode 100644 index 00000000..d4cf7c5f --- /dev/null +++ b/internal/pluginhub/llmgateway/gateway.go @@ -0,0 +1,628 @@ +// Package llmgateway exposes scoped model protocol transport for approved plugin +// instances. Client-defined function calls are data, and are never run here. +package llmgateway + +import ( + "context" + "crypto/rand" + "database/sql" + "encoding/base64" + "errors" + "net" + "net/http" + "net/url" + "runtime" + "strconv" + "strings" + "sync" + "time" + + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/pluginhub/manifest" + + "github.com/google/uuid" +) + +var ErrBinding = errors.New("invalid or unavailable plugin model channel") +var ErrUnavailable = errors.New("plugin model gateway unavailable") +var errQuota = errors.New("plugin model request quota exhausted") + +type ConfigSnapshot func() (*config.Config, error) + +type Service struct { + cfg config.PluginLLMGatewayConfig + egress config.PluginEgress + db *database.DB + mu sync.Mutex + snapshot ConfigSnapshot + server *http.Server + port int + bridgeIP string + client *http.Client + active map[string]map[string]context.CancelFunc + windows map[string]requestWindow +} + +type requestWindow struct { + minute int64 + requests int +} + +type LimitPatch struct { + Concurrency int `json:"concurrency"` + RPM int `json:"rpm"` + TokenBudget int64 `json:"token_budget"` +} + +type BindingPatch struct { + Protocol string `json:"protocol,omitempty"` + Mode string `json:"mode"` + ChannelID string `json:"channel_id,omitempty"` +} + +type Patch struct { + BindingPatch + Bindings []BindingPatch `json:"bindings,omitempty"` + Limits LimitPatch `json:"limits,omitempty"` +} + +type Credential struct { + Binding manifest.Binding + Values map[string]string +} + +func New(db *database.DB, cfg config.PluginLLMGatewayConfig, egress config.PluginEgress) *Service { + s := &Service{cfg: cfg.Effective(), egress: egress, db: db, active: map[string]map[string]context.CancelFunc{}, windows: map[string]requestWindow{}} + s.client = &http.Client{Transport: &http.Transport{Proxy: s.outboundProxy, MaxIdleConnsPerHost: 8, IdleConnTimeout: 60 * time.Second, + ResponseHeaderTimeout: 45 * time.Second, TLSHandshakeTimeout: 10 * time.Second, DialContext: (&net.Dialer{Timeout: 10 * time.Second}).DialContext}, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + return s +} + +type ChannelOption struct { + ID string `json:"id"` + Name string `json:"name"` + Provider string `json:"provider"` + Protocol string `json:"protocol"` + Model string `json:"model"` + IsDefault bool `json:"is_default"` +} + +func (s *Service) AvailableChannels() (string, []ChannelOption) { + cfg, err := s.configuration() + if err != nil { + return "", []ChannelOption{} + } + defaultID := strings.TrimSpace(cfg.AI.DefaultChannel) + options := make([]ChannelOption, 0, len(cfg.AI.Channels)+1) + if len(cfg.AI.Channels) > 0 { + ids := make([]string, 0, len(cfg.AI.Channels)) + for id := range cfg.AI.Channels { + ids = append(ids, id) + } + for i := 0; i < len(ids); i++ { + for j := i + 1; j < len(ids); j++ { + if ids[j] < ids[i] { + ids[i], ids[j] = ids[j], ids[i] + } + } + } + for _, id := range ids { + ch := cfg.AI.Channels[id] + if strings.TrimSpace(ch.BaseURL) == "" || strings.TrimSpace(ch.Model) == "" { + continue + } + name := strings.TrimSpace(ch.Name) + if name == "" { + name = id + } + provider := strings.TrimSpace(ch.Provider) + if provider == "" { + provider = "openai" + } + options = append(options, ChannelOption{ + ID: id, + Name: name, + Provider: provider, + Protocol: providerProtocol(provider), + Model: ch.Model, + IsDefault: id == defaultID, + }) + } + } + if len(options) == 0 && strings.TrimSpace(cfg.OpenAI.BaseURL) != "" && strings.TrimSpace(cfg.OpenAI.Model) != "" { + provider := strings.TrimSpace(cfg.OpenAI.Provider) + if provider == "" { + provider = "openai" + } + options = append(options, ChannelOption{ + ID: "default", + Name: "Default", + Provider: provider, + Protocol: providerProtocol(provider), + Model: cfg.OpenAI.Model, + IsDefault: true, + }) + defaultID = "default" + } + return defaultID, options +} + +// EnsureDefaultBinding automatically attaches CSAI's default LLM channel to a +// newly installed LLM-capable plugin when the default channel's protocol matches +// one of the manifest's declared bindings. Missing or incompatible default +// channels are ignored so installation still succeeds cleanly. +func (s *Service) EnsureDefaultBinding(ctx context.Context, id string, declared *manifest.LLM) (bool, error) { + if declared == nil || len(declared.Bindings) == 0 { + return false, nil + } + existing, err := s.db.PluginLLMBindings(ctx, id) + if err != nil { + return false, err + } + if len(existing) > 0 { + return false, nil + } + cfg, err := s.configuration() + if err != nil { + return false, nil + } + selected, _, err := s.selection(cfg, database.PluginLLMBinding{Mode: "follow_default"}) + if err != nil { + return false, nil + } + protocol := providerProtocol(selected.Provider) + matched := false + for _, b := range declared.Bindings { + if b.Protocol == protocol { + matched = true + break + } + } + if !matched { + return false, nil + } + binding := database.PluginLLMBinding{ + Protocol: protocol, + Mode: "follow_default", + Concurrency: s.cfg.Concurrency, + RPM: s.cfg.RPM, + TokenBudget: s.cfg.TokenBudget, + } + if err := s.db.SetPluginLLMBindings(ctx, id, []database.PluginLLMBinding{binding}); err != nil { + return false, err + } + return true, nil +} + +func (s *Service) SetSnapshot(snapshot ConfigSnapshot) { + s.mu.Lock() + defer s.mu.Unlock() + s.snapshot = snapshot +} + +func (s *Service) configuration() (*config.Config, error) { + s.mu.Lock() + fn := s.snapshot + s.mu.Unlock() + if fn == nil { + return nil, ErrUnavailable + } + cfg, err := fn() + if err != nil || cfg == nil { + return nil, ErrUnavailable + } + return cfg, nil +} + +func (s *Service) Start() error { + s.mu.Lock() + defer s.mu.Unlock() + if s.server != nil { + return nil + } + ln, err := net.Listen("tcp", net.JoinHostPort(s.cfg.ListenHost, strconv.Itoa(s.cfg.ListenPort))) + if err != nil { + return err + } + server := &http.Server{Handler: s, ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 32 << 10} + s.port = ln.Addr().(*net.TCPAddr).Port + s.server = server + go func() { _ = server.Serve(ln) }() + // Rootful Linux Docker routes host-gateway to docker0. Bind this private + // interface separately while retaining the loopback listener for native apps. + if runtime.GOOS == "linux" && net.ParseIP(s.cfg.ListenHost).IsLoopback() && + (s.cfg.ContainerHost == "" || s.cfg.ContainerHost == "host.docker.internal") { + if ip := dockerBridgeIP(); ip != "" { + if bridge, err := net.Listen("tcp4", net.JoinHostPort(ip, strconv.Itoa(s.port))); err == nil { + s.bridgeIP = ip + go func() { _ = server.Serve(bridge) }() + } + } + } + return nil +} + +func dockerBridgeIP() string { + link, err := net.InterfaceByName("docker0") + if err != nil { + return "" + } + addrs, err := link.Addrs() + if err != nil { + return "" + } + for _, addr := range addrs { + if ipNet, ok := addr.(*net.IPNet); ok && ipNet.IP.To4() != nil && ipNet.IP.IsPrivate() { + return ipNet.IP.String() + } + } + return "" +} + +func (s *Service) Close() { + s.mu.Lock() + defer s.mu.Unlock() + for id := range s.active { + s.cancelActiveLocked(id) + } + if s.server != nil { + _ = s.server.Close() + s.server = nil + s.port = 0 + s.bridgeIP = "" + } +} + +func (s *Service) selection(cfg *config.Config, b database.PluginLLMBinding) (config.OpenAIConfig, string, error) { + id := b.ChannelID + switch b.Mode { + case "follow_default": + id = strings.TrimSpace(cfg.AI.DefaultChannel) + case "channel": + if strings.TrimSpace(id) == "" { + return config.OpenAIConfig{}, "", ErrBinding + } + default: + return config.OpenAIConfig{}, "", ErrBinding + } + channel, resolved, ok := cfg.AI.ResolveChannel(id) + if !ok || strings.TrimSpace(channel.BaseURL) == "" || strings.TrimSpace(channel.Model) == "" || + (b.Protocol != "" && providerProtocol(channel.Provider) != b.Protocol) { + return config.OpenAIConfig{}, "", ErrBinding + } + return channel, resolved, nil +} + +func providerProtocol(provider string) string { + if strings.EqualFold(provider, "claude") || strings.EqualFold(provider, "anthropic") { + return manifest.Anthropic + } + return manifest.OpenAI +} + +func (s *Service) Patch(ctx context.Context, id string, declared *manifest.LLM, patch Patch) ([]database.PluginLLMBinding, error) { + if declared == nil || len(declared.Bindings) == 0 { + return nil, ErrBinding + } + limit := patch.Limits + if limit.Concurrency == 0 { + limit.Concurrency = s.cfg.Concurrency + } + if limit.RPM == 0 { + limit.RPM = s.cfg.RPM + } + if limit.TokenBudget == 0 { + limit.TokenBudget = s.cfg.TokenBudget + } + if limit.Concurrency < 1 || limit.Concurrency > s.cfg.Concurrency || limit.RPM < 1 || limit.RPM > s.cfg.RPM || limit.TokenBudget < 1 || limit.TokenBudget > s.cfg.TokenBudget { + return nil, ErrBinding + } + items := patch.Bindings + if len(items) == 0 { + items = []BindingPatch{patch.BindingPatch} + } else if patch.BindingPatch != (BindingPatch{}) { + return nil, ErrBinding + } + if len(items) > len(declared.Bindings) || declared.Selection == "single_active" && len(items) != 1 { + return nil, ErrBinding + } + result := make([]database.PluginLLMBinding, 0, len(items)) + seen := map[string]bool{} + for _, item := range items { + b := database.PluginLLMBinding{Protocol: item.Protocol, Mode: item.Mode, ChannelID: item.ChannelID, Concurrency: limit.Concurrency, RPM: limit.RPM, TokenBudget: limit.TokenBudget} + switch item.Mode { + case "disabled": + if len(items) != 1 || item.ChannelID != "" { + return nil, ErrBinding + } + b.Protocol = "" + case "channel", "follow_default": + if item.Mode == "follow_default" && item.ChannelID != "" { + return nil, ErrBinding + } + cfg, err := s.configuration() + if err != nil { + return nil, err + } + selected, resolved, err := s.selection(cfg, b) + if err != nil { + return nil, err + } + b.Protocol = providerProtocol(selected.Provider) + if item.Mode == "channel" { + b.ChannelID = resolved + } + allowed := false + for _, binding := range declared.Bindings { + if binding.Protocol == b.Protocol { + allowed = true + break + } + } + if !allowed || seen[b.Protocol] { + return nil, ErrBinding + } + default: + return nil, ErrBinding + } + seen[b.Protocol] = true + result = append(result, b) + } + s.mu.Lock() + defer s.mu.Unlock() + if err := s.db.SetPluginLLMBindings(ctx, id, result); err != nil { + return nil, err + } + s.cancelActiveLocked(id) + return result, nil +} + +func (s *Service) cancelActiveLocked(id string) { + for _, cancel := range s.active[id] { + cancel() + } + delete(s.active, id) +} + +func (s *Service) Revoke(ctx context.Context, id string) error { + s.mu.Lock() + defer s.mu.Unlock() + s.cancelActiveLocked(id) + return s.db.RevokePluginGatewayKeys(ctx, id) +} + +func (s *Service) addressesLocked(container bool) (string, string, error) { + port := s.port + if port == 0 { + return "", "", ErrUnavailable + } + host := s.cfg.ListenHost + addHost := "" + if container { + host = s.cfg.ContainerHost + if host == "" { + if runtime.GOOS == "linux" { + if net.ParseIP(s.cfg.ListenHost).IsLoopback() { + if s.bridgeIP == "" { + return "", "", ErrUnavailable + } + host = "host.docker.internal" + } else { + host = s.cfg.ListenHost + } + } else { + host = "host.docker.internal" + } + } + if host == "host.docker.internal" && runtime.GOOS == "linux" { + if net.ParseIP(s.cfg.ListenHost).IsLoopback() && s.bridgeIP == "" { + return "", "", ErrUnavailable + } + addHost = "host.docker.internal:host-gateway" + } + } + return "http://" + net.JoinHostPort(host, strconv.Itoa(port)), addHost, nil +} + +func (s *Service) Issue(ctx context.Context, id string, generation int64, declared *manifest.LLM, container bool) ([]Credential, string, string, error) { + if declared == nil { + return nil, "", "", nil + } + rows, err := s.db.PluginLLMBindings(ctx, id) + if err != nil { + return nil, "", "", err + } + var result []Credential + root, hostMapping := "", "" + s.mu.Lock() + defer s.mu.Unlock() + for _, row := range rows { + if row.Mode == "disabled" { + continue + } + var binding *manifest.Binding + for _, item := range declared.Bindings { + if item.Protocol == row.Protocol { + binding = &item + break + } + } + if binding == nil { + return nil, "", "", ErrBinding + } + if s.snapshot == nil { + return nil, "", "", ErrUnavailable + } + cfg, err := s.snapshot() + if err != nil { + return nil, "", "", ErrUnavailable + } + channel, _, err := s.selection(cfg, row) + if err != nil { + return nil, "", "", err + } + if root == "" { + root, hostMapping, err = s.addressesLocked(container) + if err != nil { + return nil, "", "", err + } + } + var b [32]byte + if _, err := rand.Read(b[:]); err != nil { + return nil, "", "", err + } + token := "csai_p_" + base64.RawURLEncoding.EncodeToString(b[:]) + if err := s.db.SavePluginGatewayKey(ctx, id, generation, row.Protocol, manifest.Digest([]byte(token))); err != nil { + return nil, "", "", err + } + provider := binding.ProviderValue + if provider == "" { + provider = channel.Provider + if provider == "" { + provider = "openai" + } + } + result = append(result, Credential{Binding: *binding, Values: map[string]string{ + "gateway_v1_url": root + "/v1", "gateway_root_url": root, "gateway_token": token, + "model_alias": "csai-managed", "provider": provider, "protocol": row.Protocol, + }}) + } + return result, root, hostMapping, nil +} + +func (s *Service) admit(ctx context.Context, k database.PluginGatewayKey, digest string) (context.Context, func(), error) { + s.mu.Lock() + defer s.mu.Unlock() + current, err := s.db.PluginGatewayKey(ctx, digest) + if err != nil || current.InstallID != k.InstallID || current.Generation != k.Generation { + return nil, nil, ErrBinding + } + now := time.Now().Unix() / 60 + window := s.windows[k.InstallID] + if window.minute != now { + window = requestWindow{minute: now} + } + if window.requests >= k.Binding.RPM || len(s.active[k.InstallID]) >= k.Binding.Concurrency { + return nil, nil, errQuota + } + window.requests++ + s.windows[k.InstallID] = window + request, cancel := context.WithCancel(ctx) + if s.active[k.InstallID] == nil { + s.active[k.InstallID] = map[string]context.CancelFunc{} + } + id := uuid.NewString() + s.active[k.InstallID][id] = cancel + return request, func() { + s.mu.Lock() + defer s.mu.Unlock() + cancel() + delete(s.active[k.InstallID], id) + if len(s.active[k.InstallID]) == 0 { + delete(s.active, k.InstallID) + } + }, nil +} + +func (s *Service) outboundProxy(r *http.Request) (*url.URL, error) { + mode, address := s.egress.ProxyMode, s.egress.ProxyURL + if mode == "direct" { + return nil, nil + } + if mode == "" { + cfg, err := s.configuration() + if err != nil { + return nil, ErrUnavailable + } + if cfg.Proxy.Mode == "fixed" { + mode, address = "fixed", cfg.Proxy.URL + } + } + if mode == "fixed" { + if !strings.Contains(address, "://") { + address = "http://" + address + } + return url.Parse(address) + } + return http.ProxyFromEnvironment(r) +} + +func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + if r.URL.Path == "/_csai_gateway/ready" && r.Method == http.MethodGet { + w.WriteHeader(http.StatusNoContent) + return + } + wanted := "" + switch { + case r.URL.Path == "/v1/models" && r.Method == http.MethodGet: + case r.URL.Path == "/v1/chat/completions" && r.Method == http.MethodPost: + wanted = manifest.OpenAI + case (r.URL.Path == "/v1/messages" || r.URL.Path == "/v1/messages/count_tokens") && r.Method == http.MethodPost: + wanted = manifest.Anthropic + default: + http.NotFound(w, r) + return + } + token, ok := gatewayToken(r) + if !ok { + gatewayError(w, http.StatusUnauthorized, "invalid_plugin_token") + return + } + digest := manifest.Digest([]byte(token)) + key, err := s.db.PluginGatewayKey(r.Context(), digest) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + gatewayError(w, http.StatusUnauthorized, "invalid_plugin_token") + } else { + gatewayError(w, http.StatusServiceUnavailable, "gateway_unavailable") + } + return + } + if wanted != "" && key.Binding.Protocol != wanted { + gatewayError(w, http.StatusForbidden, "protocol_mismatch") + return + } + cfg, err := s.configuration() + if err != nil { + gatewayError(w, http.StatusServiceUnavailable, "gateway_unavailable") + return + } + channel, channelID, err := s.selection(cfg, key.Binding) + if err != nil { + gatewayError(w, http.StatusForbidden, "channel_unavailable") + return + } + ctx, release, err := s.admit(r.Context(), key, digest) + if err != nil { + if errors.Is(err, errQuota) { + gatewayError(w, http.StatusTooManyRequests, "plugin_rate_limit") + } else { + gatewayError(w, http.StatusUnauthorized, "invalid_plugin_token") + } + return + } + defer release() + if r.URL.Path == "/v1/models" { + models(w, key.Binding.Protocol) + return + } + s.forward(ctx, w, r, key, channel, channelID) +} + +func gatewayToken(r *http.Request) (string, bool) { + token := strings.TrimSpace(r.Header.Get("x-api-key")) + if values := r.Header.Values("Authorization"); len(values) > 0 { + if len(values) != 1 { + return "", false + } + scheme, value, ok := strings.Cut(values[0], " ") + if !ok || !strings.EqualFold(scheme, "Bearer") || token != "" { + return "", false + } + token = strings.TrimSpace(value) + } + return token, len(token) == 50 && strings.HasPrefix(token, "csai_p_") && len(r.Header.Values("x-api-key")) <= 1 +} diff --git a/internal/pluginhub/llmgateway/gateway_test.go b/internal/pluginhub/llmgateway/gateway_test.go new file mode 100644 index 00000000..4d936561 --- /dev/null +++ b/internal/pluginhub/llmgateway/gateway_test.go @@ -0,0 +1,267 @@ +package llmgateway + +import ( + "bufio" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/pluginhub/manifest" + + "github.com/google/uuid" + "go.uber.org/zap" +) + +func gatewayFixture(t *testing.T, endpoint string) (*Service, *database.DB, *config.Config, *sync.RWMutex, string) { + t.Helper() + db, err := database.NewDB(filepath.Join(t.TempDir(), "gateway.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + id := uuid.NewString() + _, err = db.Exec(`INSERT INTO plugin_installs(id,plugin_id,source_identity,title,driver,observed_state,generation,created_at,updated_at) + VALUES(?,?,?,?,?,'starting',1,?,?)`, id, id, id, id, "release", time.Now().UTC(), time.Now().UTC()) + if err != nil { + t.Fatal(err) + } + cfg := &config.Config{AI: config.AIConfig{DefaultChannel: "oa", Channels: map[string]config.AIChannelConfig{ + "oa": {Provider: "openai", Model: "fixture-openai", BaseURL: endpoint + "/edge/v1", APIKey: "server-openai", Headers: map[string]string{"X-Provider-Marker": "server"}}, + "an": {Provider: "claude", Model: "fixture-claude", BaseURL: endpoint + "/edge", APIKey: "server-anthropic", Headers: map[string]string{"X-Provider-Marker": "server"}}, + }}} + var lock sync.RWMutex + gateway := New(db, config.PluginLLMGatewayConfig{}, config.PluginEgress{ProxyMode: "direct"}) + gateway.SetSnapshot(func() (*config.Config, error) { + lock.RLock() + defer lock.RUnlock() + copy := *cfg + copy.AI.Channels = map[string]config.AIChannelConfig{} + for k, v := range cfg.AI.Channels { + copy.AI.Channels[k] = v + } + return ©, nil + }) + if err := gateway.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(gateway.Close) + return gateway, db, cfg, &lock, id +} + +func gatewayCall(t *testing.T, root, path, token, body string, anthropic bool) *http.Response { + t.Helper() + method := http.MethodPost + if body == "" { + method = http.MethodGet + } + r, err := http.NewRequest(method, root+path, strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + r.Header.Set("X-Provider-Marker", "injected") + r.Header.Set("X-Forwarded-Host", "unapproved.example") + if anthropic { + r.Header.Set("X-API-Key", token) + r.Header.Set("anthropic-version", "2023-06-01") + } else { + r.Header.Set("Authorization", "Bearer "+token) + } + resp, err := (&http.Client{Timeout: 4 * time.Second}).Do(r) + if err != nil { + t.Fatal(err) + } + return resp +} + +func gatewayBody(t *testing.T, resp *http.Response, want int) string { + t.Helper() + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil || resp.StatusCode != want { + t.Fatalf("HTTP %d want %d: %s %v", resp.StatusCode, want, body, err) + } + return string(body) +} + +func TestPluginGatewayNativeProtocolsAndUsage(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("X-Provider-Marker") != "server" || r.Header.Get("X-Forwarded-Host") != "" { + http.Error(w, "unsafe header", 500) + return + } + raw, _ := io.ReadAll(r.Body) + var fields map[string]json.RawMessage + _ = json.Unmarshal(raw, &fields) + stream := string(fields["stream"]) == "true" + switch r.URL.Path { + case "/edge/v1/chat/completions": + if r.Header.Get("Authorization") != "Bearer server-openai" || string(fields["model"]) != `"fixture-openai"` || + !strings.Contains(string(raw), `"role":"tool"`) || !strings.Contains(string(raw), `"tool_call_id":"fxo"`) || + !strings.Contains(string(raw), `"reasoning_effort":"medium"`) || !strings.Contains(string(raw), `"image_url"`) || + string(fields["parallel_tool_calls"]) != "false" || fields["tools"] == nil || fields["tool_choice"] == nil { + http.Error(w, "OpenAI fixture mismatch", 500) + return + } + if stream { + if !strings.Contains(string(fields["stream_options"]), `"include_usage":true`) { + http.Error(w, "usage not requested", 500) + return + } + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"id\":\"fxo\"}]}}]}\n\ndata: {\"usage\":{\"prompt_tokens\":8,\"completion_tokens\":2}}\n\ndata: [DONE]\n\n") + return + } + _, _ = io.WriteString(w, `{"choices":[{"message":{"tool_calls":[{"id":"fxo","function":{"name":"read_demo_note"}}]}}],"usage":{"prompt_tokens":8,"completion_tokens":2}}`) + case "/edge/v1/messages": + if r.Header.Get("X-API-Key") != "server-anthropic" || r.Header.Get("anthropic-version") != "2023-06-01" || + string(fields["model"]) != `"fixture-claude"` || !strings.Contains(string(raw), `"tool_use_id":"fxa"`) || + !strings.Contains(string(raw), `"signature":"signed-fixture"`) || !strings.Contains(string(raw), `"type":"document"`) || + !strings.Contains(string(raw), `"type":"image"`) || !strings.Contains(string(raw), `"effort":"high"`) || + fields["tools"] == nil || fields["tool_choice"] == nil { + http.Error(w, "Anthropic fixture mismatch", 500) + return + } + if stream { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "event: message_start\ndata: {\"message\":{\"usage\":{\"input_tokens\":13}}}\n\nevent: content_block_start\ndata: {\"content_block\":{\"type\":\"tool_use\",\"id\":\"fxa\"}}\n\nevent: content_block_delta\ndata: {\"delta\":{\"type\":\"signature_delta\",\"signature\":\"signed-fixture\"}}\n\nevent: message_delta\ndata: {\"usage\":{\"output_tokens\":3}}\n\n") + return + } + _, _ = io.WriteString(w, `{"content":[{"type":"tool_use","id":"fxa","name":"read_demo_note"}],"usage":{"input_tokens":13,"output_tokens":3}}`) + case "/edge/v1/messages/count_tokens": + if r.Header.Get("X-API-Key") != "server-anthropic" || fields["max_tokens"] != nil { + http.Error(w, "count fixture mismatch", 500) + return + } + _, _ = io.WriteString(w, `{"input_tokens":12}`) + default: + http.NotFound(w, r) + } + })) + defer upstream.Close() + g, db, cfg, lock, id := gatewayFixture(t, upstream.URL) + declared := &manifest.LLM{Selection: "multi", Bindings: []manifest.Binding{{Protocol: manifest.OpenAI}, {Protocol: manifest.Anthropic}}} + ctx := context.Background() + if _, err := g.Patch(ctx, id, declared, Patch{Bindings: []BindingPatch{{Mode: "follow_default"}, {Mode: "channel", ChannelID: "an"}}}); err != nil { + t.Fatal(err) + } + creds, root, _, err := g.Issue(ctx, id, 1, declared, false) + if err != nil || len(creds) != 2 { + t.Fatalf("issue: %d %v", len(creds), err) + } + tokens := map[string]string{} + for _, credential := range creds { + tokens[credential.Binding.Protocol] = credential.Values["gateway_token"] + } + oa, an := tokens[manifest.OpenAI], tokens[manifest.Anthropic] + if oa == an { + t.Fatal("protocols shared a token") + } + if _, err := db.PluginGatewayKey(ctx, oa); err == nil { + t.Fatal("raw credential was stored") + } + gatewayBody(t, gatewayCall(t, root, "/v1/models", oa, "", false), 200) + const openai = `{"model":"csai-managed","reasoning_effort":"medium","parallel_tool_calls":false,"tool_choice":"auto","tools":[{"type":"function","function":{"name":"read_demo_note"}}],"messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,AA=="}}]},{"role":"assistant","tool_calls":[{"id":"fxo"}]},{"role":"tool","tool_call_id":"fxo","content":"fixed text"}]}` + const anthropic = `{"model":"csai-managed","max_tokens":32,"thinking":{"type":"adaptive"},"output_config":{"effort":"high"},"tool_choice":{"type":"auto"},"tools":[{"name":"read_demo_note","input_schema":{"type":"object"}}],"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"fixture","signature":"signed-fixture"},{"type":"tool_use","id":"fxa"}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"fxa","content":"fixed text"},{"type":"image","source":{"type":"base64","data":"AA=="}},{"type":"document","source":{"type":"base64","data":"AA=="}}]}]}` + for _, stream := range []bool{false, true} { + add := func(value string) string { + if !stream { + return value + } + return strings.TrimSuffix(value, "}") + `,"stream":true}` + } + if text := gatewayBody(t, gatewayCall(t, root, "/v1/chat/completions", oa, add(openai), false), 200); !strings.Contains(text, "fxo") { + t.Fatal("OpenAI tool output dropped") + } + if text := gatewayBody(t, gatewayCall(t, root, "/v1/messages", an, add(anthropic), true), 200); !strings.Contains(text, "fxa") { + t.Fatal("Anthropic tool output dropped") + } + } + gatewayBody(t, gatewayCall(t, root, "/v1/messages/count_tokens", an, `{"model":"csai-managed"}`, true), 200) + gatewayBody(t, gatewayCall(t, root, "/v1/messages", oa, anthropic, false), 403) + gatewayBody(t, gatewayCall(t, root, "/v1/chat/completions", oa, + `{"model":"csai-managed","base_url":"https://unapproved.example","headers":{"Authorization":"override"}}`, false), 400) + gatewayBody(t, gatewayCall(t, root, "/v1/messages", an, `{"model":"csai-managed","tools":[{"type":"web_search_20250305","name":"web_search"}]}`, true), 400) + waitUntil(t, func() bool { + var total, rows int + err := db.QueryRow("SELECT COALESCE(SUM(charged_tokens),0), COUNT(*) FROM plugin_model_usage WHERE status='ok'").Scan(&total, &rows) + return err == nil && rows == 5 && total == 64 + }) + lock.Lock() + delete(cfg.AI.Channels, "oa") + delete(cfg.AI.Channels, "an") + cfg.OpenAI = config.OpenAIConfig{BaseURL: upstream.URL, Model: "legacy-should-not-be-used"} + lock.Unlock() + gatewayBody(t, gatewayCall(t, root, "/v1/models", oa, "", false), 403) + gatewayBody(t, gatewayCall(t, root, "/v1/models", an, "", true), 403) +} + +func TestPluginGatewaySingleActiveAndRevocation(t *testing.T) { + disconnected := make(chan struct{}) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "data: {\"choices\":[]}\n\n") + w.(http.Flusher).Flush() + <-r.Context().Done() + close(disconnected) + })) + defer upstream.Close() + g, _, _, _, id := gatewayFixture(t, upstream.URL) + ctx := context.Background() + declared := &manifest.LLM{Selection: "single_active", Bindings: []manifest.Binding{{Protocol: manifest.OpenAI}, {Protocol: manifest.Anthropic}}} + if _, err := g.Patch(ctx, id, declared, Patch{BindingPatch: BindingPatch{Mode: "channel", ChannelID: "oa"}, Limits: LimitPatch{Concurrency: 1, RPM: 2, TokenBudget: 10000}}); err != nil { + t.Fatal(err) + } + creds, root, _, err := g.Issue(ctx, id, 1, declared, false) + if err != nil || len(creds) != 1 { + t.Fatalf("single-active credentials %d %v", len(creds), err) + } + old := creds[0].Values["gateway_token"] + stream := gatewayCall(t, root, "/v1/chat/completions", old, `{"model":"csai-managed","stream":true,"max_tokens":12}`, false) + defer stream.Body.Close() + line, err := bufio.NewReader(stream.Body).ReadString('\n') + if err != nil || !strings.HasPrefix(line, "data:") { + t.Fatalf("failed to flush: %q %v", line, err) + } + r := gatewayCall(t, root, "/v1/chat/completions", old, `{"model":"csai-managed","max_tokens":12}`, false) + gatewayBody(t, r, 429) + if _, err := g.Patch(ctx, id, declared, Patch{BindingPatch: BindingPatch{Mode: "channel", ChannelID: "an"}, Limits: LimitPatch{TokenBudget: 30}}); err != nil { + t.Fatal(err) + } + select { + case <-disconnected: + case <-time.After(2 * time.Second): + t.Fatal("upstream not canceled on binding change") + } + gatewayBody(t, gatewayCall(t, root, "/v1/models", old, "", false), 401) + creds, _, _, err = g.Issue(ctx, id, 1, declared, false) + if err != nil || len(creds) != 1 || creds[0].Binding.Protocol != manifest.Anthropic { + t.Fatal("single-active route did not switch") + } + token := creds[0].Values["gateway_token"] + gatewayBody(t, gatewayCall(t, root, "/v1/messages", token, `{"model":"csai-managed","max_tokens":32}`, true), 429) + if err := g.Revoke(ctx, id); err != nil { + t.Fatal(err) + } + gatewayBody(t, gatewayCall(t, root, "/v1/models", token, "", true), 401) +} + +func waitUntil(t *testing.T, condition func() bool) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for !condition() { + if time.Now().After(deadline) { + t.Fatal("fixture state did not converge") + } + time.Sleep(20 * time.Millisecond) + } +} diff --git a/internal/pluginhub/llmgateway/transport.go b/internal/pluginhub/llmgateway/transport.go new file mode 100644 index 00000000..8ffc141c --- /dev/null +++ b/internal/pluginhub/llmgateway/transport.go @@ -0,0 +1,356 @@ +package llmgateway + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" + + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/pluginhub/manifest" + + "github.com/google/uuid" +) + +const maxJSON = 24 << 20 +const maxUsageTokens int64 = 1000000000 + +func gatewayError(w http.ResponseWriter, status int, code string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]any{"type": "error", "error": map[string]string{"type": code, "message": code}}) +} + +func models(w http.ResponseWriter, protocol string) { + w.Header().Set("Content-Type", "application/json") + data := []map[string]any{{"id": "csai-managed", "object": "model", "owned_by": "csai"}} + if protocol == manifest.Anthropic { + data = []map[string]any{{"id": "csai-managed", "type": "model", "display_name": "CSAI managed model", "created_at": "1970-01-01T00:00:00Z"}} + _ = json.NewEncoder(w).Encode(map[string]any{"data": data, "has_more": false, "first_id": "csai-managed", "last_id": "csai-managed"}) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"object": "list", "data": data}) +} + +func (s *Service) forward(ctx context.Context, w http.ResponseWriter, r *http.Request, key database.PluginGatewayKey, c config.OpenAIConfig, channel string) { + payload, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxJSON)) + if err != nil { + gatewayError(w, http.StatusRequestEntityTooLarge, "request_limit") + return + } + count := strings.HasSuffix(r.URL.Path, "/count_tokens") + request, stream, reserve, err := prepareRequest(payload, c, key.Binding.Protocol, count) + if err != nil { + gatewayError(w, http.StatusBadRequest, "invalid_model_request") + return + } + endpoint, err := upstreamEndpoint(c.BaseURL, r.URL.Path) + if err != nil { + gatewayError(w, http.StatusBadGateway, "invalid_channel_endpoint") + return + } + id := uuid.NewString() + err = s.db.ReservePluginModelUsage(ctx, id, key, channel, reserve) + if errors.Is(err, database.ErrPluginModelBudget) { + gatewayError(w, http.StatusTooManyRequests, "token_budget_exhausted") + return + } + if err != nil { + gatewayError(w, http.StatusServiceUnavailable, "usage_store_unavailable") + return + } + usage := tokenUsage{} + status := "canceled" + defer func() { + finalCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _ = s.db.FinishPluginModelUsage(finalCtx, id, status, usage.Input, usage.Output, status == "ok" && usage.Metered) + }() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(request)) + if err != nil { + gatewayError(w, http.StatusBadGateway, "invalid_channel_endpoint") + return + } + setUpstreamHeaders(req, c, key.Binding.Protocol, stream, r.Header.Get("anthropic-version")) + protected := []string{c.APIKey, req.Header.Get("X-API-Key"), strings.TrimPrefix(req.Header.Get("Authorization"), "Bearer ")} + resp, err := s.client.Do(req) + if err != nil { + gatewayError(w, http.StatusBadGateway, "upstream_unavailable") + return + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + status = "upstream_error" + code := resp.StatusCode + if code < 400 || code > 599 { + code = http.StatusBadGateway + } + gatewayError(w, code, "upstream_error") + return + } + if strings.HasPrefix(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") { + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("X-Accel-Buffering", "no") + w.WriteHeader(resp.StatusCode) + if err := copySSE(w, resp.Body, &usage, protected); err == nil { + status = "ok" + } + return + } + response, err := io.ReadAll(io.LimitReader(resp.Body, maxJSON+1)) + if err != nil || len(response) > maxJSON || !json.Valid(response) || containsCredential(response, protected) { + gatewayError(w, http.StatusBadGateway, "invalid_upstream_response") + return + } + usage.observe(response) + status = "ok" + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(resp.StatusCode) + _, _ = w.Write(response) +} + +func prepareRequest(payload []byte, c config.OpenAIConfig, protocol string, count bool) ([]byte, bool, int64, error) { + var fields map[string]json.RawMessage + if err := json.Unmarshal(payload, &fields); err != nil || fields == nil { + return nil, false, 0, fmt.Errorf("invalid JSON object") + } + for name := range fields { + switch strings.ReplaceAll(strings.ReplaceAll(strings.ToLower(name), "_", ""), "-", "") { + case "baseurl", "apibase", "apikey", "authorization", "headers", "proxy", "proxyurl", "upstreamurl", "endpoint", "provider": + return nil, false, 0, fmt.Errorf("upstream settings are owned by the bound channel") + } + } + var model string + if err := json.Unmarshal(fields["model"], &model); err != nil || (model != "csai-managed" && model != c.Model) { + return nil, false, 0, fmt.Errorf("model not bound") + } + if !clientTools(fields, protocol) { + return nil, false, 0, fmt.Errorf("unsupported managed tool") + } + fields["model"], _ = json.Marshal(c.Model) + stream := false + if raw := fields["stream"]; raw != nil && json.Unmarshal(raw, &stream) != nil { + return nil, false, 0, fmt.Errorf("invalid stream") + } + maxOutput := int64(4096) + if c.MaxCompletionTokens > 0 { + maxOutput = int64(c.MaxCompletionTokens) + } + if maxOutput > maxUsageTokens { + maxOutput = maxUsageTokens + } + if !count { + limit := "max_tokens" + if protocol == manifest.OpenAI && fields["max_completion_tokens"] != nil { + limit = "max_completion_tokens" + } + if raw := fields[limit]; raw != nil { + var requested int64 + if json.Unmarshal(raw, &requested) != nil || requested < 1 { + return nil, false, 0, fmt.Errorf("invalid max tokens") + } + if requested < maxOutput { + maxOutput = requested + } + } + fields[limit], _ = json.Marshal(maxOutput) + for _, name := range []string{"max_tokens", "max_completion_tokens"} { + if name != limit { + delete(fields, name) + } + } + } else { + maxOutput = 0 + } + if protocol == manifest.OpenAI && stream { + options := map[string]json.RawMessage{} + if raw := fields["stream_options"]; raw != nil && json.Unmarshal(raw, &options) != nil { + return nil, false, 0, fmt.Errorf("invalid stream options") + } + if options == nil { + options = map[string]json.RawMessage{} + } + options["include_usage"] = json.RawMessage("true") + fields["stream_options"], _ = json.Marshal(options) + } + body, err := json.Marshal(fields) + // Charge a conservative byte-based input estimate and the bounded output + // before forwarding. Provider-reported usage replaces the estimate. + return body, stream, int64(len(payload)) + maxOutput, err +} + +func clientTools(fields map[string]json.RawMessage, protocol string) bool { + for _, name := range []string{"mcp_servers", "server_tools", "container", "computer_use", "web_search_options"} { + if _, present := fields[name]; present { + return false + } + } + if fields["tools"] == nil { + return true + } + var tools []struct { + Type string `json:"type"` + Name string `json:"name"` + Function json.RawMessage `json:"function"` + InputSchema json.RawMessage `json:"input_schema"` + } + if json.Unmarshal(fields["tools"], &tools) != nil { + return false + } + for _, tool := range tools { + if protocol == manifest.OpenAI { + if tool.Type != "function" || len(tool.Function) == 0 { + return false + } + } else if (tool.Type != "" && tool.Type != "custom") || tool.Name == "" || len(tool.InputSchema) == 0 { + return false + } + } + return true +} + +func upstreamEndpoint(base, route string) (string, error) { + u, err := url.Parse(strings.TrimSpace(base)) + if err != nil || u.Hostname() == "" || u.User != nil || u.Fragment != "" || u.RawQuery != "" || + (u.Scheme != "http" && u.Scheme != "https") { + return "", fmt.Errorf("invalid configured upstream") + } + prefix := strings.TrimRight(u.Path, "/") + for _, suffix := range []string{"/chat/completions", "/messages/count_tokens", "/messages"} { + prefix = strings.TrimSuffix(prefix, suffix) + } + if strings.HasSuffix(prefix, "/v1") { + route = strings.TrimPrefix(route, "/v1") + } + u.Path, u.RawPath = prefix+route, "" + return u.String(), nil +} + +func setUpstreamHeaders(req *http.Request, c config.OpenAIConfig, protocol string, stream bool, version string) { + req.Header.Set("Content-Type", "application/json") + if stream { + req.Header.Set("Accept", "text/event-stream") + } else { + req.Header.Set("Accept", "application/json") + } + if protocol == manifest.Anthropic { + req.Header.Set("x-api-key", c.APIKey) + } else if c.APIKey != "" { + req.Header.Set("Authorization", "Bearer "+c.APIKey) + } + for name, value := range c.Headers { + switch strings.ToLower(name) { + case "host", "content-length", "transfer-encoding", "connection", "upgrade", "proxy-authorization", "proxy-connection", + "forwarded", "cookie", "content-type", "accept": + continue + } + if strings.ContainsAny(name+value, "\r\n\x00") || strings.HasPrefix(strings.ToLower(name), "x-forwarded-") { + continue + } + req.Header.Set(name, value) + } + if protocol == manifest.Anthropic { + if req.Header.Get("anthropic-version") == "" { + if version != "2023-06-01" { + version = "2023-06-01" + } + req.Header.Set("anthropic-version", version) + } + } +} + +type tokenUsage struct { + Input, Output int64 + Metered bool +} + +func (u *tokenUsage) observe(payload []byte) { + type counts struct { + Input *int64 `json:"input_tokens"` + Output *int64 `json:"output_tokens"` + Prompt *int64 `json:"prompt_tokens"` + Completion *int64 `json:"completion_tokens"` + } + var event struct { + Input *int64 `json:"input_tokens"` + Output *int64 `json:"output_tokens"` + Usage *counts `json:"usage"` + Message struct { + Usage *counts `json:"usage"` + } `json:"message"` + } + if json.Unmarshal(payload, &event) != nil { + return + } + for _, c := range []*counts{{Input: event.Input, Output: event.Output}, event.Usage, event.Message.Usage} { + if c == nil { + continue + } + for _, i := range []*int64{c.Input, c.Prompt} { + if i != nil && *i >= 0 && *i <= maxUsageTokens { + u.Input = max(u.Input, *i) + u.Metered = true + } + } + for _, o := range []*int64{c.Output, c.Completion} { + if o != nil && *o >= 0 && *o <= maxUsageTokens { + u.Output = max(u.Output, *o) + u.Metered = true + } + } + } +} + +func containsCredential(payload []byte, credentials []string) bool { + for _, secret := range credentials { + // Short compatibility placeholders are not realistic secrets and would + // match ordinary response text. + if len(secret) >= 8 && bytes.Contains(payload, []byte(secret)) { + return true + } + } + return false +} + +func copySSE(w http.ResponseWriter, stream io.Reader, usage *tokenUsage, protected []string) error { + scanner := bufio.NewScanner(stream) + scanner.Buffer(make([]byte, 32<<10), maxJSON) + event := make([]byte, 0, 512) + for scanner.Scan() { + line := scanner.Bytes() + if containsCredential(line, protected) { + return fmt.Errorf("upstream stream contains a protected credential") + } + if len(line) == 0 { + usage.observe(event) + event = event[:0] + } else if data, ok := bytes.CutPrefix(line, []byte("data:")); ok { + if len(event)+len(data) > maxJSON { + return fmt.Errorf("SSE event exceeds limit") + } + if len(event) > 0 { + event = append(event, '\n') + } + event = append(event, bytes.TrimSpace(data)...) + } + if _, err := w.Write(line); err != nil { + return err + } + if _, err := w.Write([]byte{'\n'}); err != nil { + return err + } + if err := http.NewResponseController(w).Flush(); err != nil && !errors.Is(err, http.ErrNotSupported) { + return err + } + } + usage.observe(event) + return scanner.Err() +} diff --git a/internal/pluginhub/manager.go b/internal/pluginhub/manager.go new file mode 100644 index 00000000..b51e8faa --- /dev/null +++ b/internal/pluginhub/manager.go @@ -0,0 +1,486 @@ +package pluginhub + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "maps" + "os" + "path/filepath" + "regexp" + "slices" + "sync" + "sync/atomic" + "time" + + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/pluginhub/llmgateway" + "cyberstrike-ai/internal/pluginhub/manifest" + "cyberstrike-ai/internal/pluginhub/runner" + "cyberstrike-ai/internal/pluginhub/source" + "cyberstrike-ai/internal/pluginhub/webproxy" + "cyberstrike-ai/internal/security" + + "github.com/google/uuid" + "go.uber.org/zap" +) + +const leaseTTL = 30 * time.Second + +type Manager struct { + web *webproxy.Service + gateway *llmgateway.Service + webAuth *security.AuthManager + db *database.DB + root string + logger *zap.Logger + approvalPolicy string + approvals map[string][]string + proxyMode string + locker ArtifactLocker + inspector *source.GitHubInspector + drivers map[string]runner.Driver + owner string + wake chan struct{} + ready atomic.Bool + mu sync.Mutex + skipAutoBind map[string]bool + cancel context.CancelFunc + done chan struct{} +} + +func New(db *database.DB, cfg config.PluginsConfig, configDir string, logger *zap.Logger) (*Manager, error) { + if err := cfg.Validate(); err != nil { + return nil, err + } + network, err := source.NewEgress(cfg.Egress) + if err != nil { + return nil, err + } + root := cfg.Directory + if root == "" { + root = filepath.Join("data", "plugins") + } + if !filepath.IsAbs(root) { + root = filepath.Join(configDir, root) + } + root, err = filepath.Abs(root) + if err != nil { + return nil, err + } + m := &Manager{ + db: db, root: root, logger: logger, approvalPolicy: cfg.EffectiveApprovalPolicy(), approvals: maps.Clone(cfg.ApprovedArtifacts), proxyMode: cfg.Proxy.Effective().Mode, locker: network, + inspector: source.NewGitHubInspectorWithTransport(network.Transport(), os.Getenv(cfg.Egress.GitHubTokenEnv)), + drivers: map[string]runner.Driver{ + "release": runner.NewNative("release", network, cfg.Egress.ProxyMode, cfg.Egress.ProxyURL), + "git": runner.NewNative("git", network, cfg.Egress.ProxyMode, cfg.Egress.ProxyURL), + "container": runner.NewDocker(), + }, + owner: uuid.NewString(), wake: make(chan struct{}, 1), skipAutoBind: map[string]bool{}, + } + for key, digests := range m.approvals { + m.approvals[key] = slices.Clone(digests) + } + m.web = webproxy.New(cfg.Proxy, db, m.webTarget, m.webAuthorization) + m.gateway = llmgateway.New(db, cfg.LLMGateway, cfg.Egress) + return m, nil +} + +func (m *Manager) Inspector() *source.GitHubInspector { return m.inspector } + +func (m *Manager) Probes(ctx context.Context, isolation string) map[string]runner.Probe { + probes := map[string]runner.Probe{} + for name, driver := range m.drivers { + probes[name] = driver.Probe(ctx, isolation) + } + if docker, ok := m.drivers["container"].(interface { + ProbeCompose(context.Context, string) runner.Probe + }); ok { + probes["compose"] = docker.ProbeCompose(ctx, isolation) + } + return probes +} + +func (m *Manager) Ready() bool { return m.ready.Load() } + +func (m *Manager) Start(ctx context.Context) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.done != nil { + return nil + } + now := time.Now().UTC() + acquired, err := m.db.RenewPluginLease(ctx, m.owner, now, now.Add(leaseTTL)) + if err != nil || !acquired { + return ErrRuntimeUnavailable + } + worker, cancel := context.WithCancel(ctx) + m.cancel, m.done = cancel, make(chan struct{}) + go m.run(worker, m.done, cancel) + return nil +} + +func (m *Manager) Close(ctx context.Context) error { + m.mu.Lock() + cancel, done := m.cancel, m.done + m.mu.Unlock() + if done == nil { + return nil + } + cancel() + select { + case <-done: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (m *Manager) run(ctx context.Context, done chan struct{}, cancel context.CancelFunc) { + defer close(done) + leaseCtx, stopHeartbeat := context.WithCancel(context.Background()) + heartbeatDone := make(chan struct{}) + go func() { + defer close(heartbeatDone) + tick := time.NewTicker(5 * time.Second) + defer tick.Stop() + for { + select { + case <-leaseCtx.Done(): + return + case now := <-tick.C: + probe, finish := context.WithTimeout(leaseCtx, 3*time.Second) + ok, err := m.db.RenewPluginLease(probe, m.owner, now.UTC(), now.UTC().Add(leaseTTL)) + finish() + if !ok || err != nil { + if leaseCtx.Err() == nil { + m.logger.Warn("Plugin runtime lost its database lease") + cancel() + } + return + } + } + } + }() + defer func() { + m.ready.Store(false) + cleanup, finish := context.WithTimeout(context.Background(), 25*time.Second) + now := time.Now().UTC() + owned, err := m.db.RenewPluginLease(cleanup, m.owner, now, now.Add(leaseTTL)) + if err == nil && owned { + m.reconcile(cleanup, false) + } + finish() + stopHeartbeat() + <-heartbeatDone + release, finish := context.WithTimeout(context.Background(), 3*time.Second) + defer finish() + _ = m.db.ReleasePluginLease(release, m.owner) + }() + m.reconcile(ctx, true) + if ctx.Err() != nil { + return + } + m.ready.Store(true) + poll := time.NewTicker(350 * time.Millisecond) + defer poll.Stop() + observe := time.NewTicker(10 * time.Second) + defer observe.Stop() + for { + select { + case <-ctx.Done(): + return + case <-observe.C: + m.observe(ctx) + case <-m.wake: + case <-poll.C: + } + for ctx.Err() == nil { + op, err := m.db.ClaimPluginOperation(ctx, m.owner, time.Now().UTC()) + if err != nil { + break + } + m.runOperation(ctx, op) + } + } +} + +type OperationRequest struct { + Actor, Kind, InstallID, PlanID, PlanDigest, Key string + Purge bool + AutoBindLLM *bool +} + +func (m *Manager) consumeSkipAutoBind(installID string) bool { + m.mu.Lock() + defer m.mu.Unlock() + if !m.skipAutoBind[installID] { + return false + } + delete(m.skipAutoBind, installID) + return true +} + +var idempotencyKey = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +func (m *Manager) Queue(ctx context.Context, req OperationRequest) (database.PluginOperation, error) { + if !slices.Contains([]string{"install", "start", "stop", "restart", "upgrade", "uninstall"}, req.Kind) || + !idempotencyKey.MatchString(req.Key) || req.Actor == "" || (req.Purge && req.Kind != "uninstall") { + return database.PluginOperation{}, ErrInvalidRequest + } + var record database.PluginPlanRecord + if req.Kind == "install" || req.Kind == "upgrade" { + if req.PlanID == "" || req.PlanDigest == "" { + return database.PluginOperation{}, ErrInvalidRequest + } + var err error + record, err = m.db.GetPluginPlanForConfirmation(ctx, req.PlanID, req.Actor) + if err != nil { + return database.PluginOperation{}, err + } + if req.Kind == "install" { + req.InstallID = record.InstallID + } + if req.InstallID != record.InstallID || req.PlanDigest != record.PlanDigest { + return database.PluginOperation{}, ErrStalePlan + } + } else if req.PlanID != "" || req.PlanDigest != "" { + return database.PluginOperation{}, ErrInvalidRequest + } + instance, err := uuid.Parse(req.InstallID) + if err != nil || instance.String() != req.InstallID || instance == uuid.Nil { + return database.PluginOperation{}, ErrInvalidRequest + } + raw, _ := json.Marshal(req) + hash := manifest.Digest(raw) + previous, err := m.db.PluginOperationByKey(ctx, req.InstallID, req.Key) + if err == nil { + if previous.Actor == req.Actor && previous.RequestHash == hash { + return previous, nil + } + return database.PluginOperation{}, database.ErrPluginOperationConflict + } + if !errors.Is(err, sql.ErrNoRows) { + return database.PluginOperation{}, err + } + if !m.Ready() { + return database.PluginOperation{}, ErrRuntimeUnavailable + } + request := database.PluginQueueRequest{ + Operation: database.PluginOperation{ID: uuid.NewString(), InstallID: req.InstallID, Actor: req.Actor, + Kind: req.Kind, Key: req.Key, PlanDigest: req.PlanDigest, RequestHash: hash, PurgeData: req.Purge}, + PlanID: req.PlanID, + } + now := time.Now().UTC() + if req.PlanID != "" { + if !record.ExpiresAt.After(now) { + return database.PluginOperation{}, database.ErrPluginPlanUnavailable + } + if err := m.validateConfirmation(record, &request, now); err != nil { + return database.PluginOperation{}, err + } + } + if req.Kind == "install" && req.AutoBindLLM != nil && !*req.AutoBindLLM { + m.mu.Lock() + m.skipAutoBind[req.InstallID] = true + m.mu.Unlock() + } + operation, err := m.db.QueuePluginOperation(ctx, request, now) + if err != nil && req.Kind == "install" && req.AutoBindLLM != nil && !*req.AutoBindLLM { + m.consumeSkipAutoBind(req.InstallID) + } + if err == nil { + select { + case m.wake <- struct{}{}: + default: + } + } + return operation, err +} + +func (m *Manager) validateConfirmation(record database.PluginPlanRecord, request *database.PluginQueueRequest, now time.Time) error { + plan, err := manifest.DecodeInstallPlan([]byte(record.PlanJSON)) + if err != nil || plan.ID != record.ID || plan.ActorID != record.ActorUserID || plan.InstallID != record.InstallID || + manifest.Digest(plan.Canonical) != record.PlanDigest || manifest.Digest([]byte(record.PolicyJSON)) != plan.PolicySHA256 || + plan.ManifestSHA256 != record.ManifestDigest { + return ErrStalePlan + } + doc, err := manifest.DecodeDeclaration([]byte(record.ManifestJSON)) + if err != nil || manifest.Digest(doc.Canonical) != plan.ManifestSHA256 { + return ErrStalePlan + } + var policy planPolicy + artifactDigest := ArtifactDigest(plan.Artifact) + if err := json.Unmarshal([]byte(record.PolicyJSON), &policy); err != nil || policy.ArtifactDigest != artifactDigest || policy.Isolation != plan.Isolation { + return ErrStalePlan + } + if !m.CanConfirm(plan.ManifestSHA256, artifactDigest) { + return ErrUnapprovedArtifact + } + canonical, err := source.NormalizeGitHubRepository(doc.Metadata.Repository) + if err != nil { + return ErrStalePlan + } + approval, err := json.Marshal(versionApproval{ + Policy: json.RawMessage(record.PolicyJSON), PlanID: record.ID, PlanDigest: record.PlanDigest, + ApprovedBy: record.ActorUserID, ApprovedAt: now, + }) + if err != nil { + return err + } + request.CatalogID = policy.CatalogID + request.Install = database.PluginRuntimeInstall{ID: plan.InstallID, PluginID: doc.Metadata.ID, Source: canonical, Title: doc.Metadata.Title} + request.Version = database.PluginVersion{ + ID: uuid.NewString(), InstallID: plan.InstallID, Version: doc.Metadata.Version, Driver: plan.Artifact.Driver, + Manifest: record.ManifestJSON, ManifestDigest: plan.ManifestSHA256, + Artifact: plan.Artifact.Driver + ":" + plan.Platform.OS + ":" + plan.Platform.Arch + ":" + plan.PolicySHA256, + ArtifactDigest: artifactDigest, Policy: string(approval), Plan: record.PlanJSON, + } + return nil +} + +func (m *Manager) spec(ctx context.Context, id, versionID string) (runner.Spec, runner.Driver, error) { + record, err := m.db.PluginVersion(ctx, id, versionID) + if err != nil { + return runner.Spec{}, nil, err + } + doc, err := manifest.DecodeDeclaration([]byte(record.Manifest)) + if err != nil || manifest.Digest(doc.Canonical) != record.ManifestDigest { + return runner.Spec{}, nil, ErrStalePlan + } + plan, err := manifest.DecodeInstallPlan([]byte(record.Plan)) + if err != nil || plan.InstallID != id || plan.ManifestSHA256 != record.ManifestDigest || + plan.Artifact.Driver != record.Driver || ArtifactDigest(plan.Artifact) != record.ArtifactDigest || + !versionPolicyMatches(record.Policy, plan) { + return runner.Spec{}, nil, ErrStalePlan + } + driver := m.drivers[record.Driver] + if driver == nil { + return runner.Spec{}, nil, ErrRuntimeUnavailable + } + for _, value := range []string{id, versionID} { + parsed, err := uuid.Parse(value) + if err != nil || parsed.String() != value { + return runner.Spec{}, nil, ErrStalePlan + } + } + return runner.Spec{InstallID: id, VersionID: versionID, Root: filepath.Join(m.root, id), Declaration: doc, + Plan: plan, Log: m.logSink(id)}, driver, nil +} + +func (m *Manager) logSink(id string) func(string) { + var lock sync.Mutex + var start time.Time + var count int + return func(line string) { + lock.Lock() + now := time.Now() + if now.Sub(start) >= time.Second { + start, count = now, 0 + } + count++ + allowed := count <= 30 + lock.Unlock() + if !allowed { + return + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + _ = m.db.AppendPluginLog(ctx, id, runner.SanitizeLog(line, nil)) + } +} + +type versionApproval struct { + Policy json.RawMessage `json:"policy"` + PlanID string `json:"plan_id"` + PlanDigest string `json:"plan_digest"` + ApprovedBy string `json:"approved_by"` + ApprovedAt time.Time `json:"approved_at"` +} + +func versionPolicyMatches(raw string, plan *manifest.InstallPlan) bool { + if manifest.Digest([]byte(raw)) == plan.PolicySHA256 { + // Earlier versions stored the policy itself. Their approval timestamp + // already lives in plugin_install_plans. + return true + } + var approved versionApproval + return json.Unmarshal([]byte(raw), &approved) == nil && + approved.PlanID == plan.ID && approved.ApprovedBy == plan.ActorID && + approved.PlanDigest == manifest.Digest(plan.Canonical) && !approved.ApprovedAt.IsZero() && + manifest.Digest(approved.Policy) == plan.PolicySHA256 +} + +func (m *Manager) assertApproved(ctx context.Context, spec runner.Spec) error { + if m.approvalPolicy == config.PluginApprovalHostConfigOnly { + if m.approved(spec.Plan.ManifestSHA256, ArtifactDigest(spec.Plan.Artifact)) { + return nil + } + return ErrUnapprovedArtifact + } + approved, err := m.db.PluginPlanApproved(ctx, spec.Plan.ID, spec.InstallID, spec.Plan.ActorID, manifest.Digest(spec.Plan.Canonical)) + if err != nil { + return err + } + if !approved { + return ErrUnapprovedArtifact + } + return nil +} + +func observation(i database.PluginRuntimeInstall) database.PluginObservation { + return database.PluginObservation{Desired: i.Desired, Observed: i.Observed, Version: i.Version, Driver: i.Driver, Endpoint: i.Endpoint, Port: i.Port, ErrorCode: i.ErrorCode} +} + +func markRunning(old database.PluginObservation, state runner.State, spec runner.Spec) database.PluginObservation { + old.Desired, old.Observed, old.Endpoint, old.Port = "running", "healthy", state.Endpoint, state.Port + old.Version, old.Driver, old.ErrorCode = spec.VersionID, spec.Plan.Artifact.Driver, "" + return old +} + +func (m *Manager) runOperation(parent context.Context, op database.PluginOperation) { + ctx, cancel := context.WithTimeout(parent, 8*time.Minute) + defer cancel() + current, err := m.db.RuntimePluginInstall(ctx, op.InstallID) + result := observation(current) + if err == nil { + log := m.logSink(op.InstallID) + log("Operation started: " + op.Kind) + result, err = m.execute(ctx, current, op) + if err != nil { + switch { + case errors.Is(err, ErrUnapprovedArtifact): + result.ErrorCode = "plugin_artifact_not_approved" + case result.Observed == "cleanup_pending": + result.ErrorCode = "plugin_cleanup_pending" + default: + result.ErrorCode = "plugin_" + op.Kind + "_failed" + } + log(fmt.Sprintf("Operation failed: %s", result.ErrorCode)) + } else { + log("Operation finished: " + op.Kind) + } + } + if result.Observed == "" { + result.Observed = "failed" + } + if result.Desired == "" { + result.Desired = "stopped" + } + if result.Observed != "healthy" { + result.Endpoint, result.Port = "", 0 + } + if err == nil { + result.ErrorCode = "" + } + commit, finish := context.WithTimeout(context.Background(), 4*time.Second) + defer finish() + if commitErr := m.db.FinishPluginOperation(commit, m.owner, op, result, err != nil); commitErr != nil { + m.logger.Warn("Plugin operation outcome awaits reconciliation", zap.String("operation", op.ID), zap.Error(commitErr)) + } else if err == nil && op.Kind == "upgrade" { + _ = os.RemoveAll(snapshotPath(runner.Spec{Root: filepath.Join(m.root, op.InstallID), VersionID: op.VersionID})) + } +} diff --git a/internal/pluginhub/manager_test.go b/internal/pluginhub/manager_test.go new file mode 100644 index 00000000..f8480017 --- /dev/null +++ b/internal/pluginhub/manager_test.go @@ -0,0 +1,378 @@ +package pluginhub + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" + "time" + + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/pluginhub/manifest" + "cyberstrike-ai/internal/pluginhub/runner" + "cyberstrike-ai/internal/pluginhub/source" + + "github.com/google/uuid" + "go.uber.org/zap" +) + +type testLocker struct{} + +func (testLocker) LockRelease(context.Context, manifest.Distribution, manifest.Platform) (manifest.Artifact, error) { + return manifest.Artifact{}, source.ErrArtifactUnavailable +} + +func (testLocker) LockImage(_ context.Context, s manifest.Service, os, arch string) (manifest.LockedService, error) { + repo, _, _, err := manifest.ParseImageReference(s.Image) + return manifest.LockedService{Name: s.Name, RequestedImage: s.Image, Repository: repo, + ManifestDigest: "sha256:" + manifest.Digest([]byte(s.Image+"/"+os+"/"+arch))}, err +} + +type fixtureDriver struct { + mu sync.Mutex + running map[string]*httptest.Server + block chan struct{} +} + +func (f *fixtureDriver) Probe(context.Context, string) runner.Probe { + return runner.Probe{Available: true} +} + +func (f *fixtureDriver) Prepare(ctx context.Context, spec runner.Spec) error { + if f.block != nil { + select { + case <-f.block: + case <-ctx.Done(): + return ctx.Err() + } + } + return os.MkdirAll(spec.VersionDir(), 0700) +} + +func (f *fixtureDriver) Start(_ context.Context, spec runner.Spec) (runner.State, error) { + f.mu.Lock() + defer f.mu.Unlock() + path := filepath.Join(spec.Root, "data") + if err := os.MkdirAll(path, 0700); err != nil { + return runner.State{}, err + } + if spec.Declaration.Metadata.Version == "2.0.0" { + _ = os.WriteFile(filepath.Join(path, "observations"), []byte("corrupted replacement"), 0600) + return runner.State{}, errors.New("replacement fixture fails health") + } + if prior := f.running[spec.VersionID]; prior != nil { + return fixtureState(prior), nil + } + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) + f.running[spec.VersionID] = srv + return fixtureState(srv), nil +} + +func fixtureState(srv *httptest.Server) runner.State { + port, _ := strconv.Atoi(strings.TrimPrefix(srv.URL, "http://127.0.0.1:")) + return runner.State{Running: true, Endpoint: srv.URL, Port: port} +} + +func (f *fixtureDriver) Inspect(_ context.Context, spec runner.Spec) (runner.State, error) { + f.mu.Lock() + defer f.mu.Unlock() + if server := f.running[spec.VersionID]; server != nil { + return fixtureState(server), nil + } + return runner.State{}, nil +} + +func (f *fixtureDriver) Stop(_ context.Context, spec runner.Spec) error { + f.mu.Lock() + defer f.mu.Unlock() + if server := f.running[spec.VersionID]; server != nil { + server.Close() + delete(f.running, spec.VersionID) + } + return nil +} + +func (f *fixtureDriver) Remove(ctx context.Context, spec runner.Spec) error { + if err := f.Stop(ctx, spec); err != nil { + return err + } + return os.RemoveAll(spec.VersionDir()) +} + +const fixtureRepo = "https://github.com/example/static" + +func fixtureDeclaration(version, tag string) []byte { + return []byte(`apiVersion: plugins.csai.io/v1 +kind: WebPlugin +metadata: + id: test-static + title: Static test + repository: https://github.com/example/static + version: "` + version + `" +distribution: + - type: container + mode: docker + services: + - name: web + role: web + image: example.org/static:` + tag + ` + containerPort: 8080 + resources: {memoryMiB: 128, pids: 64} +web: {route: root, entryPath: "/", healthPath: "/"} +access: {mode: platform} +permissions: {persistentData: true, modelGateway: false, egress: []} +`) +} + +func TestPluginQueueIdempotencyRollbackAndRecovery(t *testing.T) { + root := t.TempDir() + db, err := database.NewDB(filepath.Join(root, "fixture.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + cfg := config.PluginsConfig{Directory: filepath.Join(root, "plugins")} + firstDoc := fixtureDeclaration("1.0.0", "first") + secondDoc := fixtureDeclaration("2.0.0", "second") + newManager := func(driver *fixtureDriver) *Manager { + manager, err := New(db, cfg, root, zap.NewNop()) + if err != nil { + t.Fatal(err) + } + manager.locker = testLocker{} + manager.drivers["container"] = driver + if err := manager.Start(ctx); err != nil { + t.Fatal(err) + } + waitPlugin(t, ctx, manager.Ready) + return manager + } + releaseBlock := make(chan struct{}) + driver := &fixtureDriver{running: map[string]*httptest.Server{}, block: releaseBlock} + manager := newManager(driver) + t.Cleanup(func() { _ = manager.Close(context.Background()) }) + + plan := func(declaration []byte, installID string) PlanResult { + id := uuid.NewString() + parsed, err := manifest.DecodeDeclaration(declaration) + if err != nil { + t.Fatal(err) + } + snapshot, err := json.Marshal(source.Inspection{Repository: fixtureRepo, Manifest: parsed.Canonical}) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + if err := db.SavePluginInspection(ctx, id, "actor", string(snapshot), now, now.Add(time.Minute)); err != nil { + t.Fatal(err) + } + result, err := manager.CreatePlan(ctx, PlanRequest{Actor: "actor", InspectionID: id, InstallID: installID}) + if err != nil || result.HostApproved || !manager.CanConfirm(result.Record.ManifestDigest, result.ArtifactDigest) { + t.Fatalf("expected a confirmable plan without a host allowlist: %+v %v", result, err) + } + return result + } + first := plan(firstDoc, "") + request := OperationRequest{Actor: "actor", Kind: "install", PlanID: first.Record.ID, PlanDigest: first.Record.PlanDigest, Key: "same-install"} + incorrect := request + incorrect.PlanDigest = strings.Repeat("0", 64) + if _, err := manager.Queue(ctx, incorrect); !errors.Is(err, ErrStalePlan) { + t.Fatalf("confirmation accepted a wrong digest: %v", err) + } + approved, err := db.PluginPlanApproved(ctx, first.Record.ID, first.Record.InstallID, "actor", first.Record.PlanDigest) + if err != nil || approved { + t.Fatalf("mismatched confirmation changed approval status: %t %v", approved, err) + } + var group sync.WaitGroup + results := make(chan database.PluginOperation, 8) + failures := make(chan error, 8) + for i := 0; i < 8; i++ { + group.Add(1) + go func() { + defer group.Done() + op, err := manager.Queue(ctx, request) + if err != nil { + failures <- err + return + } + results <- op + }() + } + group.Wait() + close(results) + close(failures) + for err := range failures { + t.Error(err) + } + var operation database.PluginOperation + for op := range results { + if operation.ID != "" && operation.ID != op.ID { + t.Fatal("one key accepted multiple operations") + } + operation = op + } + if operation.ID == "" { + t.Fatal("installation was not queued") + } + if _, err := manager.Queue(ctx, OperationRequest{Actor: "actor", Kind: "stop", InstallID: operation.InstallID, Key: "parallel-stop"}); !errors.Is(err, database.ErrPluginOperationConflict) { + t.Fatalf("overlapping operation not rejected: %v", err) + } + close(releaseBlock) + waitOperation(t, ctx, db, operation.ID, "succeeded") + install, err := db.RuntimePluginInstall(ctx, operation.InstallID) + if err != nil || install.Observed != "healthy" || install.Port < 1 { + t.Fatalf("install %+v %v", install, err) + } + persisted, err := db.GetPluginPlan(ctx, first.Record.ID, "actor", time.Now()) + if err != nil || persisted.ApprovedAt == nil { + t.Fatalf("confirmation did not persist the plan approval: %v", err) + } + version, err := db.PluginVersion(ctx, install.ID, install.Version) + if err != nil { + t.Fatal(err) + } + var approval versionApproval + if err := json.Unmarshal([]byte(version.Policy), &approval); err != nil || + approval.ApprovedBy != "actor" || approval.PlanDigest != first.Record.PlanDigest || + !approval.ApprovedAt.Equal(*persisted.ApprovedAt) { + t.Fatalf("version approval does not match the confirmed plan: %+v %v", approval, err) + } + marker := filepath.Join(cfg.Directory, install.ID, "data", "observations") + if err := os.WriteFile(marker, []byte("initial data"), 0600); err != nil { + t.Fatal(err) + } + + second := plan(secondDoc, install.ID) + upgrade, err := manager.Queue(ctx, OperationRequest{Actor: "actor", Kind: "upgrade", InstallID: install.ID, Key: "upgrade-once", + PlanID: second.Record.ID, PlanDigest: second.Record.PlanDigest}) + if err != nil { + t.Fatal(err) + } + waitOperation(t, ctx, db, upgrade.ID, "failed") + rolled, err := db.RuntimePluginInstall(ctx, install.ID) + restored, readErr := os.ReadFile(marker) + if err != nil || readErr != nil || rolled.Version != install.Version || rolled.Observed != "healthy" || string(restored) != "initial data" { + t.Fatalf("rollback did not restore original state: %+v %q %v %v", rolled, restored, err, readErr) + } + + if err := manager.Close(ctx); err != nil { + t.Fatal(err) + } + journal := filepath.Join(cfg.Directory, install.ID, ".rollback-"+upgrade.VersionID) + if err := os.MkdirAll(journal, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(journal, "observations"), []byte("initial data"), 0600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(marker, []byte("interrupted migration"), 0600); err != nil { + t.Fatal(err) + } + if _, err := db.ExecContext(ctx, "UPDATE plugin_operations SET status='running',lease_owner='retired-owner' WHERE id=?", upgrade.ID); err != nil { + t.Fatal(err) + } + manager = newManager(&fixtureDriver{running: map[string]*httptest.Server{}}) + restored, readErr = os.ReadFile(marker) + interrupted, lookupErr := db.GetPluginOperation(ctx, upgrade.ID) + if string(restored) != "initial data" || readErr != nil || lookupErr != nil || interrupted.ErrorCode != "plugin_operation_interrupted" { + t.Fatalf("startup did not reconcile interrupted upgrade: %+v %q %v %v", interrupted, restored, readErr, lookupErr) + } + waitPlugin(t, ctx, func() bool { + value, err := db.RuntimePluginInstall(ctx, install.ID) + return err == nil && value.Observed == "healthy" + }) + uninstall, err := manager.Queue(ctx, OperationRequest{Actor: "actor", Kind: "uninstall", InstallID: install.ID, Key: "uninstall", Purge: true}) + if err != nil { + t.Fatal(err) + } + waitOperation(t, ctx, db, uninstall.ID, "succeeded") + if _, err := os.Stat(filepath.Dir(marker)); !os.IsNotExist(err) { + t.Fatalf("data retained after approved purge: %v", err) + } + if err := manager.Close(ctx); err != nil { + t.Fatal(err) + } +} + +func waitOperation(t *testing.T, ctx context.Context, db *database.DB, id, status string) { + t.Helper() + waitPlugin(t, ctx, func() bool { op, err := db.GetPluginOperation(ctx, id); return err == nil && op.Status == status }) +} + +func waitPlugin(t *testing.T, ctx context.Context, check func() bool) { + t.Helper() + for !check() { + select { + case <-ctx.Done(): + t.Fatal("plugin state did not converge") + case <-time.After(20 * time.Millisecond): + } + } +} + +func TestPluginCatalogPlanUsesPlatformLock(t *testing.T) { + root := t.TempDir() + db, err := database.NewDB(filepath.Join(root, "catalog.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + m, err := New(db, config.PluginsConfig{}, root, zap.NewNop()) + if err != nil { + t.Fatal(err) + } + m.locker = testLocker{} + m.drivers["container"] = &fixtureDriver{} + result, err := m.CreatePlan(context.Background(), PlanRequest{Actor: "tester", CatalogID: "static-web", Isolation: "strict"}) + if err != nil { + t.Fatal(err) + } + plan, err := manifest.DecodeInstallPlan([]byte(result.Record.PlanJSON)) + if err != nil || plan.Platform.OS != "linux" || plan.Artifact.Driver != "container" || + len(plan.Artifact.Services) != 1 || result.HostApproved { + t.Fatalf("unexpected catalog execution plan: %+v %v", plan, err) + } +} + +func TestPluginHostConfigOnlyPreservesStaticApprovals(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + db, err := database.NewDB(filepath.Join(root, "host-approval.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + cfg := config.PluginsConfig{ApprovalPolicy: config.PluginApprovalHostConfigOnly} + m, err := New(db, cfg, root, zap.NewNop()) + if err != nil { + t.Fatal(err) + } + m.locker = testLocker{} + m.drivers["container"] = &fixtureDriver{} + result, err := m.CreatePlan(ctx, PlanRequest{Actor: "operator", CatalogID: "static-web", Isolation: "strict"}) + if err != nil { + t.Fatal(err) + } + var request database.PluginQueueRequest + if err := m.validateConfirmation(result.Record, &request, time.Now()); !errors.Is(err, ErrUnapprovedArtifact) { + t.Fatalf("host policy accepted a plan absent from its allowlist: %v", err) + } + cfg.ApprovedArtifacts = map[string][]string{result.Record.ManifestDigest: {result.ArtifactDigest}} + approved, err := New(db, cfg, root, zap.NewNop()) + if err != nil { + t.Fatal(err) + } + if err := approved.validateConfirmation(result.Record, &request, time.Now()); err != nil { + t.Fatalf("host policy rejected an approved exact artifact: %v", err) + } +} diff --git a/internal/pluginhub/manifest/declaration.go b/internal/pluginhub/manifest/declaration.go new file mode 100644 index 00000000..2aa53676 --- /dev/null +++ b/internal/pluginhub/manifest/declaration.go @@ -0,0 +1,648 @@ +package manifest + +import ( + "fmt" + "net/netip" + "net/url" + "regexp" + "slices" + "strings" +) + +const ( + OpenAI = "openai_chat" + Anthropic = "anthropic_messages" +) + +type Declaration struct { + Canonical []byte `json:"-"` + Metadata Metadata `json:"metadata"` + Distribution []Distribution `json:"distribution"` + Launch *Launch `json:"launch"` + Web Web `json:"web"` + Access Access `json:"access"` + LLM *LLM `json:"llm"` + Secrets map[string]Secret `json:"secrets"` + Permissions Permissions `json:"permissions"` + Extensions Extensions `json:"extensions"` +} + +type Metadata struct { + ID string `json:"id"` + Title string `json:"title"` + Summary string `json:"summary"` + Version string `json:"version"` + Repository string `json:"repository"` + License string `json:"license"` +} + +type Distribution struct { + Type string `json:"type"` + Assets []Asset `json:"assets"` + URL string `json:"url"` + Revision string `json:"revision"` + OutputRoot string `json:"outputRoot"` + Entrypoint string `json:"entrypoint"` + Build []BuildStep `json:"build"` + Mode string `json:"mode"` + Services []Service `json:"services"` +} + +type Asset struct { + OS string `json:"os"` + Arch string `json:"arch"` + Name string `json:"name"` + Format string `json:"format"` + SHA256 string `json:"sha256"` + StripComponents int `json:"stripComponents"` + URL string `json:"url"` + Entrypoint string `json:"entrypoint"` + Attestation string `json:"attestationURL"` +} + +type BuildStep struct { + Program string `json:"program"` + WorkDir string `json:"workDir"` + Args []string `json:"args"` +} + +type Environment struct { + Env map[string]string `json:"env"` + StaticEnv map[string]string `json:"staticEnv"` + SecretEnv map[string]SecretUse `json:"secretEnv"` +} + +type Launch struct { + Environment + Entrypoint string `json:"entrypoint"` + WorkDir string `json:"workDir"` + Args []string `json:"args"` +} + +type Secret struct { + Generator string `json:"generator"` + Bytes int `json:"bytes"` +} + +type SecretUse struct { + Kind string `json:"kind"` + SecretRef string `json:"secretRef"` + Service string `json:"service"` + Scheme string `json:"scheme"` + Username string `json:"username"` + Database string `json:"database"` + Options map[string]string `json:"options"` +} + +type Service struct { + Environment + Name string `json:"name"` + Role string `json:"role"` + Image string `json:"image"` + ContainerPort int `json:"containerPort"` + DependsOn map[string]string `json:"depends_on"` + Healthcheck *Healthcheck `json:"healthcheck"` + DataVolumes []Mount `json:"dataVolumes"` + ConfigMounts []Mount `json:"configMounts"` + Resources Resources `json:"resources"` +} + +type Resources struct { + MemoryMiB int `json:"memoryMiB"` + PIDs int `json:"pids"` +} + +type Mount struct { + Name string `json:"name"` + Source string `json:"source"` + MountPath string `json:"mountPath"` +} + +type Healthcheck struct { + Kind string `json:"kind"` + Path string `json:"path"` + Argv []string `json:"argv"` + IntervalSeconds int `json:"intervalSeconds"` + TimeoutSeconds int `json:"timeoutSeconds"` + Retries int `json:"retries"` + StartPeriodSeconds int `json:"startPeriodSeconds"` +} + +type Web struct { + Route string `json:"route"` + EntryPath string `json:"entryPath"` + HealthPath string `json:"healthPath"` + ReadyHeaderCheck bool `json:"readyHeaderCheck"` + AllowHealthRedirect bool `json:"allowHealthRedirect"` +} + +type Access struct { + ApplicationBearer []string `json:"applicationBearer"` + Bootstrap *Bootstrap `json:"bootstrap"` +} + +type Bootstrap struct { + UsernameEnv string `json:"usernameEnv"` + PasswordFileEnv string `json:"passwordFileEnv"` +} + +type Permissions struct { + PersistentData bool `json:"persistentData"` + Egress []string `json:"egress"` +} + +type Extensions struct { + Capabilities []Capability `json:"capabilities"` +} + +type Capability struct { + ID string `json:"id"` + Path string `json:"path"` +} + +type LLM struct { + Selection string `json:"selection"` + Bindings []Binding `json:"bindings"` +} + +type Binding struct { + Protocol string `json:"protocol"` + ProviderValue string `json:"providerValue"` + Env map[string]string `json:"env"` + ConfigTemplate *ConfigTemplate `json:"configTemplate"` +} + +type ConfigTemplate struct { + Format string `json:"format"` + Path string `json:"path"` + SourcePath string `json:"sourcePath"` + Values map[string]string `json:"values"` +} + +// DecodeDeclaration parses declarative metadata. Successful parsing never grants execution rights. +func DecodeDeclaration(data []byte) (*Declaration, error) { + var declaration Declaration + canonical, err := decode(data, declarationSchema, &declaration) + if err != nil { + return nil, err + } + declaration.Canonical = canonical + if err := declaration.validate(); err != nil { + return nil, err + } + return &declaration, nil +} + +func (m *Declaration) validate() error { + if err := ValidateHTTPS(m.Metadata.Repository); err != nil { + return fmt.Errorf("metadata.repository: %w", err) + } + if err := validateAppPaths(append([]string{m.Web.EntryPath, m.Web.HealthPath}, m.Access.ApplicationBearer...)...); err != nil { + return err + } + if m.Launch != nil { + if err := validateFiles(m.Launch.Entrypoint, m.Launch.WorkDir); err != nil { + return err + } + if err := m.validateEnvironment(m.Launch.Environment, nil, true); err != nil { + return fmt.Errorf("launch: %w", err) + } + if err := validateArgs(m.Launch.Args); err != nil { + return err + } + } + drivers := map[string]bool{} + for _, distribution := range m.Distribution { + if drivers[distribution.Type] { + return fmt.Errorf("duplicate %s distribution", distribution.Type) + } + drivers[distribution.Type] = true + if err := m.validateDistribution(distribution); err != nil { + return fmt.Errorf("%s distribution: %w", distribution.Type, err) + } + } + capabilities := map[string]bool{} + for _, capability := range m.Extensions.Capabilities { + if capabilities[capability.ID] { + return fmt.Errorf("duplicate capability ID") + } + capabilities[capability.ID] = true + if err := validateAppPaths(capability.Path); err != nil { + return err + } + } + return m.validateBindings() +} + +func (m *Declaration) validateDistribution(d Distribution) error { + switch d.Type { + case "release": + platforms := map[string]bool{} + for _, asset := range d.Assets { + platform := asset.OS + "/" + asset.Arch + if platforms[platform] { + return fmt.Errorf("duplicate asset platform %s", platform) + } + platforms[platform] = true + if err := validateFiles(asset.Name, asset.Entrypoint); err != nil || strings.Contains(asset.Name, "/") { + return fmt.Errorf("invalid release asset filename or entrypoint") + } + if err := ValidateHTTPS(asset.URL); err != nil { + return err + } + if asset.Attestation != "" { + if err := ValidateHTTPS(asset.Attestation); err != nil { + return err + } + } + } + case "git": + if err := ValidateHTTPS(d.URL); err != nil { + return err + } + if err := ValidateGitRef(d.Revision); err != nil { + return err + } + if err := validateFiles(d.OutputRoot, d.Entrypoint); err != nil { + return err + } + for _, step := range d.Build { + if err := validateFiles(step.WorkDir); err != nil { + return err + } + if err := validateArgs(step.Args); err != nil { + return err + } + } + case "container": + return m.validateServices(d.Services) + } + return nil +} + +func (m *Declaration) validateServices(services []Service) error { + byName := make(map[string]Service, len(services)) + webCount := 0 + for _, service := range services { + if _, exists := byName[service.Name]; exists { + return fmt.Errorf("duplicate container service name") + } + if err := ValidateImageReference(service.Image); err != nil { + return err + } + byName[service.Name] = service + if service.Role == "web" { + webCount++ + } + } + if webCount != 1 { + return fmt.Errorf("expected exactly one web container service") + } + for _, service := range services { + if err := m.validateEnvironment(service.Environment, byName, service.Role == "web"); err != nil { + return fmt.Errorf("service %s: %w", service.Name, err) + } + if err := m.validateService(service, byName); err != nil { + return fmt.Errorf("service %s: %w", service.Name, err) + } + } + return validateDependencyGraph(byName) +} + +func (m *Declaration) validateService(service Service, services map[string]Service) error { + if service.Healthcheck != nil { + check := service.Healthcheck + if check.TimeoutSeconds > check.IntervalSeconds || (check.Kind != "exec" && service.ContainerPort == 0) { + return fmt.Errorf("invalid healthcheck timing or missing private port") + } + if err := validateArgs(check.Argv); err != nil { + return err + } + if check.Path != "" { + if err := validateAppPaths(check.Path); err != nil { + return err + } + } + } + mountPaths := map[string]bool{} + mountNames := map[string]bool{} + for _, mount := range append(slices.Clone(service.DataVolumes), service.ConfigMounts...) { + if mount.MountPath == "/" || mountPaths[mount.MountPath] || (mount.Name != "" && mountNames[mount.Name]) { + return fmt.Errorf("duplicate or invalid mount") + } + mountPaths[mount.MountPath] = true + mountNames[mount.Name] = mount.Name != "" + if err := validateAppPaths(mount.MountPath); err != nil { + return err + } + if err := validateFiles(mount.Source); err != nil { + return err + } + } + if len(service.DataVolumes) > 0 && !m.Permissions.PersistentData { + return fmt.Errorf("data volumes require persistentData") + } + for name, condition := range service.DependsOn { + dependency, exists := services[name] + if !exists || (condition == "service_healthy" && dependency.Healthcheck == nil) { + return fmt.Errorf("dependency missing or lacks a healthcheck") + } + } + if len(service.DependsOn) > 0 && !slices.Contains(m.Permissions.Egress, "managed_dependency") { + return fmt.Errorf("service dependency requires managed_dependency egress") + } + return nil +} + +func validateDependencyGraph(services map[string]Service) error { + visiting := map[string]bool{} + done := map[string]bool{} + var visit func(string) bool + visit = func(name string) bool { + if visiting[name] { + return false + } + if done[name] { + return true + } + visiting[name] = true + for dependency := range services[name].DependsOn { + if !visit(dependency) { + return false + } + } + delete(visiting, name) + done[name] = true + return true + } + for name := range services { + if !visit(name) { + return fmt.Errorf("container services have a dependency cycle") + } + } + return nil +} + +func (m *Declaration) validateEnvironment(env Environment, services map[string]Service, web bool) error { + names := map[string]bool{} + if web && m.Access.Bootstrap != nil { + if err := addEnv(names, m.Access.Bootstrap.UsernameEnv); err != nil { + return err + } + if err := addEnv(names, m.Access.Bootstrap.PasswordFileEnv); err != nil { + return err + } + } + if web && m.LLM != nil { + for _, binding := range m.LLM.Bindings { + for name := range binding.Env { + names[name] = true + } + } + } + for name := range env.Env { + if err := addEnv(names, name); err != nil { + return err + } + } + for name, value := range env.StaticEnv { + if err := addEnv(names, name); err != nil { + return err + } + if strings.ContainsAny(value, "\x00\r\n") { + return fmt.Errorf("invalid control character in a static environment value") + } + } + for name, use := range env.SecretEnv { + if err := addEnv(names, name); err != nil { + return err + } + if _, exists := m.Secrets[use.SecretRef]; !exists { + return fmt.Errorf("unknown Secret reference") + } + if use.Kind == "connection_uri" { + destination, exists := services[use.Service] + if !exists || destination.ContainerPort == 0 || destination.Role != "dependency" || + !slices.Contains(m.Permissions.Egress, "managed_dependency") { + return fmt.Errorf("connection URI requires a private dependency service with a port") + } + } + } + return nil +} + +func (m *Declaration) validateBindings() error { + if m.LLM == nil && slices.Contains(m.Permissions.Egress, "managed_model_gateway") { + return fmt.Errorf("gateway egress requires an LLM declaration") + } + names := map[string]bool{} + if m.Access.Bootstrap != nil { + if err := addEnv(names, m.Access.Bootstrap.UsernameEnv); err != nil { + return err + } + if err := addEnv(names, m.Access.Bootstrap.PasswordFileEnv); err != nil { + return err + } + } + if m.LLM == nil { + return nil + } + if m.LLM.Selection == "" { + m.LLM.Selection = "multi" + } + protocols := map[string]bool{} + templatePaths := map[string]bool{} + for _, binding := range m.LLM.Bindings { + if protocols[binding.Protocol] { + return fmt.Errorf("duplicate LLM protocol binding") + } + protocols[binding.Protocol] = true + used := make(map[string]bool, len(names)) + for name := range names { + used[name] = true + } + values := map[string]bool{} + for name, value := range binding.Env { + if err := addEnv(used, name); err != nil { + return err + } + values[value] = true + } + if m.LLM.Selection == "multi" { + names = used + } + if template := binding.ConfigTemplate; template != nil { + if err := validateFiles(template.Path, template.SourcePath); err != nil { + return err + } + key := strings.ToLower(template.Path) + if templatePaths[key] && m.LLM.Selection == "multi" { + return fmt.Errorf("concurrent LLM bindings share a template path") + } + templatePaths[key] = true + for _, value := range template.Values { + values[value] = true + } + } + urlValue, otherURL := "gateway_v1_url", "gateway_root_url" + if binding.Protocol == Anthropic { + urlValue, otherURL = otherURL, urlValue + } + if !values["gateway_token"] || !values[urlValue] || values[otherURL] { + return fmt.Errorf("LLM binding requires a gateway token and the protocol-specific URL") + } + } + return nil +} + +// ActiveBindings selects the bindings to consider when rendering a future runtime +// environment. A single-active declaration must have an explicitly selected protocol. +func (l LLM) ActiveBindings(protocol string) ([]Binding, error) { + if l.Selection == "multi" || l.Selection == "" { + return slices.Clone(l.Bindings), nil + } + for _, binding := range l.Bindings { + if binding.Protocol == protocol { + return []Binding{binding}, nil + } + } + return nil, fmt.Errorf("active LLM protocol is missing or undeclared") +} + +func addEnv(names map[string]bool, name string) error { + if names[name] || strings.HasPrefix(name, "CSAI_PLUGIN_") || strings.HasPrefix(name, "LD_") || strings.HasPrefix(name, "DYLD_") || strings.HasPrefix(name, "GIT_") || + strings.HasPrefix(name, "BASH_") || slices.Contains([]string{ + "PATH", "PATHEXT", "HOME", "USERPROFILE", "COMSPEC", "SYSTEMROOT", "SSL_CERT_FILE", "SSL_CERT_DIR", + "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "NODE_OPTIONS", "PYTHONPATH", "PYTHONHOME", "ENV", + }, name) { + return fmt.Errorf("duplicate or reserved environment variable %s", name) + } + names[name] = true + return nil +} + +var refPattern = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._/-]{0,179}$`) +var imagePart = regexp.MustCompile(`^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$`) +var imageTag = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$`) +var imageRegistry = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]*(?::[0-9]{1,5})?$`) + +func ValidateGitRef(ref string) error { + if ref == "" { + return nil + } + if !refPattern.MatchString(ref) || strings.Contains(ref, "..") || strings.HasSuffix(ref, ".") || + (strings.HasPrefix(ref, "refs/") && !strings.HasPrefix(ref, "refs/heads/") && !strings.HasPrefix(ref, "refs/tags/")) { + return fmt.Errorf("invalid Git reference") + } + for part := range strings.SplitSeq(ref, "/") { + if part == "" || strings.HasPrefix(part, ".") || strings.HasSuffix(part, ".lock") { + return fmt.Errorf("invalid Git reference component") + } + } + return nil +} + +func ValidateHTTPS(raw string) error { + u, err := url.Parse(raw) + if err != nil || u.Scheme != "https" || u.User != nil || u.Hostname() == "" || u.Port() != "" || + u.RawQuery != "" || u.ForceQuery || strings.ContainsAny(raw, "#\\") { + return fmt.Errorf("expected an HTTPS URL without credentials, explicit port, query or fragment") + } + host := strings.ToLower(strings.TrimSuffix(u.Hostname(), ".")) + if addr, err := netip.ParseAddr(host); err == nil { + addr = addr.Unmap() + if !addr.IsGlobalUnicast() || addr.IsPrivate() { + return fmt.Errorf("non-public URL host") + } + } else if !strings.Contains(host, ".") || strings.HasSuffix(host, ".localhost") || strings.HasSuffix(host, ".local") { + return fmt.Errorf("non-public URL host") + } + for part := range strings.SplitSeq(u.Path, "/") { + if part == "." || part == ".." || strings.ContainsAny(part, "\x00\r\n") { + return fmt.Errorf("invalid URL path") + } + } + if strings.Contains(strings.ToLower(u.EscapedPath()), "%2f") || strings.Contains(strings.ToLower(u.EscapedPath()), "%5c") { + return fmt.Errorf("encoded URL separator") + } + return nil +} + +func ValidateImageReference(ref string) error { + _, _, _, err := ParseImageReference(ref) + return err +} + +// ParseImageReference splits an explicit OCI reference. The tag is descriptive +// when a digest is present, including for repository:tag@sha256 references. +func ParseImageReference(ref string) (repository, tag, digest string, err error) { + repository, digest, pinned := strings.Cut(ref, "@") + if pinned && (!strings.HasPrefix(digest, "sha256:") || !hex256.MatchString(strings.TrimPrefix(digest, "sha256:"))) { + return "", "", "", fmt.Errorf("invalid image digest") + } + if sep := strings.LastIndex(repository, ":"); sep > strings.LastIndex(repository, "/") { + tag, repository = repository[sep+1:], repository[:sep] + if !imageTag.MatchString(tag) { + return "", "", "", fmt.Errorf("invalid image tag") + } + } + if !pinned && tag == "" { + return "", "", "", fmt.Errorf("expected explicit OCI tag or digest") + } + return repository, tag, digest, validateImageRepository(repository) +} + +func validateImageRepository(repository string) error { + parts := strings.Split(repository, "/") + if len(parts) > 1 && strings.ContainsAny(parts[0], ".:") { + if !imageRegistry.MatchString(parts[0]) || strings.Contains(parts[0], "..") { + return fmt.Errorf("invalid OCI registry") + } + parts = parts[1:] + } + for _, part := range parts { + if !imagePart.MatchString(part) { + return fmt.Errorf("invalid OCI repository") + } + } + return nil +} + +func validateArgs(args []string) error { + for _, arg := range args { + if strings.ContainsAny(arg, "\x00\r\n") { + return fmt.Errorf("invalid command argument") + } + } + return nil +} + +func validateAppPaths(paths ...string) error { + for _, path := range paths { + if strings.HasPrefix(path, "/_csai_plugin/") || path == "/_csai_plugin" { + return fmt.Errorf("reserved plugin proxy path") + } + for part := range strings.SplitSeq(path, "/") { + if part == "." || part == ".." { + return fmt.Errorf("invalid application path") + } + } + } + return nil +} + +func validateFiles(paths ...string) error { + for _, path := range paths { + if path == "" { + continue + } + for part := range strings.SplitSeq(path, "/") { + base, _, _ := strings.Cut(strings.ToUpper(part), ".") + if part == "" || strings.HasSuffix(part, ".") || + slices.Contains([]string{"CON", "NUL", "PRN", "AUX", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"}, base) { + return fmt.Errorf("invalid portable file path") + } + } + } + return nil +} diff --git a/internal/pluginhub/manifest/decode.go b/internal/pluginhub/manifest/decode.go new file mode 100644 index 00000000..9c82e9df --- /dev/null +++ b/internal/pluginhub/manifest/decode.go @@ -0,0 +1,141 @@ +package manifest + +import ( + "bytes" + "crypto/sha256" + "embed" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "sync" + + "github.com/google/jsonschema-go/jsonschema" + "gopkg.in/yaml.v3" +) + +const MaxDocumentBytes = 128 << 10 + +//go:embed schemas/*.json +var schemas embed.FS + +var declarationSchema = sync.OnceValues(func() (*jsonschema.Resolved, error) { + return resolveSchema("manifest-v1") +}) +var installPlanSchema = sync.OnceValues(func() (*jsonschema.Resolved, error) { + return resolveSchema("install-plan-v1") +}) + +// Schema returns a copy of an embedded schema without resolving remote references. +func Schema(name string) ([]byte, error) { + switch name { + case "manifest-v1", "install-plan-v1": + return schemas.ReadFile("schemas/" + name + ".json") + default: + return nil, fmt.Errorf("unknown schema") + } +} + +func resolveSchema(name string) (*jsonschema.Resolved, error) { + raw, err := Schema(name) + if err != nil { + return nil, err + } + var schema jsonschema.Schema + if err := json.Unmarshal(raw, &schema); err != nil { + return nil, err + } + return schema.Resolve(nil) +} + +func Digest(raw []byte) string { + sum := sha256.Sum256(raw) + return hex.EncodeToString(sum[:]) +} + +func decode(data []byte, schema func() (*jsonschema.Resolved, error), result any) ([]byte, error) { + if len(data) > MaxDocumentBytes { + return nil, fmt.Errorf("document exceeds %d bytes", MaxDocumentBytes) + } + parser := yaml.NewDecoder(bytes.NewReader(data)) + var document yaml.Node + if err := parser.Decode(&document); err != nil { + return nil, fmt.Errorf("decode document: %w", err) + } + var trailing yaml.Node + if err := parser.Decode(&trailing); err != io.EOF { + return nil, fmt.Errorf("expected a single document") + } + if len(document.Content) != 1 { + return nil, fmt.Errorf("expected a document value") + } + nodes := 4096 + value, err := jsonValue(document.Content[0], 0, &nodes) + if err != nil { + return nil, err + } + resolved, err := schema() + if err != nil { + return nil, fmt.Errorf("resolve embedded schema: %w", err) + } + if err := resolved.Validate(value); err != nil { + return nil, fmt.Errorf("schema validation: %w", err) + } + canonical, err := json.Marshal(value) + if err != nil { + return nil, err + } + if err := json.Unmarshal(canonical, result); err != nil { + return nil, err + } + return canonical, nil +} + +func jsonValue(node *yaml.Node, depth int, remaining *int) (any, error) { + *remaining -= 1 + if depth > 32 || *remaining < 0 { + return nil, fmt.Errorf("document nesting or entry limit exceeded") + } + if node.Anchor != "" || node.Kind == yaml.AliasNode || node.Style&yaml.TaggedStyle != 0 { + return nil, fmt.Errorf("aliases, anchors and explicit tags are unsupported at line %d", node.Line) + } + switch node.Kind { + case yaml.MappingNode: + object := make(map[string]any, len(node.Content)/2) + for i := 0; i < len(node.Content); i += 2 { + key := node.Content[i] + if key.Kind != yaml.ScalarNode || key.ShortTag() != "!!str" || key.Style&yaml.TaggedStyle != 0 || key.Anchor != "" || key.Value == "<<" { + return nil, fmt.Errorf("expected a string mapping key at line %d", key.Line) + } + if _, exists := object[key.Value]; exists { + return nil, fmt.Errorf("duplicate mapping key at line %d", key.Line) + } + value, err := jsonValue(node.Content[i+1], depth+1, remaining) + if err != nil { + return nil, err + } + object[key.Value] = value + } + return object, nil + case yaml.SequenceNode: + values := make([]any, 0, len(node.Content)) + for _, child := range node.Content { + value, err := jsonValue(child, depth+1, remaining) + if err != nil { + return nil, err + } + values = append(values, value) + } + return values, nil + case yaml.ScalarNode: + switch node.ShortTag() { + case "!!str", "!!bool", "!!int", "!!float", "!!null": + var value any + if err := node.Decode(&value); err != nil { + return nil, err + } + return value, nil + } + } + return nil, fmt.Errorf("unsupported value at line %d", node.Line) +} diff --git a/internal/pluginhub/manifest/manifest_test.go b/internal/pluginhub/manifest/manifest_test.go new file mode 100644 index 00000000..537c2185 --- /dev/null +++ b/internal/pluginhub/manifest/manifest_test.go @@ -0,0 +1,137 @@ +package manifest + +import ( + "encoding/json" + "os" + "strings" + "testing" + "time" +) + +func declarationFixture(t *testing.T) string { + t.Helper() + raw, err := os.ReadFile("testdata/web-plugin.yaml") + if err != nil { + t.Fatal(err) + } + return string(raw) +} + +func TestPluginManifestDeclaration(t *testing.T) { + raw := declarationFixture(t) + got, err := DecodeDeclaration([]byte(raw)) + if err != nil { + t.Fatal(err) + } + if got.Metadata.ID != "log-review" || got.LLM.Selection != "multi" || len(got.Distribution) != 3 { + t.Fatalf("unexpected declaration: %#v", got.Metadata) + } + fromJSON, err := DecodeDeclaration(got.Canonical) + if err != nil || Digest(fromJSON.Canonical) != Digest(got.Canonical) { + t.Fatalf("canonical declaration changed after decoding JSON: %v", err) + } +} + +func TestPluginManifestNativeEnvironmentAndSingleActive(t *testing.T) { + raw := declarationFixture(t) + raw = strings.Replace(raw, "\n entrypoint: log-review\n", ` + entrypoint: log-review + staticEnv: {APP_TITLE: Review} + secretEnv: + APP_PASSWORD_FILE: {kind: file, secretRef: db-password} +`, 1) + raw = strings.Replace(raw, "llm:\n", "llm:\n selection: single_active\n", 1) + for _, suffix := range []string{"BASE_URL", "TOKEN", "MODEL", "PROVIDER"} { + raw = strings.ReplaceAll(raw, "REVIEW_OPENAI_"+suffix, "REVIEW_"+suffix) + raw = strings.ReplaceAll(raw, "REVIEW_ANTHROPIC_"+suffix, "REVIEW_"+suffix) + } + got, err := DecodeDeclaration([]byte(raw)) + if err != nil { + t.Fatal(err) + } + if got.Launch.StaticEnv["APP_TITLE"] != "Review" || got.Launch.SecretEnv["APP_PASSWORD_FILE"].SecretRef != "db-password" { + t.Fatal("native environment not decoded") + } + for _, test := range []struct{ protocol, url string }{{OpenAI, "gateway_v1_url"}, {Anthropic, "gateway_root_url"}} { + bindings, err := got.LLM.ActiveBindings(test.protocol) + if err != nil || len(bindings) != 1 || bindings[0].Env["REVIEW_BASE_URL"] != test.url { + t.Fatalf("wrong active binding: %+v, %v", bindings, err) + } + } + if _, err := got.LLM.ActiveBindings(""); err == nil { + t.Fatal("single-active selection accepted a missing protocol") + } + for _, test := range []struct{ name, declaration string }{ + {"multi collision", strings.Replace(raw, "single_active", "multi", 1)}, + {"undeclared secret", strings.Replace(raw, "APP_PASSWORD_FILE: {kind: file, secretRef: db-password}", "APP_PASSWORD_FILE: {kind: file, secretRef: missing}", 1)}, + {"reserved native env", strings.Replace(raw, "APP_TITLE", "PATH", 1)}, + {"collision with runtime", strings.Replace(raw, "APP_TITLE", "REVIEW_MODEL", 1)}, + } { + t.Run(test.name, func(t *testing.T) { + if _, err := DecodeDeclaration([]byte(test.declaration)); err == nil { + t.Fatal("invalid declaration accepted") + } + }) + } +} + +func TestPluginManifestRejectsUnsafeOrInvalidDeclarations(t *testing.T) { + raw := declarationFixture(t) + for _, test := range []struct{ name, document string }{ + {"duplicate key", raw + "\nkind: WebPlugin\n"}, + {"multiple documents", raw + "\n---\n{}"}, + {"anchor", strings.Replace(raw, "kind: WebPlugin", "kind: &name WebPlugin", 1)}, + {"tag", strings.Replace(raw, "kind: WebPlugin", "kind: !!str WebPlugin", 1)}, + {"unknown field", raw + "\nunknown: true\n"}, + {"missing required launch", strings.Replace(raw, "launch:", "unexpected:", 1)}, + {"ambiguous path", strings.Replace(raw, "healthPath: /healthz", "healthPath: /../healthz", 1)}, + {"nonportable path", strings.Replace(raw, "entrypoint: log-review.exe", "entrypoint: NUL.exe", 1)}, + {"unapproved URL credentials", strings.ReplaceAll(raw, "https://git.example.org", "https://user:secret@git.example.org")}, + {"loopback URL", strings.ReplaceAll(raw, "https://git.example.org", "https://127.0.0.1")}, + {"bad Git ref", strings.Replace(raw, "refs/tags/v1.0.0", "refs/tags/../main", 1)}, + {"implicit OCI tag", strings.Replace(raw, "log-review:1.0.0", "log-review", 1)}, + {"wrong protocol URL", strings.Replace(raw, "gateway_root_url", "gateway_v1_url", 1)}, + {"nested dependency cycle", strings.Replace(raw, "role: dependency", "role: dependency\n depends_on: {review: service_started}", 1)}, + {"privileged service", strings.Replace(raw, "containerPort: 8080", "containerPort: 8080\n privileged: true", 1)}, + {"unexpected gateway egress", strings.Replace(raw, "managed_dependency, managed_model_gateway", "managed_dependency", 1)}, + } { + t.Run(test.name, func(t *testing.T) { + if _, err := DecodeDeclaration([]byte(test.document)); err == nil { + t.Fatal("invalid declaration accepted") + } + }) + } +} + +func TestPluginManifestLockedPlans(t *testing.T) { + base := InstallPlan{ + Version: 1, ID: "348e8ed0-1534-4bb1-b28b-390e315f739e", + InstallID: "0eb46cec-7a99-4c60-9c4a-b237860e6cca", ActorID: "admin", + ManifestSHA256: strings.Repeat("a", 64), PolicySHA256: strings.Repeat("b", 64), + ExpiresAt: time.Now().UTC().Add(time.Minute), Platform: Platform{OS: "linux", Arch: "amd64"}, Isolation: "strict", + } + verify := func(a Artifact, valid bool) { + t.Helper() + base.Artifact = a + raw, err := json.Marshal(base) + if err != nil { + t.Fatal(err) + } + checked, err := DecodeInstallPlan(raw) + if (err == nil) != valid || (err == nil && len(checked.Canonical) == 0) { + t.Fatalf("artifact %+v: err=%v want valid=%v", a, err, valid) + } + } + verify(Artifact{Driver: "release", AssetURL: "https://example.org/asset.tgz", SHA256: strings.Repeat("c", 64), Verification: "declared_checksum"}, true) + git := Artifact{Driver: "git", Repository: "https://github.com/example/repo", RequestedRef: "refs/tags/v1", Commit: strings.Repeat("d", 40)} + verify(git, true) + git.Commit = "refs/tags/v1" + verify(git, false) + digest := "sha256:" + strings.Repeat("e", 64) + container := Artifact{Driver: "container", Services: []LockedService{ + {Name: "web", RequestedImage: "example.org/app:v1", Repository: "example.org/app", ManifestDigest: digest}, + }} + verify(container, true) + container.Services[0].Repository = "example.org/different" + verify(container, false) +} diff --git a/internal/pluginhub/manifest/plan.go b/internal/pluginhub/manifest/plan.go new file mode 100644 index 00000000..a1facc93 --- /dev/null +++ b/internal/pluginhub/manifest/plan.go @@ -0,0 +1,120 @@ +package manifest + +import ( + "fmt" + "regexp" + "time" + + "github.com/google/uuid" +) + +var hex256 = regexp.MustCompile(`^[a-f0-9]{64}$`) +var commitSHA = regexp.MustCompile(`^(?:[a-f0-9]{40}|[a-f0-9]{64})$`) + +func IsCommitSHA(value string) bool { + return commitSHA.MatchString(value) +} + +type InstallPlan struct { + Canonical []byte `json:"-"` + Version int `json:"version"` + ID string `json:"id"` + InstallID string `json:"installId"` + ActorID string `json:"actorId"` + ManifestSHA256 string `json:"manifestSha256"` + PolicySHA256 string `json:"policySha256"` + ConfigTemplateSHA256 string `json:"configTemplateSha256,omitempty"` + ExpiresAt time.Time `json:"expiresAt"` + Platform Platform `json:"platform"` + Isolation string `json:"isolation"` + Artifact Artifact `json:"artifact"` +} + +type Platform struct { + OS string `json:"os"` + Arch string `json:"arch"` +} + +type Artifact struct { + Driver string `json:"driver"` + AssetURL string `json:"assetURL,omitempty"` + SHA256 string `json:"sha256,omitempty"` + Verification string `json:"verification,omitempty"` + Repository string `json:"repository,omitempty"` + RequestedRef string `json:"requestedRef,omitempty"` + Commit string `json:"commit,omitempty"` + Services []LockedService `json:"services,omitempty"` +} + +type LockedService struct { + Name string `json:"name"` + RequestedImage string `json:"requestedImage"` + Repository string `json:"repository"` + ManifestDigest string `json:"manifestDigest"` + IndexDigest string `json:"indexDigest,omitempty"` +} + +func DecodeInstallPlan(data []byte) (*InstallPlan, error) { + var plan InstallPlan + canonical, err := decode(data, installPlanSchema, &plan) + if err != nil { + return nil, err + } + plan.Canonical = canonical + if err := plan.validate(); err != nil { + return nil, err + } + return &plan, nil +} + +func (p InstallPlan) validate() error { + for _, raw := range []string{p.ID, p.InstallID} { + id, err := uuid.Parse(raw) + if err != nil || id == uuid.Nil || raw != id.String() { + return fmt.Errorf("expected a canonical non-empty UUID") + } + } + switch a := p.Artifact; a.Driver { + case "release": + return ValidateHTTPS(a.AssetURL) + case "git": + if err := ValidateHTTPS(a.Repository); err != nil { + return err + } + if err := ValidateGitRef(a.RequestedRef); err != nil { + return err + } + if IsCommitSHA(a.RequestedRef) && a.RequestedRef != a.Commit { + return fmt.Errorf("commit differs from the requested Git identity") + } + case "container": + if p.Platform.OS != "linux" { + return fmt.Errorf("locked container artifact requires a Linux image platform") + } + names := map[string]bool{} + for _, service := range a.Services { + if names[service.Name] { + return fmt.Errorf("duplicate locked container service") + } + names[service.Name] = true + if err := service.validate(); err != nil { + return err + } + } + } + return nil +} + +func (s LockedService) validate() error { + repository, _, digest, err := ParseImageReference(s.RequestedImage) + if err != nil { + return err + } + if digest != "" && digest != s.ManifestDigest && digest != s.IndexDigest { + return fmt.Errorf("locked image does not match the requested digest") + } + if s.Repository != repository { + return fmt.Errorf("locked image repository differs from requested image") + } + return nil +} diff --git a/internal/pluginhub/manifest/schemas/install-plan-v1.json b/internal/pluginhub/manifest/schemas/install-plan-v1.json new file mode 100644 index 00000000..1d1fb405 --- /dev/null +++ b/internal/pluginhub/manifest/schemas/install-plan-v1.json @@ -0,0 +1,212 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://schemas.cyberstrikeai.local/plugin/install-plan/v1", + "type": "object", + "additionalProperties": false, + "required": [ + "version", + "id", + "installId", + "actorId", + "manifestSha256", + "policySha256", + "expiresAt", + "platform", + "isolation", + "artifact" + ], + "properties": { + "version": { + "const": 1 + }, + "id": { + "type": "string", + "format": "uuid" + }, + "installId": { + "type": "string", + "format": "uuid" + }, + "actorId": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "manifestSha256": { + "$ref": "#/$defs/hex" + }, + "policySha256": { + "$ref": "#/$defs/hex" + }, + "configTemplateSha256": { + "$ref": "#/$defs/hex" + }, + "expiresAt": { + "type": "string", + "format": "date-time" + }, + "platform": { + "type": "object", + "additionalProperties": false, + "required": [ + "os", + "arch" + ], + "properties": { + "os": { + "enum": [ + "linux", + "darwin", + "windows" + ] + }, + "arch": { + "enum": [ + "amd64", + "arm64" + ] + } + } + }, + "isolation": { + "enum": [ + "standard", + "strict" + ] + }, + "artifact": { + "oneOf": [ + { + "$ref": "#/$defs/releaseLock" + }, + { + "$ref": "#/$defs/gitLock" + }, + { + "$ref": "#/$defs/containerLock" + } + ] + } + }, + "$defs": { + "hex": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "digest": { + "type": "string", + "pattern": "^sha256:[a-f0-9]{64}$" + }, + "httpsURL": { + "type": "string", + "format": "uri", + "pattern": "^https://", + "maxLength": 2048 + }, + "releaseLock": { + "type": "object", + "additionalProperties": false, + "required": [ + "driver", + "assetURL", + "sha256", + "verification" + ], + "properties": { + "driver": { + "const": "release" + }, + "assetURL": { + "$ref": "#/$defs/httpsURL" + }, + "sha256": { + "$ref": "#/$defs/hex" + }, + "verification": { + "enum": [ + "declared_checksum", + "verified_attestation", + "reviewed_observed_digest" + ] + } + } + }, + "gitLock": { + "type": "object", + "additionalProperties": false, + "required": [ + "driver", + "repository", + "requestedRef", + "commit" + ], + "properties": { + "driver": { + "const": "git" + }, + "repository": { + "$ref": "#/$defs/httpsURL" + }, + "requestedRef": { + "type": "string", + "minLength": 1, + "maxLength": 180 + }, + "commit": { + "type": "string", + "pattern": "^([a-f0-9]{40}|[a-f0-9]{64})$" + } + } + }, + "containerLock": { + "type": "object", + "additionalProperties": false, + "required": [ + "driver", + "services" + ], + "properties": { + "driver": { + "const": "container" + }, + "services": { + "type": "array", + "minItems": 1, + "maxItems": 8, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "name", + "requestedImage", + "repository", + "manifestDigest" + ], + "properties": { + "name": { + "type": "string", + "pattern": "^[a-z][a-z0-9-]{1,47}$" + }, + "requestedImage": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "repository": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "manifestDigest": { + "$ref": "#/$defs/digest" + }, + "indexDigest": { + "$ref": "#/$defs/digest" + } + } + } + } + } + } + } +} diff --git a/internal/pluginhub/manifest/schemas/manifest-v1.json b/internal/pluginhub/manifest/schemas/manifest-v1.json new file mode 100644 index 00000000..b6f5336d --- /dev/null +++ b/internal/pluginhub/manifest/schemas/manifest-v1.json @@ -0,0 +1,1065 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://schemas.cyberstrikeai.local/plugin/manifest/v1", + "type": "object", + "additionalProperties": false, + "required": [ + "apiVersion", + "kind", + "metadata", + "distribution", + "web", + "access", + "permissions" + ], + "properties": { + "apiVersion": { + "const": "plugins.csai.io/v1" + }, + "kind": { + "const": "WebPlugin" + }, + "metadata": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "title", + "version", + "repository" + ], + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "summary": { + "type": "string", + "maxLength": 500 + }, + "version": { + "type": "string", + "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?(\\+[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$" + }, + "repository": { + "$ref": "#/$defs/httpsURL" + }, + "license": { + "type": "string", + "minLength": 1, + "maxLength": 100 + } + } + }, + "distribution": { + "type": "array", + "minItems": 1, + "maxItems": 3, + "items": { + "oneOf": [ + { + "$ref": "#/$defs/release" + }, + { + "$ref": "#/$defs/git" + }, + { + "$ref": "#/$defs/container" + } + ] + } + }, + "secrets": { + "type": "object", + "maxProperties": 16, + "propertyNames": { + "$ref": "#/$defs/id" + }, + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "required": [ + "generator", + "bytes" + ], + "properties": { + "generator": { + "enum": [ + "random_base64url", + "random_hex" + ] + }, + "bytes": { + "type": "integer", + "minimum": 16, + "maximum": 128 + } + } + } + }, + "launch": { + "type": "object", + "additionalProperties": false, + "required": [ + "entrypoint", + "env" + ], + "properties": { + "entrypoint": { + "$ref": "#/$defs/file" + }, + "args": { + "$ref": "#/$defs/args" + }, + "workDir": { + "$ref": "#/$defs/file" + }, + "env": { + "$ref": "#/$defs/runtimeEnv" + }, + "staticEnv": { + "$ref": "#/$defs/staticEnv" + }, + "secretEnv": { + "$ref": "#/$defs/secretEnv" + } + } + }, + "web": { + "type": "object", + "additionalProperties": false, + "required": [ + "route", + "entryPath", + "healthPath" + ], + "properties": { + "route": { + "enum": [ + "root", + "build_base_path", + "relative_prefix" + ] + }, + "entryPath": { + "$ref": "#/$defs/appPath" + }, + "healthPath": { + "$ref": "#/$defs/appPath" + }, + "readyHeaderCheck": { + "type": "boolean", + "default": false, + "description": "Require native plugins to echo CSAI_PLUGIN_READY_TOKEN in X-CSAI-Plugin-Ready." + }, + "allowHealthRedirect": { + "type": "boolean", + "default": false, + "description": "Accept a 3xx response with Location without following the redirect." + }, + "sse": { + "type": "boolean", + "default": false + }, + "websocket": { + "type": "boolean", + "default": false + } + } + }, + "access": { + "type": "object", + "additionalProperties": false, + "required": [ + "mode" + ], + "properties": { + "mode": { + "enum": [ + "platform", + "plugin_login" + ] + }, + "applicationBearer": { + "type": "array", + "uniqueItems": true, + "maxItems": 16, + "items": { + "$ref": "#/$defs/appPath" + } + }, + "bootstrap": { + "type": "object", + "additionalProperties": false, + "required": [ + "usernameEnv", + "passwordFileEnv" + ], + "properties": { + "usernameEnv": { + "$ref": "#/$defs/envName" + }, + "passwordFileEnv": { + "$ref": "#/$defs/envName" + } + } + } + }, + "dependentSchemas": { + "bootstrap": { + "properties": { + "mode": { + "const": "plugin_login" + } + } + }, + "applicationBearer": { + "properties": { + "mode": { + "const": "plugin_login" + } + } + } + } + }, + "llm": { + "type": "object", + "additionalProperties": false, + "required": [ + "bindings" + ], + "properties": { + "bindings": { + "type": "array", + "minItems": 1, + "maxItems": 2, + "items": { + "$ref": "#/$defs/llmBinding" + } + }, + "selection": { + "enum": [ + "single_active", + "multi" + ], + "default": "multi" + } + } + }, + "permissions": { + "type": "object", + "additionalProperties": false, + "required": [ + "persistentData", + "modelGateway", + "egress" + ], + "properties": { + "persistentData": { + "type": "boolean" + }, + "modelGateway": { + "type": "boolean" + }, + "egress": { + "type": "array", + "maxItems": 8, + "uniqueItems": true, + "items": { + "enum": [ + "managed_model_gateway", + "managed_dependency", + "approved_custom_model" + ] + } + } + } + }, + "extensions": { + "type": "object", + "additionalProperties": false, + "properties": { + "projectExchange": { + "type": "object", + "additionalProperties": false, + "required": [ + "version", + "accepts", + "produces" + ], + "properties": { + "version": { + "const": 1 + }, + "accepts": { + "type": "array", + "uniqueItems": true, + "items": { + "$ref": "#/$defs/qualifiedID" + } + }, + "produces": { + "type": "array", + "uniqueItems": true, + "items": { + "$ref": "#/$defs/qualifiedID" + } + } + } + }, + "capabilities": { + "type": "array", + "maxItems": 8, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "transport", + "path", + "resource" + ], + "properties": { + "id": { + "$ref": "#/$defs/id" + }, + "transport": { + "enum": [ + "mcp_http", + "mcp_sse", + "openapi" + ] + }, + "path": { + "$ref": "#/$defs/appPath" + }, + "resource": { + "$ref": "#/$defs/qualifiedID" + }, + "protocolVersion": { + "type": "string", + "minLength": 1, + "maxLength": 40 + } + } + } + } + } + } + }, + "allOf": [ + { + "if": { + "properties": { + "distribution": { + "contains": { + "properties": { + "type": { + "enum": [ + "release", + "git" + ] + } + } + } + } + } + }, + "then": { + "required": [ + "launch" + ] + } + }, + { + "if": { + "required": [ + "llm" + ] + }, + "then": { + "properties": { + "permissions": { + "properties": { + "modelGateway": { + "const": true + }, + "egress": { + "contains": { + "const": "managed_model_gateway" + } + } + } + } + } + }, + "else": { + "properties": { + "permissions": { + "properties": { + "modelGateway": { + "const": false + } + } + } + } + } + } + ], + "$defs": { + "id": { + "type": "string", + "pattern": "^[a-z][a-z0-9-]{1,47}$" + }, + "qualifiedID": { + "type": "string", + "maxLength": 160, + "pattern": "^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+:[a-zA-Z][a-zA-Z0-9._-]*$" + }, + "file": { + "type": "string", + "minLength": 1, + "maxLength": 240, + "pattern": "^[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*$" + }, + "appPath": { + "type": "string", + "maxLength": 240, + "pattern": "^/([A-Za-z0-9._~-]+/)*[A-Za-z0-9._~-]*$" + }, + "httpsURL": { + "type": "string", + "format": "uri", + "pattern": "^https://", + "maxLength": 2048 + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "envName": { + "type": "string", + "pattern": "^[A-Z][A-Z0-9_]{0,63}$" + }, + "modelValue": { + "enum": [ + "gateway_v1_url", + "gateway_root_url", + "gateway_token", + "model_alias", + "protocol", + "provider" + ] + }, + "llmBinding": { + "type": "object", + "additionalProperties": false, + "required": [ + "protocol", + "env" + ], + "properties": { + "protocol": { + "enum": [ + "openai_chat", + "anthropic_messages" + ] + }, + "providerValue": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "env": { + "type": "object", + "maxProperties": 16, + "propertyNames": { + "$ref": "#/$defs/envName" + }, + "additionalProperties": { + "$ref": "#/$defs/modelValue" + } + }, + "configTemplate": { + "type": "object", + "additionalProperties": false, + "required": [ + "path", + "format", + "values" + ], + "properties": { + "path": { + "$ref": "#/$defs/file" + }, + "sourcePath": { + "$ref": "#/$defs/file" + }, + "format": { + "enum": [ + "json", + "yaml", + "env" + ] + }, + "values": { + "type": "object", + "minProperties": 1, + "maxProperties": 24, + "propertyNames": { + "pattern": "^(/[A-Za-z0-9_~/-]+|[A-Za-z_][A-Za-z0-9_]{0,63})$" + }, + "additionalProperties": { + "$ref": "#/$defs/modelValue" + } + } + } + } + } + }, + "runtimeEnv": { + "type": "object", + "maxProperties": 16, + "propertyNames": { + "$ref": "#/$defs/envName" + }, + "additionalProperties": { + "enum": [ + "listen_host", + "listen_port", + "data_dir", + "web_base_path" + ] + } + }, + "args": { + "type": "array", + "maxItems": 40, + "items": { + "type": "string", + "maxLength": 2048 + } + }, + "release": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "assets" + ], + "properties": { + "type": { + "const": "release" + }, + "assets": { + "type": "array", + "minItems": 1, + "maxItems": 6, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "os", + "arch", + "url", + "name", + "format" + ], + "properties": { + "os": { + "enum": [ + "linux", + "darwin", + "windows" + ] + }, + "arch": { + "enum": [ + "amd64", + "arm64" + ] + }, + "url": { + "$ref": "#/$defs/httpsURL" + }, + "name": { + "$ref": "#/$defs/file" + }, + "format": { + "enum": [ + "tar_gz", + "zip" + ] + }, + "sha256": { + "$ref": "#/$defs/sha256" + }, + "attestationURL": { + "$ref": "#/$defs/httpsURL" + }, + "stripComponents": { + "type": "integer", + "minimum": 0, + "maximum": 1, + "default": 0 + }, + "entrypoint": { + "$ref": "#/$defs/file" + } + } + } + } + } + }, + "git": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "url", + "dependencies", + "build" + ], + "properties": { + "type": { + "const": "git" + }, + "url": { + "$ref": "#/$defs/httpsURL" + }, + "revision": { + "type": "string", + "maxLength": 180, + "pattern": "^[A-Za-z0-9_][A-Za-z0-9._/-]{0,179}$", + "description": "Omit for the default branch. Short names and full refs are resolved during preflight." + }, + "dependencies": { + "type": "array", + "minItems": 1, + "maxItems": 16, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "name", + "minVersion" + ], + "properties": { + "name": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]{1,40}$" + }, + "minVersion": { + "type": "string", + "pattern": "^[0-9]+(\\.[0-9]+){0,2}$" + } + } + } + }, + "build": { + "type": "array", + "minItems": 1, + "maxItems": 12, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "program", + "args" + ], + "properties": { + "program": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]{1,40}$" + }, + "args": { + "$ref": "#/$defs/args" + }, + "workDir": { + "$ref": "#/$defs/file" + } + } + } + }, + "outputRoot": { + "$ref": "#/$defs/file" + }, + "entrypoint": { + "$ref": "#/$defs/file" + } + } + }, + "container": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "mode", + "services" + ], + "properties": { + "type": { + "const": "container" + }, + "mode": { + "enum": [ + "docker", + "compose" + ] + }, + "services": { + "type": "array", + "minItems": 1, + "maxItems": 8, + "items": { + "$ref": "#/$defs/service" + } + } + }, + "allOf": [ + { + "if": { + "properties": { + "mode": { + "const": "docker" + } + } + }, + "then": { + "properties": { + "services": { + "maxItems": 1 + } + } + } + } + ] + }, + "service": { + "type": "object", + "additionalProperties": false, + "required": [ + "name", + "role", + "image", + "resources" + ], + "properties": { + "name": { + "$ref": "#/$defs/id" + }, + "role": { + "enum": [ + "web", + "dependency" + ] + }, + "image": { + "type": "string", + "maxLength": 512, + "pattern": "^[a-z0-9][a-zA-Z0-9./:_-]*(:[a-zA-Z0-9_][a-zA-Z0-9_.-]*|@sha256:[a-f0-9]{64})$", + "description": "Validate as an OCI repository with an explicit tag or digest." + }, + "containerPort": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + }, + "env": { + "$ref": "#/$defs/runtimeEnv" + }, + "staticEnv": { + "$ref": "#/$defs/staticEnv" + }, + "secretEnv": { + "$ref": "#/$defs/secretEnv" + }, + "depends_on": { + "type": "object", + "maxProperties": 7, + "propertyNames": { + "$ref": "#/$defs/id" + }, + "additionalProperties": { + "enum": [ + "service_started", + "service_healthy" + ] + } + }, + "healthcheck": { + "$ref": "#/$defs/healthcheck" + }, + "resources": { + "type": "object", + "additionalProperties": false, + "required": [ + "memoryMiB", + "pids" + ], + "properties": { + "memoryMiB": { + "type": "integer", + "minimum": 32, + "maximum": 131072 + }, + "pids": { + "type": "integer", + "minimum": 8, + "maximum": 65536 + } + } + }, + "configMounts": { + "type": "array", + "maxItems": 8, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "source", + "mountPath" + ], + "properties": { + "source": { + "$ref": "#/$defs/file" + }, + "mountPath": { + "$ref": "#/$defs/appPath" + } + } + } + }, + "dataVolumes": { + "type": "array", + "maxItems": 4, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "name", + "mountPath" + ], + "properties": { + "name": { + "$ref": "#/$defs/id" + }, + "mountPath": { + "$ref": "#/$defs/appPath" + } + } + } + } + }, + "allOf": [ + { + "if": { + "properties": { + "role": { + "const": "web" + } + } + }, + "then": { + "required": [ + "containerPort" + ] + } + } + ] + }, + "secretValue": { + "type": "object", + "additionalProperties": false, + "required": [ + "kind", + "secretRef" + ], + "properties": { + "kind": { + "enum": [ + "value", + "file" + ] + }, + "secretRef": { + "$ref": "#/$defs/id" + } + } + }, + "secretURI": { + "type": "object", + "additionalProperties": false, + "required": [ + "kind", + "secretRef", + "scheme", + "service", + "username" + ], + "properties": { + "kind": { + "const": "connection_uri" + }, + "secretRef": { + "$ref": "#/$defs/id" + }, + "scheme": { + "type": "string", + "pattern": "^[a-z][a-z0-9+.-]{1,25}$" + }, + "service": { + "$ref": "#/$defs/id" + }, + "username": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "database": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,80}$" + }, + "options": { + "type": "object", + "maxProperties": 12, + "propertyNames": { + "pattern": "^[A-Za-z][A-Za-z0-9_-]{0,39}$" + }, + "additionalProperties": { + "type": "string", + "maxLength": 256 + } + } + } + }, + "healthcheck": { + "type": "object", + "additionalProperties": false, + "required": [ + "kind", + "intervalSeconds", + "timeoutSeconds", + "retries" + ], + "properties": { + "kind": { + "enum": [ + "http", + "tcp", + "exec" + ] + }, + "path": { + "$ref": "#/$defs/appPath" + }, + "argv": { + "type": "array", + "minItems": 1, + "maxItems": 16, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 512 + } + }, + "intervalSeconds": { + "type": "integer", + "minimum": 1, + "maximum": 300 + }, + "timeoutSeconds": { + "type": "integer", + "minimum": 1, + "maximum": 60 + }, + "retries": { + "type": "integer", + "minimum": 1, + "maximum": 30 + }, + "startPeriodSeconds": { + "type": "integer", + "minimum": 0, + "maximum": 300 + } + }, + "allOf": [ + { + "if": { + "properties": { + "kind": { + "const": "http" + } + } + }, + "then": { + "required": [ + "path" + ] + }, + "else": { + "not": { + "required": [ + "path" + ] + } + } + }, + { + "if": { + "properties": { + "kind": { + "const": "exec" + } + } + }, + "then": { + "required": [ + "argv" + ] + }, + "else": { + "not": { + "required": [ + "argv" + ] + } + } + } + ] + }, + "staticEnv": { + "type": "object", + "maxProperties": 64, + "propertyNames": { + "$ref": "#/$defs/envName" + }, + "additionalProperties": { + "type": "string", + "maxLength": 4096 + } + }, + "secretEnv": { + "type": "object", + "maxProperties": 32, + "propertyNames": { + "$ref": "#/$defs/envName" + }, + "additionalProperties": { + "oneOf": [ + { + "$ref": "#/$defs/secretValue" + }, + { + "$ref": "#/$defs/secretURI" + } + ] + } + } + } +} diff --git a/internal/pluginhub/manifest/testdata/web-plugin.yaml b/internal/pluginhub/manifest/testdata/web-plugin.yaml new file mode 100644 index 00000000..f53ab196 --- /dev/null +++ b/internal/pluginhub/manifest/testdata/web-plugin.yaml @@ -0,0 +1,132 @@ +apiVersion: plugins.csai.io/v1 +kind: WebPlugin +metadata: + id: log-review + title: 日志复核 + summary: 对用户主动选择的离线运维日志生成文本摘要和复核记录 + version: "1.0.0" + repository: https://git.example.org/examples/log-review-demo.git + license: Apache-2.0 +distribution: + - type: release + assets: + - os: linux + arch: amd64 + name: log-review-linux-amd64.tar.gz + url: https://downloads.example.org/log-review/1.0.0/log-review-linux-amd64.tar.gz + format: tar_gz + sha256: "1111111111111111111111111111111111111111111111111111111111111111" + - os: darwin + arch: arm64 + name: log-review-darwin-arm64.tar.gz + url: https://downloads.example.org/log-review/1.0.0/log-review-darwin-arm64.tar.gz + format: tar_gz + sha256: "2222222222222222222222222222222222222222222222222222222222222222" + - os: windows + arch: amd64 + name: log-review-windows-amd64.zip + url: https://downloads.example.org/log-review/1.0.0/log-review-windows-amd64.zip + format: zip + attestationURL: https://downloads.example.org/log-review/1.0.0/log-review-windows-amd64.attestation.json + entrypoint: log-review.exe + - type: git + url: https://git.example.org/examples/log-review-demo.git + revision: refs/tags/v1.0.0 + dependencies: + - {name: git, minVersion: "2.43"} + - {name: go, minVersion: "1.25"} + build: + - program: go + args: [build, -trimpath, -mod=readonly, -o, dist/, ./cmd/log-review] + outputRoot: dist + - type: container + mode: compose + services: + - name: review + role: web + image: registry.example.org/examples/log-review:1.0.0 + containerPort: 8080 + staticEnv: {REVIEW_TITLE: Review} + secretEnv: + REVIEW_DB_URI: + kind: connection_uri + secretRef: db-password + scheme: postgresql + service: history + username: review + database: review + depends_on: {history: service_healthy} + healthcheck: {kind: http, path: /healthz, intervalSeconds: 5, timeoutSeconds: 2, retries: 8} + resources: {memoryMiB: 256, pids: 64} + - name: history + role: dependency + image: registry.example.org/examples/log-review-history:1.0.0 + containerPort: 5432 + staticEnv: {POSTGRES_USER: review, POSTGRES_DB: review} + secretEnv: + POSTGRES_PASSWORD_FILE: {kind: file, secretRef: db-password} + healthcheck: + kind: exec + argv: [pg_isready, -U, review, -d, review] + intervalSeconds: 5 + timeoutSeconds: 2 + retries: 12 + resources: {memoryMiB: 512, pids: 128} + dataVolumes: + - {name: review-data, mountPath: /var/lib/log-review} +secrets: + db-password: {generator: random_base64url, bytes: 32} +launch: + entrypoint: log-review + env: + REVIEW_LISTEN_HOST: listen_host + REVIEW_LISTEN_PORT: listen_port + REVIEW_DATA_DIR: data_dir +web: + route: root + entryPath: / + healthPath: /healthz + sse: true + websocket: false +access: + mode: plugin_login + bootstrap: + usernameEnv: REVIEW_BOOTSTRAP_USER + passwordFileEnv: REVIEW_BOOTSTRAP_PASSWORD_FILE +llm: + bindings: + - protocol: openai_chat + providerValue: openai + env: + REVIEW_OPENAI_BASE_URL: gateway_v1_url + REVIEW_OPENAI_TOKEN: gateway_token + REVIEW_OPENAI_MODEL: model_alias + REVIEW_OPENAI_PROVIDER: provider + configTemplate: + path: run/openai-settings.json + format: json + values: + /channel/protocol: protocol + /channel/model: model_alias + - protocol: anthropic_messages + providerValue: anthropic + env: + REVIEW_ANTHROPIC_BASE_URL: gateway_root_url + REVIEW_ANTHROPIC_TOKEN: gateway_token + REVIEW_ANTHROPIC_MODEL: model_alias + REVIEW_ANTHROPIC_PROVIDER: provider +permissions: + persistentData: true + modelGateway: true + egress: [managed_dependency, managed_model_gateway] +extensions: + projectExchange: + version: 1 + accepts: ["org.example.review:project-summary"] + produces: ["org.example.review:report-draft"] + capabilities: + - id: log-summary + transport: openapi + path: /api/read-only/openapi.json + resource: "org.example.review:summary" + protocolVersion: "3.1" diff --git a/internal/pluginhub/planning.go b/internal/pluginhub/planning.go new file mode 100644 index 00000000..c9c81e7d --- /dev/null +++ b/internal/pluginhub/planning.go @@ -0,0 +1,254 @@ +// Package pluginhub manages the lifecycle of reviewed plugin applications. +package pluginhub + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "runtime" + "slices" + "strings" + "time" + + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/pluginhub/catalog" + "cyberstrike-ai/internal/pluginhub/manifest" + "cyberstrike-ai/internal/pluginhub/source" + + "github.com/google/uuid" +) + +var ( + ErrCatalogManifest = errors.New("catalog entry has no executable distribution declaration") + ErrManifestRequired = errors.New("a reviewed declaration is required") + ErrInvalidManifest = errors.New("invalid plugin declaration") + ErrSourceMismatch = errors.New("manifest repository or revision differs from inspection") + ErrUnapprovedArtifact = errors.New("the locked plugin version has not been approved") + ErrRuntimeUnavailable = errors.New("plugin operation worker is not available") + ErrInvalidRequest = errors.New("invalid plugin operation or installation request") + ErrStalePlan = errors.New("plugin plan failed integrity or scope validation") +) + +type PlanRequest struct { + Actor, InspectionID, CatalogID, InstallID, Driver, Isolation string + Manifest json.RawMessage +} + +type PlanResult struct { + Record database.PluginPlanRecord + ArtifactDigest string + HostApproved bool +} + +type planPolicy struct { + CatalogID string `json:"catalog_id,omitempty"` + Isolation string `json:"isolation"` + Permissions manifest.Permissions `json:"permissions"` + ArtifactDigest string `json:"artifact_digest"` +} + +type ArtifactLocker interface { + LockRelease(context.Context, manifest.Distribution, manifest.Platform) (manifest.Artifact, error) + LockImage(context.Context, manifest.Service, string, string) (manifest.LockedService, error) +} + +func (m *Manager) CreatePlan(ctx context.Context, request PlanRequest) (PlanResult, error) { + if (request.InspectionID == "") == (request.CatalogID == "") || request.Actor == "" || + (request.Driver != "" && !slices.Contains([]string{"auto", "release", "git", "container"}, request.Driver)) { + return PlanResult{}, ErrInvalidRequest + } + if request.Isolation == "" { + request.Isolation = "standard" + } + if request.Isolation != "standard" && request.Isolation != "strict" { + return PlanResult{}, ErrInvalidRequest + } + ctx, cancel := context.WithTimeout(ctx, 90*time.Second) + defer cancel() + now := time.Now().UTC() + var inspected source.Inspection + if request.CatalogID != "" { + if len(request.Manifest) != 0 { + return PlanResult{}, ErrInvalidRequest + } + data, ok := catalog.Manifest(request.CatalogID) + if !ok { + return PlanResult{}, ErrCatalogManifest + } + request.Manifest = data + } else { + payload, err := m.db.GetPluginInspection(ctx, request.InspectionID, request.Actor, now) + if err != nil { + return PlanResult{}, err + } + if err := json.Unmarshal([]byte(payload), &inspected); err != nil { + return PlanResult{}, err + } + if len(request.Manifest) == 0 { + request.Manifest = inspected.Manifest + } + } + if len(request.Manifest) == 0 { + return PlanResult{}, ErrManifestRequired + } + declaration, err := manifest.DecodeDeclaration(request.Manifest) + if err != nil { + return PlanResult{}, ErrInvalidManifest + } + repository, err := source.NormalizeGitHubRepository(declaration.Metadata.Repository) + if err != nil || (inspected.Repository != "" && inspected.Repository != repository) { + return PlanResult{}, ErrSourceMismatch + } + if request.InstallID != "" { + install, err := m.db.RuntimePluginInstall(ctx, request.InstallID) + if err != nil { + return PlanResult{}, err + } + if install.Source != repository || install.PluginID != declaration.Metadata.ID || install.Observed == "removed" { + return PlanResult{}, ErrSourceMismatch + } + } else { + request.InstallID = uuid.NewString() + } + a, platform, err := m.lockArtifact(ctx, declaration, inspected, repository, request) + if err != nil { + return PlanResult{}, err + } + artifactDigest := ArtifactDigest(a) + policy, err := json.Marshal(planPolicy{CatalogID: request.CatalogID, Isolation: request.Isolation, + Permissions: declaration.Permissions, ArtifactDigest: artifactDigest}) + if err != nil { + return PlanResult{}, err + } + now = time.Now().UTC() + if request.CatalogID != "" { + request.InspectionID = uuid.NewString() + payload, err := json.Marshal(source.Inspection{Repository: repository, Manifest: declaration.Canonical}) + if err != nil { + return PlanResult{}, err + } + if err := m.db.SavePluginInspection(ctx, request.InspectionID, request.Actor, string(payload), now, now.Add(10*time.Minute)); err != nil { + return PlanResult{}, err + } + } + plan := manifest.InstallPlan{ + Version: 1, ID: uuid.NewString(), InstallID: request.InstallID, ActorID: request.Actor, + ManifestSHA256: manifest.Digest(declaration.Canonical), PolicySHA256: manifest.Digest(policy), + ExpiresAt: now.Add(5 * time.Minute), Platform: platform, Isolation: request.Isolation, Artifact: a, + } + raw, err := json.Marshal(plan) + if err != nil { + return PlanResult{}, err + } + checked, err := manifest.DecodeInstallPlan(raw) + if err != nil { + return PlanResult{}, err + } + record := database.PluginPlanRecord{ID: plan.ID, InstallID: plan.InstallID, ActorUserID: plan.ActorID, InspectionID: request.InspectionID, + ManifestJSON: string(declaration.Canonical), ManifestDigest: plan.ManifestSHA256, PolicyJSON: string(policy), + PlanJSON: string(checked.Canonical), PlanDigest: manifest.Digest(checked.Canonical), ExpiresAt: plan.ExpiresAt} + if err := m.db.SavePluginPlan(ctx, record, now); err != nil { + return PlanResult{}, err + } + return PlanResult{Record: record, ArtifactDigest: artifactDigest, HostApproved: m.approved(plan.ManifestSHA256, artifactDigest)}, nil +} + +func (m *Manager) lockArtifact(ctx context.Context, doc *manifest.Declaration, inspected source.Inspection, repo string, request PlanRequest) (manifest.Artifact, manifest.Platform, error) { + auto := request.Driver == "" || request.Driver == "auto" + priority := []string{"release", "git", "container"} + if auto { + var available, unavailable []string + for _, name := range priority { + hasDistribution := slices.ContainsFunc(doc.Distribution, func(d manifest.Distribution) bool { + return d.Type == name + }) + if !hasDistribution || (request.Isolation == "strict" && name != "container") { + continue + } + probe, cancel := context.WithTimeout(ctx, 3*time.Second) + usable := m.drivers[name].Probe(probe, request.Isolation).Available + cancel() + if usable { + available = append(available, name) + } else { + unavailable = append(unavailable, name) + } + } + priority = append(available, unavailable...) + } + var firstError error + for _, driver := range priority { + if (!auto && request.Driver != driver) || (request.Isolation == "strict" && driver != "container") { + continue + } + for _, distribution := range doc.Distribution { + if distribution.Type != driver { + continue + } + platform := manifest.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH} + var artifact manifest.Artifact + var err error + switch driver { + case "release": + artifact, err = m.locker.LockRelease(ctx, distribution, platform) + case "git": + artifact, err = lockGit(distribution, repo, inspected) + case "container": + platform.OS = "linux" + artifact.Driver = "container" + for _, service := range distribution.Services { + var serviceLock manifest.LockedService + serviceLock, err = m.locker.LockImage(ctx, service, platform.OS, platform.Arch) + if err != nil { + break + } + artifact.Services = append(artifact.Services, serviceLock) + } + } + if err == nil { + return artifact, platform, nil + } + if !auto || errors.Is(err, ErrSourceMismatch) { + return manifest.Artifact{}, platform, err + } + if firstError == nil { + firstError = err + } + } + } + if firstError == nil { + firstError = source.ErrArtifactUnavailable + } + return manifest.Artifact{}, manifest.Platform{}, firstError +} + +func lockGit(distribution manifest.Distribution, canonical string, inspected source.Inspection) (manifest.Artifact, error) { + repo, err := source.NormalizeGitHubRepository(distribution.URL) + rev := distribution.Revision + if err != nil || repo != canonical || !manifest.IsCommitSHA(inspected.Commit) || + (rev != "" && rev != inspected.Commit && rev != inspected.ResolvedRef && + rev != strings.TrimPrefix(strings.TrimPrefix(inspected.ResolvedRef, "refs/heads/"), "refs/tags/")) { + return manifest.Artifact{}, fmt.Errorf("%w: repeat inspection using the declared ref", ErrSourceMismatch) + } + return manifest.Artifact{Driver: "git", Repository: repo, Commit: inspected.Commit, RequestedRef: inspected.ResolvedRef}, nil +} + +// ArtifactDigest identifies the complete ordered lock, including OCI child manifests. +func ArtifactDigest(a manifest.Artifact) string { + raw, _ := json.Marshal(a) + return manifest.Digest(raw) +} + +func (m *Manager) approved(document, artifact string) bool { + return slices.Contains(m.approvals[document], artifact) +} + +func (m *Manager) ApprovalPolicy() string { + return m.approvalPolicy +} + +func (m *Manager) CanConfirm(declaration, artifact string) bool { + return m.approvalPolicy == config.PluginApprovalAdminConfirm || m.approved(declaration, artifact) +} diff --git a/internal/pluginhub/runner/archive.go b/internal/pluginhub/runner/archive.go new file mode 100644 index 00000000..a3a82434 --- /dev/null +++ b/internal/pluginhub/runner/archive.go @@ -0,0 +1,141 @@ +package runner + +import ( + "archive/tar" + "archive/zip" + "compress/gzip" + "context" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "strings" +) + +const maxUnpacked = 1 << 30 +const maxArchiveEntries = 15000 + +type unpacker struct { + ctx context.Context + root *os.Root + strip int + remaining int64 + entries int +} + +func extract(ctx context.Context, path, destination, format string, strip int) error { + root, err := os.OpenRoot(destination) + if err != nil { + return err + } + defer root.Close() + extractor := unpacker{ctx: ctx, root: root, strip: strip, remaining: maxUnpacked} + if format == "zip" { + reader, err := zip.OpenReader(path) + if err != nil { + return err + } + defer reader.Close() + for _, entry := range reader.File { + if entry.UncompressedSize64 > maxUnpacked { + return fmt.Errorf("archive entry exceeds extraction limit") + } + stream, err := entry.Open() + if err != nil { + return err + } + err = extractor.write(entry.Name, entry.Mode(), int64(entry.UncompressedSize64), stream) + stream.Close() + if err != nil { + return err + } + } + return nil + } + if format != "tar_gz" { + return fmt.Errorf("unsupported release archive") + } + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + stream, err := gzip.NewReader(file) + if err != nil { + return err + } + defer stream.Close() + reader := tar.NewReader(stream) + for { + entry, err := reader.Next() + if err == io.EOF { + return nil + } + if err != nil { + return err + } + if entry.Typeflag != tar.TypeReg && entry.Typeflag != tar.TypeDir { + return fmt.Errorf("archive contains an unsupported entry") + } + if err := extractor.write(entry.Name, entry.FileInfo().Mode(), entry.Size, reader); err != nil { + return err + } + } +} + +func (u *unpacker) write(name string, mode fs.FileMode, size int64, content io.Reader) error { + if err := u.ctx.Err(); err != nil { + return err + } + u.entries++ + if u.entries > maxArchiveEntries || size < 0 || size > u.remaining { + return fmt.Errorf("archive extraction limit exceeded") + } + name = strings.TrimSuffix(strings.TrimPrefix(name, "./"), "/") + if name == "" && mode.IsDir() { + return nil + } + if !fs.ValidPath(name) || name == "." || strings.ContainsAny(name, "\\:") || len(name) > 512 { + return fmt.Errorf("archive contains an invalid path") + } + if !mode.IsRegular() && !mode.IsDir() { + return fmt.Errorf("archive contains an unsupported entry") + } + if u.strip == 1 { + _, child, present := strings.Cut(name, "/") + if !present && mode.IsDir() { + return nil + } + if !present { + return fmt.Errorf("archive entry lacks expected root directory") + } + name = child + } + filename, err := filepath.Localize(name) + if err != nil { + return fmt.Errorf("archive path unsupported on this host") + } + if mode.IsDir() { + return u.root.MkdirAll(filename, 0700) + } + parent := path.Dir(name) + if parent != "." { + if err := u.root.MkdirAll(filepath.FromSlash(parent), 0700); err != nil { + return err + } + } + permission := fs.FileMode(0600) | mode.Perm()&0100 + output, err := u.root.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, permission) + if err != nil { + return err + } + n, copyErr := io.Copy(output, io.LimitReader(content, size+1)) + closeErr := output.Close() + if copyErr != nil || closeErr != nil || n != size { + return fmt.Errorf("archive entry length or write failed") + } + u.remaining -= n + return nil +} diff --git a/internal/pluginhub/runner/docker.go b/internal/pluginhub/runner/docker.go new file mode 100644 index 00000000..b0b04422 --- /dev/null +++ b/internal/pluginhub/runner/docker.go @@ -0,0 +1,768 @@ +package runner + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "strconv" + "strings" + "sync" + "time" + + "cyberstrike-ai/internal/pluginhub/manifest" +) + +const installLabel = "io.csai.plugin.install" +const versionLabel = "io.csai.plugin.version" + +type dockerCommand func(context.Context, io.Writer, ...string) ([]byte, error) + +type dockerLogStream struct { + cancel context.CancelFunc + done <-chan struct{} +} + +type Docker struct { + run dockerCommand + mu sync.Mutex + follow map[string]dockerLogStream +} + +func NewDocker() *Docker { + return &Docker{run: localDockerCommand, follow: map[string]dockerLogStream{}} +} + +func localDockerCommand(ctx context.Context, output io.Writer, args ...string) ([]byte, error) { + executable, err := exec.LookPath("docker") + if err != nil { + return nil, err + } + target := os.Getenv("DOCKER_HOST") + if target == "" { + cmd := exec.CommandContext(ctx, executable, "context", "inspect", "--format", "{{.Endpoints.docker.Host}}") + value, err := cmd.Output() + if err != nil { + return nil, fmt.Errorf("local Docker context unavailable") + } + target = strings.TrimSpace(string(value)) + } + if !strings.HasPrefix(target, "unix:///") && !strings.HasPrefix(target, "npipe:////./pipe/") { + return nil, fmt.Errorf("Docker context is not a local socket") + } + cmd := exec.CommandContext(ctx, executable, append([]string{"--host", target}, args...)...) + env := []string{} + for _, name := range []string{"PATH", "HOME", "USERPROFILE", "SystemRoot", "DOCKER_CONFIG", "TMPDIR", "TMP", "TEMP"} { + if value, ok := os.LookupEnv(name); ok { + env = append(env, name+"="+value) + } + } + cmd.Env = env + var capture limitWriter + if output == nil { + cmd.Stdout = &capture + } else { + cmd.Stdout, cmd.Stderr = output, output + } + if err := cmd.Run(); err != nil { + return nil, fmt.Errorf("Docker %s failed: %w", args[0], err) + } + if capture.overflow { + return nil, fmt.Errorf("Docker output exceeded limit") + } + return capture.Bytes(), nil +} + +type limitWriter struct { + bytes.Buffer + overflow bool +} + +func (l *limitWriter) Write(p []byte) (int, error) { + if l.Len()+len(p) > 2<<20 { + l.overflow = true + return len(p), nil + } + return l.Buffer.Write(p) +} + +func runningInContainer() bool { + for _, path := range []string{"/.dockerenv", "/run/.containerenv"} { + if _, err := os.Stat(path); err == nil { + return true + } + } + return false +} + +func (d *Docker) Probe(ctx context.Context, isolation string) Probe { + return d.probe(ctx, isolation, false) +} + +func (d *Docker) probe(ctx context.Context, isolation string, compose bool) Probe { + guidance := "Install Docker Desktop and start its local engine." + if runtime.GOOS == "linux" { + guidance = "Install and start a local Docker Engine using your distribution instructions." + } + if runningInContainer() { + if _, err := os.Stat("/var/run/docker.sock"); err != nil && os.Getenv("DOCKER_HOST") == "" { + return Probe{Code: "docker_socket_missing", Guidance: "Configure a local Docker socket for CSAI or select an approved native distribution."} + } + } + out, err := d.run(ctx, nil, "version", "--format", "{{.Server.Os}}/{{.Server.Version}}") + if err != nil { + if errors.Is(err, exec.ErrNotFound) { + return Probe{Code: "docker_cli_missing", Guidance: guidance} + } + return Probe{Code: "docker_daemon_unavailable", Guidance: guidance + " Check your local context and socket permissions."} + } + osName, version, _ := strings.Cut(strings.TrimSpace(string(out)), "/") + major, _, _ := strings.Cut(version, ".") + majorNumber, _ := strconv.Atoi(major) + minimum := 24 + if isolation == "strict" { + minimum = 28 + } + if osName != "linux" || majorNumber < minimum { + return Probe{Code: "docker_engine_unsupported", Guidance: fmt.Sprintf( + "Use a local Linux-container Docker Engine version %d or later for %s isolation.", minimum, isolation)} + } + if compose { + if _, err := d.run(ctx, nil, "compose", "version", "--short"); err != nil { + return Probe{Code: "docker_compose_missing", Guidance: "Install the Docker Compose v2 CLI plugin."} + } + } + if majorNumber < 28 { + return Probe{Available: true, Guidance: "Docker versions before 28 can expose loopback-published ports to hosts on the same L2 network."} + } + return Probe{Available: true} +} + +func (d *Docker) ProbeCompose(ctx context.Context, isolation string) Probe { + return d.probe(ctx, isolation, true) +} + +func (d *Docker) Prepare(ctx context.Context, spec Spec) error { + distribution, err := spec.Distribution() + if err != nil { + return err + } + if probe := d.probe(ctx, spec.Plan.Isolation, distribution.Mode == "compose"); !probe.Available { + return fmt.Errorf("%s: %s", probe.Code, probe.Guidance) + } + platform := spec.Plan.Platform.OS + "/" + spec.Plan.Platform.Arch + for _, service := range spec.Plan.Artifact.Services { + image := service.Repository + "@" + service.ManifestDigest + info, err := d.run(ctx, nil, "image", "inspect", "--format", "{{.Os}}/{{.Architecture}}", image) + if err != nil || strings.TrimSpace(string(info)) != platform { + if _, err := d.run(ctx, nil, "pull", "--platform", platform, image); err != nil { + return err + } + info, err = d.run(ctx, nil, "image", "inspect", "--format", "{{.Os}}/{{.Architecture}}", image) + if err != nil || strings.TrimSpace(string(info)) != platform { + return fmt.Errorf("local image platform differs from locked platform") + } + } + } + return os.MkdirAll(spec.VersionDir(), 0700) +} + +type containerSpec struct { + service manifest.Service + name string + image string + env map[string]string + mounts []dockerMount +} + +type dockerMount struct { + Type string `json:"type"` + Source string `json:"source"` + Target string `json:"target"` + ReadOnly bool `json:"read_only"` +} + +func projectName(spec Spec) string { + return "csai-p-" + manifest.Digest([]byte(spec.InstallID + "/" + spec.VersionID))[:24] +} + +func serviceName(spec Spec, service string) string { + return projectName(spec) + "-" + manifest.Digest([]byte(service))[:10] +} + +func operatorLabels(spec Spec) map[string]string { + return map[string]string{installLabel: spec.InstallID, versionLabel: spec.VersionID} +} + +func containerSpecs(spec Spec, distribution manifest.Distribution, modelEnv map[string]string, modelSecrets []string) ([]containerSpec, []string, error) { + deps := map[string]manifest.Service{} + images := map[string]string{} + for _, service := range distribution.Services { + deps[service.Name] = service + } + for _, locked := range spec.Plan.Artifact.Services { + images[locked.Name] = locked.Repository + "@" + locked.ManifestDigest + } + var specs []containerSpec + secrets := slices.Clone(modelSecrets) + for _, service := range distribution.Services { + if images[service.Name] == "" { + return nil, nil, fmt.Errorf("container service is missing online lock") + } + env, masks, err := environment(spec, service.Environment, runtimeValues{ + host: "0.0.0.0", port: service.ContainerPort, dataDir: "/run/csai/data", fileDir: "/run/csai/secrets", container: true, + }, deps) + if err != nil { + return nil, nil, err + } + secrets = append(secrets, masks...) + if service.Role == "web" { + for name, value := range modelEnv { + env[name] = value + } + delete(env, "CSAI_PLUGIN_MODEL_CONFIG_DIR") + } + item := containerSpec{service: service, name: serviceName(spec, service.Name), image: images[service.Name], env: env} + for _, ref := range service.SecretEnv { + if ref.Kind == "file" { + target := "/run/csai/secrets/" + ref.SecretRef + if !containsMount(item.mounts, target) { + item.mounts = append(item.mounts, dockerMount{"bind", filepath.Join(spec.VersionDir(), "secret-mounts", ref.SecretRef), target, true}) + } + } + } + for _, mount := range service.DataVolumes { + if !allowedMountTarget(mount.MountPath) { + return nil, nil, fmt.Errorf("container data mount target is reserved") + } + directory := filepath.Join(spec.Root, "data", service.Name, mount.Name) + if err := os.MkdirAll(directory, 0700); err != nil { + return nil, nil, err + } + item.mounts = append(item.mounts, dockerMount{"bind", directory, mount.MountPath, false}) + } + for _, mount := range service.ConfigMounts { + if !allowedMountTarget(mount.MountPath) { + return nil, nil, fmt.Errorf("container config mount target is reserved") + } + // Phase B mounts only approved files already staged in the private version directory. + root := spec.VersionDir() + modelMount := false + if service.Role == "web" && spec.Declaration.LLM != nil { + for _, binding := range spec.Declaration.LLM.Bindings { + if binding.ConfigTemplate != nil && binding.ConfigTemplate.Path == mount.Source { + modelMount = true + break + } + } + if modelMount { + if spec.Model == nil || !slices.ContainsFunc(spec.Model.Templates, func(t ModelTemplate) bool { return t.Manifest.Path == mount.Source }) { + continue + } + root = filepath.Join(root, modelSubdir) + } + } + source, err := existingPath(root, filepath.FromSlash(mount.Source)) + if err != nil { + return nil, nil, err + } + item.mounts = append(item.mounts, dockerMount{"bind", source, mount.MountPath, true}) + } + specs = append(specs, item) + } + return specs, secrets, nil +} + +func allowedMountTarget(value string) bool { + for _, reserved := range []string{"/proc", "/sys", "/dev", "/run/csai/secrets", "/run/docker.sock", "/var/run/docker.sock"} { + if value == reserved || strings.HasPrefix(value, reserved+"/") { + return false + } + } + return value != "/" +} + +func containsMount(mounts []dockerMount, path string) bool { + for _, mount := range mounts { + if mount.Target == path { + return true + } + } + return false +} + +func (d *Docker) Start(ctx context.Context, spec Spec) (State, error) { + distribution, err := spec.Distribution() + if err != nil { + return State{}, err + } + if probe := d.probe(ctx, spec.Plan.Isolation, distribution.Mode == "compose"); !probe.Available { + return State{}, fmt.Errorf("%s: %s", probe.Code, probe.Guidance) + } + modelEnv, modelSecrets, err := renderModelConfig(spec) + if err != nil { + return State{}, err + } + items, secrets, err := containerSpecs(spec, distribution, modelEnv, modelSecrets) + if err != nil { + return State{}, err + } + if distribution.Mode == "compose" { + err = d.startCompose(ctx, spec, items) + } else if len(items) == 1 { + err = d.startSingle(ctx, spec, items[0]) + } else { + err = fmt.Errorf("Docker mode expects a single service") + } + if err != nil { + return State{}, err + } + state, err := d.Inspect(ctx, spec) + if err != nil || !state.Running { + return State{}, fmt.Errorf("Docker service has no verified loopback endpoint") + } + wait, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + for state.CheckHealth(wait, spec.Declaration.Web) != nil { + select { + case <-wait.Done(): + return State{}, fmt.Errorf("Docker WebUI readiness check failed") + case <-time.After(150 * time.Millisecond): + } + } + d.startLogs(spec, items, secrets) + return state, nil +} + +func composeFile(spec Spec) string { return filepath.Join(spec.VersionDir(), "compose.generated.json") } + +func (d *Docker) startCompose(ctx context.Context, spec Spec, items []containerSpec) error { + for _, network := range managedNetworks(spec) { + if _, err := d.findNetwork(ctx, spec, network); err != nil { + return err + } + } + private, web := privateNetwork(spec), webNetwork(spec) + if spec.Model != nil { + if err := d.ensureNetwork(ctx, spec, web); err != nil { + return err + } + for _, item := range items { + if item.service.Role == "web" { + if err := d.probeModel(ctx, spec, item, web); err != nil { + return err + } + break + } + } + } + services := map[string]any{} + for _, item := range items { + s := item.service + env := map[string]string{} + for key, value := range item.env { + env[key] = strings.ReplaceAll(value, "$", "$$") + } + networks := map[string]any{"private": map[string]any{"aliases": []string{s.Name}}} + cfg := map[string]any{ + "image": item.image, "container_name": item.name, "platform": spec.Plan.Platform.OS + "/" + spec.Plan.Platform.Arch, + "environment": env, "labels": operatorLabels(spec), + "mem_limit": strconv.Itoa(s.Resources.MemoryMiB) + "m", "pids_limit": s.Resources.PIDs, + "restart": "no", "cap_drop": []string{"ALL"}, "security_opt": []string{"no-new-privileges:true"}, + "networks": networks, + } + if len(item.mounts) > 0 { + cfg["volumes"] = item.mounts + } + if capabilities := initializationCaps(spec.Plan.Isolation, s); len(capabilities) > 0 { + cfg["cap_add"] = capabilities + } + if s.Role == "web" { + networks["web"] = map[string]any{} + cfg["ports"] = []string{"127.0.0.1::" + strconv.Itoa(s.ContainerPort)} + if spec.Model != nil && spec.Model.DockerHostMapping != "" { + cfg["extra_hosts"] = []string{spec.Model.DockerHostMapping} + } + } + if s.Healthcheck != nil { + h := s.Healthcheck + command := healthArguments(s) + for i, arg := range command { + command[i] = strings.ReplaceAll(arg, "$", "$$") + } + cfg["healthcheck"] = map[string]any{ + "test": append([]string{"CMD"}, command...), "interval": seconds(h.IntervalSeconds), "timeout": seconds(h.TimeoutSeconds), + "retries": h.Retries, "start_period": seconds(h.StartPeriodSeconds), + } + } + if len(s.DependsOn) != 0 { + conditions := map[string]any{} + for name, condition := range s.DependsOn { + conditions[name] = map[string]string{"condition": condition} + } + cfg["depends_on"] = conditions + } + services[s.Name] = cfg + } + webConfig := map[string]any{"driver": "bridge", "internal": web.internal, "name": web.name, "labels": operatorLabels(spec)} + if spec.Model != nil { + webConfig = map[string]any{"external": true, "name": web.name} + } + raw, err := json.Marshal(map[string]any{"services": services, "networks": map[string]any{ + "private": map[string]any{"driver": "bridge", "internal": private.internal, "name": private.name, "labels": operatorLabels(spec)}, + "web": webConfig, + }}) + if err != nil { + return err + } + if err := os.WriteFile(composeFile(spec), raw, 0600); err != nil { + return err + } + if spec.Model != nil { + defer os.Remove(composeFile(spec)) + } + _, err = d.run(ctx, nil, "compose", "--env-file", os.DevNull, "--project-directory", spec.VersionDir(), "-p", projectName(spec), "-f", composeFile(spec), "up", "-d", "--no-build", "--pull", "never", "--wait") + return err +} + +func (d *Docker) startSingle(ctx context.Context, spec Spec, item containerSpec) error { + web := webNetwork(spec) + if err := d.ensureNetwork(ctx, spec, web); err != nil { + return err + } + if spec.Model != nil { + if err := d.probeModel(ctx, spec, item, web); err != nil { + return err + } + } + var env strings.Builder + for key, value := range item.env { + env.WriteString(key + "=" + value + "\n") + } + path := filepath.Join(spec.VersionDir(), "docker.env") + if err := os.WriteFile(path, []byte(env.String()), 0600); err != nil { + return err + } + defer os.Remove(path) + s := item.service + args := []string{"create", "--name", item.name, "--platform", spec.Plan.Platform.OS + "/" + spec.Plan.Platform.Arch, + "--label", installLabel + "=" + spec.InstallID, "--label", versionLabel + "=" + spec.VersionID, + "--network", web.name, "--restart", "no", "--cap-drop", "ALL", "--security-opt", "no-new-privileges:true", + "--memory", strconv.Itoa(s.Resources.MemoryMiB) + "m", "--pids-limit", strconv.Itoa(s.Resources.PIDs), + "--publish", "127.0.0.1::" + strconv.Itoa(s.ContainerPort), "--env-file", path} + for _, capability := range initializationCaps(spec.Plan.Isolation, s) { + args = append(args, "--cap-add", capability) + } + + if spec.Model != nil && spec.Model.DockerHostMapping != "" { + args = append(args, "--add-host", spec.Model.DockerHostMapping) + } + for _, mount := range item.mounts { + if strings.ContainsAny(mount.Source+mount.Target, ",\r\n") { + return fmt.Errorf("unsupported Docker mount path") + } + value := "type=bind,source=" + mount.Source + ",target=" + mount.Target + if mount.ReadOnly { + value += ",readonly" + } + args = append(args, "--mount", value) + } + if _, err := d.run(ctx, nil, append(args, item.image)...); err != nil { + return err + } + if _, err := d.run(ctx, nil, "start", item.name); err != nil { + return err + } + h := s.Healthcheck + if h == nil { + return nil + } + for attempt := 0; attempt < h.Retries; attempt++ { + probeCtx, cancel := context.WithTimeout(ctx, time.Duration(h.TimeoutSeconds)*time.Second) + _, err := d.run(probeCtx, nil, append([]string{"exec", item.name}, healthArguments(s)...)...) + cancel() + if err == nil { + return nil + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(time.Duration(h.IntervalSeconds) * time.Second): + } + } + return fmt.Errorf("Docker container healthcheck failed") +} + +// Official image entrypoints may fix directory ownership and switch to the +// service user. Keep this bootstrap profile narrow even in standard mode. +func initializationCaps(isolation string, service manifest.Service) []string { + if isolation == "strict" { + return nil + } + capabilities := []string{"CHOWN", "DAC_OVERRIDE", "FOWNER", "SETGID", "SETUID"} + if service.Role == "web" { + capabilities = append(capabilities, "KILL") + } + if service.ContainerPort > 0 && service.ContainerPort < 1024 { + capabilities = append(capabilities, "NET_BIND_SERVICE") + } + return capabilities +} + +// Run the compatibility probe in the approved Web image on its actual bridge, +// before bringing up the Web process. No gateway credential enters probe argv. +func (d *Docker) probeModel(ctx context.Context, spec Spec, item containerSpec, bridge managedNetwork) error { + endpoint := spec.Model.GatewayRoot + "/_csai_gateway/ready" + base := []string{"run", "--rm", "--pull", "never", "--network", bridge.name, "--cap-drop", "ALL", + "--security-opt", "no-new-privileges:true", "--pids-limit", "16", "--memory", "96m"} + if spec.Model.DockerHostMapping != "" { + base = append(base, "--add-host", spec.Model.DockerHostMapping) + } + for _, probe := range [][]string{ + {"--entrypoint", "curl", item.image, "--fail", "--silent", "--max-time", "4", "--output", "/dev/null", endpoint}, + {"--entrypoint", "wget", item.image, "-q", "-T", "4", "-O", "/dev/null", endpoint}, + } { + child, cancel := context.WithTimeout(ctx, 8*time.Second) + _, err := d.run(child, nil, append(slices.Clone(base), probe...)...) + cancel() + if err == nil { + return nil + } + } + return fmt.Errorf("container cannot reach the private model gateway (curl or wget is required in the Web image)") +} + +func healthArguments(s manifest.Service) []string { + h := s.Healthcheck + switch h.Kind { + case "http": + return []string{"wget", "-q", "-O", "/dev/null", "http://127.0.0.1:" + strconv.Itoa(s.ContainerPort) + h.Path} + case "tcp": + return []string{"nc", "-z", "-w", strconv.Itoa(h.TimeoutSeconds), "127.0.0.1", strconv.Itoa(s.ContainerPort)} + default: + return append([]string(nil), h.Argv...) + } +} + +func seconds(n int) string { return strconv.Itoa(n) + "s" } + +type dockerInspect struct { + ID string + Config struct{ Labels map[string]string } + State struct{ Running bool } + HostConfig struct { + Memory int64 + PidsLimit int64 + } + NetworkSettings struct { + Ports map[string][]struct{ HostIP, HostPort string } + } +} + +func (d *Docker) find(ctx context.Context, name string, spec Spec) (*dockerInspect, error) { + raw, err := d.run(ctx, nil, "ps", "-aq", "--filter", "name=^/"+name+"$") + if err != nil || len(bytes.TrimSpace(raw)) == 0 { + return nil, err + } + raw, err = d.run(ctx, nil, "inspect", "--type", "container", name) + if err != nil { + return nil, err + } + var items []dockerInspect + if json.Unmarshal(raw, &items) != nil || len(items) != 1 || items[0].ID == "" || + items[0].Config.Labels[installLabel] != spec.InstallID || items[0].Config.Labels[versionLabel] != spec.VersionID { + return nil, fmt.Errorf("Docker container ownership not verified") + } + return &items[0], nil +} + +func (d *Docker) Inspect(ctx context.Context, spec Spec) (State, error) { + distribution, err := spec.Distribution() + if err != nil { + return State{}, err + } + var state State + for _, s := range distribution.Services { + item, err := d.find(ctx, serviceName(spec, s.Name), spec) + if err != nil || item == nil || !item.State.Running { + return State{}, err + } + if item.HostConfig.Memory != int64(s.Resources.MemoryMiB)<<20 || item.HostConfig.PidsLimit != int64(s.Resources.PIDs) { + return State{}, fmt.Errorf("Docker resource limits differ from approved limits") + } + if s.Role == "web" { + ports := item.NetworkSettings.Ports[strconv.Itoa(s.ContainerPort)+"/tcp"] + if len(ports) != 1 || ports[0].HostIP != "127.0.0.1" { + return State{}, fmt.Errorf("Docker port is not exclusively mapped to loopback") + } + port, err := strconv.Atoi(ports[0].HostPort) + if err != nil || port < 1 || port > 65535 { + return State{}, fmt.Errorf("invalid Docker port") + } + state = State{Running: true, Port: port, Endpoint: "http://" + net.JoinHostPort("127.0.0.1", ports[0].HostPort)} + } + } + return state, nil +} + +func (d *Docker) Stop(ctx context.Context, spec Spec) error { + d.mu.Lock() + stream, following := d.follow[spec.VersionID] + if following { + stream.cancel() + delete(d.follow, spec.VersionID) + } + d.mu.Unlock() + if following { + select { + case <-stream.done: + case <-ctx.Done(): + return ctx.Err() + } + } + distribution, err := spec.Distribution() + if err != nil { + return err + } + for _, s := range stopOrder(distribution.Services) { + item, err := d.find(ctx, serviceName(spec, s.Name), spec) + if err != nil { + return err + } + if item != nil { + if item.State.Running { + _, _ = d.run(ctx, nil, "stop", "--time", "5", item.ID) + } + if _, err := d.run(ctx, nil, "rm", "--force", item.ID); err != nil { + return err + } + } + } + var cleanupError error + for _, network := range managedNetworks(spec) { + found, err := d.findNetwork(ctx, spec, network) + if err == nil && found { + _, err = d.run(ctx, nil, "network", "rm", network.name) + } + cleanupError = errors.Join(cleanupError, err) + } + return cleanupError +} + +func stopOrder(services []manifest.Service) []manifest.Service { + byName := make(map[string]manifest.Service, len(services)) + for _, service := range services { + byName[service.Name] = service + } + seen := map[string]bool{} + var result []manifest.Service + var visit func(manifest.Service) + visit = func(value manifest.Service) { + if seen[value.Name] { + return + } + seen[value.Name] = true + for name := range value.DependsOn { + visit(byName[name]) + } + result = append(result, value) + } + for _, service := range services { + visit(service) + } + slices.Reverse(result) + return result +} + +type managedNetwork struct { + name string + internal bool +} + +func privateNetwork(spec Spec) managedNetwork { + // Keep the original project network name so reconciliation can retire it. + return managedNetwork{name: projectName(spec), internal: true} +} + +func webNetwork(spec Spec) managedNetwork { + return managedNetwork{name: projectName(spec) + "-web"} +} + +func managedNetworks(spec Spec) []managedNetwork { + return []managedNetwork{webNetwork(spec), privateNetwork(spec)} +} + +func (d *Docker) findNetwork(ctx context.Context, spec Spec, network managedNetwork) (bool, error) { + name := network.name + raw, err := d.run(ctx, nil, "network", "ls", "--filter", "name=^"+name+"$", "--format", "{{.Name}}") + if err != nil || strings.TrimSpace(string(raw)) == "" { + return false, err + } + raw, err = d.run(ctx, nil, "network", "inspect", name) + if err != nil { + return false, err + } + var result []struct { + Name string + Labels map[string]string + Internal bool + } + if json.Unmarshal(raw, &result) != nil || len(result) != 1 || result[0].Name != name || result[0].Internal != network.internal || + result[0].Labels[installLabel] != spec.InstallID || result[0].Labels[versionLabel] != spec.VersionID { + return false, fmt.Errorf("Docker network ownership not verified") + } + return true, nil +} + +func (d *Docker) ensureNetwork(ctx context.Context, spec Spec, network managedNetwork) error { + if exists, err := d.findNetwork(ctx, spec, network); err != nil || exists { + return err + } + args := []string{"network", "create", "--driver", "bridge", "--label", installLabel + "=" + spec.InstallID, + "--label", versionLabel + "=" + spec.VersionID} + if network.internal { + args = append(args, "--internal") + } + _, err := d.run(ctx, nil, append(args, network.name)...) + return err +} + +func (d *Docker) Remove(ctx context.Context, spec Spec) error { + if err := d.Stop(ctx, spec); err != nil { + return err + } + return os.RemoveAll(spec.VersionDir()) +} + +func (d *Docker) startLogs(spec Spec, items []containerSpec, secrets []string) { + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + d.mu.Lock() + if old, ok := d.follow[spec.VersionID]; ok { + old.cancel() + } + d.follow[spec.VersionID] = dockerLogStream{cancel: cancel, done: done} + d.mu.Unlock() + go func() { + defer close(done) + var group sync.WaitGroup + for _, item := range items { + group.Add(1) + go func(name string) { + defer group.Done() + logger := &lineLogger{emit: spec.Log, secrets: secrets} + _, _ = d.run(ctx, logger, "logs", "--tail", "50", "--follow", name) + logger.flush() + }(item.name) + } + group.Wait() + }() +} diff --git a/internal/pluginhub/runner/docker_test.go b/internal/pluginhub/runner/docker_test.go new file mode 100644 index 00000000..009b75a9 --- /dev/null +++ b/internal/pluginhub/runner/docker_test.go @@ -0,0 +1,261 @@ +package runner + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + + "cyberstrike-ai/internal/pluginhub/manifest" + + "github.com/google/uuid" +) + +func TestPluginDockerAndComposeFixtures(t *testing.T) { + t.Setenv("DOCKER_HOST", "unix:///fixture.sock") + for _, test := range []struct{ mode, isolation, version string }{ + {"docker", "standard", "24.0.9"}, {"compose", "standard", "27.5.1"}, + {"docker", "strict", "28.0.1"}, {"compose", "strict", "28.0.1"}, + } { + t.Run(test.mode+"/"+test.isolation, func(t *testing.T) { + mode := test.mode + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) + defer server.Close() + port := strings.TrimPrefix(server.URL, "http://127.0.0.1:") + digest := "sha256:" + strings.Repeat("1", 64) + web := manifest.Service{Name: "web", Role: "web", ContainerPort: 80, Resources: manifest.Resources{MemoryMiB: 128, PIDs: 64}, + Environment: manifest.Environment{StaticEnv: map[string]string{"GREETING": "hello $ demo"}}} + items := []manifest.Service{web} + locks := []manifest.LockedService{{Name: "web", Repository: "example.org/web", ManifestDigest: digest}} + if mode == "compose" { + web.SecretEnv = map[string]manifest.SecretUse{"DB_URI": {Kind: "connection_uri", SecretRef: "db-password", Scheme: "postgresql", Service: "db", Username: "app", Database: "demo"}} + web.DependsOn = map[string]string{"db": "service_healthy"} + items = []manifest.Service{web, {Name: "db", Role: "dependency", ContainerPort: 5432, Resources: manifest.Resources{MemoryMiB: 128, PIDs: 64}, + Environment: manifest.Environment{SecretEnv: map[string]manifest.SecretUse{"PASSWORD_FILE": {Kind: "file", SecretRef: "db-password"}}}, + Healthcheck: &manifest.Healthcheck{Kind: "tcp", TimeoutSeconds: 1, IntervalSeconds: 2, Retries: 2}}} + locks = append(locks, manifest.LockedService{Name: "db", Repository: "example.org/db", ManifestDigest: digest}) + } + spec := Spec{InstallID: uuid.NewString(), VersionID: uuid.NewString(), Root: t.TempDir(), + Declaration: &manifest.Declaration{Distribution: []manifest.Distribution{{Type: "container", Mode: mode, Services: items}}, + Web: manifest.Web{HealthPath: "/"}, Secrets: map[string]manifest.Secret{"db-password": {Generator: "random_base64url", Bytes: 32}}}, + Plan: &manifest.InstallPlan{Platform: manifest.Platform{OS: "linux", Arch: "arm64"}, Isolation: test.isolation, + Artifact: manifest.Artifact{Driver: "container", Services: locks}}} + d := NewDocker() + var mu sync.Mutex + started, removed := false, 0 + networks := map[string]bool{} + d.run = func(ctx context.Context, _ io.Writer, args ...string) ([]byte, error) { + mu.Lock() + defer mu.Unlock() + switch args[0] { + case "version": + return []byte("linux/" + test.version), nil + case "pull": + return nil, nil + case "image": + return []byte("linux/arm64"), nil + case "compose": + if args[1] == "version" { + return []byte("2.39.0"), nil + } + raw, err := os.ReadFile(composeFile(spec)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(raw), "service_healthy") || !strings.Contains(string(raw), "postgresql://app:") || + !strings.Contains(string(raw), "@db:5432/demo") || !strings.Contains(string(raw), "/run/csai/secrets/db-password") || + !strings.Contains(string(raw), `"internal":true`) || !strings.Contains(string(raw), `"pids_limit":64`) || + !strings.Contains(string(raw), "hello $$ demo") { + t.Fatal("normalized Compose fixture lacks isolation, dependencies or injected config") + } + var compose struct { + Services map[string]struct { + Networks map[string]json.RawMessage `json:"networks"` + CapAdd []string `json:"cap_add"` + CapDrop []string `json:"cap_drop"` + } + Networks map[string]struct { + Name string + Driver string + Internal bool + } + } + if err := json.Unmarshal(raw, &compose); err != nil { + t.Fatal(err) + } + if len(compose.Services["web"].Networks) != 2 || compose.Services["web"].Networks["private"] == nil || + compose.Services["web"].Networks["web"] == nil || len(compose.Services["db"].Networks) != 1 || + compose.Services["db"].Networks["private"] == nil { + t.Fatal("Compose exposed a dependency or omitted a WebUI attachment") + } + if len(compose.Networks) != 2 || !compose.Networks["private"].Internal || compose.Networks["web"].Internal { + t.Fatal("Compose did not separate the private and published bridges") + } + if !slices.Equal(compose.Services["web"].CapAdd, initializationCaps(test.isolation, items[0])) || + !slices.Equal(compose.Services["db"].CapAdd, initializationCaps(test.isolation, items[1])) || + !slices.Equal(compose.Services["web"].CapDrop, []string{"ALL"}) { + t.Fatal("Compose did not apply the expected capability profile") + } + started = true + for _, network := range compose.Networks { + if network.Driver != "bridge" { + t.Fatal("Compose network is not a bridge") + } + networks[network.Name] = network.Internal + } + return nil, nil + case "network": + switch args[1] { + case "ls": + name := strings.TrimSuffix(strings.TrimPrefix(args[3], "name=^"), "$") + if _, found := networks[name]; found { + return []byte(name), nil + } + return nil, nil + case "create": + networks[args[len(args)-1]] = slices.Contains(args, "--internal") + return nil, nil + case "inspect": + name := args[2] + return json.Marshal([]map[string]any{{"Name": name, "Labels": operatorLabels(spec), "Internal": networks[name]}}) + case "rm": + delete(networks, args[2]) + return nil, nil + } + case "create": + if !strings.Contains(strings.Join(args, " "), "127.0.0.1::80") || !strings.Contains(strings.Join(args, " "), "--pids-limit 64") { + t.Fatal("Docker publishing or limits missing") + } + internal, found := networks[webNetwork(spec).name] + if !found || internal { + t.Fatal("Single container is missing a published bridge") + } + var added []string + for i, arg := range args[:len(args)-1] { + if arg == "--cap-add" { + added = append(added, args[i+1]) + } + } + if !slices.Equal(added, initializationCaps(test.isolation, web)) { + t.Fatal("Docker did not apply the expected capability profile") + } + return nil, nil + case "start": + started = true + return nil, nil + case "ps": + if started { + return []byte("control-plane-owned"), nil + } + return nil, nil + case "inspect": + return []byte(fmt.Sprintf(`[{"Id":"owned","Config":{"Labels":{%q:%q,%q:%q}},"State":{"Running":true},"HostConfig":{"Memory":%d,"PidsLimit":64},"NetworkSettings":{"Ports":{"80/tcp":[{"HostIp":"127.0.0.1","HostPort":%q}]}}}]`, installLabel, spec.InstallID, versionLabel, spec.VersionID, 128<<20, port)), nil + case "logs": + return nil, nil + case "rm": + removed++ + if removed == len(items) { + started = false + } + return nil, nil + } + return nil, fmt.Errorf("unexpected command") + } + if err := d.Prepare(ctx, spec); err != nil { + t.Fatal(err) + } + state, err := d.Start(ctx, spec) + p, _ := strconv.Atoi(port) + if err != nil || state.Port != p || state.Endpoint != server.URL { + t.Fatalf("start: %+v %v", state, err) + } + if mode == "compose" { + data, err := os.ReadFile(filepath.Join(spec.VersionDir(), "secret-mounts", "db-password")) + if err != nil || len(data) < 32 { + t.Fatal("Compose secret file missing") + } + again, err := instanceSecret(spec, "db-password") + if err != nil || string(data) != again { + t.Fatal("cross-service secret was not shared") + } + } + if err := d.Remove(ctx, spec); err != nil { + t.Fatal(err) + } + mu.Lock() + if removed != len(items) || len(networks) != 0 { + t.Fatal("owned Docker resources survived removal") + } + mu.Unlock() + if _, err := os.Stat(spec.VersionDir()); !errors.Is(err, os.ErrNotExist) { + t.Fatal("staged Docker directory survived removal") + } + }) + } +} + +func TestPluginDockerMissingCLIReportsGuidance(t *testing.T) { + t.Setenv("DOCKER_HOST", "unix:///fixture.sock") + d := NewDocker() + d.run = func(context.Context, io.Writer, ...string) ([]byte, error) { return nil, exec.ErrNotFound } + if probe := d.Probe(context.Background(), "strict"); probe.Available || probe.Guidance == "" { + t.Fatalf("probe %+v", probe) + } +} + +func TestPluginRuntimeLogRedactsBearerJSONAndDSN(t *testing.T) { + input := "authorization: Bearer fixture-secret-1; \"db_password\":\"fixture-secret-2\" postgresql://user:fixture-secret-3@db:5432/test" + if output := SanitizeLog(input, nil); strings.Contains(output, "fixture-secret") || strings.Count(output, "[redacted]") != 3 { + t.Fatalf("sensitive fields preserved: %s", output) + } +} + +func TestPluginDockerVersionAndInitializationCapabilities(t *testing.T) { + t.Setenv("DOCKER_HOST", "unix:///fixture.sock") + for _, test := range []struct { + version, isolation string + available, advisory bool + }{ + {"23.0.6", "standard", false, false}, + {"24.0.9", "standard", true, true}, + {"27.5.1", "standard", true, true}, + {"27.5.1", "strict", false, false}, + {"28.0.1", "strict", true, false}, + } { + d := NewDocker() + d.run = func(context.Context, io.Writer, ...string) ([]byte, error) { + return []byte("linux/" + test.version), nil + } + for _, probe := range []Probe{d.Probe(context.Background(), test.isolation), d.ProbeCompose(context.Background(), test.isolation)} { + if probe.Available != test.available || (probe.Available && (probe.Guidance != "") != test.advisory) { + t.Fatalf("unexpected probe for %s/%s: %+v", test.version, test.isolation, probe) + } + } + } + dependency := manifest.Service{Role: "dependency", ContainerPort: 5432} + web := manifest.Service{Role: "web", ContainerPort: 80} + common := []string{"CHOWN", "DAC_OVERRIDE", "FOWNER", "SETGID", "SETUID"} + if got := initializationCaps("standard", dependency); !slices.Equal(got, common) { + t.Fatalf("unexpected database capabilities: %v", got) + } + if got := initializationCaps("standard", web); !slices.Equal(got, append(common, "KILL", "NET_BIND_SERVICE")) { + t.Fatalf("unexpected WebUI capabilities: %v", got) + } + if got := initializationCaps("strict", web); len(got) != 0 { + t.Fatalf("strict allowed extra capabilities: %v", got) + } +} diff --git a/internal/pluginhub/runner/environment.go b/internal/pluginhub/runner/environment.go new file mode 100644 index 00000000..0fdf0670 --- /dev/null +++ b/internal/pluginhub/runner/environment.go @@ -0,0 +1,224 @@ +package runner + +import ( + "bufio" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "fmt" + "io" + "net" + "net/url" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "sync" + + "cyberstrike-ai/internal/pluginhub/manifest" +) + +type runtimeValues struct { + host, dataDir, fileDir string + port int + container bool +} + +func environment(spec Spec, declared manifest.Environment, values runtimeValues, services map[string]manifest.Service) (map[string]string, []string, error) { + env := map[string]string{} + secrets := []string{} + for name, value := range declared.StaticEnv { + env[name] = value + } + for name, key := range declared.Env { + switch key { + case "listen_host": + env[name] = values.host + case "listen_port": + env[name] = strconv.Itoa(values.port) + case "data_dir": + env[name] = values.dataDir + case "web_base_path": + env[name] = spec.WebBasePath() + } + } + for name, ref := range declared.SecretEnv { + value, err := instanceSecret(spec, ref.SecretRef) + if err != nil { + return nil, nil, err + } + secrets = append(secrets, value) + switch ref.Kind { + case "file": + if values.container { + folder := filepath.Join(spec.VersionDir(), "secret-mounts") + if err := os.MkdirAll(folder, 0700); err != nil { + return nil, nil, err + } + if err := os.WriteFile(filepath.Join(folder, ref.SecretRef), []byte(value), 0444); err != nil && !sameSecret(filepath.Join(folder, ref.SecretRef), value) { + return nil, nil, err + } + } + env[name] = filepath.ToSlash(filepath.Join(values.fileDir, ref.SecretRef)) + case "connection_uri": + service, exists := services[ref.Service] + if !exists || service.ContainerPort < 1 { + return nil, nil, fmt.Errorf("Secret URI has no locked dependency service") + } + uri := url.URL{Scheme: ref.Scheme, User: url.UserPassword(ref.Username, value), + Host: net.JoinHostPort(ref.Service, strconv.Itoa(service.ContainerPort))} + if ref.Database != "" { + uri.Path = "/" + ref.Database + } + options := url.Values{} + for key, value := range ref.Options { + options.Set(key, value) + } + uri.RawQuery = options.Encode() + env[name] = uri.String() + secrets = append(secrets, env[name]) + default: + env[name] = value + } + } + return env, secrets, nil +} + +func sameSecret(path, expected string) bool { + data, err := os.ReadFile(path) + return err == nil && string(data) == expected +} + +func instanceSecret(spec Spec, name string) (string, error) { + definition, exists := spec.Declaration.Secrets[name] + if !exists || definition.Bytes < 16 || definition.Bytes > 128 { + return "", fmt.Errorf("unavailable Secret reference") + } + dir := filepath.Join(spec.Root, "secrets") + if err := os.MkdirAll(dir, 0700); err != nil { + return "", err + } + root, err := os.OpenRoot(dir) + if err != nil { + return "", err + } + defer root.Close() + data, err := root.ReadFile(name) + if err == nil && len(data) > 0 && len(data) <= 256 { + return string(data), nil + } + if !os.IsNotExist(err) { + return "", fmt.Errorf("instance Secret unavailable") + } + random := make([]byte, definition.Bytes) + if _, err := rand.Read(random); err != nil { + return "", err + } + value := base64.RawURLEncoding.EncodeToString(random) + if definition.Generator == "random_hex" { + value = hex.EncodeToString(random) + } + tmp, err := root.OpenFile(name+".new", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) + if err != nil { + return "", err + } + _, writeErr := io.WriteString(tmp, value) + closeErr := tmp.Close() + if writeErr != nil || closeErr != nil { + _ = root.Remove(name + ".new") + return "", fmt.Errorf("could not store instance Secret") + } + return value, root.Rename(name+".new", name) +} + +func cleanEnv(root string) ([]string, error) { + temp := filepath.Join(root, "tmp") + if err := os.MkdirAll(temp, 0700); err != nil { + return nil, err + } + env := []string{"PATH=" + os.Getenv("PATH"), "HOME=" + root, "USERPROFILE=" + root, + "TMPDIR=" + temp, "TMP=" + temp, "TEMP=" + temp, "GOTOOLCHAIN=local", "GOWORK=off", + "GOCACHE=" + filepath.Join(root, "go-cache"), "GOMODCACHE=" + filepath.Join(root, "go-mod")} + for _, key := range []string{"SystemRoot", "WINDIR", "PATHEXT", "LANG"} { + if value := os.Getenv(key); value != "" { + env = append(env, key+"="+value) + } + } + return env, nil +} + +func withEnv(env []string, values map[string]string) []string { + keys := make([]string, 0, len(values)) + for name := range values { + keys = append(keys, name) + } + slices.Sort(keys) + for _, name := range keys { + env = append(env, name+"="+values[name]) + } + return env +} + +var sensitiveLog = regexp.MustCompile(`(?i)(bearer[[:space:]]+|[a-z0-9_-]*(?:authorization|api[_-]?key|token|password|secret|cookie)["']?[[:space:]]*[:=][[:space:]]*["']?(?:bearer[[:space:]]+)?)[^[:space:],;"']+`) +var uriCredentials = regexp.MustCompile(`(://)[^[:space:]/@]+:[^[:space:]/@]+@`) + +func SanitizeLog(line string, secrets []string) string { + for _, secret := range secrets { + if secret != "" { + line = strings.ReplaceAll(line, secret, "[redacted]") + line = strings.ReplaceAll(line, url.QueryEscape(secret), "[redacted]") + } + } + line = sensitiveLog.ReplaceAllString(line, "${1}[redacted]") + line = uriCredentials.ReplaceAllString(line, "${1}[redacted]@") + line = strings.ToValidUTF8(line, "") + return strings.Map(func(r rune) rune { + if r < 32 && r != '\t' || r == 127 { + return -1 + } + return r + }, line) +} + +type lineLogger struct { + mu sync.Mutex + emit func(string) + secrets []string + line []byte + full bool +} + +func (l *lineLogger) Write(b []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + for _, c := range b { + if c == '\n' { + l.flush() + } else if len(l.line) < 8192 { + l.line = append(l.line, c) + } else { + l.full = true + } + } + return len(b), nil +} + +func (l *lineLogger) flush() { + if l.emit != nil && l.full { + l.emit("[oversize output omitted]") + } else if l.emit != nil && len(l.line) != 0 { + l.emit(SanitizeLog(string(l.line), l.secrets)) + } + l.line = l.line[:0] + l.full = false +} + +func scanOutput(stream io.Reader, logger *lineLogger) { + reader := bufio.NewReaderSize(stream, 8192) + _, _ = io.Copy(logger, reader) + logger.mu.Lock() + defer logger.mu.Unlock() + logger.flush() +} diff --git a/internal/pluginhub/runner/model_config.go b/internal/pluginhub/runner/model_config.go new file mode 100644 index 00000000..5fe13956 --- /dev/null +++ b/internal/pluginhub/runner/model_config.go @@ -0,0 +1,196 @@ +package runner + +import ( + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + + "cyberstrike-ai/internal/pluginhub/manifest" + + "gopkg.in/yaml.v3" +) + +type ModelConfig struct { + Env map[string]string + Templates []ModelTemplate + GatewayRoot string + DockerHostMapping string +} + +type ModelTemplate struct { + Manifest manifest.ConfigTemplate + Values map[string]string +} + +const modelSubdir = ".csai-model" + +func renderModelConfig(spec Spec) (map[string]string, []string, error) { + base := filepath.Join(spec.VersionDir(), modelSubdir) + // This workspace contains only generated configuration for this generation. + if err := os.RemoveAll(base); err != nil { + return nil, nil, err + } + if spec.Model == nil { + return nil, nil, nil + } + env := map[string]string{} + var sensitive []string + for k, v := range spec.Model.Env { + env[k] = v + sensitive = append(sensitive, v) + } + if len(spec.Model.Templates) > 0 { + if err := os.MkdirAll(base, 0700); err != nil { + return nil, nil, err + } + root, err := os.OpenRoot(base) + if err != nil { + return nil, nil, err + } + defer root.Close() + for _, template := range spec.Model.Templates { + data, err := renderTemplate(spec.VersionDir(), template) + if err != nil { + return nil, nil, err + } + target := filepath.FromSlash(template.Manifest.Path) + if !filepath.IsLocal(target) { + return nil, nil, fmt.Errorf("invalid plugin model template output path") + } + if dir := filepath.Dir(target); dir != "." { + if err := root.MkdirAll(dir, 0700); err != nil { + return nil, nil, err + } + } + f, err := root.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) + if err != nil { + return nil, nil, err + } + _, writeErr := f.Write(data) + closeErr := f.Close() + if writeErr != nil { + return nil, nil, writeErr + } + if closeErr != nil { + return nil, nil, closeErr + } + for _, value := range template.Values { + sensitive = append(sensitive, value) + } + } + env["CSAI_PLUGIN_MODEL_CONFIG_DIR"] = base + } + return env, sensitive, nil +} + +func renderTemplate(version string, t ModelTemplate) ([]byte, error) { + var original []byte + if t.Manifest.SourcePath != "" { + filename, err := existingPath(version, filepath.FromSlash(t.Manifest.SourcePath)) + if err != nil { + return nil, err + } + file, err := os.Open(filename) + if err != nil { + return nil, err + } + defer file.Close() + original, err = io.ReadAll(io.LimitReader(file, manifest.MaxDocumentBytes+1)) + if err != nil || len(original) > manifest.MaxDocumentBytes { + return nil, fmt.Errorf("plugin model template too large") + } + } + if t.Manifest.Format == "env" { + lines := strings.Split(strings.TrimSuffix(string(original), "\n"), "\n") + var out strings.Builder + for _, line := range lines { + if strings.TrimSpace(line) == "" { + continue + } + if key, _, ok := strings.Cut(line, "="); ok { + if _, replaced := t.Values[strings.TrimSpace(key)]; replaced { + continue + } + } + out.WriteString(line + "\n") + } + keys := make([]string, 0, len(t.Values)) + for k := range t.Values { + keys = append(keys, k) + } + sort.Strings(keys) + for _, key := range keys { + if strings.ContainsAny(key, "=\r\n") || strings.ContainsAny(t.Values[key], "\r\n\x00") { + return nil, fmt.Errorf("invalid model template environment value") + } + out.WriteString(key + "=" + t.Values[key] + "\n") + } + return []byte(out.String()), nil + } + var document any = map[string]any{} + if len(original) != 0 { + var err error + switch t.Manifest.Format { + case "json": + err = json.Unmarshal(original, &document) + case "yaml": + err = yaml.Unmarshal(original, &document) + default: + return nil, fmt.Errorf("unrecognized plugin model template format") + } + if err != nil { + return nil, fmt.Errorf("invalid plugin model template") + } + } + keys := make([]string, 0, len(t.Values)) + for k := range t.Values { + keys = append(keys, k) + } + sort.Strings(keys) + for _, key := range keys { + parts := strings.Split(strings.TrimPrefix(key, "/"), "/") + for i, v := range parts { + parts[i] = strings.ReplaceAll(strings.ReplaceAll(v, "~1", "/"), "~0", "~") + } + if err := replaceTemplateValue(document, parts, t.Values[key]); err != nil { + return nil, err + } + } + if t.Manifest.Format == "yaml" { + return yaml.Marshal(document) + } + return json.MarshalIndent(document, "", " ") +} + +func replaceTemplateValue(node any, parts []string, value string) error { + switch current := node.(type) { + case map[string]any: + if len(parts) == 1 { + current[parts[0]] = value + return nil + } + child := current[parts[0]] + if child == nil { + child = map[string]any{} + current[parts[0]] = child + } + return replaceTemplateValue(child, parts[1:], value) + case []any: + i, err := strconv.Atoi(parts[0]) + if err != nil || i < 0 || i >= len(current) { + return fmt.Errorf("invalid plugin model template array index") + } + if len(parts) == 1 { + current[i] = value + return nil + } + return replaceTemplateValue(current[i], parts[1:], value) + default: + return fmt.Errorf("invalid plugin model template pointer") + } +} diff --git a/internal/pluginhub/runner/model_config_test.go b/internal/pluginhub/runner/model_config_test.go new file mode 100644 index 00000000..638744e2 --- /dev/null +++ b/internal/pluginhub/runner/model_config_test.go @@ -0,0 +1,62 @@ +package runner + +import ( + "context" + "encoding/json" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "cyberstrike-ai/internal/pluginhub/manifest" +) + +func TestPluginModelTemplatesAndContainerPreflight(t *testing.T) { + spec := Spec{Root: t.TempDir(), InstallID: "fixture", VersionID: "version", + Plan: &manifest.InstallPlan{Platform: manifest.Platform{OS: "linux", Arch: "arm64"}}, + Model: &ModelConfig{GatewayRoot: "http://host.docker.internal:40331", DockerHostMapping: "host.docker.internal:host-gateway", + Env: map[string]string{"OPENAI_API_KEY": "private-fixture-token"}, Templates: []ModelTemplate{ + {Manifest: manifest.ConfigTemplate{Format: "json", Path: "nested/provider.json"}, Values: map[string]string{"/provider/key": "private-fixture-token"}}, + {Manifest: manifest.ConfigTemplate{Format: "yaml", Path: "settings.yaml"}, Values: map[string]string{"/model": "fixture-model"}}, + {Manifest: manifest.ConfigTemplate{Format: "env", Path: "model.env"}, Values: map[string]string{"API_KEY": "private-fixture-token"}}, + }}} + if err := os.MkdirAll(spec.VersionDir(), 0700); err != nil { + t.Fatal(err) + } + env, sensitive, err := renderModelConfig(spec) + if err != nil || len(sensitive) < 2 || env["OPENAI_API_KEY"] != "private-fixture-token" { + t.Fatalf("model env: %v", err) + } + root := env["CSAI_PLUGIN_MODEL_CONFIG_DIR"] + var config struct{ Provider struct{ Key string } } + raw, err := os.ReadFile(filepath.Join(root, "nested", "provider.json")) + if err != nil || json.Unmarshal(raw, &config) != nil || config.Provider.Key != "private-fixture-token" { + t.Fatal("JSON template not populated") + } + info, err := os.Stat(filepath.Join(root, "model.env")) + if err != nil || info.Mode().Perm()&0077 != 0 && os.PathSeparator == '/' { + t.Fatal("model config is accessible outside the runner account") + } + for _, check := range []struct{ path, text string }{{"settings.yaml", "fixture-model"}, {"model.env", "API_KEY=private-fixture-token"}} { + raw, err := os.ReadFile(filepath.Join(root, check.path)) + if err != nil || !strings.Contains(string(raw), check.text) { + t.Fatalf("template %s: %v", check.path, err) + } + } + d := NewDocker() + checked := false + d.run = func(_ context.Context, _ io.Writer, args ...string) ([]byte, error) { + joined := strings.Join(args, " ") + if !strings.Contains(joined, "--add-host host.docker.internal:host-gateway") || + !strings.Contains(joined, "/_csai_gateway/ready") || + strings.Contains(joined, "private-fixture-token") { + t.Fatal("unsafe or incomplete private network preflight") + } + checked = true + return nil, nil + } + if err := d.probeModel(context.Background(), spec, containerSpec{image: "fixture@sha256:locked"}, webNetwork(spec)); err != nil || !checked { + t.Fatalf("container preflight: %v", err) + } +} diff --git a/internal/pluginhub/runner/native.go b/internal/pluginhub/runner/native.go new file mode 100644 index 00000000..3b6bf4da --- /dev/null +++ b/internal/pluginhub/runner/native.go @@ -0,0 +1,449 @@ +package runner + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "net" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "strconv" + "strings" + "sync" + "time" + + "cyberstrike-ai/internal/pluginhub/manifest" + "cyberstrike-ai/internal/processguard" +) + +type Native struct { + driver string + downloader Downloader + gitProxyMode string + gitProxy string + mu sync.Mutex + processes map[string]*applicationProcess +} + +type applicationProcess struct { + version string + cmd *exec.Cmd + group processguard.Group + done chan struct{} + state State +} + +func NewNative(driver string, downloader Downloader, proxyMode, proxyURL string) *Native { + return &Native{driver: driver, downloader: downloader, gitProxyMode: proxyMode, gitProxy: proxyURL, + processes: map[string]*applicationProcess{}} +} + +func (n *Native) Probe(_ context.Context, isolation string) Probe { + if isolation == "strict" { + return Probe{Code: "strict_container_required", Guidance: "Choose a container distribution for strict isolation."} + } + if n.driver == "git" { + if _, err := exec.LookPath("git"); err != nil { + return Probe{Code: "git_missing", Guidance: "Install Git with your platform package manager and retry."} + } + } + return Probe{Available: true} +} + +func (n *Native) Prepare(ctx context.Context, spec Spec) error { + if !n.Probe(ctx, spec.Plan.Isolation).Available { + return fmt.Errorf("native runtime unavailable") + } + d, err := spec.Distribution() + if err != nil || d.Type != n.driver || spec.Declaration.Launch == nil { + return fmt.Errorf("native launch declaration unavailable") + } + platform := spec.Plan.Platform + if platform.OS != runtime.GOOS || platform.Arch != runtime.GOARCH { + return fmt.Errorf("native artifact platform differs from host") + } + parent := filepath.Dir(spec.VersionDir()) + if err := os.MkdirAll(parent, 0700); err != nil { + return err + } + if _, err := os.Stat(spec.VersionDir()); err == nil { + return nil + } + stage, err := os.MkdirTemp(parent, ".stage-") + if err != nil { + return err + } + defer os.RemoveAll(stage) + slog(spec, "Preparing approved "+n.driver+" artifact") + if n.driver == "release" { + err = n.unpackRelease(ctx, spec, d, stage) + } else { + err = n.buildGit(ctx, spec, d, stage) + } + if err != nil { + return err + } + if _, err := nativeEntrypoint(spec, d, stage); err != nil { + return err + } + return os.Rename(stage, spec.VersionDir()) +} + +func (n *Native) unpackRelease(ctx context.Context, spec Spec, d manifest.Distribution, stage string) error { + for _, asset := range d.Assets { + if asset.OS != spec.Plan.Platform.OS || asset.Arch != spec.Plan.Platform.Arch || asset.URL != spec.Plan.Artifact.AssetURL { + continue + } + file, err := os.CreateTemp(filepath.Dir(stage), ".archive-") + if err != nil { + return err + } + defer os.Remove(file.Name()) + sum, err := n.downloader.Download(ctx, asset.URL, file) + closeErr := file.Close() + if err != nil || closeErr != nil || sum != spec.Plan.Artifact.SHA256 { + return fmt.Errorf("release archive transfer or digest verification failed") + } + return extract(ctx, file.Name(), stage, asset.Format, asset.StripComponents) + } + return fmt.Errorf("approved release asset is unavailable for host platform") +} + +func (n *Native) buildGit(ctx context.Context, spec Spec, d manifest.Distribution, stage string) error { + if !manifest.IsCommitSHA(spec.Plan.Artifact.Commit) { + return fmt.Errorf("missing pinned commit") + } + if err := manifest.ValidateHTTPS(spec.Plan.Artifact.Repository); err != nil { + return err + } + home := filepath.Join(stage, ".csai-build") + if err := os.MkdirAll(home, 0700); err != nil { + return err + } + env, err := cleanEnv(home) + if err != nil { + return err + } + gitEnv := append(slices.Clone(env), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL="+os.DevNull, "GIT_TERMINAL_PROMPT=0") + switch n.gitProxyMode { + case "fixed": + gitEnv = append(gitEnv, "HTTPS_PROXY="+n.gitProxy, "https_proxy="+n.gitProxy) + case "", "system": + for _, name := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} { + if value, ok := os.LookupEnv(name); ok { + gitEnv = append(gitEnv, name+"="+value) + } + } + } + group, err := processguard.New("plugin-build-" + spec.VersionID) + if err != nil { + return err + } + defer closeGroup(group) + git := func(args ...string) error { + // Ignore host and repository-wide recursive fetching or alternate transports. + base := []string{"-c", "protocol.file.allow=never", "-c", "protocol.ext.allow=never", + "-c", "http.followRedirects=false", "-c", "submodule.recurse=false"} + return runBuild(ctx, group, spec, stage, gitEnv, "git", append(base, args...)) + } + if err := git("init", "--quiet", "--template="); err != nil { + return err + } + if err := git("fetch", "--quiet", "--depth=1", "--no-tags", "--no-recurse-submodules", + spec.Plan.Artifact.Repository, spec.Plan.Artifact.Commit); err != nil { + return err + } + data, err := os.ReadFile(filepath.Join(stage, ".git", "FETCH_HEAD")) + if err != nil || !strings.HasPrefix(string(data), spec.Plan.Artifact.Commit+"\t") { + return fmt.Errorf("Git fetch did not return the approved commit") + } + if err := git("checkout", "--quiet", "--detach", spec.Plan.Artifact.Commit); err != nil { + return err + } + // The build-time route prefix is public and contains no gateway credentials. + if spec.Declaration.Web.Route == "build_base_path" { + for name, value := range spec.Declaration.Launch.Environment.Env { + if value == "web_base_path" { + env = append(env, name+"="+spec.WebBasePath()) + } + } + } + // Place dependency caches beside the repository for reproducible build steps. + for _, step := range d.Build { + if !slices.Contains([]string{"go", "npm", "pnpm", "yarn", "cargo", "make", "python3", "node"}, step.Program) { + return fmt.Errorf("build tool is not supported") + } + dir := stage + if step.WorkDir != "" { + dir, err = existingPath(stage, step.WorkDir) + if err != nil { + return err + } + } + if err := runBuild(ctx, group, spec, dir, env, step.Program, step.Args); err != nil { + return err + } + } + return nil +} + +func runBuild(ctx context.Context, group processguard.Group, spec Spec, dir string, env []string, program string, args []string) error { + path, err := exec.LookPath(program) + if err != nil { + return fmt.Errorf("approved build program %s unavailable", program) + } + cmd := exec.CommandContext(ctx, path, args...) + cmd.Dir, cmd.Env = dir, env + log := &lineLogger{emit: spec.Log} + cmd.Stdout, cmd.Stderr = log, log + if err := startGuarded(group, cmd); err != nil { + return err + } + err = cmd.Wait() + log.flush() + if err != nil { + return fmt.Errorf("%s build step failed: %w", program, err) + } + return nil +} + +func nativeEntrypoint(spec Spec, distribution manifest.Distribution, versionDir string) (string, error) { + entry := spec.Declaration.Launch.Entrypoint + if distribution.Entrypoint != "" { + entry = distribution.Entrypoint + } + for _, asset := range distribution.Assets { + if asset.URL == spec.Plan.Artifact.AssetURL && asset.OS == runtime.GOOS && asset.Arch == runtime.GOARCH && asset.Entrypoint != "" { + entry = asset.Entrypoint + } + } + if runtime.GOOS == "windows" && filepath.Ext(entry) == "" { + entry += ".exe" + } + if distribution.OutputRoot != "" { + entry = filepath.Join(distribution.OutputRoot, entry) + } + resolved, err := existingPath(versionDir, entry) + if err != nil { + return "", err + } + info, err := os.Stat(resolved) + if err != nil || !info.Mode().IsRegular() || (runtime.GOOS != "windows" && info.Mode().Perm()&0100 == 0) { + return "", fmt.Errorf("approved native entrypoint is not executable") + } + return resolved, nil +} + +func (n *Native) Start(ctx context.Context, spec Spec) (State, error) { + d, err := spec.Distribution() + if err != nil { + return State{}, err + } + path, err := nativeEntrypoint(spec, d, spec.VersionDir()) + if err != nil { + return State{}, err + } + if state, err := n.Inspect(ctx, spec); err != nil || state.Running { + return state, err + } + if err := n.Stop(ctx, spec); err != nil { + return State{}, err + } + modelEnv, modelSecrets, err := renderModelConfig(spec) + if err != nil { + return State{}, err + } + for attempt := 0; attempt < 3; attempt++ { + state, err := n.startOnce(ctx, spec, path, modelEnv, modelSecrets) + if err == nil { + return state, nil + } + if cleanup := n.Stop(ctx, spec); cleanup != nil { + return State{}, cleanup + } + if ctx.Err() != nil { + return State{}, ctx.Err() + } + } + return State{}, fmt.Errorf("native application could not claim a healthy loopback endpoint") +} + +func (n *Native) startOnce(ctx context.Context, spec Spec, executable string, modelEnv map[string]string, modelSecrets []string) (State, error) { + listener, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + return State{}, err + } + defer listener.Close() + port := listener.Addr().(*net.TCPAddr).Port + dataDir := filepath.Join(spec.Root, "data") + if err := os.MkdirAll(dataDir, 0700); err != nil { + return State{}, err + } + env, err := cleanEnv(spec.Root) + if err != nil { + return State{}, err + } + values, secrets, err := environment(spec, spec.Declaration.Launch.Environment, + runtimeValues{host: "127.0.0.1", port: port, dataDir: dataDir, fileDir: filepath.Join(spec.Root, "secrets")}, nil) + if err != nil { + return State{}, err + } + for name, value := range modelEnv { + values[name] = value + } + secrets = append(secrets, modelSecrets...) + var nonce string + if spec.Declaration.Web.ReadyHeaderCheck { + var randomness [24]byte + if _, err := rand.Read(randomness[:]); err != nil { + return State{}, err + } + nonce = hex.EncodeToString(randomness[:]) + values["CSAI_PLUGIN_READY_TOKEN"] = nonce + secrets = append(secrets, nonce) + } + dir := spec.VersionDir() + if spec.Declaration.Launch.WorkDir != "" { + dir, err = existingPath(dir, spec.Declaration.Launch.WorkDir) + if err != nil { + return State{}, err + } + } + cmd := exec.Command(executable, spec.Declaration.Launch.Args...) + cmd.Dir, cmd.Env = dir, withEnv(env, values) + output := &lineLogger{emit: spec.Log, secrets: secrets} + cmd.Stdout, cmd.Stderr = output, output + group, err := processguard.New("plugin-app-" + spec.VersionID) + if err != nil { + return State{}, err + } + if err := listener.Close(); err != nil { + closeGroup(group) + return State{}, err + } + if err := startGuarded(group, cmd); err != nil { + closeGroup(group) + return State{}, err + } + + state := State{Running: true, Endpoint: "http://127.0.0.1:" + strconv.Itoa(port), Port: port, readyNonce: nonce} + process := &applicationProcess{version: spec.VersionID, cmd: cmd, group: group, done: make(chan struct{}), state: state} + n.mu.Lock() + if n.processes[spec.InstallID] != nil { + n.mu.Unlock() + go cmd.Wait() + closeGroup(group) + return State{}, fmt.Errorf("native process is already supervised") + } + n.processes[spec.InstallID] = process + n.mu.Unlock() + go func() { + _ = cmd.Wait() + output.flush() + close(process.done) + }() + wait, cancel := context.WithTimeout(ctx, 8*time.Second) + defer cancel() + for { + if err := state.CheckHealth(wait, spec.Declaration.Web); err == nil { + select { + case <-process.done: + return State{}, fmt.Errorf("native application exited during readiness") + default: + slog(spec, "Native application is healthy") + return state, nil + } + } + select { + case <-process.done: + return State{}, fmt.Errorf("native application exited before readiness") + case <-wait.Done(): + return State{}, fmt.Errorf("native readiness timed out") + case <-time.After(100 * time.Millisecond): + } + } +} + +func (n *Native) Inspect(_ context.Context, spec Spec) (State, error) { + n.mu.Lock() + defer n.mu.Unlock() + process := n.processes[spec.InstallID] + if process == nil { + return State{}, nil + } + if process.version != spec.VersionID { + return State{}, fmt.Errorf("native process belongs to a different version") + } + select { + case <-process.done: + return State{}, nil + default: + return process.state, nil + } +} + +func (n *Native) Stop(_ context.Context, spec Spec) error { + n.mu.Lock() + process := n.processes[spec.InstallID] + n.mu.Unlock() + if process == nil { + return nil + } + if process.version != spec.VersionID { + return nil + } + _ = process.cmd.Process.Signal(os.Interrupt) + select { + case <-process.done: + case <-time.After(300 * time.Millisecond): + } + if err := closeGroup(process.group); err != nil { + return err + } + n.mu.Lock() + if n.processes[spec.InstallID] == process { + delete(n.processes, spec.InstallID) + } + n.mu.Unlock() + return nil +} + +func (n *Native) Remove(ctx context.Context, spec Spec) error { + if err := n.Stop(ctx, spec); err != nil { + return err + } + return os.RemoveAll(spec.VersionDir()) +} + +func startGuarded(group processguard.Group, cmd *exec.Cmd) error { + launch, err := group.Prepare(cmd) + if err != nil { + return err + } + defer launch.Dispose() + if err := cmd.Start(); err != nil { + return err + } + if err := launch.Commit(); err != nil { + _ = cmd.Process.Kill() + _ = cmd.Wait() + return err + } + return nil +} + +func closeGroup(group processguard.Group) error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + return group.Close(ctx) +} + +func slog(spec Spec, message string) { + if spec.Log != nil { + spec.Log(message) + } +} diff --git a/internal/pluginhub/runner/native_test.go b/internal/pluginhub/runner/native_test.go new file mode 100644 index 00000000..f35f0800 --- /dev/null +++ b/internal/pluginhub/runner/native_test.go @@ -0,0 +1,228 @@ +package runner + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "cyberstrike-ai/internal/pluginhub/manifest" + + "github.com/google/uuid" +) + +type archiveDownloader []byte + +func (d archiveDownloader) Download(_ context.Context, _ string, output io.Writer) (string, error) { + _, err := output.Write(d) + return manifest.Digest(d), err +} + +func TestPluginNativeFixtureWeb(t *testing.T) { + port := os.Getenv("FIXTURE_PORT") + if port == "" { + return + } + if secret := os.Getenv("FIXTURE_SECRET"); secret != "" { + fmt.Fprintln(os.Stdout, "fixture output", secret) + } + http.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { + if nonce := os.Getenv("CSAI_PLUGIN_READY_TOKEN"); nonce != "" { + w.Header().Set("X-CSAI-Plugin-Ready", nonce) + } + _, _ = io.WriteString(w, "ready") + }) + if err := http.ListenAndServe(os.Getenv("FIXTURE_HOST")+":"+port, nil); err != nil { + t.Fatal(err) + } +} + +func TestPluginNativeReleaseAndPortLifecycle(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("fixture archives the parent test executable; Windows job behavior has separate platform tests") + } + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + binary, err := os.ReadFile(executable) + if err != nil { + t.Fatal(err) + } + archive := fixtureArchive(t, "fixture-web", binary) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + n := NewNative("release", archiveDownloader(archive), "direct", "") + declaration := &manifest.Declaration{ + Distribution: []manifest.Distribution{{Type: "release", Assets: []manifest.Asset{ + {OS: runtime.GOOS, Arch: runtime.GOARCH, URL: "https://example.com/web.tar.gz", Format: "tar_gz"}, + }}}, + Launch: &manifest.Launch{Entrypoint: "fixture-web", Args: []string{"-test.run=^TestPluginNativeFixtureWeb$"}, + Environment: manifest.Environment{Env: map[string]string{"FIXTURE_HOST": "listen_host", "FIXTURE_PORT": "listen_port"}, + SecretEnv: map[string]manifest.SecretUse{"FIXTURE_SECRET": {Kind: "value", SecretRef: "fixture-secret"}}}}, + Web: manifest.Web{HealthPath: "/health"}, + Secrets: map[string]manifest.Secret{"fixture-secret": {Generator: "random_hex", Bytes: 20}}, + } + var calls sync.Mutex + var lines []string + spec := Spec{InstallID: uuid.NewString(), VersionID: uuid.NewString(), Root: t.TempDir(), Declaration: declaration, + Plan: &manifest.InstallPlan{Isolation: "standard", Platform: manifest.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH}, + Artifact: manifest.Artifact{Driver: "release", AssetURL: "https://example.com/web.tar.gz", SHA256: manifest.Digest(archive)}}, + Log: func(line string) { calls.Lock(); defer calls.Unlock(); lines = append(lines, line) }} + spec.Plan.Artifact.SHA256 = strings.Repeat("0", 64) + if err := n.Prepare(ctx, spec); err == nil { + t.Fatal("preparation accepted archive with mismatched SHA256") + } + spec.Plan.Artifact.SHA256 = manifest.Digest(archive) + if err := n.Prepare(ctx, spec); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = n.Stop(context.Background(), spec) }) + state, err := n.Start(ctx, spec) + if err != nil || state.Port <= 0 || !state.Running { + t.Fatalf("start: %+v %v", state, err) + } + if state.readyNonce != "" { + t.Fatal("default readiness generated a custom header token") + } + if err := state.CheckHealth(ctx, declaration.Web); err != nil { + t.Fatal(err) + } + if err := n.Stop(ctx, spec); err != nil { + t.Fatal(err) + } + if err := state.CheckHealth(ctx, declaration.Web); err == nil { + t.Fatal("native listener retained after stop") + } + declaration.Web.ReadyHeaderCheck = true + withHeader, err := n.Start(ctx, spec) + if err != nil || withHeader.readyNonce == "" { + t.Fatalf("opt-in native header check did not activate: %v", err) + } + if err := withHeader.CheckHealth(ctx, declaration.Web); err != nil { + t.Fatal(err) + } + sanitized := func() string { calls.Lock(); defer calls.Unlock(); return strings.Join(lines, "\n") }() + if !strings.Contains(sanitized, "fixture output [redacted]") { + t.Fatalf("secret line was not redacted: %s", sanitized) + } + if err := n.Remove(ctx, spec); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(spec.VersionDir()); !os.IsNotExist(err) { + t.Fatalf("artifact retained: %v", err) + } +} + +func TestPluginHealthRedirectAndHeaderCheck(t *testing.T) { + var redirected atomic.Bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/health": + w.Header().Set("X-CSAI-Plugin-Ready", "expected") + http.Redirect(w, r, "/login", http.StatusFound) + case "/unavailable": + http.Error(w, "unavailable", http.StatusServiceUnavailable) + default: + redirected.Store(true) + } + })) + defer server.Close() + + state := State{Running: true, Endpoint: server.URL, readyNonce: "expected"} + web := manifest.Web{HealthPath: "/health", ReadyHeaderCheck: true} + if err := state.CheckHealth(context.Background(), web); err == nil { + t.Fatal("default readiness accepted a login redirect") + } + web.AllowHealthRedirect = true + if err := state.CheckHealth(context.Background(), web); err != nil { + t.Fatal(err) + } + if redirected.Load() { + t.Fatal("readiness followed a login redirect") + } + state.readyNonce = "incorrect" + if err := state.CheckHealth(context.Background(), web); err == nil { + t.Fatal("readiness accepted a wrong header") + } + state.readyNonce = "" + web.HealthPath = "/unavailable" + if err := state.CheckHealth(context.Background(), web); err == nil { + t.Fatal("redirect allowance accepted a server error") + } +} + +func TestPluginGitFixtureBuildsPinnedSnapshot(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("POSIX mock of the Git transport") + } + bin := t.TempDir() + commit := strings.Repeat("b", 40) + script := "#!/bin/sh\nset -eu\ncase \"$*\" in\n*" + "' init '*" + ") mkdir -p .git ;;\n" + + "*' fetch '* ) printf '" + commit + "\\tfixture\\n' > .git/FETCH_HEAD ;;\n" + + "*' checkout '* ) printf 'module example.org/demo\\n\\ngo 1.25.0\\n' > go.mod\n" + + "printf 'package main\\nfunc main() {}\\n' > main.go ;;\n*) exit 1 ;;\nesac\n" + if err := os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + n := NewNative("git", nil, "direct", "") + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + spec := Spec{InstallID: uuid.NewString(), VersionID: uuid.NewString(), Root: t.TempDir(), + Declaration: &manifest.Declaration{Launch: &manifest.Launch{Entrypoint: "fixture-web"}, + Distribution: []manifest.Distribution{{Type: "git", Build: []manifest.BuildStep{{Program: "go", Args: []string{"build", "-buildvcs=false", "-o", "fixture-web", "."}}}}}}, + Plan: &manifest.InstallPlan{Isolation: "standard", Platform: manifest.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH}, + Artifact: manifest.Artifact{Driver: "git", Repository: "https://github.com/example/passive-web", Commit: commit}}, Log: func(s string) { t.Log(s) }} + if err := n.Prepare(ctx, spec); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(spec.VersionDir(), "fixture-web")); err != nil { + t.Fatal(err) + } + if n.Probe(ctx, "strict").Available { + t.Fatal("native driver accepted strict isolation") + } +} + +func TestPluginArchiveRejectsTraversal(t *testing.T) { + archive := t.TempDir() + "/invalid.tar.gz" + if err := os.WriteFile(archive, fixtureArchive(t, "../outside", []byte("sample")), 0600); err != nil { + t.Fatal(err) + } + if err := extract(context.Background(), archive, t.TempDir(), "tar_gz", 0); err == nil { + t.Fatal("archive traversal accepted") + } +} + +func fixtureArchive(t *testing.T, name string, data []byte) []byte { + t.Helper() + var archive bytes.Buffer + g := gzip.NewWriter(&archive) + writer := tar.NewWriter(g) + if err := writer.WriteHeader(&tar.Header{Name: name, Mode: 0700, Size: int64(len(data)), Typeflag: tar.TypeReg}); err != nil { + t.Fatal(err) + } + if _, err := writer.Write(data); err != nil { + t.Fatal(err) + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + if err := g.Close(); err != nil { + t.Fatal(err) + } + return archive.Bytes() +} diff --git a/internal/pluginhub/runner/runner.go b/internal/pluginhub/runner/runner.go new file mode 100644 index 00000000..dc2369b8 --- /dev/null +++ b/internal/pluginhub/runner/runner.go @@ -0,0 +1,132 @@ +// Package runner supervises approved plugin applications. +package runner + +import ( + "context" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "time" + + "cyberstrike-ai/internal/pluginhub/manifest" +) + +type Driver interface { + Probe(context.Context, string) Probe + Prepare(context.Context, Spec) error + Start(context.Context, Spec) (State, error) + Inspect(context.Context, Spec) (State, error) + Stop(context.Context, Spec) error + Remove(context.Context, Spec) error +} + +type Probe struct { + Available bool `json:"available"` + Code string `json:"code,omitempty"` + Guidance string `json:"guidance,omitempty"` +} + +type Spec struct { + Model *ModelConfig + InstallID string + VersionID string + Root string + Declaration *manifest.Declaration + Plan *manifest.InstallPlan + Log func(string) +} + +func (s Spec) WebBasePath() string { + if s.Declaration.Web.Route == "build_base_path" { + return "/apps/" + s.InstallID + } + return "/" +} + +func (s Spec) VersionDir() string { return filepath.Join(s.Root, "versions", s.VersionID) } + +func (s Spec) Distribution() (manifest.Distribution, error) { + for _, distribution := range s.Declaration.Distribution { + if distribution.Type == s.Plan.Artifact.Driver { + return distribution, nil + } + } + return manifest.Distribution{}, fmt.Errorf("locked driver missing from approved declaration") +} + +type State struct { + Running bool + Endpoint string + Port int + readyNonce string +} + +type Downloader interface { + Download(context.Context, string, io.Writer) (string, error) +} + +func (s State) CheckHealth(ctx context.Context, web manifest.Web) error { + if !s.Running { + return fmt.Errorf("application is not running") + } + client := &http.Client{ + Transport: &http.Transport{DisableKeepAlives: true}, + Timeout: time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + } + request, err := http.NewRequestWithContext(ctx, http.MethodGet, s.Endpoint+web.HealthPath, nil) + if err != nil { + return err + } + response, err := client.Do(request) + if err != nil { + return err + } + defer response.Body.Close() + status := response.StatusCode + success := status >= 200 && status < 300 + redirect := web.AllowHealthRedirect && status >= 300 && status < 400 && response.Header.Get("Location") != "" + if (!success && !redirect) || + (s.readyNonce != "" && response.Header.Get("X-CSAI-Plugin-Ready") != s.readyNonce) { + return fmt.Errorf("readiness check failed") + } + return nil +} + +func existingPath(root, relative string) (string, error) { + if !filepath.IsLocal(relative) { + return "", fmt.Errorf("invalid artifact path") + } + dir, err := os.OpenRoot(root) + if err != nil { + return "", err + } + defer dir.Close() + if _, err := dir.Stat(relative); err != nil { + return "", err + } + // Do not accept even in-root links for executing code or mounting config. + path := root + for _, part := range splitPath(relative) { + path = filepath.Join(path, part) + info, err := os.Lstat(path) + if err != nil || info.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("artifact path is missing or a symlink") + } + } + return path, nil +} + +func splitPath(relative string) []string { + var result []string + for relative != "." && relative != "" { + dir, base := filepath.Split(relative) + result = append([]string{base}, result...) + relative = filepath.Clean(dir) + } + return result +} diff --git a/internal/pluginhub/services.go b/internal/pluginhub/services.go new file mode 100644 index 00000000..f6784143 --- /dev/null +++ b/internal/pluginhub/services.go @@ -0,0 +1,182 @@ +package pluginhub + +import ( + "context" + "crypto/tls" + "fmt" + "net/http" + "time" + + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/pluginhub/llmgateway" + "cyberstrike-ai/internal/pluginhub/manifest" + "cyberstrike-ai/internal/pluginhub/runner" + "cyberstrike-ai/internal/pluginhub/webproxy" + "cyberstrike-ai/internal/security" +) + +func (m *Manager) ConfigureServices(auth *security.AuthManager, snapshot llmgateway.ConfigSnapshot) { + m.webAuth = auth + if auth != nil { + m.web.SetPlatformTokenCheck(func(raw string) bool { _, ok := auth.ValidateToken(raw); return ok }) + } + m.gateway.SetSnapshot(snapshot) +} + +func (m *Manager) StartServices(bindHost string, mainPort int, tlsConfig *tls.Config) error { + m.web.Start(bindHost, mainPort, tlsConfig) + return m.gateway.Start() +} + +func (m *Manager) CloseServices() { + m.web.Shutdown() + m.gateway.Close() +} + +func (m *Manager) WebHandler(main http.Handler) http.Handler { return m.web.Wrap(main) } + +func (m *Manager) IssueEmbed(r *http.Request, id, token string, expires time.Time) (webproxy.Embed, error) { + return m.web.Issue(r, id, token, expires) +} + +func (m *Manager) webAuthorization(ctx context.Context, id, token string) bool { + if m.webAuth == nil { + return false + } + session, ok := m.webAuth.ValidateToken(token) + return ok && session.Permissions["plugins:use"] && m.db.UserCanAccessResource(session.UserID, session.ScopeFor("plugins:use"), "plugin_install", id) +} + +func (m *Manager) webTarget(ctx context.Context, id string) (webproxy.Target, error) { + i, err := m.db.RuntimePluginInstall(ctx, id) + if err != nil || i.Observed != "healthy" || i.Endpoint == "" || i.Version == "" { + return webproxy.Target{}, webproxy.ErrUnavailable + } + spec, _, err := m.spec(ctx, id, i.Version) + if err != nil { + return webproxy.Target{}, webproxy.ErrUnavailable + } + return webproxy.Target{Endpoint: i.Endpoint, Generation: i.Generation, Route: spec.Declaration.Web.Route, + EntryPath: spec.Declaration.Web.EntryPath, ApplicationBearer: spec.Declaration.Access.ApplicationBearer}, nil +} + +func (m *Manager) AvailableLLMChannels() (string, []llmgateway.ChannelOption) { + return m.gateway.AvailableChannels() +} + +type InstallDetail struct { + database.PluginInstallSummary + Version string `json:"version,omitempty"` + Repository string `json:"repository,omitempty"` + Summary string `json:"summary,omitempty"` + License string `json:"license,omitempty"` + Generation int64 `json:"generation"` + Web *manifest.Web `json:"web,omitempty"` + Permissions *manifest.Permissions `json:"permissions,omitempty"` + Extensions *manifest.Extensions `json:"extensions,omitempty"` + LLMDeclared *manifest.LLM `json:"llm_declared,omitempty"` + LLMBindings []database.PluginLLMBinding `json:"llm_bindings"` + ProxyMode string `json:"proxy_mode"` +} + +func (m *Manager) InstallDetail(ctx context.Context, id string) (InstallDetail, error) { + summary, err := m.db.GetPluginInstall(ctx, id) + if err != nil { + return InstallDetail{}, err + } + detail := InstallDetail{ + PluginInstallSummary: summary, + LLMBindings: []database.PluginLLMBinding{}, + ProxyMode: m.proxyMode, + } + if bindings, err := m.db.PluginLLMBindings(ctx, id); err == nil && len(bindings) > 0 { + detail.LLMBindings = bindings + } + if rt, err := m.db.RuntimePluginInstall(ctx, id); err == nil { + detail.Generation = rt.Generation + if rt.Version != "" { + if spec, _, err := m.spec(ctx, id, rt.Version); err == nil && spec.Declaration != nil { + decl := spec.Declaration + detail.Version = decl.Metadata.Version + detail.Repository = decl.Metadata.Repository + detail.Summary = decl.Metadata.Summary + detail.License = decl.Metadata.License + web := decl.Web + perms := decl.Permissions + ext := decl.Extensions + detail.Web = &web + detail.Permissions = &perms + detail.Extensions = &ext + detail.LLMDeclared = decl.LLM + } + } + } + return detail, nil +} + +func (m *Manager) PatchLLM(ctx context.Context, id string, patch llmgateway.Patch) ([]database.PluginLLMBinding, bool, error) { + install, err := m.db.RuntimePluginInstall(ctx, id) + if err != nil { + return nil, false, err + } + if install.Version == "" || install.Observed == "removed" { + return nil, false, llmgateway.ErrBinding + } + spec, _, err := m.spec(ctx, id, install.Version) + if err != nil { + return nil, false, err + } + bindings, err := m.gateway.Patch(ctx, id, spec.Declaration.LLM, patch) + return bindings, install.Observed == "healthy" || install.Observed == "starting", err +} + +func (m *Manager) stopTraffic(ctx context.Context, id string) error { + err := m.db.BlockPluginTraffic(ctx, m.owner, id) + m.revokeServices(ctx, id) + return err +} + +func (m *Manager) revokeServices(ctx context.Context, id string) { + m.web.Revoke(id) + _ = m.gateway.Revoke(ctx, id) +} + +func (m *Manager) startPlugin(ctx context.Context, driver runner.Driver, spec runner.Spec) (runner.State, error) { + m.revokeServices(ctx, spec.InstallID) + generation, err := m.db.BeginPluginLaunch(ctx, m.owner, spec.InstallID) + if err != nil { + return runner.State{}, err + } + credentials, root, hostMapping, err := m.gateway.Issue(ctx, spec.InstallID, generation, spec.Declaration.LLM, spec.Plan.Artifact.Driver == "container") + if err != nil { + m.revokeAfterStartFailure(spec.InstallID) + return runner.State{}, fmt.Errorf("prepare model gateway binding: %w", err) + } + if len(credentials) > 0 { + cfg := &runner.ModelConfig{Env: map[string]string{}, GatewayRoot: root, DockerHostMapping: hostMapping} + for _, credential := range credentials { + for name, slot := range credential.Binding.Env { + cfg.Env[name] = credential.Values[slot] + } + if template := credential.Binding.ConfigTemplate; template != nil { + values := map[string]string{} + for name, slot := range template.Values { + values[name] = credential.Values[slot] + } + cfg.Templates = append(cfg.Templates, runner.ModelTemplate{Manifest: *template, Values: values}) + } + } + spec.Model = cfg + } + state, err := driver.Start(ctx, spec) + if err != nil { + m.revokeAfterStartFailure(spec.InstallID) + } + return state, err +} + +func (m *Manager) revokeAfterStartFailure(id string) { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + m.revokeServices(ctx, id) +} diff --git a/internal/pluginhub/snapshot.go b/internal/pluginhub/snapshot.go new file mode 100644 index 00000000..da497aa0 --- /dev/null +++ b/internal/pluginhub/snapshot.go @@ -0,0 +1,108 @@ +package pluginhub + +import ( + "context" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + + "cyberstrike-ai/internal/pluginhub/runner" +) + +const maxSnapshotBytes = 1 << 30 +const maxSnapshotFiles = 12000 + +func snapshotPath(spec runner.Spec) string { + return filepath.Join(spec.Root, ".rollback-"+spec.VersionID) +} + +func snapshotData(ctx context.Context, spec runner.Spec) error { + source := filepath.Join(spec.Root, "data") + if err := os.MkdirAll(source, 0700); err != nil { + return err + } + temp, err := os.MkdirTemp(spec.Root, ".snapshot-") + if err != nil { + return err + } + defer os.RemoveAll(temp) + if err := copyData(ctx, source, temp); err != nil { + return err + } + return os.Rename(temp, snapshotPath(spec)) +} + +func copyData(ctx context.Context, source, destination string) error { + root, err := os.OpenRoot(source) + if err != nil { + return err + } + defer root.Close() + remaining, count := int64(maxSnapshotBytes), 0 + return fs.WalkDir(root.FS(), ".", func(name string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if err := ctx.Err(); err != nil { + return err + } + info, err := entry.Info() + if err != nil { + return err + } + if info.Mode()&os.ModeSymlink != 0 || (!info.IsDir() && !info.Mode().IsRegular()) { + return fmt.Errorf("snapshot data contains an unsupported file type") + } + count++ + if count > maxSnapshotFiles || info.Size() < 0 || info.Size() > remaining { + return fmt.Errorf("snapshot data exceeds size or entry limits") + } + target := filepath.Join(destination, filepath.FromSlash(name)) + if info.IsDir() { + return os.MkdirAll(target, info.Mode().Perm()&0770|0700) + } + in, err := root.Open(name) + if err != nil { + return err + } + defer in.Close() + out, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, info.Mode().Perm()&0770|0600) + if err != nil { + return err + } + n, copyErr := io.Copy(out, io.LimitReader(in, remaining+1)) + closeErr := out.Close() + if copyErr != nil || closeErr != nil || n != info.Size() { + return fmt.Errorf("snapshot file changed or could not be copied") + } + remaining -= n + return nil + }) +} + +func restoreData(spec runner.Spec) error { + if err := validSnapshotVersion(spec); err != nil { + return err + } + backup := snapshotPath(spec) + data := filepath.Join(spec.Root, "data") + failed := filepath.Join(spec.Root, ".failed-data-"+spec.VersionID) + if _, err := os.Stat(backup); os.IsNotExist(err) { + return os.RemoveAll(failed) + } else if err != nil { + return err + } + if _, err := os.Stat(failed); os.IsNotExist(err) { + if err := os.Rename(data, failed); err != nil && !os.IsNotExist(err) { + return err + } + } else if err != nil { + return err + } + if err := os.Rename(backup, data); err != nil { + return err + } + return os.RemoveAll(failed) +} diff --git a/internal/pluginhub/source/egress.go b/internal/pluginhub/source/egress.go new file mode 100644 index 00000000..f6ac1bc7 --- /dev/null +++ b/internal/pluginhub/source/egress.go @@ -0,0 +1,149 @@ +package source + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "net" + "net/http" + "net/netip" + "net/url" + "strings" + "time" + + "cyberstrike-ai/internal/config" +) + +const MaxArchiveBytes int64 = 512 << 20 + +type Egress struct { + client *http.Client +} + +// NewEgress constrains plugin metadata and artifact traffic to approved HTTPS +// authorities. The token for GitHub metadata is added by its separate inspector. +func NewEgress(cfg config.PluginEgress) (*Egress, error) { + hosts := map[string]bool{ + "api.github.com": true, "github.com": true, "codeload.github.com": true, + "release-assets.githubusercontent.com": true, "objects.githubusercontent.com": true, + "registry-1.docker.io": true, "auth.docker.io": true, "ghcr.io": true, + "pkg-containers.githubusercontent.com": true, + "production.cloudfront.docker.com": true, "production.cloudflare.docker.com": true, + "registry.librechat.ai": true, + } + for _, host := range cfg.AdditionalHosts { + hosts[host] = true + } + transport := http.DefaultTransport.(*http.Transport).Clone() + switch cfg.ProxyMode { + case "direct": + transport.Proxy = nil + case "fixed": + proxy, err := url.Parse(cfg.ProxyURL) + if err != nil || proxy.Host == "" { + return nil, fmt.Errorf("invalid plugin outbound proxy") + } + transport.Proxy = http.ProxyURL(proxy) + } + // Keep default dialing for the operator's proxy. Direct artifact connections + // resolve once, reject non-public targets, and dial the validated address. + direct := transport.Clone() + direct.Proxy = nil + dialer := net.Dialer{Timeout: 12 * time.Second, KeepAlive: 30 * time.Second} + direct.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) { + host, port, err := net.SplitHostPort(address) + if err != nil { + return nil, err + } + addrs, err := net.DefaultResolver.LookupNetIP(ctx, "ip", host) + if err != nil { + return nil, err + } + for _, address := range addrs { + ip := address.Unmap() + if !ip.IsGlobalUnicast() || ip.IsPrivate() || netip.MustParsePrefix("100.64.0.0/10").Contains(ip) { + return nil, fmt.Errorf("non-public plugin egress address") + } + } + for _, ip := range addrs { + connection, err := dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port)) + if err == nil { + return connection, nil + } + } + return nil, fmt.Errorf("plugin egress endpoint unavailable") + } + roundTrip := egressTransport{direct: direct, proxied: transport, hosts: hosts} + return &Egress{client: &http.Client{ + Transport: roundTrip, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) > 4 || req.URL.Scheme != "https" || !hosts[req.URL.Host] { + return fmt.Errorf("plugin egress redirect not approved") + } + req.Header.Del("Authorization") + return nil + }, + }}, nil +} + +type egressTransport struct { + direct, proxied *http.Transport + hosts map[string]bool +} + +func (t egressTransport) RoundTrip(req *http.Request) (*http.Response, error) { + if req.URL.Scheme != "https" || req.URL.User != nil || !t.hosts[req.URL.Host] { + return nil, fmt.Errorf("plugin egress destination not approved") + } + if t.proxied.Proxy != nil { + proxy, err := t.proxied.Proxy(req) + if err != nil { + return nil, err + } + if proxy != nil { + return t.proxied.RoundTrip(req) + } + } + return t.direct.RoundTrip(req) +} + +func (e *Egress) Transport() http.RoundTripper { + return e.client.Transport +} + +func (e *Egress) Download(ctx context.Context, address string, dst io.Writer) (string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil) + if err != nil { + return "", fmt.Errorf("invalid artifact URL") + } + res, err := e.client.Do(req) + if err != nil { + return "", fmt.Errorf("artifact download could not connect") + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK || res.ContentLength > MaxArchiveBytes { + return "", fmt.Errorf("artifact response rejected (HTTP %d)", res.StatusCode) + } + sum := sha256.New() + n, err := io.Copy(io.MultiWriter(dst, sum), io.LimitReader(res.Body, MaxArchiveBytes+1)) + if err != nil || n == 0 || n > MaxArchiveBytes { + return "", fmt.Errorf("artifact size or transfer invalid") + } + return hex.EncodeToString(sum.Sum(nil)), nil +} + +func normalizeRegistry(repository string) (host, path string) { + first, rest, split := strings.Cut(repository, "/") + if split && (strings.ContainsAny(first, ".:") || first == "localhost") { + if first == "docker.io" || first == "index.docker.io" { + return "registry-1.docker.io", rest + } + return first, rest + } + if split { + return "registry-1.docker.io", repository + } + return "registry-1.docker.io", "library/" + repository +} diff --git a/internal/pluginhub/source/github.go b/internal/pluginhub/source/github.go new file mode 100644 index 00000000..022ab257 --- /dev/null +++ b/internal/pluginhub/source/github.go @@ -0,0 +1,396 @@ +// Package source previews repository metadata without fetching or executing repository code. +package source + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "strings" + "time" + + "cyberstrike-ai/internal/pluginhub/manifest" +) + +var ( + ErrRateLimited = errors.New("GitHub metadata rate limit exceeded") + ErrInvalidSource = errors.New("expected a public GitHub HTTPS repository URL") + ErrInvalidRevision = errors.New("invalid Git revision") + ErrAmbiguousRef = errors.New("Git ref exists as both a branch and a tag") + ErrSourceNotFound = errors.New("repository or revision not found") + ErrUpstream = errors.New("repository metadata unavailable") + ErrManifestInvalid = errors.New("repository plugin manifest is invalid") +) + +const gitHubAPI = "https://api.github.com" +const maxAPIResponse = 1 << 20 + +type GitHubInspector struct { + client *http.Client + token string +} + +func NewGitHubInspector() *GitHubInspector { + return NewGitHubInspectorWithTransport(nil, "") +} + +func NewGitHubInspectorWithTransport(transport http.RoundTripper, token string) *GitHubInspector { + if transport == nil { + transport = http.DefaultTransport + } + return &GitHubInspector{token: strings.TrimSpace(token), client: &http.Client{ + Transport: transport, + Timeout: 8 * time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + }} +} + +type Inspection struct { + Repository string `json:"repository"` + RequestedRef string `json:"requested_ref"` + ResolvedRef string `json:"resolved_ref"` + Commit string `json:"commit"` + Manifest json.RawMessage `json:"manifest,omitempty"` + Evidence []string `json:"evidence"` + Candidates []string `json:"candidates"` + Release *Release `json:"release,omitempty"` + ReleaseState string `json:"release_state"` +} + +type Release struct { + Tag string `json:"tag"` + Assets []string `json:"assets"` +} + +type repository struct { + Owner string + Name string +} + +var ( + ownerPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9-]{0,38}$`) + repoPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,100}$`) +) + +func NormalizeGitHubRepository(raw string) (string, error) { + repo, err := parseRepository(raw) + if err != nil { + return "", err + } + return "https://github.com/" + repo.Owner + "/" + repo.Name, nil +} + +func parseRepository(raw string) (repository, error) { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || u.Scheme != "https" || !strings.EqualFold(u.Host, "github.com") || + u.User != nil || u.RawQuery != "" || u.ForceQuery || strings.ContainsAny(raw, "#%\\") { + return repository{}, ErrInvalidSource + } + parts := strings.Split(strings.TrimSuffix(strings.TrimPrefix(u.Path, "/"), "/"), "/") + if len(parts) != 2 { + return repository{}, ErrInvalidSource + } + owner := strings.ToLower(parts[0]) + name := strings.TrimSuffix(strings.ToLower(parts[1]), ".git") + if !ownerPattern.MatchString(owner) || !repoPattern.MatchString(name) || name == "." || name == ".." { + return repository{}, ErrInvalidSource + } + return repository{Owner: owner, Name: name}, nil +} + +func (g *GitHubInspector) Inspect(ctx context.Context, input, revision string) (*Inspection, error) { + repo, err := parseRepository(input) + if err != nil { + return nil, err + } + revision = strings.TrimSpace(revision) + if err := manifest.ValidateGitRef(revision); err != nil { + return nil, ErrInvalidRevision + } + ctx, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + + endpoint := "/repos/" + repo.Owner + "/" + repo.Name + var metadata struct { + DefaultBranch string `json:"default_branch"` + FullName string `json:"full_name"` + Private bool `json:"private"` + } + if err := g.get(ctx, endpoint, &metadata); err != nil { + return nil, err + } + if metadata.Private || !strings.EqualFold(metadata.FullName, repo.Owner+"/"+repo.Name) { + return nil, ErrSourceNotFound + } + resolvedRef, commit, err := g.resolve(ctx, endpoint, revision, metadata.DefaultBranch) + if err != nil { + return nil, err + } + var commitData struct { + SHA string `json:"sha"` + Commit struct { + Tree struct { + SHA string `json:"sha"` + } `json:"tree"` + } `json:"commit"` + } + if err := g.get(ctx, endpoint+"/commits/"+commit, &commitData); err != nil { + return nil, err + } + if commitData.SHA != commit || !manifest.IsCommitSHA(commitData.Commit.Tree.SHA) { + return nil, ErrUpstream + } + result := &Inspection{ + Repository: "https://github.com/" + repo.Owner + "/" + repo.Name, RequestedRef: revision, + ResolvedRef: resolvedRef, Commit: commit, Evidence: []string{}, Candidates: []string{"git"}, + } + if err := g.inspectTree(ctx, endpoint, commitData.Commit.Tree.SHA, result); err != nil { + return nil, err + } + g.inspectRelease(ctx, endpoint, result) + return result, nil +} + +type gitObject struct { + Type string `json:"type"` + SHA string `json:"sha"` +} + +func (g *GitHubInspector) resolve(ctx context.Context, endpoint, revision, defaultBranch string) (string, string, error) { + if manifest.IsCommitSHA(revision) { + return revision, revision, nil + } + if revision == "" { + if defaultBranch == "" || manifest.ValidateGitRef(defaultBranch) != nil { + return "", "", ErrUpstream + } + revision = "refs/heads/" + defaultBranch + } + if strings.HasPrefix(revision, "refs/") { + object, err := g.getRef(ctx, endpoint, revision) + if err != nil { + return "", "", err + } + commit, err := g.peel(ctx, endpoint, object) + return revision, commit, err + } + + headRef, tagRef := "refs/heads/"+revision, "refs/tags/"+revision + head, headErr := g.getRef(ctx, endpoint, headRef) + tag, tagErr := g.getRef(ctx, endpoint, tagRef) + for _, err := range []error{headErr, tagErr} { + if err != nil && !errors.Is(err, ErrSourceNotFound) { + return "", "", err + } + } + switch { + case headErr == nil && tagErr == nil: + return "", "", ErrAmbiguousRef + case headErr == nil: + commit, err := g.peel(ctx, endpoint, head) + return headRef, commit, err + case tagErr == nil: + commit, err := g.peel(ctx, endpoint, tag) + return tagRef, commit, err + default: + return "", "", ErrSourceNotFound + } +} + +func (g *GitHubInspector) getRef(ctx context.Context, endpoint, ref string) (gitObject, error) { + if !strings.HasPrefix(ref, "refs/heads/") && !strings.HasPrefix(ref, "refs/tags/") { + return gitObject{}, ErrInvalidRevision + } + var result struct { + Ref string `json:"ref"` + Object gitObject `json:"object"` + } + if err := g.get(ctx, endpoint+"/git/ref/"+strings.TrimPrefix(ref, "refs/"), &result); err != nil { + return gitObject{}, err + } + if result.Ref != ref || !manifest.IsCommitSHA(result.Object.SHA) { + return gitObject{}, ErrUpstream + } + return result.Object, nil +} + +func (g *GitHubInspector) peel(ctx context.Context, endpoint string, object gitObject) (string, error) { + for depth := 0; depth < 8; depth++ { + if !manifest.IsCommitSHA(object.SHA) { + return "", ErrUpstream + } + switch object.Type { + case "commit": + return object.SHA, nil + case "tag": + var result struct { + SHA string `json:"sha"` + Object gitObject `json:"object"` + } + if err := g.get(ctx, endpoint+"/git/tags/"+object.SHA, &result); err != nil { + return "", err + } + if result.SHA != object.SHA { + return "", ErrUpstream + } + object = result.Object + default: + return "", ErrSourceNotFound + } + } + return "", ErrUpstream +} + +func (g *GitHubInspector) inspectTree(ctx context.Context, endpoint, treeSHA string, result *Inspection) error { + var tree struct { + SHA string `json:"sha"` + Truncated bool `json:"truncated"` + Files []struct { + Path string `json:"path"` + Mode string `json:"mode"` + Type string `json:"type"` + SHA string `json:"sha"` + Size int `json:"size"` + } `json:"tree"` + } + if err := g.get(ctx, endpoint+"/git/trees/"+treeSHA, &tree); err != nil { + return err + } + if tree.SHA != treeSHA || tree.Truncated { + return ErrUpstream + } + container := false + for _, f := range tree.Files { + if f.Path == "csai-plugin.yaml" { + if f.Type != "blob" || (f.Mode != "100644" && f.Mode != "100755") || + f.Size <= 0 || f.Size > manifest.MaxDocumentBytes || !manifest.IsCommitSHA(f.SHA) { + return ErrManifestInvalid + } + if err := g.readManifest(ctx, endpoint, f.SHA, result); err != nil { + return err + } + result.Evidence = append(result.Evidence, f.Path) + continue + } + if f.Type != "blob" || (f.Mode != "100644" && f.Mode != "100755") { + continue + } + switch f.Path { + case "Dockerfile", "compose.yaml", "compose.yml", "docker-compose.yml", "docker-compose.yaml": + container = true + result.Evidence = append(result.Evidence, f.Path) + case "go.mod", "package.json", "pyproject.toml", "requirements.txt", "Cargo.toml", "pom.xml": + result.Evidence = append(result.Evidence, f.Path) + } + } + if container { + result.Candidates = append(result.Candidates, "container") + } + return nil +} + +func (g *GitHubInspector) readManifest(ctx context.Context, endpoint, blobSHA string, result *Inspection) error { + var blob struct { + SHA string `json:"sha"` + Encoding string `json:"encoding"` + Content string `json:"content"` + Size int `json:"size"` + } + if err := g.get(ctx, endpoint+"/git/blobs/"+blobSHA, &blob); err != nil { + return err + } + raw, err := base64.StdEncoding.DecodeString(blob.Content) + if err != nil || blob.SHA != blobSHA || blob.Encoding != "base64" || len(raw) != blob.Size { + return ErrUpstream + } + declaration, err := manifest.DecodeDeclaration(raw) + if err != nil { + return ErrManifestInvalid + } + repository, err := NormalizeGitHubRepository(declaration.Metadata.Repository) + if err != nil || repository != result.Repository { + return ErrManifestInvalid + } + result.Manifest = declaration.Canonical + return nil +} + +func (g *GitHubInspector) inspectRelease(ctx context.Context, endpoint string, result *Inspection) { + var data struct { + Tag string `json:"tag_name"` + Assets []struct { + Name string `json:"name"` + } `json:"assets"` + } + err := ErrSourceNotFound + if name, tagged := strings.CutPrefix(result.ResolvedRef, "refs/tags/"); tagged { + err = g.get(ctx, endpoint+"/releases/tags/"+url.PathEscape(name), &data) + } + if errors.Is(err, ErrSourceNotFound) { + err = g.get(ctx, endpoint+"/releases/latest", &data) + } + switch { + case errors.Is(err, ErrSourceNotFound): + result.ReleaseState = "none" + case err != nil: + result.ReleaseState = "unavailable" + default: + result.ReleaseState = "found" + result.Release = &Release{Tag: data.Tag, Assets: []string{}} + hasPackage := false + for _, asset := range data.Assets { + if len(result.Release.Assets) == 32 { + break + } + if len(asset.Name) > 0 && len(asset.Name) <= 240 && !strings.ContainsAny(asset.Name, "/\\\x00\r\n") { + result.Release.Assets = append(result.Release.Assets, asset.Name) + name := strings.ToLower(asset.Name) + hasPackage = hasPackage || strings.HasSuffix(name, ".tar.gz") || strings.HasSuffix(name, ".zip") + } + } + if hasPackage { + result.Candidates = append([]string{"release"}, result.Candidates...) + } + } +} + +// Only constant-host HTTPS metadata requests are used. Links supplied by the API +// response are never followed. +func (g *GitHubInspector) get(ctx context.Context, path string, out any) error { + request, err := http.NewRequestWithContext(ctx, http.MethodGet, gitHubAPI+path, nil) + if err != nil { + return ErrUpstream + } + request.Header.Set("Accept", "application/vnd.github+json") + if g.token != "" { + request.Header.Set("Authorization", "Bearer "+g.token) + } + request.Header.Set("X-GitHub-Api-Version", "2022-11-28") + response, err := g.client.Do(request) + if err != nil { + return ErrUpstream + } + defer response.Body.Close() + if response.StatusCode == http.StatusNotFound { + return ErrSourceNotFound + } + if response.StatusCode == http.StatusTooManyRequests || + (response.StatusCode == http.StatusForbidden && response.Header.Get("X-RateLimit-Remaining") == "0") { + return ErrRateLimited + } + if response.StatusCode != http.StatusOK { + return fmt.Errorf("%w (GitHub status %d)", ErrUpstream, response.StatusCode) + } + raw, err := io.ReadAll(io.LimitReader(response.Body, maxAPIResponse+1)) + if err != nil || len(raw) > maxAPIResponse || json.Unmarshal(raw, out) != nil { + return ErrUpstream + } + return nil +} diff --git a/internal/pluginhub/source/github_test.go b/internal/pluginhub/source/github_test.go new file mode 100644 index 00000000..c3962671 --- /dev/null +++ b/internal/pluginhub/source/github_test.go @@ -0,0 +1,102 @@ +package source + +import ( + "context" + "encoding/base64" + "errors" + "fmt" + "io" + "net/http" + "os" + "strings" + "testing" +) + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (roundTrip roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { + return roundTrip(request) +} + +func TestPluginGitHubInspectorUsesOnlyPinnedMetadata(t *testing.T) { + commit := strings.Repeat("a", 40) + tree := strings.Repeat("b", 40) + blob := strings.Repeat("c", 40) + tag := strings.Repeat("d", 40) + raw, err := os.ReadFile("../manifest/testdata/web-plugin.yaml") + if err != nil { + t.Fatal(err) + } + raw = []byte(strings.ReplaceAll(string(raw), "https://git.example.org/examples/log-review-demo.git", "https://github.com/example/review")) + prefix := "/repos/example/review" + responses := map[string]string{ + prefix: `{"full_name":"Example/Review","default_branch":"main"}`, + prefix + "/git/ref/tags/v1": fmt.Sprintf(`{"ref":"refs/tags/v1","object":{"type":"tag","sha":%q}}`, tag), + prefix + "/git/tags/" + tag: fmt.Sprintf(`{"sha":%q,"object":{"type":"commit","sha":%q}}`, tag, commit), + prefix + "/commits/" + commit: fmt.Sprintf(`{"sha":%q,"commit":{"tree":{"sha":%q}}}`, commit, tree), + prefix + "/git/trees/" + tree: fmt.Sprintf(`{"sha":%q,"tree":[{"path":"csai-plugin.yaml","type":"blob","mode":"100644","sha":%q,"size":%d},{"path":"Dockerfile","type":"blob","mode":"100644"}]}`, tree, blob, len(raw)), + prefix + "/git/blobs/" + blob: fmt.Sprintf(`{"sha":%q,"encoding":"base64","size":%d,"content":%q}`, blob, len(raw), base64.StdEncoding.EncodeToString(raw)), + prefix + "/releases/tags/v1": `{"tag_name":"v1","assets":[{"name":"review.tar.gz","browser_download_url":"http://127.0.0.1/private"}]}`, + } + calls := map[string]int{} + inspector := NewGitHubInspector() + inspector.client.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if request.URL.Scheme != "https" || request.URL.Host != "api.github.com" || request.Method != http.MethodGet { + t.Fatalf("unexpected metadata request %s %s", request.Method, request.URL) + } + calls[request.URL.Path]++ + response, ok := responses[request.URL.Path] + if !ok && request.URL.Path != prefix+"/git/ref/heads/v1" { + t.Fatalf("unexpected request: %s", request.URL) + } + status := http.StatusOK + if !ok { + status = http.StatusNotFound + } + return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(response)), Header: http.Header{}}, nil + }) + result, err := inspector.Inspect(context.Background(), "https://github.com/Example/Review.git", "v1") + if err != nil { + t.Fatal(err) + } + if result.Repository != "https://github.com/example/review" || result.Commit != commit || result.ResolvedRef != "refs/tags/v1" || + len(result.Manifest) == 0 || strings.Join(result.Candidates, ",") != "release,git,container" { + t.Fatalf("unexpected inspection: %+v", result) + } + if len(calls) != len(responses)+1 { + t.Fatalf("unexpected metadata calls: %+v", calls) + } + + responses[prefix+"/git/ref/heads/v1"] = fmt.Sprintf(`{"ref":"refs/heads/v1","object":{"type":"commit","sha":%q}}`, commit) + if _, err := inspector.Inspect(context.Background(), "https://github.com/example/review", "v1"); !errors.Is(err, ErrAmbiguousRef) { + t.Fatalf("expected an ambiguous ref error, got %v", err) + } +} + +func TestPluginGitHubInspectorRejectsURLsAndRedirects(t *testing.T) { + inspector := NewGitHubInspector() + calls := 0 + inspector.client.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + calls++ + return &http.Response{StatusCode: http.StatusFound, Body: io.NopCloser(strings.NewReader("")), + Header: http.Header{"Location": []string{"http://127.0.0.1/private"}}}, nil + }) + for _, input := range []string{ + "http://github.com/example/review", "https://github.com@127.0.0.1/example/review", + "https://github.com:443/example/review", "https://github.com/example/%2e%2e", + "https://github.com/example/review?url=http://127.0.0.1", + } { + if _, err := inspector.Inspect(context.Background(), input, ""); !errors.Is(err, ErrInvalidSource) { + t.Fatalf("accepted %q: %v", input, err) + } + } + if _, err := inspector.Inspect(context.Background(), "https://github.com/example/review", "--upload-pack"); !errors.Is(err, ErrInvalidRevision) { + t.Fatalf("accepted invalid revision: %v", err) + } + if calls != 0 { + t.Fatal("invalid inputs reached the HTTP client") + } + if _, err := inspector.Inspect(context.Background(), "https://github.com/example/review", ""); !errors.Is(err, ErrUpstream) || calls != 1 { + t.Fatalf("redirect followed or unexpectedly accepted: %d calls (%v)", calls, err) + } +} diff --git a/internal/pluginhub/source/locks.go b/internal/pluginhub/source/locks.go new file mode 100644 index 00000000..48983dba --- /dev/null +++ b/internal/pluginhub/source/locks.go @@ -0,0 +1,247 @@ +package source + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "strings" + + "cyberstrike-ai/internal/pluginhub/manifest" +) + +var ErrArtifactUnavailable = errors.New("plugin artifact unavailable for selected platform") + +func (e *Egress) LockRelease(ctx context.Context, d manifest.Distribution, platform manifest.Platform) (manifest.Artifact, error) { + for _, asset := range d.Assets { + if asset.OS != platform.OS || asset.Arch != platform.Arch { + continue + } + digest := asset.SHA256 + method := "declared_checksum" + if digest == "" { + var err error + digest, err = e.Download(ctx, asset.URL, io.Discard) + if err != nil { + return manifest.Artifact{}, err + } + method = "reviewed_observed_digest" + } else if !validRegistryDigest("sha256:" + digest) { + return manifest.Artifact{}, fmt.Errorf("invalid declared release checksum") + } + return manifest.Artifact{Driver: "release", AssetURL: asset.URL, SHA256: digest, Verification: method}, nil + } + return manifest.Artifact{}, ErrArtifactUnavailable +} + +type manifestDescriptor struct { + MediaType string `json:"mediaType"` + Digest string `json:"digest"` + Platform struct { + OS string `json:"os"` + Architecture string `json:"architecture"` + Variant string `json:"variant"` + OSFeatures []string `json:"os.features"` + } `json:"platform"` +} + +type registryDocument struct { + SchemaVersion int `json:"schemaVersion"` + MediaType string `json:"mediaType"` + Manifests []manifestDescriptor `json:"manifests"` + Config manifestDescriptor `json:"config"` + Layers []manifestDescriptor `json:"layers"` +} + +const registryAccept = "application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json" + +func (e *Egress) LockImage(ctx context.Context, service manifest.Service, os, arch string) (manifest.LockedService, error) { + repo, tag, digest, err := manifest.ParseImageReference(service.Image) + if err != nil { + return manifest.LockedService{}, err + } + host, path := normalizeRegistry(repo) + base := "https://" + host + "/v2/" + path + reference := tag + if digest != "" { + reference = digest + } + response, err := e.registryFetch(ctx, base+"/manifests/"+reference, path, registryAccept, "") + if err != nil { + return manifest.LockedService{}, err + } + doc, actual, err := verifyRegistryDocument(response, digest) + if err != nil { + return manifest.LockedService{}, err + } + entry := manifest.LockedService{Name: service.Name, Repository: repo, RequestedImage: service.Image} + isIndex := doc.MediaType == "application/vnd.oci.image.index.v1+json" || doc.MediaType == "application/vnd.docker.distribution.manifest.list.v2+json" || len(doc.Manifests) > 0 + if isIndex { + entry.IndexDigest = actual + digest, err = selectPlatform(doc.Manifests, os, arch) + if err != nil { + return manifest.LockedService{}, err + } + response, err = e.registryFetch(ctx, base+"/manifests/"+digest, path, registryAccept, response.token) + if err != nil { + return manifest.LockedService{}, err + } + doc, actual, err = verifyRegistryDocument(response, digest) + if err != nil { + return manifest.LockedService{}, err + } + } + if !validRegistryDigest(doc.Config.Digest) || len(doc.Manifests) != 0 || doc.Layers == nil { + return manifest.LockedService{}, fmt.Errorf("registry manifest does not describe a runnable image") + } + cfg, err := e.registryFetch(ctx, base+"/blobs/"+doc.Config.Digest, path, "", response.token) + if err != nil { + return manifest.LockedService{}, err + } + if "sha256:"+manifest.Digest(cfg.body) != doc.Config.Digest { + return manifest.LockedService{}, fmt.Errorf("registry image configuration checksum mismatch") + } + var platform struct { + OS string `json:"os"` + Architecture string `json:"architecture"` + } + if json.Unmarshal(cfg.body, &platform) != nil || platform.OS != os || platform.Architecture != arch { + return manifest.LockedService{}, ErrArtifactUnavailable + } + entry.ManifestDigest = actual + return entry, nil +} + +func selectPlatform(descriptors []manifestDescriptor, os, arch string) (string, error) { + found := "" + for _, desc := range descriptors { + if desc.Platform.OS != os || desc.Platform.Architecture != arch || len(desc.Platform.OSFeatures) != 0 { + continue + } + if desc.Platform.Variant != "" && !(arch == "arm64" && desc.Platform.Variant == "v8") { + continue + } + if !validRegistryDigest(desc.Digest) || (found != "" && found != desc.Digest) { + return "", fmt.Errorf("ambiguous or invalid registry platform descriptor") + } + found = desc.Digest + } + if found == "" { + return "", ErrArtifactUnavailable + } + return found, nil +} + +type registryResponse struct { + body []byte + digest string + token string +} + +var registryDigest = regexp.MustCompile(`^sha256:[a-f0-9]{64}$`) +var registryAuthField = regexp.MustCompile(`([a-z]+)="([^"]+)"`) + +func validRegistryDigest(s string) bool { return registryDigest.MatchString(s) } + +func verifyRegistryDocument(res registryResponse, pinned string) (registryDocument, string, error) { + var document registryDocument + actual := "sha256:" + manifest.Digest(res.body) + if (pinned != "" && pinned != actual) || (res.digest != "" && res.digest != actual) { + return document, "", fmt.Errorf("registry manifest checksum mismatch") + } + if json.Unmarshal(res.body, &document) != nil || document.SchemaVersion != 2 { + return document, "", fmt.Errorf("unsupported registry manifest") + } + return document, actual, nil +} + +func (e *Egress) registryFetch(ctx context.Context, address, repository, accept, token string) (registryResponse, error) { + get := func(token string) (*http.Response, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil) + if err != nil { + return nil, err + } + if accept != "" { + req.Header.Set("Accept", accept) + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + return e.client.Do(req) + } + res, err := get(token) + if err != nil { + return registryResponse{}, fmt.Errorf("registry endpoint unavailable") + } + if res.StatusCode == http.StatusUnauthorized { + challenge := res.Header.Get("WWW-Authenticate") + res.Body.Close() + token, err = e.registryToken(ctx, challenge, repository) + if err != nil { + return registryResponse{}, err + } + res, err = get(token) + if err != nil { + return registryResponse{}, fmt.Errorf("registry endpoint unavailable after challenge") + } + } + defer res.Body.Close() + if res.StatusCode == http.StatusNotFound { + return registryResponse{}, ErrArtifactUnavailable + } + if res.StatusCode != http.StatusOK { + return registryResponse{}, fmt.Errorf("registry response rejected (HTTP %d)", res.StatusCode) + } + body, err := io.ReadAll(io.LimitReader(res.Body, 4<<20+1)) + if err != nil || len(body) > 4<<20 { + return registryResponse{}, fmt.Errorf("registry response exceeds metadata limit") + } + return registryResponse{body: body, digest: res.Header.Get("Docker-Content-Digest"), token: token}, nil +} + +func (e *Egress) registryToken(ctx context.Context, challenge, repository string) (string, error) { + if !strings.HasPrefix(strings.ToLower(challenge), "bearer ") || len(challenge) > 4096 { + return "", fmt.Errorf("unsupported registry authentication challenge") + } + fields := map[string]string{} + for _, pair := range registryAuthField.FindAllStringSubmatch(challenge, -1) { + fields[pair[1]] = pair[2] + } + realm, err := url.Parse(fields["realm"]) + scope := "repository:" + repository + ":pull" + if err != nil || realm.Scheme != "https" || realm.User != nil || realm.Fragment != "" || (fields["scope"] != "" && fields["scope"] != scope) { + return "", fmt.Errorf("invalid registry pull challenge") + } + params := url.Values{"scope": {scope}} + if fields["service"] != "" { + params.Set("service", fields["service"]) + } + realm.RawQuery = params.Encode() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, realm.String(), nil) + if err != nil { + return "", fmt.Errorf("invalid registry token endpoint") + } + res, err := e.client.Do(req) + if err != nil { + return "", fmt.Errorf("registry token endpoint unavailable") + } + defer res.Body.Close() + var token struct { + Token string `json:"token"` + AccessToken string `json:"access_token"` + } + if res.StatusCode != http.StatusOK || json.NewDecoder(io.LimitReader(res.Body, 64<<10)).Decode(&token) != nil { + return "", fmt.Errorf("registry pull token unavailable") + } + if token.Token == "" { + token.Token = token.AccessToken + } + if token.Token == "" || strings.ContainsAny(token.Token, "\r\n\x00") { + return "", fmt.Errorf("invalid registry pull token") + } + return token.Token, nil +} diff --git a/internal/pluginhub/source/locks_test.go b/internal/pluginhub/source/locks_test.go new file mode 100644 index 00000000..cd4c1f53 --- /dev/null +++ b/internal/pluginhub/source/locks_test.go @@ -0,0 +1,92 @@ +package source + +import ( + "context" + "fmt" + "io" + "net/http" + "strings" + "testing" + + "cyberstrike-ai/internal/config" + + "cyberstrike-ai/internal/pluginhub/manifest" +) + +func TestPluginReleaseChecksumAndImageIndex(t *testing.T) { + const config = `{"architecture":"arm64","os":"linux"}` + configDigest := "sha256:" + manifest.Digest([]byte(config)) + child := fmt.Sprintf(`{"schemaVersion":2,"config":{"digest":%q},"layers":[]}`, configDigest) + childDigest := "sha256:" + manifest.Digest([]byte(child)) + index := fmt.Sprintf(`{"schemaVersion":2,"manifests":[{"digest":%q,"platform":{"architecture":"arm64","os":"linux","variant":"v8"}}]}`, childDigest) + indexDigest := "sha256:" + manifest.Digest([]byte(index)) + visited := map[string]bool{} + client := &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) { + visited[request.URL.Path] = true + body, digest := "", "" + switch request.URL.Path { + case "/v2/example/web/manifests/" + indexDigest: + body, digest = index, indexDigest + case "/v2/example/web/manifests/" + childDigest: + body, digest = child, childDigest + case "/v2/example/web/blobs/" + configDigest: + body = config + case "/asset.tar.gz": + body = "fixture archive" + default: + t.Fatalf("unexpected request: %s", request.URL.Path) + } + response := &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}} + response.Header.Set("Docker-Content-Digest", digest) + return response, nil + })} + egress := &Egress{client: client} + ctx := context.Background() + plan, err := egress.LockImage(ctx, manifest.Service{Name: "web", Image: "example/web:stable@" + indexDigest}, "linux", "arm64") + if err != nil || plan.ManifestDigest != childDigest || plan.IndexDigest != indexDigest || plan.Repository != "example/web" { + t.Fatalf("image lock %+v %v", plan, err) + } + if !visited["/v2/example/web/blobs/"+configDigest] { + t.Fatal("image configuration did not establish the platform") + } + d := manifest.Distribution{Type: "release", Assets: []manifest.Asset{ + {OS: "darwin", Arch: "arm64", URL: "https://example.org/asset.tar.gz", SHA256: manifest.Digest([]byte("fixture archive"))}, + }} + a, err := egress.LockRelease(ctx, d, manifest.Platform{OS: "darwin", Arch: "arm64"}) + if err != nil || a.Verification != "declared_checksum" || a.SHA256 != d.Assets[0].SHA256 || visited["/asset.tar.gz"] { + t.Fatalf("declared checksum planning downloaded the archive or returned a bad lock: %+v %v", a, err) + } + d.Assets[0].SHA256 = "" + observed, err := egress.LockRelease(ctx, d, manifest.Platform{OS: "darwin", Arch: "arm64"}) + if err != nil || !visited["/asset.tar.gz"] || observed.SHA256 != a.SHA256 || observed.Verification != "reviewed_observed_digest" { + t.Fatalf("missing checksum did not trigger online locking: %+v %v", observed, err) + } +} + +func TestPluginGitHubMetadataUsesConfiguredToken(t *testing.T) { + inspector := NewGitHubInspectorWithTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.Host != "api.github.com" || req.Header.Get("Authorization") != "Bearer test-placeholder" { + t.Fatal("GitHub metadata authorization was not scoped to the API host") + } + return &http.Response{StatusCode: http.StatusForbidden, Header: http.Header{"X-Ratelimit-Remaining": {"0"}}, Body: io.NopCloser(strings.NewReader(""))}, nil + }), "test-placeholder") + if _, err := inspector.Inspect(context.Background(), "https://github.com/example/web", ""); err != ErrRateLimited { + t.Fatalf("rate-limit diagnosis: %v", err) + } +} + +func TestPluginGHCRBlobRedirectAllowsDeliveryWithoutAuthorization(t *testing.T) { + egress, err := NewEgress(config.PluginEgress{ProxyMode: "direct"}) + if err != nil { + t.Fatal(err) + } + origin, _ := http.NewRequest(http.MethodGet, "https://ghcr.io/v2/example/web/blobs/sha256:placeholder", nil) + blob, _ := http.NewRequest(http.MethodGet, "https://pkg-containers.githubusercontent.com/blob", nil) + blob.Header.Set("Authorization", "Bearer fixture-token") + if err := egress.client.CheckRedirect(blob, []*http.Request{origin}); err != nil { + t.Fatal(err) + } + if blob.Header.Get("Authorization") != "" { + t.Fatal("registry credentials reached the blob delivery host") + } +} diff --git a/internal/pluginhub/webproxy/proxy.go b/internal/pluginhub/webproxy/proxy.go new file mode 100644 index 00000000..aec2b1d6 --- /dev/null +++ b/internal/pluginhub/webproxy/proxy.go @@ -0,0 +1,302 @@ +package webproxy + +import ( + "context" + "crypto/sha256" + "fmt" + "net" + "net/http" + "net/http/httputil" + "net/netip" + "net/url" + "path" + "strings" + "time" +) + +func routePrefix(id, route string) string { + if route == "build_base_path" || route == "relative_prefix" { + return "/apps/" + id + } + return "" +} + +var appTransport = &http.Transport{MaxIdleConnsPerHost: 4, IdleConnTimeout: 45 * time.Second, ResponseHeaderTimeout: 30 * time.Second} + +func (s *Service) Handler(id string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !s.isReady() { + http.Error(w, "plugin listener unavailable", http.StatusServiceUnavailable) + return + } + w.Header().Set("Referrer-Policy", "no-referrer") + if r.URL.Path == SessionPath && r.URL.RawPath == "" { + s.exchange(w, r, id) + return + } + if !safePath(r.URL) || strings.HasPrefix(r.URL.Path, "/_csai_plugin/") || r.Header.Get("Service-Worker") != "" || + r.Header.Get("Sec-Fetch-Dest") == "serviceworker" || r.Method == http.MethodConnect || r.Method == http.MethodTrace { + http.NotFound(w, r) + return + } + session := s.session(r, id) + if session == nil || !s.authorize(r.Context(), id, session.mainToken) { + http.Error(w, "plugin session required", http.StatusUnauthorized) + return + } + ws := strings.EqualFold(r.Header.Get("Upgrade"), "websocket") + unsafe := r.Method != http.MethodGet && r.Method != http.MethodHead + if !requestOrigin(r, session.pluginOrigin, ws || unsafe) { + http.Error(w, "plugin request origin rejected", http.StatusForbidden) + return + } + target, err := s.resolve(r.Context(), id) + if err != nil || target.Generation != session.generation { + http.Error(w, "plugin session expired", http.StatusUnauthorized) + return + } + endpoint, err := loopbackEndpoint(target.Endpoint) + if err != nil { + http.Error(w, "invalid plugin endpoint", http.StatusBadGateway) + return + } + prefix := routePrefix(id, target.Route) + upstreamPath := r.URL.Path + if prefix != "" { + if r.URL.Path == prefix { + http.Redirect(w, r, prefix+"/", http.StatusTemporaryRedirect) + return + } + if !strings.HasPrefix(r.URL.Path, prefix+"/") { + http.NotFound(w, r) + return + } + if target.Route == "relative_prefix" { + upstreamPath = strings.TrimPrefix(upstreamPath, prefix) + } + } + ctx, cancel := context.WithCancel(r.Context()) + defer cancel() + stop := context.AfterFunc(session.ctx, cancel) + defer stop() + // Streams and upgraded connections are fenced even if a role or the + // application generation changes after the request has been admitted. + go s.watch(ctx, cancel, id, session) + proxy := s.reverseProxy(endpoint, upstreamPath, prefix, target, session, r) + proxy.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +func (s *Service) session(r *http.Request, id string) *browserSession { + for _, secure := range []bool{true, false} { + name := cookieName(id, secure) + var value string + for _, cookie := range r.CookiesNamed(name) { + if value != "" { + return nil + } + value = cookie.Value + } + if len(value) != 43 { + continue + } + hash := sha256.Sum256([]byte(value)) + s.mu.Lock() + s.prune(time.Now()) + session := s.sessions[hash] + s.mu.Unlock() + if session != nil && session.install == id && + secure == strings.HasPrefix(session.pluginOrigin, "https://") && matchesOrigin(r, session.pluginOrigin) { + return session + } + } + return nil +} + +func (s *Service) watch(ctx context.Context, cancel context.CancelFunc, id string, session *browserSession) { + tick := time.NewTicker(350 * time.Millisecond) + defer tick.Stop() + for { + select { + case <-ctx.Done(): + return + case <-tick.C: + if !s.authorize(ctx, id, session.mainToken) { + cancel() + return + } + target, err := s.resolve(ctx, id) + if err != nil || target.Generation != session.generation { + cancel() + return + } + } + } +} + +func (s *Service) reverseProxy(endpoint *url.URL, upstreamPath, prefix string, target Target, session *browserSession, r *http.Request) *httputil.ReverseProxy { + return &httputil.ReverseProxy{ + Transport: appTransport, + FlushInterval: -1, + Rewrite: func(pr *httputil.ProxyRequest) { + pr.Out.URL.Path, pr.Out.URL.RawPath = upstreamPath, "" + pr.SetURL(endpoint) + pr.Out.Header.Del("Cookie") + pr.Out.Header.Del("Authorization") + pr.Out.Header.Del("Proxy-Authorization") + if bearer := s.applicationBearer(r, target.ApplicationBearer, upstreamPath, session.mainToken); bearer != "" { + pr.Out.Header.Set("Authorization", "Bearer "+bearer) + } + for name := range pr.Out.Header { + lower := strings.ToLower(name) + if strings.HasPrefix(lower, "x-csai-") || lower == "x-real-ip" || lower == "x-api-key" { + pr.Out.Header.Del(name) + } + } + for _, cookie := range session.jar.Cookies(jarURL(pr.Out.URL, session.pluginOrigin)) { + pr.Out.AddCookie(cookie) + } + // Scope the forwarded authority to this validated plugin request. + pr.Out.Header.Set("X-Forwarded-Host", r.Host) + pr.Out.Header.Set("X-Forwarded-Proto", strings.SplitN(session.pluginOrigin, ":", 2)[0]) + if prefix != "" { + pr.Out.Header.Set("X-Forwarded-Prefix", prefix) + } + }, + ModifyResponse: func(resp *http.Response) error { + session.jar.SetCookies(jarURL(resp.Request.URL, session.pluginOrigin), resp.Cookies()) + resp.Header.Del("Set-Cookie") + for _, name := range []string{"X-Frame-Options", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods", "Report-To", "Reporting-Endpoints", "Clear-Site-Data", "Refresh"} { + resp.Header.Del(name) + } + if loc := resp.Header.Get("Location"); loc != "" { + rewritten, err := safeLocation(loc, resp.Request.URL, endpoint, session.pluginOrigin, prefix, target.Route) + if err != nil { + return err + } + resp.Header.Set("Location", rewritten) + } + // Multiple CSP policies are intersected. Remove only the upstream + // framing directive since the outer application owns embedding. + policies := resp.Header.Values("Content-Security-Policy") + resp.Header.Del("Content-Security-Policy") + for _, p := range policies { + var kept []string + for d := range strings.SplitSeq(p, ";") { + d = strings.TrimSpace(d) + fields := strings.Fields(d) + if len(fields) > 0 && !strings.EqualFold(fields[0], "frame-ancestors") { + kept = append(kept, d) + } + } + if len(kept) > 0 { + resp.Header.Add("Content-Security-Policy", strings.Join(kept, "; ")) + } + } + resp.Header.Add("Content-Security-Policy", "frame-ancestors "+session.parentOrigin+"; object-src 'none'") + resp.Header.Set("Cache-Control", "no-store") + resp.Header.Set("Cross-Origin-Resource-Policy", "same-origin") + resp.Header.Set("X-Content-Type-Options", "nosniff") + return nil + }, + ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) { + http.Error(w, "plugin upstream unavailable", http.StatusBadGateway) + }, + } +} + +func (s *Service) applicationBearer(r *http.Request, allowed []string, path, primaryToken string) string { + headers := r.Header.Values("Authorization") + if len(headers) != 1 { + return "" + } + scheme, token, ok := strings.Cut(headers[0], " ") + token = strings.TrimSpace(token) + if !ok || !strings.EqualFold(scheme, "Bearer") || token == "" || token == primaryToken || + s.isPlatformToken != nil && s.isPlatformToken(token) { + return "" + } + for _, prefix := range allowed { + if path == prefix || prefix != "/" && strings.HasPrefix(path, strings.TrimRight(prefix, "/")+"/") { + return token + } + } + return "" +} + +func jarURL(upstream *url.URL, browserOrigin string) *url.URL { + public, _ := url.Parse(browserOrigin) + copy := *upstream + copy.Scheme, copy.Host = public.Scheme, public.Host + return © +} + +func safePath(u *url.URL) bool { + escaped := strings.ToLower(u.EscapedPath()) + if !strings.HasPrefix(u.Path, "/") || strings.ContainsAny(u.Path, "\\\x00") || strings.HasPrefix(u.Path, "//") || + strings.Contains(escaped, "%2f") || strings.Contains(escaped, "%5c") || strings.Contains(escaped, "%25") { + return false + } + clean := path.Clean(u.Path) + return clean == u.Path || clean+"/" == u.Path +} + +func loopbackEndpoint(raw string) (*url.URL, error) { + u, err := url.Parse(raw) + if err != nil || u.Scheme != "http" || u.User != nil || u.Port() == "" || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + return nil, fmt.Errorf("invalid endpoint") + } + addr, err := netip.ParseAddr(u.Hostname()) + if err != nil || !addr.IsLoopback() { + return nil, fmt.Errorf("endpoint is not a managed loopback address") + } + u.Path = "" + return u, nil +} + +func safeLocation(raw string, requestURL, upstream *url.URL, browserOrigin, prefix, route string) (string, error) { + rel, err := url.Parse(raw) + if err != nil || rel.User != nil || rel.Opaque != "" || strings.HasPrefix(raw, "//") || strings.Contains(raw, "\\") { + return "", fmt.Errorf("invalid redirect") + } + target := requestURL.ResolveReference(rel) + public, _ := url.Parse(browserOrigin) + if target.Host != upstream.Host && !sameAuthority(target, public) { + return "", fmt.Errorf("non-plugin redirect") + } + if target.Scheme != "http" && target.Scheme != "https" || !safePath(target) { + return "", fmt.Errorf("invalid redirect target") + } + result := target.EscapedPath() + if prefix != "" && result != prefix && !strings.HasPrefix(result, prefix+"/") { + if route != "relative_prefix" { + return "", fmt.Errorf("redirect escaped application base path") + } + result = prefix + result + } + if strings.HasPrefix(result, "/_csai_plugin/") { + return "", fmt.Errorf("reserved redirect") + } + if target.RawQuery != "" { + result += "?" + target.RawQuery + } + if target.Fragment != "" { + result += "#" + target.EscapedFragment() + } + return result, nil +} + +func sameAuthority(a, b *url.URL) bool { + host := func(u *url.URL) string { + port := u.Port() + if port == "" { + if u.Scheme == "https" { + port = "443" + } else { + port = "80" + } + } + return net.JoinHostPort(strings.ToLower(u.Hostname()), port) + } + return a.Scheme == b.Scheme && host(a) == host(b) +} diff --git a/internal/pluginhub/webproxy/server.go b/internal/pluginhub/webproxy/server.go new file mode 100644 index 00000000..89b6f4f4 --- /dev/null +++ b/internal/pluginhub/webproxy/server.go @@ -0,0 +1,501 @@ +// Package webproxy serves application UI on installation-specific origins. +package webproxy + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "database/sql" + "encoding/base64" + "errors" + "net" + "net/http" + "net/http/cookiejar" + "net/netip" + "net/url" + "regexp" + "strconv" + "strings" + "sync" + "time" + + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + + "github.com/google/uuid" + "golang.org/x/net/publicsuffix" +) + +var ErrUnavailable = errors.New("plugin web origin unavailable") +var ErrForbidden = errors.New("plugin web origin or permission rejected") + +const SessionPath = "/_csai_plugin/session" +const maxSessions = 1024 +const ticketTTL = 45 * time.Second +const sessionTTL = 2 * time.Hour + +type Target struct { + Endpoint string + Route string + EntryPath string + Generation int64 + ApplicationBearer []string +} + +type Resolve func(context.Context, string) (Target, error) +type Authorize func(context.Context, string, string) bool + +type Service struct { + cfg config.PluginProxyConfig + db *database.DB + resolve Resolve + authorize Authorize + isPlatformToken func(string) bool + mu sync.Mutex + listeners map[string]*http.Server + tickets map[[32]byte]grant + sessions map[[32]byte]*browserSession + tlsConfig *tls.Config + bindHost string + mainPort int + started bool +} + +type grant struct { + install, parentOrigin, pluginOrigin, mainToken string + generation int64 + expires time.Time +} + +type browserSession struct { + grant + jar http.CookieJar + ctx context.Context + cancel context.CancelFunc +} + +type Embed struct { + Ticket string `json:"ticket"` + Action string `json:"action"` + Origin string `json:"origin"` + ExpiresAt time.Time `json:"expires_at"` +} + +func New(cfg config.PluginProxyConfig, db *database.DB, resolve Resolve, authorize Authorize) *Service { + return &Service{cfg: cfg.Effective(), db: db, resolve: resolve, authorize: authorize, listeners: map[string]*http.Server{}, + tickets: map[[32]byte]grant{}, sessions: map[[32]byte]*browserSession{}} +} + +// SetPlatformTokenCheck is configured during application assembly. +func (s *Service) SetPlatformTokenCheck(fn func(string) bool) { s.isPlatformToken = fn } + +func (s *Service) Start(bindHost string, mainPort int, tlsConfig *tls.Config) { + s.mu.Lock() + defer s.mu.Unlock() + if s.cfg.BindHost != "" { + bindHost = s.cfg.BindHost + } + s.bindHost, s.mainPort, s.tlsConfig, s.started = bindHost, mainPort, tlsConfig, true +} + +func (s *Service) isReady() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.started +} + +func (s *Service) Shutdown() { + s.mu.Lock() + defer s.mu.Unlock() + s.started = false + for id, server := range s.listeners { + _ = server.Close() + delete(s.listeners, id) + } + clear(s.tickets) + for key, session := range s.sessions { + session.cancel() + delete(s.sessions, key) + } +} + +func (s *Service) Revoke(id string) { + s.mu.Lock() + defer s.mu.Unlock() + for key, ticket := range s.tickets { + if ticket.install == id { + delete(s.tickets, key) + } + } + for key, session := range s.sessions { + if session.install == id { + session.cancel() + delete(s.sessions, key) + } + } +} + +func (s *Service) Retire(ctx context.Context, id string) error { + s.Revoke(id) + s.mu.Lock() + defer s.mu.Unlock() + if listener := s.listeners[id]; listener != nil { + _ = listener.Close() + delete(s.listeners, id) + } + return s.db.RetirePluginWebOrigin(ctx, id) +} + +func (s *Service) parentOrigin(r *http.Request) (string, error) { + scheme := "http" + if r.TLS != nil { + scheme = "https" + } + expected := scheme + "://" + r.Host + if s.cfg.PublicOrigin != "" { + expected = s.cfg.PublicOrigin + } + normalized, err := canonicalOrigin(expected) + if err != nil { + return "", ErrForbidden + } + origins := r.Header.Values("Origin") + if len(origins) > 1 { + return "", ErrForbidden + } + if len(origins) == 1 { + client, err := canonicalOrigin(origins[0]) + if err != nil || client != normalized { + return "", ErrForbidden + } + } + return normalized, nil +} + +var dnsOrigin = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$`) + +func canonicalOrigin(raw string) (string, error) { + u, err := url.Parse(raw) + if err != nil || u.User != nil || u.Hostname() == "" || u.Fragment != "" || u.RawQuery != "" || u.ForceQuery || + (u.Scheme != "http" && u.Scheme != "https") || (u.Path != "" && u.Path != "/") { + return "", ErrForbidden + } + host := strings.ToLower(u.Hostname()) + if ip, err := netip.ParseAddr(host); err != nil { + if len(host) > 253 || !dnsOrigin.MatchString(host) { + return "", ErrForbidden + } + } else if ip.Zone() != "" { + return "", ErrForbidden + } + port := u.Port() + if (u.Scheme == "https" && port == "443") || (u.Scheme == "http" && port == "80") { + port = "" + } + if port != "" { + n, err := strconv.Atoi(port) + if err != nil || n < 1 || n > 65535 { + return "", ErrForbidden + } + host = net.JoinHostPort(host, port) + } else if strings.Contains(host, ":") { + host = "[" + host + "]" + } + return u.Scheme + "://" + host, nil +} + +func (s *Service) Issue(r *http.Request, id, token string, mainExpiry time.Time) (Embed, error) { + ctx := r.Context() + parsed, err := uuid.Parse(id) + if err != nil || parsed.String() != id || token == "" || !s.authorize(ctx, id, token) { + return Embed{}, ErrForbidden + } + parent, err := s.parentOrigin(r) + if err != nil { + return Embed{}, err + } + target, err := s.resolve(ctx, id) + if err != nil { + return Embed{}, ErrUnavailable + } + s.mu.Lock() + defer s.mu.Unlock() + if !s.started { + return Embed{}, ErrUnavailable + } + now := time.Now() + s.prune(now) + if len(s.tickets)+len(s.sessions) >= maxSessions { + return Embed{}, ErrUnavailable + } + origin, err := s.origin(ctx, id, parent) + if err != nil { + return Embed{}, err + } + tokenText, hash, err := opaque() + if err != nil { + return Embed{}, err + } + expires := now.Add(ticketTTL) + if mainExpiry.Before(expires) { + expires = mainExpiry + } + if !expires.After(now) { + return Embed{}, ErrForbidden + } + s.tickets[hash] = grant{install: id, parentOrigin: parent, pluginOrigin: origin, generation: target.Generation, mainToken: token, expires: expires} + return Embed{Ticket: tokenText, Action: origin + SessionPath, Origin: origin, ExpiresAt: expires}, nil +} + +func (s *Service) origin(ctx context.Context, id, parent string) (string, error) { + row, err := s.db.PluginWebOrigin(ctx, id) + parentURL, _ := url.Parse(parent) + switch { + case errors.Is(err, sql.ErrNoRows): + row = database.PluginWebOrigin{InstallID: id, Mode: s.cfg.Mode} + if s.cfg.Mode == "host" { + row.Hostname = "p-" + id + "." + s.cfg.HostSuffix + if row.Hostname == parentURL.Hostname() { + return "", ErrForbidden + } + } else { + rows, err := s.db.PluginWebOrigins(ctx) + if err != nil { + return "", err + } + used := map[int]bool{} + for _, entry := range rows { + if entry.Mode == "port" { + used[entry.Port] = true + } + } + parentPort := parentURL.Port() + if parentPort == "" { + parentPort = "80" + if parentURL.Scheme == "https" { + parentPort = "443" + } + } + for port := s.cfg.PortPool.Start; port <= s.cfg.PortPool.End; port++ { + if used[port] || port == s.mainPort || strconv.Itoa(s.externalPort(port)) == parentPort { + continue + } + row.Port = port + if err := s.listen(row); err == nil { + break + } + row.Port = 0 + } + if row.Port == 0 { + return "", ErrUnavailable + } + } + if err := s.db.SavePluginWebOrigin(ctx, row); err != nil { + if srv := s.listeners[id]; srv != nil { + _ = srv.Close() + delete(s.listeners, id) + } + return "", err + } + case err != nil: + return "", err + case row.Retired != nil || row.Mode != s.cfg.Mode: + return "", ErrUnavailable + } + host := row.Hostname + if row.Mode == "port" { + if row.Port < s.cfg.PortPool.Start || row.Port > s.cfg.PortPool.End || row.Port == s.mainPort { + return "", ErrUnavailable + } + if err := s.listen(row); err != nil { + return "", err + } + host = net.JoinHostPort(parentURL.Hostname(), strconv.Itoa(s.externalPort(row.Port))) + } else if parentURL.Port() != "" { + host = net.JoinHostPort(host, parentURL.Port()) + } + origin, err := canonicalOrigin(parentURL.Scheme + "://" + host) + if err != nil || origin == parent { + return "", ErrForbidden + } + return origin, nil +} + +func (s *Service) externalPort(port int) int { + if mapped, ok := s.cfg.ExternalPorts[port]; ok { + return mapped + } + return port +} + +// listen runs with the origin lock held. Each port is scoped to its installation, +// even if two browser origins use the same host-only cookie namespace. +func (s *Service) listen(row database.PluginWebOrigin) error { + if s.listeners[row.InstallID] != nil { + return nil + } + ln, err := net.Listen("tcp", net.JoinHostPort(s.bindHost, strconv.Itoa(row.Port))) + if err != nil { + return err + } + server := &http.Server{Handler: s.Handler(row.InstallID), ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second, + MaxHeaderBytes: 32 << 10} + if s.tlsConfig != nil { + server.TLSConfig = s.tlsConfig.Clone() + } + s.listeners[row.InstallID] = server + go func() { + if server.TLSConfig != nil { + _ = server.ServeTLS(ln, "", "") + } else { + _ = server.Serve(ln) + } + }() + return nil +} + +func (s *Service) Wrap(main http.Handler) http.Handler { + if s.cfg.Mode != "host" { + return main + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + host := r.Host + if name, _, err := net.SplitHostPort(host); err == nil { + host = name + } + host = strings.ToLower(host) + label, ok := strings.CutSuffix(host, "."+s.cfg.HostSuffix) + if !ok || !strings.HasPrefix(label, "p-") { + main.ServeHTTP(w, r) + return + } + id := strings.TrimPrefix(label, "p-") + parsed, err := uuid.Parse(id) + if err != nil || parsed.String() != id { + http.NotFound(w, r) + return + } + s.Handler(id).ServeHTTP(w, r) + }) +} + +func (s *Service) prune(now time.Time) { + for key, ticket := range s.tickets { + if !ticket.expires.After(now) { + delete(s.tickets, key) + } + } + for key, session := range s.sessions { + if !session.expires.After(now) { + session.cancel() + delete(s.sessions, key) + } + } +} + +func opaque() (string, [32]byte, error) { + var b [32]byte + if _, err := rand.Read(b[:]); err != nil { + return "", [32]byte{}, err + } + value := base64.RawURLEncoding.EncodeToString(b[:]) + return value, sha256.Sum256([]byte(value)), nil +} + +func cookieName(id string, secure bool) string { + prefix := "csai_plugin_" + if secure { + prefix = "__Host-" + prefix + } + return prefix + id +} + +func (s *Service) exchange(w http.ResponseWriter, r *http.Request, id string) { + if r.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + r.Body = http.MaxBytesReader(w, r.Body, 4096) + if err := r.ParseForm(); err != nil || len(r.PostForm["ticket"]) != 1 || len(r.URL.Query()) != 0 { + http.Error(w, "invalid ticket", http.StatusBadRequest) + return + } + hash := sha256.Sum256([]byte(r.PostForm.Get("ticket"))) + s.mu.Lock() + now := time.Now() + s.prune(now) + ticket, ok := s.tickets[hash] + if !ok || ticket.install != id || !matchesOrigin(r, ticket.pluginOrigin) || !requestOrigin(r, ticket.parentOrigin, true) { + s.mu.Unlock() + http.Error(w, "ticket rejected", http.StatusForbidden) + return + } + delete(s.tickets, hash) + s.mu.Unlock() + if !s.authorize(r.Context(), id, ticket.mainToken) { + http.Error(w, "ticket revoked", http.StatusForbidden) + return + } + target, err := s.resolve(r.Context(), id) + if err != nil || target.Generation != ticket.generation { + http.Error(w, "ticket expired", http.StatusForbidden) + return + } + jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) + if err != nil { + http.Error(w, "session unavailable", http.StatusServiceUnavailable) + return + } + raw, key, err := opaque() + if err != nil { + http.Error(w, "session unavailable", http.StatusServiceUnavailable) + return + } + sessionCtx, cancel := context.WithTimeout(context.Background(), sessionTTL) + ticket.expires = now.Add(sessionTTL) + s.mu.Lock() + if !s.started || len(s.tickets)+len(s.sessions) >= maxSessions { + s.mu.Unlock() + cancel() + http.Error(w, "session unavailable", http.StatusServiceUnavailable) + return + } + s.sessions[key] = &browserSession{grant: ticket, jar: jar, ctx: sessionCtx, cancel: cancel} + s.mu.Unlock() + secure := strings.HasPrefix(ticket.pluginOrigin, "https://") + sameSite := http.SameSiteLaxMode + if secure { + sameSite = http.SameSiteNoneMode + } + http.SetCookie(w, &http.Cookie{Name: cookieName(id, secure), Value: raw, Path: "/", HttpOnly: true, Secure: secure, + SameSite: sameSite, Partitioned: secure, MaxAge: int(sessionTTL.Seconds())}) + w.Header().Set("Cache-Control", "no-store") + entry := target.EntryPath + if entry == "" { + entry = "/" + } + http.Redirect(w, r, routePrefix(id, target.Route)+entry, http.StatusSeeOther) +} + +func matchesOrigin(r *http.Request, expected string) bool { + u, err := url.Parse(expected) + if err != nil { + return false + } + actual, err := canonicalOrigin(u.Scheme + "://" + r.Host) + return err == nil && actual == expected +} + +func requestOrigin(r *http.Request, want string, required bool) bool { + values := r.Header.Values("Origin") + if len(values) == 0 { + return !required + } + if len(values) != 1 { + return false + } + origin, err := canonicalOrigin(values[0]) + return err == nil && origin == want +} diff --git a/internal/pluginhub/webproxy/server_test.go b/internal/pluginhub/webproxy/server_test.go new file mode 100644 index 00000000..133d7b3b --- /dev/null +++ b/internal/pluginhub/webproxy/server_test.go @@ -0,0 +1,306 @@ +package webproxy + +import ( + "bufio" + "context" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + + "github.com/google/uuid" + "github.com/gorilla/websocket" + "go.uber.org/zap" +) + +func fixtureInstall(t *testing.T, db *database.DB) string { + t.Helper() + id := uuid.NewString() + _, err := db.Exec(`INSERT INTO plugin_installs(id,plugin_id,source_identity,title,driver,observed_state,created_at,updated_at) + VALUES(?,?,?,?,?,'healthy',?,?)`, id, id, id, id, "release", time.Now().UTC(), time.Now().UTC()) + if err != nil { + t.Fatal(err) + } + return id +} + +func issueFixture(t *testing.T, s *Service, parent, id string) Embed { + t.Helper() + request := httptest.NewRequest(http.MethodPost, parent+"/api/plugins/installs/"+id+"/embed-sessions", nil) + request.Header.Set("Origin", parent) + out, err := s.Issue(request, id, "platform-token", time.Now().Add(time.Hour)) + if err != nil { + t.Fatal(err) + } + return out +} + +func exchangeFixture(t *testing.T, client *http.Client, embed Embed, parent string, want int) *http.Cookie { + t.Helper() + req, err := http.NewRequest(http.MethodPost, embed.Action, strings.NewReader(url.Values{"ticket": {embed.Ticket}}.Encode())) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Origin", parent) + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != want { + t.Fatalf("exchange status=%d want=%d", resp.StatusCode, want) + } + if want != 303 { + return nil + } + cookies := resp.Cookies() + if len(cookies) != 1 || !cookies[0].HttpOnly || cookies[0].Path != "/" { + t.Fatal("missing protected plugin session cookie") + } + return cookies[0] +} + +func TestPluginPortOriginsCookiesStreamsAndRevocation(t *testing.T) { + db, err := database.NewDB(filepath.Join(t.TempDir(), "proxy.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + a, b := fixtureInstall(t, db), fixtureInstall(t, db) + var parent = "http://127.0.0.1:19000" + var gen atomic.Int64 + gen.Store(1) + showStream := make(chan struct{}) + upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "" || strings.Contains(r.Header.Get("Cookie"), "platform-secret") { + http.Error(w, "platform credential forwarded", 500) + return + } + switch r.URL.Path { + case "/ws": + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + defer conn.Close() + for { + typ, msg, err := conn.ReadMessage() + if err != nil { + return + } + if conn.WriteMessage(typ, msg) != nil { + return + } + } + case "/events": + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: first\n\n") + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + case <-showStream: + _, _ = io.WriteString(w, "data: second\n\n") + } + case "/_next/static/app.js": + _, _ = io.WriteString(w, "fixture bundle") + case "/api/set": + http.SetCookie(w, &http.Cookie{Name: "app", Value: "jar-cookie", Path: "/", HttpOnly: true}) + w.WriteHeader(http.StatusNoContent) + case "/api/get": + cookie, _ := r.Cookie("app") + if cookie != nil { + _, _ = io.WriteString(w, cookie.Value) + } + default: + http.NotFound(w, r) + } + })) + defer upstream.Close() + s := New(config.PluginProxyConfig{Mode: "port", PortPool: config.PluginPortPool{Start: 44100, End: 44300}}, db, + func(context.Context, string) (Target, error) { + return Target{Endpoint: upstream.URL, Route: "root", EntryPath: "/", Generation: gen.Load()}, nil + }, + func(_ context.Context, id, token string) bool { + return (id == a || id == b) && token == "platform-token" + }) + s.Start("127.0.0.1", 19000, nil) + defer s.Shutdown() + client := &http.Client{Timeout: 3 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + x, y := issueFixture(t, s, parent, a), issueFixture(t, s, parent, b) + if x.Origin == y.Origin { + t.Fatal("instances shared a browser origin") + } + ca := exchangeFixture(t, client, x, parent, 303) + cb := exchangeFixture(t, client, y, parent, 303) + exchangeFixture(t, client, x, parent, 403) + get := func(origin, path string, cookie *http.Cookie, want int) string { + t.Helper() + req, _ := http.NewRequest(http.MethodGet, origin+path, nil) + req.AddCookie(cookie) + req.AddCookie(&http.Cookie{Name: "auth_token", Value: "platform-secret"}) + req.Header.Set("Authorization", "Bearer platform-secret") + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode != want { + t.Fatalf("%s %d: %s", path, resp.StatusCode, body) + } + if len(resp.Cookies()) != 0 { + t.Fatal("upstream cookie leaked to browser") + } + if want < 400 && !strings.Contains(resp.Header.Get("Content-Security-Policy"), "frame-ancestors "+parent) { + t.Fatal("wrong iframe ancestor policy") + } + return string(body) + } + get(y.Origin, "/api/get", ca, 401) + get(x.Origin, "/api/set", ca, 204) + if got := get(x.Origin, "/api/get", ca, 200); got != "jar-cookie" { + t.Fatalf("lost backend cookie: %s", got) + } + if got := get(y.Origin, "/api/get", cb, 200); got != "" { + t.Fatal("cookie jar crossed instances") + } + if got := get(x.Origin, "/_next/static/app.js", ca, 200); got != "fixture bundle" { + t.Fatal("root asset was not proxied") + } + + req, _ := http.NewRequest(http.MethodGet, x.Origin+"/events", nil) + req.AddCookie(ca) + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + line, err := bufio.NewReader(resp.Body).ReadString('\n') + if err != nil || line != "data: first\n" { + t.Fatalf("SSE did not flush: %q %v", line, err) + } + resp.Body.Close() + + headers := http.Header{"Origin": {x.Origin}, "Cookie": {ca.String()}} + socket, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(x.Origin, "http")+"/ws", headers) + if err != nil { + t.Fatal(err) + } + defer socket.Close() + socket.SetReadDeadline(time.Now().Add(3 * time.Second)) + if err := socket.WriteMessage(websocket.TextMessage, []byte("fixture echo")); err != nil { + t.Fatal(err) + } + _, message, err := socket.ReadMessage() + if err != nil || string(message) != "fixture echo" { + t.Fatalf("WS proxy: %s %v", message, err) + } + gen.Add(1) + if _, _, err := socket.ReadMessage(); err == nil { + t.Fatal("stale websocket remained active") + } + get(x.Origin, "/api/get", ca, 401) + if err := s.Retire(context.Background(), a); err != nil { + t.Fatal(err) + } + saved, err := db.PluginWebOrigin(context.Background(), a) + if err != nil || saved.Retired == nil { + t.Fatal("retired port was not recorded") + } +} + +func TestPluginHostModeTLSAndRedirectPolicies(t *testing.T) { + db, err := database.NewDB(filepath.Join(t.TempDir(), "host.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + id := fixtureInstall(t, db) + parent := "https://console.localhost" + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/home": + http.SetCookie(w, &http.Cookie{Name: "secure_app", Value: "secure-jar", Path: "/", Secure: true}) + http.Redirect(w, r, "/login", http.StatusFound) + case "/login": + c, _ := r.Cookie("secure_app") + if c != nil { + _, _ = fmt.Fprint(w, c.Value) + } + default: + http.Redirect(w, r, "https://outside.example/escape", http.StatusFound) + } + })) + defer upstream.Close() + s := New(config.PluginProxyConfig{Mode: "host", HostSuffix: "localhost", PublicOrigin: parent}, db, + func(context.Context, string) (Target, error) { + return Target{Endpoint: upstream.URL, Route: "relative_prefix", EntryPath: "/home", Generation: 7}, nil + }, + func(context.Context, string, string) bool { return true }) + s.Start("127.0.0.1", 443, nil) + defer s.Shutdown() + main := httptest.NewTLSServer(s.Wrap(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) }))) + defer main.Close() + transport := main.Client().Transport.(*http.Transport).Clone() + transport.TLSClientConfig.ServerName = main.Certificate().IPAddresses[0].String() // pin the loopback fixture certificate + transport.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, network, main.Listener.Addr().String()) + } + client := &http.Client{Timeout: 3 * time.Second, Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + embed := issueFixture(t, s, parent, id) + if embed.Origin != "https://p-"+id+".localhost" { + t.Fatalf("host origin: %s", embed.Origin) + } + cookie := exchangeFixture(t, client, embed, parent, 303) + if !cookie.Secure || !strings.HasPrefix(cookie.Name, "__Host-") || cookie.Domain != "" { + t.Fatal("TLS cookie not scoped") + } + get := func(path string) (int, string, string) { + req, _ := http.NewRequest(http.MethodGet, embed.Origin+routePrefix(id, "relative_prefix")+path, nil) + req.AddCookie(cookie) + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + if len(resp.Cookies()) != 0 { + t.Fatal("backend cookie escaped server jar") + } + return resp.StatusCode, resp.Header.Get("Location"), string(body) + } + if status, loc, _ := get("/home"); status != 302 || loc != "/apps/"+id+"/login" { + t.Fatalf("redirect: %d %q", status, loc) + } + if status, _, body := get("/login"); status != 200 || body != "secure-jar" { + t.Fatalf("secure jar: %d %q", status, body) + } + if status, _, _ := get("/external"); status != 502 { + t.Fatalf("external Location passed through: %d", status) + } +} + +func TestPluginBuildBasePathRedirectStaysWithinApplication(t *testing.T) { + id := uuid.NewString() + prefix := routePrefix(id, "build_base_path") + target, _ := url.Parse("http://127.0.0.1:48000") + request, _ := url.Parse(target.String() + prefix + "/home") + if location, err := safeLocation(target.String()+prefix+"/login?next=home", request, target, + "https://plugin.localhost:44320", prefix, "build_base_path"); err != nil || location != prefix+"/login?next=home" { + t.Fatalf("location within application: %q %v", location, err) + } + if _, err := safeLocation("/outside-prefix", request, target, "https://plugin.localhost:44320", prefix, "build_base_path"); err == nil { + t.Fatal("build-time prefix allowed an escaping redirect") + } +} diff --git a/internal/security/auth_middleware.go b/internal/security/auth_middleware.go index 8b4d5e24..55024ea6 100644 --- a/internal/security/auth_middleware.go +++ b/internal/security/auth_middleware.go @@ -21,8 +21,18 @@ const ( // AuthMiddleware enforces authentication on protected routes. func AuthMiddleware(manager *AuthManager) gin.HandlerFunc { + return authMiddleware(manager, true) +} + +// AuthMiddlewareWithoutCookie preserves header and streaming-token transport +// while preventing same-host plugin ports from using the primary session cookie. +func AuthMiddlewareWithoutCookie(manager *AuthManager) gin.HandlerFunc { + return authMiddleware(manager, false) +} + +func authMiddleware(manager *AuthManager, allowCookie bool) gin.HandlerFunc { return func(c *gin.Context) { - token := extractTokenFromRequest(c) + token := extractRequestToken(c, allowCookie) session, ok := manager.ValidateToken(token) if !ok { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ @@ -127,6 +137,10 @@ func SessionHasPermission(c *gin.Context, permission string) bool { } func extractTokenFromRequest(c *gin.Context) string { + return extractRequestToken(c, true) +} + +func extractRequestToken(c *gin.Context, allowCookie bool) string { authHeader := c.GetHeader("Authorization") if authHeader != "" { if len(authHeader) > 7 && strings.EqualFold(authHeader[0:7], "Bearer ") { @@ -143,8 +157,10 @@ func extractTokenFromRequest(c *gin.Context) string { } } - if cookie, err := c.Cookie("auth_token"); err == nil { - return strings.TrimSpace(cookie) + if allowCookie { + if cookie, err := c.Cookie("auth_token"); err == nil { + return strings.TrimSpace(cookie) + } } return "" diff --git a/internal/security/rbac.go b/internal/security/rbac.go index cde984c4..1fef058c 100644 --- a/internal/security/rbac.go +++ b/internal/security/rbac.go @@ -13,6 +13,9 @@ import ( // Platform permissions use module:action naming. They are intentionally // separate from AI testing roles under roles/. var PermissionCatalog = map[string]string{ + "plugins:read": "View plugin catalog and authorized installations", + "plugins:use": "Open authorized plugin workspaces", + "plugins:manage": "Inspect sources and manage platform plugin installations", "auth:self": "Manage own session and password", "dashboard:read": "View dashboard summaries", "chat:read": "View conversations", diff --git a/internal/security/rbac_middleware.go b/internal/security/rbac_middleware.go index 42120e1c..07221ad6 100644 --- a/internal/security/rbac_middleware.go +++ b/internal/security/rbac_middleware.go @@ -91,6 +91,8 @@ func permissionAlternativesForRequest(method, path string) []string { func permissionForRequest(method, fullPath string) string { path := strings.TrimPrefix(fullPath, "/api") switch { + case strings.HasPrefix(path, "/plugins/"): + return pluginPermission(method, path) case path == "/rbac/me": return "auth:self" case path == "/rbac/resources": @@ -207,6 +209,30 @@ func permissionForRequest(method, fullPath string) string { } } +func pluginPermission(method, path string) string { + switch method { + case http.MethodGet: + switch path { + case "/plugins/catalog", "/plugins/schemas/:name", "/plugins/installs", "/plugins/installs/:id", "/plugins/llm/channels": + return "plugins:read" + case "/plugins/install-plans/:id", "/plugins/runtime/probes", "/plugins/operations/:id", "/plugins/installs/:id/logs": + return "plugins:manage" + } + case http.MethodPost: + switch path { + case "/plugins/installs/:id/embed-sessions": + return "plugins:use" + case "/plugins/imports/inspect", "/plugins/install-plans", "/plugins/installs", "/plugins/installs/:id/operations": + return "plugins:manage" + } + case http.MethodPatch: + if path == "/plugins/installs/:id/llm" { + return "plugins:manage" + } + } + return "" +} + func crudPermission(method, module string) string { switch method { case http.MethodGet, http.MethodHead: @@ -225,6 +251,10 @@ func resourceAllowed(c *gin.Context, db *database.DB) bool { } path := strings.TrimPrefix(c.FullPath(), "/api") switch { + case pluginPermission(c.Request.Method, path) == "plugins:manage": + return false + case path == "/plugins/installs/:id" || path == "/plugins/installs/:id/embed-sessions": + return db.UserCanAccessResource(session.UserID, session.Scope, "plugin_install", c.Param("id")) case path == "/tool-guard" && isMutationMethod(c.Request.Method): return session.Scope == database.RBACScopeAll case path == "/monitor/stats", path == "/monitor/calls-timeline": diff --git a/web/frontend/src/lib/nav.js b/web/frontend/src/lib/nav.js index 2af4ccf0..2a26dc0f 100644 --- a/web/frontend/src/lib/nav.js +++ b/web/frontend/src/lib/nav.js @@ -2,7 +2,7 @@ * 导航配置:id 即路由段(#/),与后端页面和权限键保持一致。 */ import { - IconArticle, IconBolt, IconBook, IconBranch, IconBriefcase, IconCheckList, + IconApps, IconArticle, IconBolt, IconBook, IconBranch, IconBriefcase, IconCheckList, IconComment, IconFlag, IconFolder, IconHome, IconLock, IconPuzzle, IconServer, IconSetting, IconShield, IconTerminal, IconUser, IconUserGroup } from '@douyinfe/semi-icons'; @@ -45,6 +45,7 @@ export const NAV_TREE = [ ] }, { id: 'chat-files', i18n: 'nav.chatFiles', fallback: '文件管理', icon: IconFolder }, + { id: 'plugin-hub', i18n: 'nav.pluginHub', fallback: '能力平台', icon: IconApps, permission: 'plugins:read' }, { id: 'mcp', i18n: 'nav.mcp', fallback: 'MCP', icon: IconServer, children: [ @@ -86,7 +87,7 @@ export const NAV_TREE = [ export const NAV_SECTIONS = [ { id: 'workspace', i18n: 'nav.groupWorkspace', fallback: '工作台', pages: ['dashboard', 'chat', 'deep-assessments', 'security'] }, { id: 'operations', i18n: 'nav.groupOperations', fallback: '安全作业', pages: ['projects', 'assets', 'vulnerabilities', 'tasks', 'workflows', 'webshell', 'c2', 'chat-files'] }, - { id: 'capabilities', i18n: 'nav.groupCapabilities', fallback: '能力中心', pages: ['mcp', 'knowledge', 'skills', 'agents', 'roles'] }, + { id: 'capabilities', i18n: 'nav.groupCapabilities', fallback: '能力中心', pages: ['plugin-hub', 'mcp', 'knowledge', 'skills', 'agents', 'roles'] }, { id: 'platform', i18n: 'nav.groupPlatform', fallback: '平台管理', pages: ['platform-rbac', 'settings', 'api-docs'] } ]; diff --git a/web/frontend/src/pages/plugin-hub/Drawers.jsx b/web/frontend/src/pages/plugin-hub/Drawers.jsx new file mode 100644 index 00000000..ab8c1156 --- /dev/null +++ b/web/frontend/src/pages/plugin-hub/Drawers.jsx @@ -0,0 +1,714 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { + Banner, Button, Checkbox, Input, InputNumber, Radio, RadioGroup, Select, Space, Tabs, TabPane, Tag, TextArea, Typography +} from '@douyinfe/semi-ui'; +import { IconCheckCircleStroked, IconPlay, IconRefresh, IconStop } from '@douyinfe/semi-icons'; +import { useT } from '../../lib/i18n'; +import { CopyButton, Drawer, JsonViewer, KeyValueList, toastError, toastSuccess } from '../../components/ui'; +import { + driverLabel, pluginApi, pluginErrorText, starterManifestTemplate, stateColor, stateLabel, streamPluginLogs +} from './api'; + +const { Text, Paragraph } = Typography; + +export function PlanApprovalDrawer({ planResponse, channels, visible, onCancel, onConfirmed }) { + const t = useT(); + const [autoBindLLM, setAutoBindLLM] = useState(true); + const [submitting, setSubmitting] = useState(false); + + useEffect(() => { + if (visible) setAutoBindLLM(true); + }, [visible, planResponse?.plan?.id]); + + const plan = planResponse?.plan; + const manifest = planResponse?.manifest; + const llmDeclared = Boolean(manifest?.llm?.bindings?.length); + const defaultChannel = useMemo( + () => (channels || []).find(ch => ch.is_default) || (channels || [])[0] || null, + [channels] + ); + const matchingDefault = useMemo(() => { + if (!llmDeclared || !defaultChannel) return false; + return manifest.llm.bindings.some(b => b.protocol === defaultChannel.protocol); + }, [llmDeclared, defaultChannel, manifest]); + + const handleConfirm = async () => { + if (!plan || !planResponse?.plan_digest) return; + setSubmitting(true); + try { + const op = await pluginApi.install({ + planId: plan.id, + planDigest: planResponse.plan_digest, + autoBindLLM: llmDeclared ? autoBindLLM : undefined + }); + toastSuccess(t('pluginHub.installQueued', null, '安装任务已提交,正在后台准备并启动')); + onConfirmed?.(op); + } catch (err) { + toastError(pluginErrorText(t, err, t('pluginHub.installFailed', null, '提交安装失败'))); + } finally { + setSubmitting(false); + } + }; + + const artifact = plan?.artifact; + + return ( + + + + + } + > + {plan && manifest && ( +
+ {!planResponse.can_confirm && ( + + )} + {manifest.metadata?.repository} }, + { label: t('pluginHub.driver', null, '运行驱动'), value: driverLabel(t, artifact?.driver) }, + { label: t('pluginHub.isolation', null, '隔离档位'), value: plan.isolation }, + { label: t('pluginHub.platform', null, '目标平台'), value: `${plan.platform?.os}/${plan.platform?.arch}` }, + { label: t('pluginHub.approvalPolicy', null, '审批策略'), value: planResponse.approval_policy || 'admin_confirm' }, + { label: 'Manifest SHA-256', value: {plan.manifestSha256} }, + { label: t('pluginHub.artifactDigest', null, '锁定制品摘要'), value: {planResponse.artifact_digest} } + ]} /> + + {artifact?.driver === 'git' && ( + {artifact.commit} ({artifact.requestedRef}) } + ]} /> + )} + {artifact?.driver === 'release' && ( + {artifact.assetURL} }, + { label: 'SHA-256', value: {artifact.sha256} ({artifact.verification}) } + ]} /> + )} + {artifact?.driver === 'container' && Array.isArray(artifact.services) && ( +
+ {t('pluginHub.lockedImages', null, '锁定容器镜像 Digest')} +
+ {artifact.services.map(svc => ( +
+ + {svc.name} + {svc.requestedImage} + + + {svc.repository}@{svc.manifestDigest} + +
+ ))} +
+
+ )} + +
+ {t('pluginHub.declaredPermissions', null, '声明权限摘要')} + + + {t('pluginHub.permPersistentData', null, '持久化数据卷')}: {manifest.permissions?.persistentData ? 'Yes' : 'No'} + + + {t('pluginHub.permModelGateway', null, 'CSAI 模型网关')}: {manifest.permissions?.modelGateway ? 'Yes' : 'No'} + + {(manifest.permissions?.egress || []).map(item => ( + {item} + ))} + +
+ + {llmDeclared && ( +
+ setAutoBindLLM(Boolean(e.target.checked))}> + {t('pluginHub.autoBindDefaultLLM', null, '安装时自动复用 CSAI 默认模型通道(开箱即用,不泄露真实上游 API Key)')} + + {defaultChannel ? ( + + {matchingDefault + ? t('pluginHub.defaultChannelMatch', { name: `${defaultChannel.name} (${defaultChannel.model})` }, `当前默认通道:${defaultChannel.name} (${defaultChannel.model}),协议匹配,启动即自动注入。`) + : t('pluginHub.defaultChannelMismatch', { name: `${defaultChannel.name} (${defaultChannel.protocol})` }, `当前默认通道 ${defaultChannel.name} (${defaultChannel.protocol}) 与该插件声明协议不同,安装后可在插件设置中指定通道。`)} + + ) : ( + + {t('pluginHub.noDefaultChannelHint', null, '尚未在 CSAI 系统设置中配置模型通道,安装后可随时在插件详情中绑定模型。')} + + )} +
+ )} + + +
+ )} +
+ ); +} + +export function ImportGitDrawer({ visible, onCancel, onPlanReady }) { + const t = useT(); + const [repository, setRepository] = useState(''); + const [revision, setRevision] = useState(''); + const [inspecting, setInspecting] = useState(false); + const [inspected, setInspected] = useState(null); + const [manifestText, setManifestText] = useState(''); + const [driver, setDriver] = useState('auto'); + const [isolation, setIsolation] = useState('standard'); + const [planning, setPlanning] = useState(false); + + const handleInspect = async () => { + if (!repository.trim()) return; + setInspecting(true); + setInspected(null); + try { + const res = await pluginApi.inspectGit(repository, revision); + setInspected(res); + if (res?.inspection?.manifest) { + setManifestText(JSON.stringify(res.inspection.manifest, null, 2)); + } else { + setManifestText(starterManifestTemplate(res?.inspection)); + } + toastSuccess(t('pluginHub.inspectSucceeded', null, '仓库只读探测完成')); + } catch (err) { + toastError(pluginErrorText(t, err, t('pluginHub.inspectFailed', null, '探测仓库失败'))); + } finally { + setInspecting(false); + } + }; + + const handleGeneratePlan = async () => { + if (!inspected?.id) return; + let parsedManifest; + try { + parsedManifest = JSON.parse(manifestText); + } catch { + toastError(t('pluginHub.manifestJsonInvalid', null, 'Manifest 草案需为合法 JSON 格式')); + return; + } + setPlanning(true); + try { + const planRes = await pluginApi.createPlan({ + inspection_id: inspected.id, + manifest: parsedManifest, + driver, + isolation + }); + onPlanReady?.(planRes); + } catch (err) { + toastError(pluginErrorText(t, err, t('pluginHub.createPlanFailed', null, '生成锁定安装计划失败'))); + } finally { + setPlanning(false); + } + }; + + const info = inspected?.inspection; + + return ( + + + + + } + > +
+ + {t('pluginHub.importDesc', null, '输入公开 GitHub HTTPS 仓库地址后,CSAI 会以只读方式解析 Commit、根目录 csai-plugin.yaml 及构建/容器线索,不会执行任何第三方代码。')} + + +
+ {t('pluginHub.repositoryURL', null, 'GitHub 仓库地址')} + +
+
+ {t('pluginHub.revisionOptional', null, '分支 / Tag / Commit(可选)')} + +
+ +
+ + {info && ( + <> +
+ {info.repository} }, + { label: t('pluginHub.resolvedRef', null, '解析引用'), value: {info.resolved_ref} }, + { label: 'Commit', value: {info.commit} }, + { label: t('pluginHub.detectedCandidates', null, '候选驱动'), value: (info.candidates || []).map(c => {c}) } + ]} /> + {info.evidence?.length > 0 && ( + + {t('pluginHub.detectedFiles', null, '检测到文件')}: + {info.evidence.map(file => {file})} + + )} + {info.release?.tag && ( + + Release {info.release.tag}: {(info.release.assets || []).slice(0, 6).join(', ') || '—'} + + )} +
+ + +
+ {t('pluginHub.driver', null, '安装驱动')} + +
+
+ +
+ + + {info.manifest + ? t('pluginHub.manifestFromRepo', null, '已从仓库读取 csai-plugin.yaml(可审阅)') + : t('pluginHub.manifestDraftLabel', null, '仓库无自带 Manifest,请编辑以下接入草案(JSON)')} + + +