feat(plugin-hub): add plugin capability platform with embedded WebUI proxy and unified LLM gateway

This commit is contained in:
Sycun 2026-11-28 20:10:45 +08:00
parent 43aa4fe1eb
commit aaa284586f
127 changed files with 15299 additions and 168 deletions

View File

@ -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:
# # "<manifest SHA-256>": ["<artifact SHA-256>"]
# 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 # 登录有效期(小时),超时后需重新登录

2
go.mod
View File

@ -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

View File

@ -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)

View File

@ -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())
}
})
}
}

View File

@ -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
}

205
internal/config/plugins.go Normal file
View File

@ -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
}

View File

@ -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))
}

View File

@ -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)
}
}

View File

@ -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()
}

View File

@ -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
}

View File

@ -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")
}
}

View File

@ -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":

View File

@ -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);

469
internal/handler/plugins.go Normal file
View File

@ -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})
}

View File

@ -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())
}

View File

@ -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"

View File

@ -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
}
}

View File

@ -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)
}
}
}

View File

@ -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: []}

View File

@ -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("<h1>Embedded Plugin OK</h1>"))
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)
}
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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 &copy, 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)
}
}

View File

@ -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()
}

View File

@ -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}))
}
}

View File

@ -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)
}
}

View File

@ -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
}

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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
}

View File

@ -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"
}
}
}
}
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -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"

View File

@ -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)
}

View File

@ -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
}

View File

@ -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()
}()
}

View File

@ -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)
}
}

View File

@ -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()
}

View File

@ -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")
}
}

View File

@ -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)
}
}

View File

@ -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)
}
}

View File

@ -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()
}

View File

@ -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
}

View File

@ -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)
}

View File

@ -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)
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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)
}
}

View File

@ -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
}

View File

@ -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")
}
}

View File

@ -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 &copy
}
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)
}

View File

@ -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
}

View File

@ -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")
}
}

View File

@ -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,9 +157,11 @@ func extractTokenFromRequest(c *gin.Context) string {
}
}
if allowCookie {
if cookie, err := c.Cookie("auth_token"); err == nil {
return strings.TrimSpace(cookie)
}
}
return ""
}

View File

@ -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",

View File

@ -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":

View File

@ -2,7 +2,7 @@
* 导航配置:id 即路由段(#/<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'] }
];

View File

@ -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 (
<Drawer
title={t('pluginHub.planApprovalTitle', null, '确认插件安装计划')}
visible={visible}
onCancel={onCancel}
width={680}
footer={
<Space>
<Button onClick={onCancel}>{t('common.cancel', null, '取消')}</Button>
<Button
theme="solid"
type="primary"
loading={submitting}
disabled={!planResponse?.can_confirm}
onClick={handleConfirm}
>
{t('pluginHub.confirmInstall', null, '确认并一键安装')}
</Button>
</Space>
}
>
{plan && manifest && (
<div className="cs-ph-drawer-stack">
{!planResponse.can_confirm && (
<Banner
type="warning"
bordered
closeIcon={null}
description={t('pluginHub.hostApprovalRequiredBanner', null, '当前宿主开启了 host_config_only 策略,需要先将下方 Manifest 与制品摘要写入 config.yaml 的 plugins.approved_artifacts 后方可安装。')}
/>
)}
<KeyValueList columns={2} items={[
{ label: t('pluginHub.pluginTitle', null, '插件名称'), value: `${manifest.metadata?.title || manifest.metadata?.id} (${manifest.metadata?.version || '—'})` },
{ label: t('pluginHub.repository', null, '原作者仓库'), value: <span className="cs-ph-mono">{manifest.metadata?.repository}</span> },
{ 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: <span className="cs-ph-mono">{plan.manifestSha256}</span> },
{ label: t('pluginHub.artifactDigest', null, '锁定制品摘要'), value: <span className="cs-ph-mono">{planResponse.artifact_digest}</span> }
]} />
{artifact?.driver === 'git' && (
<KeyValueList columns={1} items={[
{ label: t('pluginHub.lockedCommit', null, '锁定 Git Commit'), value: <span className="cs-ph-mono">{artifact.commit} ({artifact.requestedRef})</span> }
]} />
)}
{artifact?.driver === 'release' && (
<KeyValueList columns={1} items={[
{ label: t('pluginHub.lockedReleaseAsset', null, '锁定 Release 制品'), value: <span className="cs-ph-mono">{artifact.assetURL}</span> },
{ label: 'SHA-256', value: <span className="cs-ph-mono">{artifact.sha256} ({artifact.verification})</span> }
]} />
)}
{artifact?.driver === 'container' && Array.isArray(artifact.services) && (
<div>
<Text strong>{t('pluginHub.lockedImages', null, '锁定容器镜像 Digest')}</Text>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 6 }}>
{artifact.services.map(svc => (
<div key={svc.name} className="cs-ph-probe-card">
<Space>
<Tag color="blue" size="small">{svc.name}</Tag>
<Text size="small" className="cs-ph-mono">{svc.requestedImage}</Text>
</Space>
<Text type="tertiary" size="small" className="cs-ph-mono">
{svc.repository}@{svc.manifestDigest}
</Text>
</div>
))}
</div>
</div>
)}
<div className="cs-ph-probe-card">
<Text strong>{t('pluginHub.declaredPermissions', null, '声明权限摘要')}</Text>
<Space wrap>
<Tag color={manifest.permissions?.persistentData ? 'amber' : 'grey'}>
{t('pluginHub.permPersistentData', null, '持久化数据卷')}: {manifest.permissions?.persistentData ? 'Yes' : 'No'}
</Tag>
<Tag color={manifest.permissions?.modelGateway ? 'blue' : 'grey'}>
{t('pluginHub.permModelGateway', null, 'CSAI 模型网关')}: {manifest.permissions?.modelGateway ? 'Yes' : 'No'}
</Tag>
{(manifest.permissions?.egress || []).map(item => (
<Tag key={item} color="purple">{item}</Tag>
))}
</Space>
</div>
{llmDeclared && (
<div className="cs-ph-probe-card">
<Checkbox checked={autoBindLLM} onChange={e => setAutoBindLLM(Boolean(e.target.checked))}>
{t('pluginHub.autoBindDefaultLLM', null, '安装时自动复用 CSAI 默认模型通道(开箱即用,不泄露真实上游 API Key)')}
</Checkbox>
{defaultChannel ? (
<Text type="tertiary" size="small">
{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}) 与该插件声明协议不同,安装后可在插件设置中指定通道。`)}
</Text>
) : (
<Text type="tertiary" size="small">
{t('pluginHub.noDefaultChannelHint', null, '尚未在 CSAI 系统设置中配置模型通道,安装后可随时在插件详情中绑定模型。')}
</Text>
)}
</div>
)}
<JsonViewer value={manifest} collapsed title="Manifest" />
</div>
)}
</Drawer>
);
}
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 (
<Drawer
title={t('pluginHub.importTitle', null, '手工导入 Git 仓库插件')}
visible={visible}
onCancel={onCancel}
width={720}
footer={
<Space>
<Button onClick={onCancel}>{t('common.cancel', null, '取消')}</Button>
<Button
theme="solid"
type="primary"
loading={planning}
disabled={!inspected?.id || !manifestText.trim()}
onClick={handleGeneratePlan}
>
{t('pluginHub.generatePlan', null, '生成锁定安装计划')}
</Button>
</Space>
}
>
<div className="cs-ph-drawer-stack">
<Paragraph type="tertiary" style={{ margin: 0 }}>
{t('pluginHub.importDesc', null, '输入公开 GitHub HTTPS 仓库地址后,CSAI 会以只读方式解析 Commit、根目录 csai-plugin.yaml 及构建/容器线索,不会执行任何第三方代码。')}
</Paragraph>
<Space style={{ width: '100%' }} align="end" wrap>
<div style={{ flex: 2, minWidth: 280 }}>
<Text strong size="small">{t('pluginHub.repositoryURL', null, 'GitHub 仓库地址')}</Text>
<Input
value={repository}
onChange={setRepository}
placeholder="https://github.com/owner/repo"
style={{ marginTop: 4 }}
/>
</div>
<div style={{ flex: 1, minWidth: 140 }}>
<Text strong size="small">{t('pluginHub.revisionOptional', null, '分支 / Tag / Commit(可选)')}</Text>
<Input
value={revision}
onChange={setRevision}
placeholder="main / v1.0.0"
style={{ marginTop: 4 }}
/>
</div>
<Button theme="solid" type="primary" loading={inspecting} onClick={handleInspect}>
{t('pluginHub.inspectRepo', null, '只读探测')}
</Button>
</Space>
{info && (
<>
<div className="cs-ph-probe-card">
<KeyValueList columns={2} items={[
{ label: t('pluginHub.repository', null, '标准化仓库'), value: <span className="cs-ph-mono">{info.repository}</span> },
{ label: t('pluginHub.resolvedRef', null, '解析引用'), value: <span className="cs-ph-mono">{info.resolved_ref}</span> },
{ label: 'Commit', value: <span className="cs-ph-mono">{info.commit}</span> },
{ label: t('pluginHub.detectedCandidates', null, '候选驱动'), value: (info.candidates || []).map(c => <Tag key={c} size="small" style={{ marginInlineEnd: 4 }}>{c}</Tag>) }
]} />
{info.evidence?.length > 0 && (
<Space wrap style={{ marginTop: 6 }}>
<Text size="small" type="tertiary">{t('pluginHub.detectedFiles', null, '检测到文件')}:</Text>
{info.evidence.map(file => <Tag key={file} size="small" color="cyan">{file}</Tag>)}
</Space>
)}
{info.release?.tag && (
<Text size="small" type="tertiary">
Release {info.release.tag}: {(info.release.assets || []).slice(0, 6).join(', ') || '—'}
</Text>
)}
</div>
<Space wrap>
<div>
<Text strong size="small">{t('pluginHub.driver', null, '安装驱动')}</Text>
<Select
value={driver}
onChange={setDriver}
style={{ width: 240, display: 'block', marginTop: 4 }}
optionList={[
{ value: 'auto', label: driverLabel(t, 'auto') },
{ value: 'release', label: driverLabel(t, 'release') },
{ value: 'git', label: driverLabel(t, 'git') },
{ value: 'container', label: driverLabel(t, 'container') }
]}
/>
</div>
<div>
<Text strong size="small">{t('pluginHub.isolation', null, '隔离档位')}</Text>
<Select
value={isolation}
onChange={setIsolation}
style={{ width: 200, display: 'block', marginTop: 4 }}
optionList={[
{ value: 'standard', label: t('pluginHub.isolationStandard', null, 'standard(非 root 单机默认)') },
{ value: 'strict', label: t('pluginHub.isolationStrict', null, 'strict(强制容器隔离)') }
]}
/>
</div>
</Space>
<div>
<Space style={{ justifyContent: 'space-between', width: '100%', marginBottom: 4 }}>
<Text strong size="small">
{info.manifest
? t('pluginHub.manifestFromRepo', null, '已从仓库读取 csai-plugin.yaml(可审阅)')
: t('pluginHub.manifestDraftLabel', null, '仓库无自带 Manifest,请编辑以下接入草案(JSON)')}
</Text>
</Space>
<TextArea
className="cs-ph-code-editor"
value={manifestText}
onChange={setManifestText}
autosize={{ minRows: 12, maxRows: 22 }}
/>
</div>
</>
)}
</div>
</Drawer>
);
}
export function PluginDetailDrawer({
installId, initialTab = 'overview', visible, canManage, channels, onCancel, onRestartRequested, onChanged
}) {
const t = useT();
const [activeTab, setActiveTab] = useState(initialTab);
const [detail, setDetail] = useState(null);
const [loading, setLoading] = useState(false);
// LLM form state
const [llmMode, setLlmMode] = useState('follow_default');
const [channelId, setChannelId] = useState('');
const [concurrency, setConcurrency] = useState(4);
const [rpm, setRpm] = useState(60);
const [tokenBudget, setTokenBudget] = useState(2000000);
const [savingLLM, setSavingLLM] = useState(false);
const [restartBanner, setRestartBanner] = useState(false);
// Log stream state
const [logs, setLogs] = useState([]);
const [streaming, setStreaming] = useState(false);
const logBoxRef = useRef(null);
const abortRef = useRef(null);
useEffect(() => {
if (visible) setActiveTab(initialTab || 'overview');
}, [visible, initialTab, installId]);
const loadDetail = async () => {
if (!installId) return;
setLoading(true);
try {
const data = await pluginApi.getInstall(installId);
setDetail(data);
const first = Array.isArray(data?.llm_bindings) ? data.llm_bindings[0] : null;
if (first) {
setLlmMode(first.mode || 'follow_default');
setChannelId(first.channel_id || '');
setConcurrency(first.concurrency || 4);
setRpm(first.rpm || 60);
setTokenBudget(first.token_budget || 2000000);
} else {
setLlmMode('follow_default');
setChannelId('');
}
setRestartBanner(false);
} catch (err) {
toastError(pluginErrorText(t, err));
} finally {
setLoading(false);
}
};
useEffect(() => {
if (visible && installId) loadDetail();
}, [visible, installId]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!visible || !installId || activeTab !== 'logs' || !canManage) {
abortRef.current?.();
abortRef.current = null;
setStreaming(false);
return undefined;
}
let active = true;
setLogs([]);
(async () => {
try {
const initial = await pluginApi.readLogs(installId, 0, 200);
if (!active) return;
const items = Array.isArray(initial?.items) ? initial.items : [];
setLogs(items);
setStreaming(true);
abortRef.current = streamPluginLogs(installId, {
after: initial?.next_cursor || 0,
onEntry: entry => {
setLogs(prev => [...prev.slice(-499), entry]);
},
onClose: () => setStreaming(false),
onError: () => setStreaming(false)
});
} catch (err) {
if (active) toastError(pluginErrorText(t, err));
}
})();
return () => {
active = false;
abortRef.current?.();
abortRef.current = null;
setStreaming(false);
};
}, [visible, installId, activeTab, canManage]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (logBoxRef.current) {
logBoxRef.current.scrollTop = logBoxRef.current.scrollHeight;
}
}, [logs]);
const saveLLM = async () => {
if (!installId) return;
setSavingLLM(true);
try {
const body = {
mode: llmMode,
channel_id: llmMode === 'channel' ? channelId : '',
limits: {
concurrency: Number(concurrency) || 4,
rpm: Number(rpm) || 60,
token_budget: Number(tokenBudget) || 2000000
}
};
const res = await pluginApi.patchLLM(installId, body);
toastSuccess(t('pluginHub.llmSaved', null, '模型通道绑定已更新'));
setRestartBanner(Boolean(res?.restart_required));
await loadDetail();
onChanged?.();
} catch (err) {
toastError(pluginErrorText(t, err, t('pluginHub.llmSaveFailed', null, '保存模型配置失败')));
} finally {
setSavingLLM(false);
}
};
const declaredProtocols = useMemo(
() => new Set((detail?.llm_declared?.bindings || []).map(b => b.protocol)),
[detail]
);
const compatibleChannels = useMemo(
() => (channels || []).filter(ch => declaredProtocols.size === 0 || declaredProtocols.has(ch.protocol)),
[channels, declaredProtocols]
);
const logText = useMemo(
() => logs.map(item => `[${item.created_at || ''}] ${item.line}`).join('\n'),
[logs]
);
return (
<Drawer
title={detail?.title || detail?.plugin_id || t('pluginHub.detailTitle', null, '插件详情')}
visible={visible}
onCancel={onCancel}
width={760}
>
<Tabs activeKey={activeTab} onChange={setActiveTab}>
<TabPane tab={t('pluginHub.tabOverview', null, '概览与权限')} itemKey="overview">
{detail && (
<div className="cs-ph-drawer-stack" style={{ marginTop: 12 }}>
<KeyValueList columns={2} items={[
{ label: t('pluginHub.installId', null, '实例 ID'), value: <span className="cs-ph-mono">{detail.id}</span> },
{ label: t('pluginHub.pluginId', null, '插件标识'), value: detail.plugin_id },
{ label: t('pluginHub.version', null, '版本'), value: detail.version || '—' },
{ label: t('pluginHub.driver', null, '驱动'), value: driverLabel(t, detail.driver) },
{ label: t('pluginHub.observedState', null, '运行状态'), value: <Tag color={stateColor(detail.observed_state)}>{stateLabel(t, detail.observed_state)}</Tag> },
{ label: t('pluginHub.proxyMode', null, '代理隔离模式'), value: detail.proxy_mode || 'port' },
{ label: t('pluginHub.repository', null, '源码仓库'), value: detail.repository ? <span className="cs-ph-mono">{detail.repository}</span> : '—' },
{ label: t('pluginHub.lastError', null, '最近错误'), value: detail.last_error_code || '—' }
]} />
{detail.summary && <Paragraph type="tertiary">{detail.summary}</Paragraph>}
{detail.permissions && (
<div className="cs-ph-probe-card">
<Text strong>{t('pluginHub.declaredPermissions', null, '声明权限')}</Text>
<Space wrap>
<Tag>{t('pluginHub.permPersistentData', null, '持久化数据卷')}: {detail.permissions.persistentData ? 'Yes' : 'No'}</Tag>
<Tag>{t('pluginHub.permModelGateway', null, 'CSAI 模型网关')}: {detail.permissions.modelGateway ? 'Yes' : 'No'}</Tag>
{(detail.permissions.egress || []).map(e => <Tag key={e} color="purple">{e}</Tag>)}
</Space>
</div>
)}
{detail.extensions?.capabilities?.length > 0 && (
<div className="cs-ph-probe-card">
<Text strong>{t('pluginHub.declaredExtensions', null, '声明的扩展能力(MCP / OpenAPI 预留)')}</Text>
<Space wrap>
{detail.extensions.capabilities.map(cap => (
<Tag key={cap.id} color="cyan">{cap.id} ({cap.transport} {cap.path})</Tag>
))}
</Space>
</div>
)}
</div>
)}
</TabPane>
{detail?.llm_declared && (
<TabPane tab={t('pluginHub.tabLLM', null, 'CSAI 模型绑定')} itemKey="llm">
<div className="cs-ph-drawer-stack" style={{ marginTop: 12 }}>
{restartBanner && (
<Banner
type="info"
bordered
closeIcon={null}
description={
<Space wrap>
<span>{t('pluginHub.restartRequiredForLLM', null, '模型绑定已更新,重启插件后将立即注入新的 CSAI 网关凭据。')}</span>
{canManage && onRestartRequested && (
<Button size="small" theme="solid" type="primary" onClick={() => onRestartRequested(detail)}>
{t('pluginHub.restartNow', null, '立即重启生效')}
</Button>
)}
</Space>
}
/>
)}
<Paragraph type="tertiary" style={{ margin: 0 }}>
{t('pluginHub.llmBindingDesc', null, 'CSAI 通过本地模型网关向插件注入隔离 Token 与通道配置,插件无法接触您的真实上游 API Key。')}
</Paragraph>
<RadioGroup value={llmMode} onChange={e => setLlmMode(e.target.value)} disabled={!canManage}>
<Radio value="follow_default">{t('pluginHub.llmModeFollowDefault', null, '跟随 CSAI 默认模型通道')}</Radio>
<Radio value="channel">{t('pluginHub.llmModeChannel', null, '指定 CSAI 模型通道')}</Radio>
<Radio value="disabled">{t('pluginHub.llmModeDisabled', null, '关闭模型托管')}</Radio>
</RadioGroup>
{llmMode === 'channel' && (
<div>
<Text strong size="small">{t('pluginHub.selectChannel', null, '选择兼容通道')}</Text>
<Select
value={channelId}
onChange={setChannelId}
disabled={!canManage}
style={{ width: '100%', marginTop: 4 }}
placeholder={t('pluginHub.selectChannelPlaceholder', null, '请选择在 CSAI 系统设置中配置的模型通道')}
optionList={compatibleChannels.map(ch => ({
value: ch.id,
label: `${ch.name} (${ch.model} · ${ch.provider})${ch.is_default ? ' [Default]' : ''}`
}))}
/>
</div>
)}
{llmMode !== 'disabled' && (
<Space wrap>
<div>
<Text size="small" type="tertiary">{t('pluginHub.limitConcurrency', null, '并发上限')}</Text>
<InputNumber value={concurrency} onChange={setConcurrency} min={1} max={32} disabled={!canManage} style={{ display: 'block', marginTop: 4 }} />
</div>
<div>
<Text size="small" type="tertiary">{t('pluginHub.limitRPM', null, '每分钟请求 (RPM)')}</Text>
<InputNumber value={rpm} onChange={setRpm} min={1} max={1000} disabled={!canManage} style={{ display: 'block', marginTop: 4 }} />
</div>
<div>
<Text size="small" type="tertiary">{t('pluginHub.limitTokenBudget', null, '每日 Token 预算')}</Text>
<InputNumber value={tokenBudget} onChange={setTokenBudget} min={1000} step={100000} disabled={!canManage} style={{ display: 'block', marginTop: 4, width: 180 }} />
</div>
</Space>
)}
{canManage && (
<div>
<Button theme="solid" type="primary" loading={savingLLM} onClick={saveLLM}>
{t('pluginHub.saveLLM', null, '保存模型配置')}
</Button>
</div>
)}
</div>
</TabPane>
)}
{canManage && (
<TabPane tab={t('pluginHub.logs', null, '运行日志')} itemKey="logs">
<div className="cs-ph-drawer-stack" style={{ marginTop: 12 }}>
<Space style={{ justifyContent: 'space-between', width: '100%' }}>
<Space>
<Tag color={streaming ? 'green' : 'grey'}>
{streaming ? t('pluginHub.logStreaming', null, 'SSE 实时追踪中') : t('pluginHub.logPaused', null, '已停止追踪')}
</Tag>
<Text size="small" type="tertiary">{logs.length} lines</Text>
</Space>
<Space>
<CopyButton text={logText} label={t('common.copy', null, '复制')} />
<Button size="small" icon={<IconRefresh />} onClick={() => setActiveTab('overview') || setTimeout(() => setActiveTab('logs'), 0)}>
{t('common.refresh', null, '刷新')}
</Button>
</Space>
</Space>
<pre ref={logBoxRef} className="cs-ph-log-box">
{logText || t('pluginHub.noLogs', null, '暂无运行日志')}
</pre>
</div>
</TabPane>
)}
</Tabs>
{loading && !detail && <Text type="tertiary">{t('common.loading', null, '加载中…')}</Text>}
</Drawer>
);
}
export function RuntimeProbesDrawer({ visible, onCancel }) {
const t = useT();
const [isolation, setIsolation] = useState('standard');
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const load = async (targetIsolation = isolation) => {
setLoading(true);
try {
const res = await pluginApi.probes(targetIsolation);
setData(res);
} catch (err) {
toastError(pluginErrorText(t, err));
} finally {
setLoading(false);
}
};
useEffect(() => {
if (visible) load(isolation);
}, [visible, isolation]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<Drawer
title={t('pluginHub.runtimeProbesTitle', null, '宿主运行环境与驱动预检')}
visible={visible}
onCancel={onCancel}
width={620}
>
<div className="cs-ph-drawer-stack">
<Space style={{ justifyContent: 'space-between', width: '100%' }} wrap>
<RadioGroup type="button" value={isolation} onChange={e => setIsolation(e.target.value)}>
<Radio value="standard">standard</Radio>
<Radio value="strict">strict</Radio>
</RadioGroup>
<Button icon={<IconRefresh />} loading={loading} onClick={() => load(isolation)}>
{t('common.refresh', null, '重新检测')}
</Button>
</Space>
{data && (
<>
<KeyValueList columns={2} items={[
{ label: t('pluginHub.hostPlatform', null, '宿主平台'), value: `${data.os}/${data.arch}` },
{
label: t('pluginHub.workerReady', null, '运行调度器'),
value: (
<Tag color={data.execution_enabled ? 'green' : 'amber'}>
{data.execution_enabled ? t('pluginHub.ready', null, '就绪') : t('pluginHub.notReady', null, '未就绪')}
</Tag>
)
}
]} />
{Object.entries(data.drivers || {}).map(([name, probe]) => (
<div key={name} className="cs-ph-probe-card">
<Space style={{ justifyContent: 'space-between', width: '100%' }}>
<Text strong>{driverLabel(t, name)}</Text>
<Tag color={probe.available ? 'green' : 'red'} prefixIcon={probe.available ? <IconCheckCircleStroked /> : <IconStop />}>
{probe.available ? t('pluginHub.available', null, '可用') : (probe.code || t('pluginHub.unavailable', null, '不可用'))}
</Tag>
</Space>
{probe.guidance && <Text type="tertiary" size="small">{probe.guidance}</Text>}
</div>
))}
{data.drivers?.container && !data.drivers.container.available && (
<Banner
type="info"
bordered
closeIcon={null}
description={
data.os === 'linux'
? t('pluginHub.dockerInstallLinuxHint', null, 'Linux / Kali 宿主可在确认提权后通过发行版官方源安装 docker.io / docker-ce 与 docker-compose-plugin 并启动 dockerd,完成后点击上方「重新检测」;或优先使用 Release / Git 原生驱动。')
: t('pluginHub.dockerInstallDesktopHint', null, 'macOS / Windows 请先安装并启动 Docker Desktop(或 OrbStack / WSL2 Docker),或选择 Release / Git 原生驱动。')
}
/>
)}
</>
)}
</div>
</Drawer>
);
}

View File

@ -0,0 +1,173 @@
import { useCallback, useEffect, useId, useRef, useState } from 'react';
import { Button, Space, Spin, Tag, Tooltip, Typography } from '@douyinfe/semi-ui';
import {
IconChevronLeft, IconExternalOpen, IconMaximize, IconMinimize, IconRefresh, IconSetting, IconTerminal
} from '@douyinfe/semi-icons';
import { useT } from '../../lib/i18n';
import { toastError } from '../../components/ui';
import { pluginApi, pluginErrorText, stateColor, stateLabel } from './api';
const { Text } = Typography;
function submitTicketForm(action, ticket, target) {
const form = document.createElement('form');
form.method = 'POST';
form.action = action;
form.target = target;
form.style.display = 'none';
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'ticket';
input.value = ticket;
form.appendChild(input);
document.body.appendChild(form);
form.submit();
form.remove();
}
export default function WorkspaceView({ install, canManage, onBack, onOpenDetail, onOpenLogs }) {
const t = useT();
const rawId = useId();
const frameName = `csai-plugin-frame-${rawId.replace(/[^a-zA-Z0-9_-]/g, '')}`;
const containerRef = useRef(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [sessionInfo, setSessionInfo] = useState(null);
const [expanded, setExpanded] = useState(false);
const connect = useCallback(async () => {
if (!install?.id) return;
setLoading(true);
setError('');
try {
const embed = await pluginApi.issueEmbedSession(install.id);
setSessionInfo(embed);
requestAnimationFrame(() => {
submitTicketForm(embed.action, embed.ticket, frameName);
});
} catch (err) {
setError(pluginErrorText(t, err, t('pluginHub.embedInitFailed', null, '无法建立插件工作区会话')));
setLoading(false);
}
}, [install?.id, frameName, t]);
useEffect(() => {
connect();
}, [connect]);
const openStandaloneWindow = async () => {
try {
const embed = await pluginApi.issueEmbedSession(install.id);
const winName = `csai-plugin-standalone-${Date.now()}`;
window.open('about:blank', winName, 'noopener');
submitTicketForm(embed.action, embed.ticket, winName);
} catch (err) {
toastError(pluginErrorText(t, err, t('pluginHub.embedInitFailed', null, '无法打开独立窗口')));
}
};
const toggleFullscreen = async () => {
const el = containerRef.current;
if (!el) return;
if (document.fullscreenElement) {
try { await document.exitFullscreen(); } catch { /* ignore */ }
setExpanded(false);
return;
}
if (el.requestFullscreen) {
try {
await el.requestFullscreen();
setExpanded(true);
return;
} catch {
// fallback to CSS overlay expand
}
}
setExpanded(current => !current);
};
useEffect(() => {
const onFsChange = () => {
if (!document.fullscreenElement) setExpanded(false);
};
document.addEventListener('fullscreenchange', onFsChange);
return () => document.removeEventListener('fullscreenchange', onFsChange);
}, []);
return (
<div ref={containerRef} className={`cs-ph-workspace ${expanded ? 'is-expanded' : ''}`}>
<div className="cs-ph-workspace-bar">
<div className="cs-ph-workspace-title">
<Button size="small" theme="borderless" icon={<IconChevronLeft />} onClick={onBack}>
{t('pluginHub.backToHub', null, '返回能力平台')}
</Button>
<Text strong ellipsis style={{ maxWidth: 260 }}>{install.title || install.plugin_id}</Text>
<Tag size="small" color={stateColor(install.observed_state)} shape="square">
{stateLabel(t, install.observed_state)}
</Tag>
{sessionInfo?.origin && (
<Text type="tertiary" size="small" className="cs-ph-mono" ellipsis style={{ maxWidth: 260 }}>
{sessionInfo.origin}
</Text>
)}
</div>
<Space spacing={6} wrap>
<Tooltip content={t('pluginHub.reconnectSession', null, '刷新 / 重新建立隔离会话')}>
<Button size="small" icon={<IconRefresh />} onClick={connect} loading={loading}>
{t('common.refresh', null, '刷新')}
</Button>
</Tooltip>
<Tooltip content={t('pluginHub.openFirstPartyTip', null, '若浏览器严格拦截跨站 Cookie,可在独立首方窗口中打开')}>
<Button size="small" icon={<IconExternalOpen />} onClick={openStandaloneWindow}>
{t('pluginHub.openStandalone', null, '独立窗口')}
</Button>
</Tooltip>
{canManage && (
<Button size="small" icon={<IconTerminal />} onClick={onOpenLogs}>
{t('pluginHub.logs', null, '日志')}
</Button>
)}
<Button size="small" icon={<IconSetting />} onClick={onOpenDetail}>
{t('pluginHub.settingsAndDetail', null, '详情与模型')}
</Button>
<Button
size="small"
icon={expanded ? <IconMinimize /> : <IconMaximize />}
onClick={toggleFullscreen}
>
{expanded ? t('pluginHub.exitFullscreen', null, '退出全屏') : t('mobile.fullscreen', null, '全屏')}
</Button>
</Space>
</div>
<div className="cs-ph-workspace-frame-wrap">
<iframe
name={frameName}
title={install.title || install.plugin_id}
className="cs-ph-workspace-iframe"
sandbox="allow-scripts allow-same-origin allow-forms allow-downloads"
allow="clipboard-read; clipboard-write"
onLoad={() => setLoading(false)}
/>
{loading && !error && (
<div className="cs-ph-workspace-overlay">
<Spin size="large" />
<Text type="tertiary">{t('pluginHub.connectingWorkspace', null, '正在建立隔离代理会话并加载插件页面…')}</Text>
</div>
)}
{error && (
<div className="cs-ph-workspace-overlay">
<Text type="danger" strong>{error}</Text>
<Text type="tertiary" size="small">
{t('pluginHub.embedTroubleshooting', null, '请确认插件处于运行中状态;若浏览器限制跨站 Cookie,可点击上方「独立窗口」以首方会话打开。')}
</Text>
<Space>
<Button theme="solid" type="primary" onClick={connect}>{t('pluginHub.retryConnect', null, '重试连接')}</Button>
<Button icon={<IconExternalOpen />} onClick={openStandaloneWindow}>{t('pluginHub.openStandalone', null, '独立窗口')}</Button>
</Space>
</div>
)}
</div>
</div>
);
}

View File

@ -0,0 +1,230 @@
import { api, getAuthToken } from '../../lib/http';
export function newIdempotencyKey(prefix = 'op') {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return `${prefix}-${crypto.randomUUID()}`;
}
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}
const ERROR_KEYS = {
plugin_bearer_required: ['pluginHub.errorBearerRequired', '需要 Bearer 登录凭据才能访问插件平台'],
plugin_invalid_source: ['pluginHub.errorInvalidSource', '仅支持公开的 GitHub HTTPS 仓库地址及合法分支/Tag/Commit'],
plugin_ambiguous_git_ref: ['pluginHub.errorAmbiguousRef', '分支与 Tag 同名,请填写完整引用(如 refs/tags/xxx 或 refs/heads/xxx)'],
plugin_source_not_found: ['pluginHub.errorSourceNotFound', '未找到目标仓库或指定版本'],
plugin_invalid_manifest: ['pluginHub.errorInvalidManifest', '插件 Manifest 格式或字段校验未通过'],
plugin_github_rate_limited: ['pluginHub.errorRateLimited', 'GitHub API 触发限流,建议配置 plugins.egress.github_token_env 后重试'],
plugin_source_unavailable: ['pluginHub.errorSourceUnavailable', '无法连接上游仓库,请检查网络或插件代理配置'],
plugin_manifest_required: ['pluginHub.errorManifestRequired', '该仓库未自带 csai-plugin.yaml,请先补全 Manifest 草案'],
plugin_manifest_source_mismatch: ['pluginHub.errorSourceMismatch', 'Manifest 中的仓库地址或版本与探测结果不一致'],
plugin_artifact_not_approved: ['pluginHub.errorArtifactNotApproved', '当前宿主策略未批准该制品摘要,请联系管理员或核对批准策略'],
plugin_operation_conflict: ['pluginHub.errorOperationConflict', '该插件已有正在执行的变更任务,请等待当前操作完成'],
plugin_plan_stale: ['pluginHub.errorPlanStale', '安装计划已过期或已被消费,请重新生成锁定计划'],
plugin_runtime_unavailable: ['pluginHub.errorRuntimeUnavailable', '插件运行调度器尚未就绪,请稍后重试'],
plugin_artifact_unavailable: ['pluginHub.errorArtifactUnavailable', '未找到适配当前系统架构的可安装制品或镜像'],
plugin_llm_binding_invalid: ['pluginHub.errorLLMBindingInvalid', '所选模型通道无效或与该插件声明的协议不兼容'],
plugin_llm_gateway_unavailable: ['pluginHub.errorLLMGatewayUnavailable', 'CSAI 插件模型网关未就绪'],
plugin_web_unavailable: ['pluginHub.errorWebUnavailable', '插件 WebUI 代理未就绪或应用尚未健康启动'],
plugin_embed_origin_or_permission_rejected: ['pluginHub.errorEmbedRejected', '无权访问该插件工作区或请求来源校验未通过'],
plugin_record_not_found: ['pluginHub.errorNotFound', '未找到对应的插件记录或计划已过期']
};
export function pluginErrorText(t, error, fallback) {
const code = error?.payload?.error || (typeof error?.message === 'string' ? error.message : '');
const entry = ERROR_KEYS[code];
if (entry) {
return t(entry[0], null, entry[1]);
}
return error?.message || fallback || t('common.loadFailed', null, '操作失败');
}
export function stateColor(state) {
switch (String(state || '').toLowerCase()) {
case 'healthy': return 'green';
case 'starting':
case 'installing':
case 'stopping': return 'blue';
case 'degraded':
case 'cleanup_pending': return 'amber';
case 'failed': return 'red';
case 'stopped':
case 'removed':
default: return 'grey';
}
}
export function stateLabel(t, state) {
const map = {
healthy: ['pluginHub.stateHealthy', '运行中'],
starting: ['pluginHub.stateStarting', '启动中'],
installing: ['pluginHub.stateInstalling', '安装中'],
stopping: ['pluginHub.stateStopping', '停止中'],
stopped: ['pluginHub.stateStopped', '已停止'],
degraded: ['pluginHub.stateDegraded', '状态异常'],
failed: ['pluginHub.stateFailed', '失败'],
cleanup_pending: ['pluginHub.stateCleanupPending', '待清理'],
removed: ['pluginHub.stateRemoved', '已卸载']
};
const item = map[String(state || '').toLowerCase()];
return item ? t(item[0], null, item[1]) : (state || '—');
}
export function driverLabel(t, driver) {
const map = {
auto: ['pluginHub.driverAuto', '自动择优(Release → Git → 容器)'],
release: ['pluginHub.driverRelease', 'Release 预编译包'],
git: ['pluginHub.driverGit', 'Git 源码构建'],
container: ['pluginHub.driverContainer', 'Docker / Compose 容器'],
compose: ['pluginHub.driverCompose', 'Docker Compose']
};
const item = map[String(driver || '').toLowerCase()];
return item ? t(item[0], null, item[1]) : (driver || '—');
}
export const pluginApi = {
listCatalog: () => api.get('/plugins/catalog'),
listInstalls: () => api.get('/plugins/installs'),
getInstall: id => api.get(`/plugins/installs/${encodeURIComponent(id)}`),
listLLMChannels: () => api.get('/plugins/llm/channels'),
probes: (isolation = 'standard') => api.get('/plugins/runtime/probes', { isolation }),
inspectGit: (repository, revision) => api.post('/plugins/imports/inspect', {
repository: repository.trim(),
revision: (revision || '').trim()
}),
createPlan: payload => api.post('/plugins/install-plans', payload),
install: ({ planId, planDigest, autoBindLLM }) => api.post('/plugins/installs', {
kind: 'install',
plan_id: planId,
plan_digest: planDigest,
idempotency_key: newIdempotencyKey('install'),
auto_bind_llm: autoBindLLM
}),
operate: (id, kind, extra = {}) => api.post(`/plugins/installs/${encodeURIComponent(id)}/operations`, {
kind,
idempotency_key: newIdempotencyKey(kind),
...extra
}),
getOperation: id => api.get(`/plugins/operations/${encodeURIComponent(id)}`),
readLogs: (id, after = 0, limit = 100) => api.get(`/plugins/installs/${encodeURIComponent(id)}/logs`, { after, limit }),
issueEmbedSession: id => api.post(`/plugins/installs/${encodeURIComponent(id)}/embed-sessions`, {}),
patchLLM: (id, body) => api.patch(`/plugins/installs/${encodeURIComponent(id)}/llm`, body)
};
/**
* 订阅插件脱敏日志 SSE 流(使用 fetch + Bearer Token,避免 EventSource 无法带 Authorization 头)。
*/
export function streamPluginLogs(installId, { after = 0, onEntry, onError, onClose } = {}) {
const controller = new AbortController();
const token = getAuthToken();
const headers = { Accept: 'text/event-stream' };
if (token) headers.Authorization = `Bearer ${token}`;
const url = `/api/plugins/installs/${encodeURIComponent(installId)}/logs?after=${encodeURIComponent(String(after))}`;
(async () => {
try {
const response = await fetch(url, { method: 'GET', headers, signal: controller.signal });
if (response.status === 401) {
window.dispatchEvent(new CustomEvent('csai:unauthorized'));
}
if (!response.ok || !response.body) {
throw new Error(`HTTP ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let idx;
while ((idx = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, idx).replace(/\r$/, '');
buffer = buffer.slice(idx + 1);
if (!line.startsWith('data:')) continue;
const raw = line.slice(5).trim();
if (!raw) continue;
try {
onEntry?.(JSON.parse(raw));
} catch {
// ignore malformed keepalive payload
}
}
}
onClose?.();
} catch (err) {
if (err?.name === 'AbortError') {
onClose?.();
return;
}
onError?.(err);
}
})();
return () => controller.abort();
}
export function starterManifestTemplate(inspection) {
const repo = inspection?.repository || 'https://github.com/owner/repo';
const rawName = repo.split('/').pop() || 'my-plugin';
const id = rawName.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '') || 'my-plugin';
const hasContainer = (inspection?.candidates || []).includes('container');
if (hasContainer) {
return JSON.stringify({
apiVersion: 'plugins.csai.io/v1',
kind: 'WebPlugin',
metadata: {
id,
title: rawName,
summary: 'Imported container WebUI plugin',
version: '1.0.0',
repository: repo
},
distribution: [
{
type: 'container',
mode: 'docker',
services: [
{
name: 'web',
role: 'web',
image: `ghcr.io/${repo.replace('https://github.com/', '').toLowerCase()}:latest`,
containerPort: 8080,
resources: { memoryMiB: 512, pids: 128 }
}
]
}
],
web: { route: 'root', entryPath: '/', healthPath: '/', allowHealthRedirect: true },
access: { mode: 'plugin_login' },
permissions: { persistentData: false, modelGateway: false, egress: [] }
}, null, 2);
}
return JSON.stringify({
apiVersion: 'plugins.csai.io/v1',
kind: 'WebPlugin',
metadata: {
id,
title: rawName,
summary: 'Imported Git WebUI plugin',
version: '1.0.0',
repository: repo
},
distribution: [
{
type: 'git',
url: repo,
revision: inspection?.resolved_ref || inspection?.commit || 'main',
dependencies: [{ name: 'git', minVersion: '2.30' }, { name: 'go', minVersion: '1.22' }],
build: [{ program: 'go', args: ['build', '-o', 'dist/app', '.'] }],
outputRoot: 'dist'
}
],
launch: {
entrypoint: 'app',
env: { PORT: 'listen_port', HOST: 'listen_host' }
},
web: { route: 'root', entryPath: '/', healthPath: '/', allowHealthRedirect: true },
access: { mode: 'platform' },
permissions: { persistentData: false, modelGateway: false, egress: [] }
}, null, 2);
}

View File

@ -0,0 +1,513 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import {
Banner, Button, Checkbox, Input, Space, Tabs, TabPane, Tag, Tooltip, Typography
} from '@douyinfe/semi-ui';
import {
IconApps, IconBolt, IconDelete, IconDownload, IconExternalOpen, IconPlay, IconPlus, IconRefresh,
IconSearch, IconSetting, IconStop, IconSync, IconTerminal, IconWrench
} from '@douyinfe/semi-icons';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
import { useInterval, useResource } from '../../components/hooks';
import {
DataTable, ErrorBanner, PageHeader, SectionCard, StatGrid, confirmAction, toastError, toastSuccess
} from '../../components/ui';
import { formatDateTime } from '../../lib/format';
import { driverLabel, pluginApi, pluginErrorText, stateColor, stateLabel } from './api';
import WorkspaceView from './WorkspaceView';
import { ImportGitDrawer, PlanApprovalDrawer, PluginDetailDrawer, RuntimeProbesDrawer } from './Drawers';
import './page.css';
const { Text, Paragraph } = Typography;
export default function PluginHubPage() {
const t = useT();
const { hasPermission } = useAuth();
const canManage = hasPermission('plugins:manage');
const canUse = hasPermission('plugins:use');
const [searchParams, setSearchParams] = useSearchParams();
const activeAppId = searchParams.get('app') || '';
const activeTab = searchParams.get('tab') || 'installed';
const [search, setSearch] = useState('');
const [importOpen, setImportOpen] = useState(false);
const [probesOpen, setProbesOpen] = useState(false);
const [planState, setPlanState] = useState(null);
const [planningCatalogId, setPlanningCatalogId] = useState('');
const [detailTarget, setDetailTarget] = useState(null);
const [activeOp, setActiveOp] = useState(null);
const [busyInstallId, setBusyInstallId] = useState('');
const installsRes = useResource(() => pluginApi.listInstalls(), []);
const catalogRes = useResource(() => pluginApi.listCatalog(), []);
const channelsRes = useResource(() => pluginApi.listLLMChannels(), []);
const probesRes = useResource(() => pluginApi.probes('standard'), [], { skip: !canManage });
const installs = Array.isArray(installsRes.data?.items) ? installsRes.data.items : [];
const catalogItems = Array.isArray(catalogRes.data?.items) ? catalogRes.data.items : [];
const channels = Array.isArray(channelsRes.data?.channels) ? channelsRes.data.channels : [];
const activeApp = useMemo(
() => installs.find(item => item.id === activeAppId) || null,
[installs, activeAppId]
);
const setTab = nextTab => {
const next = new URLSearchParams(searchParams);
next.set('tab', nextTab);
next.delete('app');
setSearchParams(next, { replace: true });
};
const openApp = install => {
const next = new URLSearchParams(searchParams);
next.set('tab', 'installed');
next.set('app', install.id);
setSearchParams(next);
};
const closeApp = () => {
const next = new URLSearchParams(searchParams);
next.delete('app');
setSearchParams(next, { replace: true });
};
const reloadAll = useCallback(() => {
installsRes.reload({ silent: true });
catalogRes.reload({ silent: true });
channelsRes.reload({ silent: true });
}, [installsRes, catalogRes, channelsRes]);
// Poll active asynchronous operation until terminal state
useInterval(async () => {
if (!activeOp?.id || !canManage) return;
try {
const latest = await pluginApi.getOperation(activeOp.id);
setActiveOp(latest);
if (latest.status !== 'queued' && latest.status !== 'running') {
installsRes.reload({ silent: true });
if (latest.status === 'succeeded') {
toastSuccess(t('pluginHub.opSucceeded', { kind: latest.kind }, `操作 ${latest.kind} 已完成`));
} else if (latest.status === 'failed') {
toastError(t('pluginHub.opFailed', { kind: latest.kind }, `操作 ${latest.kind} 失败,请查看插件日志`));
}
}
} catch {
// keep last known status
}
}, activeOp && (activeOp.status === 'queued' || activeOp.status === 'running') ? 1500 : null);
// Light background refresh when any install is transitioning
const hasTransitioning = installs.some(i => ['installing', 'starting', 'stopping'].includes(i.observed_state));
useInterval(() => {
installsRes.reload({ silent: true });
}, hasTransitioning ? 3000 : null);
const handleCatalogInstall = async entry => {
if (entry.availability !== 'plan_available') {
setImportOpen(true);
return;
}
setPlanningCatalogId(entry.id);
try {
const planRes = await pluginApi.createPlan({
catalog_id: entry.id,
driver: 'auto',
isolation: 'standard'
});
setPlanState(planRes);
} catch (err) {
toastError(pluginErrorText(t, err, t('pluginHub.createPlanFailed', null, '生成安装计划失败')));
} finally {
setPlanningCatalogId('');
}
};
const runOperation = async (install, kind, extra = {}) => {
setBusyInstallId(install.id);
try {
const op = await pluginApi.operate(install.id, kind, extra);
setActiveOp(op);
toastSuccess(t('pluginHub.opQueued', { kind }, `已提交 ${kind} 任务`));
installsRes.reload({ silent: true });
} catch (err) {
toastError(pluginErrorText(t, err));
} finally {
setBusyInstallId('');
}
};
const confirmUninstall = install => {
let purgeData = false;
confirmAction({
title: t('pluginHub.confirmUninstallTitle', { name: install.title || install.plugin_id }, `卸载插件「${install.title || install.plugin_id}」?`),
content: (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<Text type="tertiary">
{t('pluginHub.confirmUninstallDesc', null, '将停止插件进程/容器、撤销代理会话与模型网关 Token,并退役隔离端口。')}
</Text>
<Checkbox onChange={e => { purgeData = Boolean(e.target.checked); }}>
{t('pluginHub.purgeDataOption', null, '同时删除持久化运行数据与卷(默认保留数据)')}
</Checkbox>
</div>
),
okText: t('pluginHub.uninstall', null, '卸载'),
onOk: () => runOperation(install, 'uninstall', { purge_data: purgeData })
});
};
const filteredInstalls = useMemo(() => {
const kw = search.trim().toLowerCase();
if (!kw) return installs;
return installs.filter(item =>
String(item.title || '').toLowerCase().includes(kw) ||
String(item.plugin_id || '').toLowerCase().includes(kw) ||
String(item.driver || '').toLowerCase().includes(kw)
);
}, [installs, search]);
const filteredCatalog = useMemo(() => {
const kw = search.trim().toLowerCase();
if (!kw) return catalogItems;
return catalogItems.filter(item =>
String(item.title || '').toLowerCase().includes(kw) ||
String(item.id || '').toLowerCase().includes(kw) ||
String(item.summary || '').toLowerCase().includes(kw)
);
}, [catalogItems, search]);
const healthyCount = installs.filter(i => i.observed_state === 'healthy').length;
const probes = probesRes.data?.drivers || {};
const readyDrivers = Object.entries(probes).filter(([, p]) => p?.available).map(([k]) => k);
// Render embedded full-area workspace when an app is open
if (activeAppId && activeApp) {
return (
<div className="cs-ph-root">
<WorkspaceView
install={activeApp}
canManage={canManage}
onBack={closeApp}
onOpenDetail={() => setDetailTarget({ id: activeApp.id, tab: 'overview' })}
onOpenLogs={() => setDetailTarget({ id: activeApp.id, tab: 'logs' })}
/>
<PluginDetailDrawer
installId={detailTarget?.id}
initialTab={detailTarget?.tab}
visible={Boolean(detailTarget)}
canManage={canManage}
channels={channels}
onCancel={() => setDetailTarget(null)}
onRestartRequested={item => runOperation(item, 'restart')}
onChanged={reloadAll}
/>
</div>
);
}
const installColumns = [
{
title: t('pluginHub.pluginTitle', null, '插件应用'),
dataIndex: 'title',
render: (value, record) => (
<Space vertical spacing={2} align="start">
<Space spacing={6}>
<Text strong>{value || record.plugin_id}</Text>
<Tag size="small" color="grey">{record.plugin_id}</Tag>
</Space>
{record.last_error_code && (
<Text type="danger" size="small">{record.last_error_code}</Text>
)}
</Space>
)
},
{
title: t('pluginHub.observedState', null, '运行状态'),
dataIndex: 'observed_state',
width: 130,
render: value => <Tag color={stateColor(value)} shape="square">{stateLabel(t, value)}</Tag>
},
{
title: t('pluginHub.driver', null, '驱动'),
dataIndex: 'driver',
width: 160,
render: value => driverLabel(t, value)
},
{
title: t('pluginHub.updatedAt', null, '更新时间'),
dataIndex: 'updated_at',
width: 170,
render: value => formatDateTime(value)
},
{
title: t('common.actions', null, '操作'),
width: 300,
render: (_, record) => {
const isRunning = record.observed_state === 'healthy';
const isBusy = busyInstallId === record.id || ['installing', 'starting', 'stopping'].includes(record.observed_state);
return (
<Space spacing={4} wrap>
{canUse && (
<Button
size="small"
theme="solid"
type="primary"
icon={<IconExternalOpen />}
disabled={!isRunning}
onClick={() => openApp(record)}
>
{t('pluginHub.openWorkspace', null, '打开应用')}
</Button>
)}
{canManage && !isRunning && (
<Tooltip content={t('pluginHub.start', null, '启动')}>
<Button size="small" icon={<IconPlay />} loading={isBusy} onClick={() => runOperation(record, 'start')} />
</Tooltip>
)}
{canManage && isRunning && (
<>
<Tooltip content={t('pluginHub.restart', null, '重启')}>
<Button size="small" icon={<IconSync />} loading={isBusy} onClick={() => runOperation(record, 'restart')} />
</Tooltip>
<Tooltip content={t('pluginHub.stop', null, '停止')}>
<Button size="small" icon={<IconStop />} loading={isBusy} onClick={() => runOperation(record, 'stop')} />
</Tooltip>
</>
)}
{canManage && (
<Tooltip content={t('pluginHub.logs', null, '实时日志')}>
<Button size="small" theme="borderless" icon={<IconTerminal />} onClick={() => setDetailTarget({ id: record.id, tab: 'logs' })} />
</Tooltip>
)}
<Tooltip content={t('pluginHub.settingsAndDetail', null, '详情与模型绑定')}>
<Button size="small" theme="borderless" icon={<IconSetting />} onClick={() => setDetailTarget({ id: record.id, tab: 'overview' })} />
</Tooltip>
{canManage && (
<Tooltip content={t('pluginHub.uninstall', null, '卸载')}>
<Button size="small" theme="borderless" type="danger" icon={<IconDelete />} onClick={() => confirmUninstall(record)} />
</Tooltip>
)}
</Space>
);
}
}
];
return (
<div className="cs-ph-root">
<PageHeader
title={t('pluginHub.title', null, '插件化能力平台')}
description={t('pluginHub.subtitle', null, '按需拉取独立红队与安全开源项目,保留原作者仓库隔离,支持页面无缝内嵌与 CSAI 模型通道统一复用。')}
extra={
<Space wrap>
{canManage && (
<Button icon={<IconWrench />} onClick={() => setProbesOpen(true)}>
{t('pluginHub.runtimeProbes', null, '运行环境预检')}
</Button>
)}
{canManage && (
<Button theme="solid" type="primary" icon={<IconPlus />} onClick={() => setImportOpen(true)}>
{t('pluginHub.importGit', null, '手工导入 Git 仓库')}
</Button>
)}
<Button icon={<IconRefresh />} onClick={reloadAll} loading={installsRes.loading || catalogRes.loading}>
{t('common.refresh', null, '刷新')}
</Button>
</Space>
}
/>
<StatGrid
columns={4}
metrics={[
{
id: 'installed',
label: t('pluginHub.statInstalled', null, '已安装插件'),
value: installs.length,
icon: <IconApps />,
onClick: () => setTab('installed')
},
{
id: 'healthy',
label: t('pluginHub.statRunning', null, '运行中应用'),
value: healthyCount,
tone: healthyCount > 0 ? 'success' : undefined,
icon: <IconPlay />,
onClick: () => setTab('installed')
},
{
id: 'catalog',
label: t('pluginHub.statCatalog', null, '官方精选目录'),
value: catalogItems.length,
icon: <IconDownload />,
onClick: () => setTab('market')
},
{
id: 'drivers',
label: t('pluginHub.statDrivers', null, '宿主可用驱动'),
value: canManage ? (readyDrivers.length ? readyDrivers.join(' / ') : '—') : '—',
detail: probesRes.data ? `${probesRes.data.os}/${probesRes.data.arch}` : undefined,
icon: <IconBolt />,
onClick: canManage ? () => setProbesOpen(true) : undefined
}
]}
/>
{activeOp && (
<Banner
type={activeOp.status === 'failed' ? 'danger' : activeOp.status === 'succeeded' ? 'success' : 'info'}
bordered
onClose={() => setActiveOp(null)}
description={
<Space wrap>
<Text strong>{t('pluginHub.latestOperation', null, '最近任务')}: {activeOp.kind}</Text>
<Tag size="small" color={activeOp.status === 'succeeded' ? 'green' : activeOp.status === 'failed' ? 'red' : 'blue'}>
{activeOp.status}
</Tag>
{canManage && activeOp.install_id && (
<Button size="small" theme="borderless" onClick={() => setDetailTarget({ id: activeOp.install_id, tab: 'logs' })}>
{t('pluginHub.viewLogs', null, '查看日志')}
</Button>
)}
</Space>
}
/>
)}
<SectionCard>
<ErrorBanner error={installsRes.error || catalogRes.error} onRetry={reloadAll} />
<Tabs
activeKey={activeTab}
onChange={setTab}
tabBarExtraContent={
<Input
prefix={<IconSearch />}
value={search}
onChange={setSearch}
placeholder={t('pluginHub.searchPlaceholder', null, '搜索插件名称或描述')}
style={{ width: 260 }}
showClear
/>
}
>
<TabPane tab={`${t('pluginHub.tabInstalled', null, '已安装应用')} (${installs.length})`} itemKey="installed">
<div style={{ marginTop: 12 }}>
<DataTable
columns={installColumns}
dataSource={filteredInstalls}
loading={installsRes.loading}
emptyText={t('pluginHub.emptyInstalled', null, '暂未安装插件,可切换到「能力市场」一键下载或手工导入 Git 仓库')}
/>
</div>
</TabPane>
<TabPane tab={`${t('pluginHub.marketTitle', null, '能力市场')} (${catalogItems.length})`} itemKey="market">
<div className="cs-ph-catalog-grid" style={{ marginTop: 14 }}>
{filteredCatalog.map(entry => {
const existing = installs.find(i => i.plugin_id === entry.id);
const oneClick = entry.availability === 'plan_available';
return (
<div key={entry.id} className="cs-ph-card">
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<div className="cs-ph-card-head">
<div>
<Text strong size="normal">{entry.title}</Text>
<div>
<Text type="tertiary" size="small" className="cs-ph-mono">{entry.id}</Text>
</div>
</div>
<Tag size="small" color={oneClick ? 'green' : 'blue'}>
{oneClick
? t('pluginHub.catalogOneClick', null, '支持一键安装')
: t('pluginHub.catalogInspectOnly', null, '支持探测导入')}
</Tag>
</div>
<Paragraph type="tertiary" size="small" style={{ margin: 0 }}>
{entry.summary}
</Paragraph>
<div className="cs-ph-card-meta">
<a href={entry.repository} target="_blank" rel="noreferrer" style={{ fontSize: 12 }}>
{entry.repository.replace('https://github.com/', 'github.com/')}
</a>
</div>
</div>
<div className="cs-ph-card-footer">
{existing ? (
<Tag color={stateColor(existing.observed_state)}>
{t('pluginHub.installedBadge', null, '已安装')} · {stateLabel(t, existing.observed_state)}
</Tag>
) : (
<Text type="tertiary" size="small">{t('pluginHub.externalRepoHint', null, '代码保留在原作者仓库')}</Text>
)}
<Space spacing={6}>
{existing && canUse && existing.observed_state === 'healthy' && (
<Button size="small" theme="solid" type="primary" onClick={() => openApp(existing)}>
{t('pluginHub.openWorkspace', null, '打开应用')}
</Button>
)}
{!existing && canManage && (
<Button
size="small"
theme={oneClick ? 'solid' : 'light'}
type="primary"
icon={<IconDownload />}
loading={planningCatalogId === entry.id}
onClick={() => handleCatalogInstall(entry)}
>
{oneClick
? t('pluginHub.oneClickInstall', null, '一键下载安装')
: t('pluginHub.inspectAndImport', null, '探测并导入')}
</Button>
)}
</Space>
</div>
</div>
);
})}
</div>
</TabPane>
</Tabs>
</SectionCard>
<ImportGitDrawer
visible={importOpen}
onCancel={() => setImportOpen(false)}
onPlanReady={res => {
setImportOpen(false);
setPlanState(res);
}}
/>
<PlanApprovalDrawer
planResponse={planState}
channels={channels}
visible={Boolean(planState)}
onCancel={() => setPlanState(null)}
onConfirmed={op => {
setPlanState(null);
setActiveOp(op);
setTab('installed');
installsRes.reload({ silent: true });
}}
/>
<PluginDetailDrawer
installId={detailTarget?.id}
initialTab={detailTarget?.tab}
visible={Boolean(detailTarget)}
canManage={canManage}
channels={channels}
onCancel={() => setDetailTarget(null)}
onRestartRequested={item => runOperation(item, 'restart')}
onChanged={reloadAll}
/>
<RuntimeProbesDrawer
visible={probesOpen}
onCancel={() => setProbesOpen(false)}
/>
</div>
);
}

View File

@ -0,0 +1,167 @@
.cs-ph-root {
display: flex;
flex-direction: column;
gap: 16px;
}
.cs-ph-catalog-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
gap: 16px;
}
.cs-ph-card {
display: flex;
flex-direction: column;
justify-content: space-between;
gap: 12px;
padding: 16px;
border-radius: 10px;
border: 1px solid var(--semi-color-border);
background: var(--semi-color-bg-2);
transition: border-color 0.16s ease, box-shadow 0.16s ease;
}
.cs-ph-card:hover {
border-color: var(--semi-color-primary);
box-shadow: var(--semi-shadow-elevated);
}
.cs-ph-card-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 8px;
}
.cs-ph-card-meta {
display: flex;
flex-wrap: wrap;
gap: 6px;
align-items: center;
}
.cs-ph-card-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding-top: 8px;
border-top: 1px solid var(--semi-color-border);
}
.cs-ph-probes-bar {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.cs-ph-probe-card {
display: flex;
flex-direction: column;
gap: 6px;
padding: 12px;
border-radius: 8px;
border: 1px solid var(--semi-color-border);
background: var(--semi-color-fill-0);
}
.cs-ph-workspace {
display: flex;
flex-direction: column;
height: calc(100vh - 136px);
min-height: 540px;
border-radius: 10px;
border: 1px solid var(--semi-color-border);
background: var(--semi-color-bg-1);
overflow: hidden;
}
.cs-ph-workspace.is-expanded {
position: fixed;
inset: 0;
z-index: 1050;
height: 100vh;
border-radius: 0;
border: none;
}
.cs-ph-workspace-bar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 14px;
border-bottom: 1px solid var(--semi-color-border);
background: var(--semi-color-bg-2);
flex-wrap: wrap;
}
.cs-ph-workspace-title {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.cs-ph-workspace-frame-wrap {
position: relative;
flex: 1;
min-height: 0;
background: var(--semi-color-bg-0);
}
.cs-ph-workspace-iframe {
width: 100%;
height: 100%;
border: 0;
display: block;
background: var(--semi-color-bg-0);
}
.cs-ph-workspace-overlay {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
padding: 24px;
text-align: center;
background: var(--semi-color-bg-0);
}
.cs-ph-log-box {
margin: 0;
padding: 12px;
border-radius: 8px;
border: 1px solid var(--semi-color-border);
background: var(--semi-color-fill-0);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 12px;
line-height: 1.55;
max-height: 420px;
overflow: auto;
white-space: pre-wrap;
word-break: break-word;
color: var(--semi-color-text-0);
}
.cs-ph-code-editor {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 12px;
}
.cs-ph-drawer-stack {
display: flex;
flex-direction: column;
gap: 14px;
}
.cs-ph-mono {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 12px;
word-break: break-all;
}

View File

@ -22,6 +22,7 @@ export const PAGES = {
'c2-events': lazy(() => import('./c2-events')),
'c2-profiles': lazy(() => import('./c2-profiles')),
'chat-files': lazy(() => import('./chat-files')),
'plugin-hub': lazy(() => import('./plugin-hub')),
'mcp-monitor': lazy(() => import('./mcp-monitor')),
'mcp-management': lazy(() => import('./mcp-management')),
'knowledge-retrieval-logs': lazy(() => import('./knowledge-retrieval-logs')),

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{$t as t,F as n,M as r,W as i}from"./semi-CHxO7u8f.js";import{A as a,T as o,j as s,x as c}from"./assetTarget-D2PEjBAg.js";import{t as l}from"./react-QV7DAAIx.js";var u=e(l(),1),{Text:d}=i;function f({text:e,max:n=42,className:r=``,placeholder:i=`—`}){let a=String(e??``).trim();if(!a)return(0,u.jsx)(d,{type:`tertiary`,children:i});if(a.length<=n)return(0,u.jsx)(`span`,{className:r,children:a});let o=`${a.slice(0,n)}…`;return(0,u.jsx)(t,{content:a,position:`topLeft`,children:(0,u.jsx)(`span`,{className:r,children:o})})}function p({asset:e,size:t=`small`}){let n=s(e);return(0,u.jsx)(r,{size:t,color:c[n]||`grey`,shape:`circle`,children:a(n)})}function m({status:e,size:t=`small`}){let n=String(e||`active`).toLowerCase();return(0,u.jsx)(r,{size:t,color:n===`inactive`?`grey`:`green`,shape:`square`,children:o[n]||e||`—`})}function h({protocol:e,port:t,size:i=`small`}){let a=String(e||``).trim(),o=Number(t||0)>0?`:${t}`:``;return!a&&!o?(0,u.jsx)(d,{type:`tertiary`,children:`—`}):(0,u.jsxs)(n,{spacing:4,children:[a?(0,u.jsx)(r,{size:i,color:`blue`,shape:`square`,children:a}):null,o?(0,u.jsx)(d,{type:`tertiary`,size:`small`,children:o}):null]})}function g({tags:e,max:i=3}){let a=Array.isArray(e)?e.filter(Boolean):[];if(!a.length)return(0,u.jsx)(d,{type:`tertiary`,children:`—`});let o=a.slice(0,i),s=a.slice(i);return(0,u.jsxs)(n,{spacing:4,wrap:!0,children:[o.map(e=>(0,u.jsx)(r,{size:`small`,color:`violet`,shape:`square`,children:e},e)),s.length?(0,u.jsx)(t,{content:s.join(`、`),children:(0,u.jsx)(`span`,{children:(0,u.jsxs)(r,{size:`small`,shape:`square`,children:[`+`,s.length]})})}):null]})}export{f as a,g as i,h as n,p as r,m as t};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{G as t,I as n,N as r,on as i}from"./semi-65W_4I1v.js";import{A as a,T as o,j as s,x as c}from"./assetTarget-D2PEjBAg.js";import{t as l}from"./react-QV7DAAIx.js";var u=e(l(),1),{Text:d}=t;function f({text:e,max:t=42,className:n=``,placeholder:r=`—`}){let a=String(e??``).trim();if(!a)return(0,u.jsx)(d,{type:`tertiary`,children:r});if(a.length<=t)return(0,u.jsx)(`span`,{className:n,children:a});let o=`${a.slice(0,t)}…`;return(0,u.jsx)(i,{content:a,position:`topLeft`,children:(0,u.jsx)(`span`,{className:n,children:o})})}function p({asset:e,size:t=`small`}){let n=s(e);return(0,u.jsx)(r,{size:t,color:c[n]||`grey`,shape:`circle`,children:a(n)})}function m({status:e,size:t=`small`}){let n=String(e||`active`).toLowerCase();return(0,u.jsx)(r,{size:t,color:n===`inactive`?`grey`:`green`,shape:`square`,children:o[n]||e||`—`})}function h({protocol:e,port:t,size:i=`small`}){let a=String(e||``).trim(),o=Number(t||0)>0?`:${t}`:``;return!a&&!o?(0,u.jsx)(d,{type:`tertiary`,children:`—`}):(0,u.jsxs)(n,{spacing:4,children:[a?(0,u.jsx)(r,{size:i,color:`blue`,shape:`square`,children:a}):null,o?(0,u.jsx)(d,{type:`tertiary`,size:`small`,children:o}):null]})}function g({tags:e,max:t=3}){let a=Array.isArray(e)?e.filter(Boolean):[];if(!a.length)return(0,u.jsx)(d,{type:`tertiary`,children:`—`});let o=a.slice(0,t),s=a.slice(t);return(0,u.jsxs)(n,{spacing:4,wrap:!0,children:[o.map(e=>(0,u.jsx)(r,{size:`small`,color:`violet`,shape:`square`,children:e},e)),s.length?(0,u.jsx)(i,{content:s.join(`、`),children:(0,u.jsx)(`span`,{children:(0,u.jsxs)(r,{size:`small`,shape:`square`,children:[`+`,s.length]})})}):null]})}export{f as a,g as i,h as n,p as r,m as t};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,Ot as s,W as c,i as l,jt as u,lt as d,ot as f,st as p}from"./semi-CHxO7u8f.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-CFmEgVyi.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(a,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(r,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(i,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(l,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,I as i,Lt as a,N as o,Pt as s,R as c,U as l,ft as u,i as d,lt as f,ut as p}from"./semi-65W_4I1v.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-D_JyAVdp.js";var k=e(t(),1),A=e(n(),1),{Text:j}=r;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),r=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(i,{children:[(0,A.jsx)(c,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(c,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(u,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(i,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(i,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(i,{children:[(0,A.jsx)(c,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(c,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),r&&(0,A.jsx)(c,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(a,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(l,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(d,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(d.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(d.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(d.Input,{field:`description`,label:`描述`}),(0,A.jsx)(d.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(d.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(d.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{I as e,L as t}from"./index-CFmEgVyi.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
import{I as e,L as t}from"./index-D_JyAVdp.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-CHxO7u8f.js";import{E as i,P as a,k as o}from"./index-CFmEgVyi.js";import"./c2-shared-Bp5-se02.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{G as t,I as n,R as r}from"./semi-65W_4I1v.js";import{E as i,P as a,k as o}from"./index-D_JyAVdp.js";import"./c2-shared-CtmcbePz.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=t,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:t,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(n,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(n=>(0,c.jsx)(r,{size:`small`,theme:n.value===e?`solid`:`borderless`,type:n.value===e?`primary`:`tertiary`,onClick:()=>t(n.value),children:o(`c2.${i}.preset${n.value===`all`?`All`:n.value}`,null,n.label)},n.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{t}from"./react-QV7DAAIx.js";import{Et as n,Gt as r,St as i,Tt as a,Ut as o,X as s,Zt as c,gt as l,it as u,ot as d,vt as f,xt as p}from"./semi-CHxO7u8f.js";var m=e(t(),1),h={target:i,infra:u,auth:f,finding:d,chain:o,exploit:r,poc:s,vulnerability:c,missing:p,goal:a,step:o,fact:n,receipt:s,observation:d,memory:l,digest:n,guidance:r};function g({type:e}){let t=h[e]||n;return(0,m.jsx)(`span`,{className:`graph-node-icon`,"aria-hidden":`true`,children:(0,m.jsx)(t,{size:`small`})})}function _({id:e,title:t,type:n,category:r,color:i,factKey:a,boundary:o,ports:s=[],selected:c,card:l,onSelect:u,onPreview:d}){let{density:f,box:p}=l,h=f===`detail`,_=Math.min(Math.max(p.width/216,1),1.6);return(0,m.jsxs)(`button`,{type:`button`,className:`graph-node graph-node--${f}`,title:t,"aria-label":t,"aria-pressed":c,"data-root":n===`goal`||n===`target`||void 0,"data-boundary":o||void 0,"data-wrap":f===`standard`&&p.height>=50||void 0,style:{...p,"--graph-node-color":i,"--graph-node-text-scale":_},onClick:()=>u(e),onMouseEnter:()=>d?.(e,!0),onMouseLeave:()=>d?.(e,!1),onFocus:()=>d?.(e,!0),onBlur:()=>d?.(e,!1),children:[(0,m.jsxs)(`span`,{className:`graph-node-content`,children:[f!==`compact`&&(0,m.jsxs)(`span`,{className:`graph-node-kind`,children:[(0,m.jsx)(g,{type:n}),(0,m.jsx)(`span`,{children:r})]}),(0,m.jsx)(`span`,{className:`graph-node-title`,dir:`auto`,children:t}),h&&p.height>=84&&a&&t!==a&&(0,m.jsx)(`span`,{className:`graph-node-keyline`,dir:`auto`,children:a})]}),h&&[...s].map(e=>(0,m.jsx)(`span`,{className:`graph-node-port is-${e}`,"aria-hidden":`true`},e))]})}function v(e,{anchorId:t,allowCompact:n=()=>!0}={}){let r=e.width(),i=e.height(),a=216*e.zoom(),o=98*e.zoom(),s=o>=68?`detail`:o>=36?`standard`:`compact`,c=[];for(let l of e.nodes(`:visible`)){let e=l.id();if(l.hasClass(`dim`)||s===`compact`&&e!==t&&(a<49||!n(l)))continue;let{x:u,y:d}=l.renderedPosition(),f=u-a/2,p=d-o/2;if(f+a<=0||f>=r||p+o<=0||p>=i)continue;let m={left:f,top:p,width:a,height:o};e===t&&a<49&&(m={left:Math.max(3,f),top:d-13,width:Math.min(108,r-Math.max(3,f)),height:26}),c.push({id:e,density:s,box:m})}return c}function y(e,t,n={x:e.width()/2,y:e.height()/2}){e.zoom({level:e.zoom()*t,renderedPosition:n})}function b(e,t){let n=n=>{if(!n.deltaY)return;n.preventDefault();let{left:r,top:i,height:a}=e.getBoundingClientRect(),o=n.deltaMode===1?33:n.deltaMode===2?a:1;y(t,10**(-n.deltaY*o/1250),{x:n.clientX-r,y:n.clientY-i})};return e.addEventListener(`wheel`,n,{passive:!1}),()=>e.removeEventListener(`wheel`,n)}function x(e,t){let n=new Map,r=new Set;for(let i of e){if(t(i.target)||n.has(i.target))continue;let e=i.source;for(;e&&e!==i.target;)e=n.get(e);e!==i.target&&(n.set(i.target,i.source),r.add(i))}return{parents:n,parentEdges:r}}export{v as a,b as i,_ as n,y as o,g as r,x as t};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{t}from"./react-QV7DAAIx.js";import{At as n,Ct as r,Dt as i,Et as a,Q as o,Yt as s,Zt as c,in as l,jt as u,lt as d,st as f,xt as p}from"./semi-65W_4I1v.js";var m=e(t(),1),h={target:i,infra:f,auth:r,finding:d,chain:s,exploit:c,poc:o,vulnerability:l,missing:a,goal:n,step:s,fact:u,receipt:o,observation:d,memory:p,digest:u,guidance:c};function g({type:e}){let t=h[e]||u;return(0,m.jsx)(`span`,{className:`graph-node-icon`,"aria-hidden":`true`,children:(0,m.jsx)(t,{size:`small`})})}function _({id:e,title:t,type:n,category:r,color:i,factKey:a,boundary:o,ports:s=[],selected:c,card:l,onSelect:u,onPreview:d}){let{density:f,box:p}=l,h=f===`detail`,_=Math.min(Math.max(p.width/216,1),1.6);return(0,m.jsxs)(`button`,{type:`button`,className:`graph-node graph-node--${f}`,title:t,"aria-label":t,"aria-pressed":c,"data-root":n===`goal`||n===`target`||void 0,"data-boundary":o||void 0,"data-wrap":f===`standard`&&p.height>=50||void 0,style:{...p,"--graph-node-color":i,"--graph-node-text-scale":_},onClick:()=>u(e),onMouseEnter:()=>d?.(e,!0),onMouseLeave:()=>d?.(e,!1),onFocus:()=>d?.(e,!0),onBlur:()=>d?.(e,!1),children:[(0,m.jsxs)(`span`,{className:`graph-node-content`,children:[f!==`compact`&&(0,m.jsxs)(`span`,{className:`graph-node-kind`,children:[(0,m.jsx)(g,{type:n}),(0,m.jsx)(`span`,{children:r})]}),(0,m.jsx)(`span`,{className:`graph-node-title`,dir:`auto`,children:t}),h&&p.height>=84&&a&&t!==a&&(0,m.jsx)(`span`,{className:`graph-node-keyline`,dir:`auto`,children:a})]}),h&&[...s].map(e=>(0,m.jsx)(`span`,{className:`graph-node-port is-${e}`,"aria-hidden":`true`},e))]})}function v(e,{anchorId:t,allowCompact:n=()=>!0}={}){let r=e.width(),i=e.height(),a=216*e.zoom(),o=98*e.zoom(),s=o>=68?`detail`:o>=36?`standard`:`compact`,c=[];for(let l of e.nodes(`:visible`)){let e=l.id();if(l.hasClass(`dim`)||s===`compact`&&e!==t&&(a<49||!n(l)))continue;let{x:u,y:d}=l.renderedPosition(),f=u-a/2,p=d-o/2;if(f+a<=0||f>=r||p+o<=0||p>=i)continue;let m={left:f,top:p,width:a,height:o};e===t&&a<49&&(m={left:Math.max(3,f),top:d-13,width:Math.min(108,r-Math.max(3,f)),height:26}),c.push({id:e,density:s,box:m})}return c}function y(e,t,n={x:e.width()/2,y:e.height()/2}){e.zoom({level:e.zoom()*t,renderedPosition:n})}function b(e,t){let n=n=>{if(!n.deltaY)return;n.preventDefault();let{left:r,top:i,height:a}=e.getBoundingClientRect(),o=n.deltaMode===1?33:n.deltaMode===2?a:1;y(t,10**(-n.deltaY*o/1250),{x:n.clientX-r,y:n.clientY-i})};return e.addEventListener(`wheel`,n,{passive:!1}),()=>e.removeEventListener(`wheel`,n)}function x(e,t){let n=new Map,r=new Set;for(let i of e){if(t(i.target)||n.has(i.target))continue;let e=i.source;for(;e&&e!==i.target;)e=n.get(e);e!==i.target&&(n.set(i.target,i.source),r.add(i))}return{parents:n,parentEdges:r}}export{v as a,b as i,_ as n,y as o,g as r,x as t};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,W as s,jt as c,ot as l,st as u}from"./semi-CHxO7u8f.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-CFmEgVyi.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(a,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(r,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(c,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:s,onChange:O,style:{width:260}}),(0,E.jsx)(i,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{G as r,I as i,Lt as a,N as o,R as s,U as c,lt as l,ut as u}from"./semi-65W_4I1v.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-D_JyAVdp.js";var T=e(t(),1),E=e(n(),1),{Text:D}=r;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[r,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:r||void 0,limit:k}),[r,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(s,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(i,{children:[(0,E.jsx)(s,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(a,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(i,{children:[(0,E.jsx)(c,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:r,onChange:O,style:{width:260}}),(0,E.jsx)(c,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More