Skip to content

Modern Docker Management, Designed for Everyone

feat: allow mTLS auth for edge agents (#2116)

Kyle Mendellaa2827b01374
diff --git a/.gitignore b/.gitignore
index 0490afc72..81cb41c91 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,6 +17,10 @@ dist/
# Claude
CLAUDE.md
+/.tmp/
+*.key
+*.pem
+*.crt
# OS
.DS_Store
diff --git a/Justfile b/Justfile
index 9ee69f0d8..66bdaf2e5 100644
--- a/Justfile
+++ b/Justfile
@@ -15,6 +15,45 @@ _dev-frontend:
_dev-backend:
cd backend && air
+[group('dev')]
+_dev-agent:
+ #!/usr/bin/env bash
+ set -euo pipefail
+
+ if [ -z "${AGENT_TOKEN:-}" ]; then
+ echo "AGENT_TOKEN is required. Run: AGENT_TOKEN=<edge-environment-token> just dev agent"
+ exit 1
+ fi
+
+ port="${PORT:-3553}"
+ app_url="${APP_URL:-http://localhost:${port}}"
+ manager_api_url="${MANAGER_API_URL:-https://localhost:3552}"
+ edge_mtls_assets_dir="${EDGE_MTLS_ASSETS_DIR:-./.tmp/edge-test-agent/edge-mtls-agent}"
+ edge_mtls_ca_file="${EDGE_MTLS_CA_FILE:-./backend/local-manager.crt}"
+ database_url="${DATABASE_URL:-file:./.tmp/edge-test-agent/arcane.db?_pragma=journal_mode(WAL)&_pragma=busy_timeout(2500)&_txlock=immediate}"
+ projects_directory="${PROJECTS_DIRECTORY:-./.tmp/edge-test-agent/projects}"
+ git_work_dir="${GIT_WORK_DIR:-./.tmp/edge-test-agent/git}"
+ jwt_secret="${JWT_SECRET:-local-edge-test-jwt-secret-please-change}"
+ encryption_key="${ENCRYPTION_KEY:-local-edge-test-encryption-key-32}"
+
+ mkdir -p "${projects_directory}" "${git_work_dir}" "${edge_mtls_assets_dir}"
+
+ PORT="${port}" \
+ APP_URL="${app_url}" \
+ EDGE_AGENT=true \
+ EDGE_TRANSPORT=poll \
+ EDGE_MTLS_MODE=required \
+ EDGE_MTLS_ASSETS_DIR="${edge_mtls_assets_dir}" \
+ EDGE_MTLS_CA_FILE="${edge_mtls_ca_file}" \
+ AGENT_TOKEN="${AGENT_TOKEN}" \
+ MANAGER_API_URL="${manager_api_url}" \
+ DATABASE_URL="${database_url}" \
+ PROJECTS_DIRECTORY="${projects_directory}" \
+ GIT_WORK_DIR="${git_work_dir}" \
+ JWT_SECRET="${jwt_secret}" \
+ ENCRYPTION_KEY="${encryption_key}" \
+ go run ./backend/cmd
+
[group('dev')]
_dev-all:
#!/usr/bin/env bash
@@ -32,11 +71,53 @@ _dev-docker:
_dev-logs:
./scripts/development/dev.sh logs
-# Run development servers. Valid targets: "frontend", "backend", "all", "docker", "logs".
+# Run development servers. Valid targets: "frontend", "backend", "agent", "all", "docker", "logs".
[group('dev')]
dev target="docker":
@just "_dev-{{ target }}"
+# Generate a self-signed TLS cert + key for the local manager (used by the
+# backend HTTPS listener on :3552 and pinned as EDGE_MTLS_CA_FILE by the
+# local edge agent). Writes to backend/local-manager.{crt,key} with SANs for
+# localhost + 127.0.0.1. Both files are gitignored via *.crt / *.key.
+#
+# Usage:
+# just dev-tls # generate if missing
+
+# just dev-tls force=true # overwrite existing files
+[group('dev')]
+dev-tls force="false":
+ #!/usr/bin/env bash
+ set -euo pipefail
+
+ cert_path="./backend/local-manager.crt"
+ key_path="./backend/local-manager.key"
+
+ if [ "{{ force }}" != "true" ] && [ -f "${cert_path}" ] && [ -f "${key_path}" ]; then
+ echo "Cert already exists at ${cert_path}; pass force=true to regenerate."
+ exit 0
+ fi
+
+ go run ./cli generate tls \
+ --out-dir ./backend \
+ --cert-name "$(basename "${cert_path}")" \
+ --key-name "$(basename "${key_path}")" \
+ --common-name arcane-local-manager \
+ --host localhost \
+ --host arcane-local \
+ --host 127.0.0.1 \
+ --host ::1
+
+ echo ""
+ echo "Generated self-signed TLS cert:"
+ echo " cert: ${cert_path}"
+ echo " key: ${key_path}"
+ echo ""
+ echo "Run the backend with HTTPS enabled:"
+ echo " TLS_ENABLED=true TLS_CERT_FILE=${cert_path} TLS_KEY_FILE=${key_path} just dev backend"
+ echo ""
+ echo "The local edge agent recipe already pins this cert via EDGE_MTLS_CA_FILE."
+
# --- Deploy ---
# Deploy a local swarm worker plus a locally built Arcane edge agent into DinD.
#
diff --git a/backend/go.mod b/backend/go.mod
index c0c13ee28..83c75d8ed 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -56,6 +56,7 @@ require (
golang.org/x/oauth2 v0.36.0
golang.org/x/sync v0.20.0
golang.org/x/text v0.36.0
+ golang.org/x/time v0.14.0
google.golang.org/grpc v1.80.0
google.golang.org/protobuf v1.36.11
gorm.io/driver/postgres v1.6.0
@@ -234,7 +235,6 @@ require (
golang.org/x/exp v0.0.0-20250911091902-df9299821621 // indirect
golang.org/x/sys v0.43.0 // indirect
golang.org/x/term v0.42.0 // indirect
- golang.org/x/time v0.14.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index 0f31af339..de5ad968d 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -216,18 +216,20 @@ func startEdgeTunnelClientIfConfigured(appCtx context.Context, cfg *config.Confi
EdgeAgent: cfg.EdgeAgent,
EdgeTransport: cfg.EdgeTransport,
EdgeReconnectInterval: cfg.EdgeReconnectInterval,
+ EdgeMTLSMode: cfg.EdgeMTLSMode,
+ EdgeMTLSCAFile: cfg.EdgeMTLSCAFile,
+ EdgeMTLSCertFile: cfg.EdgeMTLSCertFile,
+ EdgeMTLSKeyFile: cfg.EdgeMTLSKeyFile,
+ EdgeMTLSServerName: cfg.EdgeMTLSServerName,
+ EdgeMTLSAssetsDir: cfg.EdgeMTLSAssetsDir,
+ AppURL: cfg.GetAppURL(),
ManagerApiUrl: cfg.ManagerApiUrl,
AgentToken: cfg.AgentToken,
Port: cfg.Port,
Listen: cfg.Listen,
}
- slog.InfoContext(appCtx, "Starting edge tunnel client",
- "transport_mode", edge.NormalizeEdgeTransport(edgeCfg.EdgeTransport),
- "live_tunnel_attempt_grpc", edge.UseGRPCEdgeTransport(edgeCfg) || (edge.UsePollEdgeTransport(edgeCfg) && strings.TrimSpace(edgeCfg.GetManagerGRPCAddr()) != ""),
- "live_tunnel_attempt_websocket", edge.UseWebSocketEdgeTransport(edgeCfg) || (edge.UsePollEdgeTransport(edgeCfg) && strings.TrimSpace(edgeCfg.GetManagerBaseURL()) != ""),
- "manager_url", cfg.ManagerApiUrl,
- )
+ slog.InfoContext(appCtx, "Starting edge agent session client", edge.StartupLogAttrs(edgeCfg)...)
errCh, err := edge.StartTunnelClientWithErrors(appCtx, edgeCfg, router)
if err != nil {
slog.ErrorContext(appCtx, "Failed to start edge tunnel client", "error", err)
@@ -257,6 +259,22 @@ func handleAgentBootstrapPairing(ctx context.Context, cfg *config.Config, httpCl
req.Header.Set("X-API-Key", cfg.AgentToken)
+ if cfg.EdgeAgent && strings.TrimSpace(cfg.ManagerApiUrl) != "" {
+ edgeClient, edgeErr := edge.NewManagerHTTPClient(&edge.Config{
+ ManagerApiUrl: cfg.ManagerApiUrl,
+ EdgeMTLSMode: cfg.EdgeMTLSMode,
+ EdgeMTLSCAFile: cfg.EdgeMTLSCAFile,
+ EdgeMTLSCertFile: cfg.EdgeMTLSCertFile,
+ EdgeMTLSKeyFile: cfg.EdgeMTLSKeyFile,
+ EdgeMTLSServerName: cfg.EdgeMTLSServerName,
+ EdgeMTLSAssetsDir: cfg.EdgeMTLSAssetsDir,
+ }, 10*time.Second)
+ if edgeErr != nil {
+ return fmt.Errorf("failed to configure edge pairing client: %w", edgeErr)
+ }
+ httpClient = edgeClient
+ }
+
resp, err := httpClient.Do(req) //nolint:gosec // intentional request to configured manager pairing endpoint
if err != nil {
return fmt.Errorf("pairing request failed: %w", err)
@@ -301,45 +319,20 @@ func runServices(appCtx context.Context, cfg *config.Config, router http.Handler
}
listenAddr := cfg.ListenAddr()
- httpHandler := router
- useTLS := cfg.TLSEnabled
- tlsCertFile := strings.TrimSpace(cfg.TLSCertFile)
- tlsKeyFile := strings.TrimSpace(cfg.TLSKeyFile)
-
- if useTLS && (tlsCertFile == "" || tlsKeyFile == "") {
- return fmt.Errorf("TLS_ENABLED requires both TLS_CERT_FILE and TLS_KEY_FILE")
+ useTLS, tlsCertFile, tlsKeyFile, edgeCfg, err := prepareServerTLSInternal(appCtx, cfg)
+ if err != nil {
+ return err
}
-
- var grpcServer *grpc.Server
- if !cfg.AgentMode && tunnelServer != nil {
- grpcServer = grpc.NewServer(tunnelServer.GRPCServerOptions(appCtx)...)
- tunnelpb.RegisterTunnelServiceServer(grpcServer, tunnelServer)
-
- httpHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if isTunnelGRPCRequestInternal(r) {
- grpcReq := normalizeTunnelGRPCRequestPathInternal(r)
- grpcServer.ServeHTTP(w, grpcReq)
- return
- }
- router.ServeHTTP(w, r)
- })
- slog.InfoContext(appCtx, "Using shared HTTP/gRPC listener for edge tunnel", "addr", listenAddr)
+ if tunnelServer != nil {
+ tunnelServer.SetConfig(edgeCfg)
}
- var protocols http.Protocols
- protocols.SetHTTP1(true)
- if useTLS {
- protocols.SetHTTP2(true)
- } else {
- protocols.SetUnencryptedHTTP2(true)
- httpHandler = h2c.NewHandler(httpHandler, &http2.Server{})
- }
+ httpHandler, grpcServer := configureTunnelServerInternal(appCtx, cfg, router, tunnelServer, listenAddr)
+ httpHandler, protocols := configureHTTPProtocolsInternal(useTLS, httpHandler)
- srv := &http.Server{
- Addr: listenAddr,
- Handler: httpHandler,
- Protocols: &protocols,
- ReadHeaderTimeout: 5 * time.Second,
+ srv, err := newHTTPServerInternal(listenAddr, httpHandler, protocols, useTLS, edgeCfg)
+ if err != nil {
+ return err
}
go func() {
@@ -389,6 +382,106 @@ func runServices(appCtx context.Context, cfg *config.Config, router http.Handler
return nil
}
+func prepareServerTLSInternal(ctx context.Context, cfg *config.Config) (bool, string, string, *edge.Config, error) {
+ useTLS := cfg.TLSEnabled
+ tlsCertFile := strings.TrimSpace(cfg.TLSCertFile)
+ tlsKeyFile := strings.TrimSpace(cfg.TLSKeyFile)
+ edgeCfg := buildEdgeRuntimeConfigInternal(cfg)
+ if useTLS && (tlsCertFile == "" || tlsKeyFile == "") {
+ return false, "", "", nil, fmt.Errorf("TLS_ENABLED requires both TLS_CERT_FILE and TLS_KEY_FILE")
+ }
+
+ if cfg.AgentMode {
+ return useTLS, tlsCertFile, tlsKeyFile, edgeCfg, nil
+ }
+
+ if err := edge.PrepareManagerMTLSAssetsWithContext(ctx, edgeCfg); err != nil {
+ return false, "", "", nil, err
+ }
+
+ if edge.NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode) != edge.EdgeMTLSModeDisabled {
+ if err := edge.ValidateManagerMTLSConfig(edgeCfg, useTLS); err != nil {
+ return false, "", "", nil, err
+ }
+ }
+
+ return useTLS, tlsCertFile, tlsKeyFile, edgeCfg, nil
+}
+
+func configureTunnelServerInternal(appCtx context.Context, cfg *config.Config, router http.Handler, tunnelServer *edge.TunnelServer, listenAddr string) (http.Handler, *grpc.Server) {
+ httpHandler := router
+ var grpcServer *grpc.Server
+
+ if !cfg.AgentMode && tunnelServer != nil {
+ grpcServer = grpc.NewServer(tunnelServer.GRPCServerOptions(appCtx)...)
+ tunnelpb.RegisterTunnelServiceServer(grpcServer, tunnelServer)
+
+ httpHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if isTunnelGRPCRequestInternal(r) {
+ grpcReq := normalizeTunnelGRPCRequestPathInternal(r)
+ grpcServer.ServeHTTP(w, grpcReq)
+ return
+ }
+ router.ServeHTTP(w, r)
+ })
+ slog.InfoContext(appCtx, "Using shared HTTP/gRPC listener for edge tunnel", "addr", listenAddr)
+ }
+
+ return httpHandler, grpcServer
+}
+
+func configureHTTPProtocolsInternal(useTLS bool, handler http.Handler) (http.Handler, *http.Protocols) {
+ var protocols http.Protocols
+ protocols.SetHTTP1(true)
+ if useTLS {
+ protocols.SetHTTP2(true)
+ return handler, &protocols
+ }
+
+ protocols.SetUnencryptedHTTP2(true)
+ return h2c.NewHandler(handler, &http2.Server{}), &protocols
+}
+
+func newHTTPServerInternal(listenAddr string, handler http.Handler, protocols *http.Protocols, useTLS bool, edgeCfg *edge.Config) (*http.Server, error) {
+ srv := &http.Server{
+ Addr: listenAddr,
+ Handler: handler,
+ Protocols: protocols,
+ ReadHeaderTimeout: 5 * time.Second,
+ }
+ if !useTLS {
+ return srv, nil
+ }
+
+ tlsConfig, err := edge.BuildManagerServerTLSConfig(edgeCfg)
+ if err != nil {
+ return nil, err
+ }
+ if tlsConfig != nil {
+ srv.TLSConfig = tlsConfig
+ }
+ return srv, nil
+}
+
+func buildEdgeRuntimeConfigInternal(cfg *config.Config) *edge.Config {
+ return &edge.Config{
+ EdgeAgent: cfg.EdgeAgent,
+ EdgeTransport: cfg.EdgeTransport,
+ EdgeReconnectInterval: cfg.EdgeReconnectInterval,
+ EdgeMTLSMode: cfg.EdgeMTLSMode,
+ EdgeMTLSCAFile: cfg.EdgeMTLSCAFile,
+ EdgeMTLSCertFile: cfg.EdgeMTLSCertFile,
+ EdgeMTLSKeyFile: cfg.EdgeMTLSKeyFile,
+ EdgeMTLSServerName: cfg.EdgeMTLSServerName,
+ EdgeMTLSAssetsDir: cfg.EdgeMTLSAssetsDir,
+ AppURL: cfg.GetAppURL(),
+ ManagerApiUrl: cfg.ManagerApiUrl,
+ AgentToken: cfg.AgentToken,
+ Port: cfg.Port,
+ Listen: cfg.Listen,
+ }
+}
+
func normalizeTunnelGRPCRequestPathInternal(r *http.Request) *http.Request {
if r == nil {
return nil
diff --git a/backend/internal/bootstrap/bootstrap_test.go b/backend/internal/bootstrap/bootstrap_test.go
index 354472621..4f02b8ff8 100644
--- a/backend/internal/bootstrap/bootstrap_test.go
+++ b/backend/internal/bootstrap/bootstrap_test.go
@@ -1,12 +1,15 @@
package bootstrap
import (
+ "context"
"net/http"
"net/http/httptest"
"testing"
+ "github.com/getarcaneapp/arcane/backend/internal/config"
tunnelpb "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge/proto/tunnel/v1"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
func TestNormalizeTunnelGRPCRequestPathInternal(t *testing.T) {
@@ -114,3 +117,19 @@ func TestIsTunnelGRPCRequestInternal(t *testing.T) {
assert.False(t, isTunnelGRPCRequestInternal(req))
})
}
+
+func TestPrepareServerTLSInternal_AgentModeSkipsManagerMTLSValidation(t *testing.T) {
+ cfg := &config.Config{
+ AgentMode: true,
+ EdgeMTLSMode: "required",
+ ManagerApiUrl: "https://127.0.0.1:3552",
+ }
+
+ useTLS, tlsCertFile, tlsKeyFile, edgeCfg, err := prepareServerTLSInternal(context.Background(), cfg)
+ require.NoError(t, err)
+ assert.False(t, useTLS)
+ assert.Empty(t, tlsCertFile)
+ assert.Empty(t, tlsKeyFile)
+ require.NotNil(t, edgeCfg)
+ assert.Equal(t, "required", edgeCfg.EdgeMTLSMode)
+}
diff --git a/backend/internal/bootstrap/edge_bootstrap.go b/backend/internal/bootstrap/edge_bootstrap.go
index f2826c60a..e34d43392 100644
--- a/backend/internal/bootstrap/edge_bootstrap.go
+++ b/backend/internal/bootstrap/edge_bootstrap.go
@@ -7,6 +7,7 @@ import (
"log/slog"
"github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
@@ -82,10 +83,58 @@ func registerEdgeTunnelRoutes(
}
server := edge.NewTunnelServer(resolver, statusCallback)
+ server.SetConfig(&edge.Config{
+ EdgeMTLSMode: cfg.EdgeMTLSMode,
+ EdgeMTLSCAFile: cfg.EdgeMTLSCAFile,
+ EdgeMTLSCertFile: cfg.EdgeMTLSCertFile,
+ EdgeMTLSKeyFile: cfg.EdgeMTLSKeyFile,
+ EdgeMTLSServerName: cfg.EdgeMTLSServerName,
+ EdgeMTLSAssetsDir: cfg.EdgeMTLSAssetsDir,
+ AppURL: cfg.GetAppURL(),
+ ManagerApiUrl: cfg.ManagerApiUrl,
+ })
+ server.SetEnvironmentNameResolver(func(ctx context.Context, envID string) (string, error) {
+ env, err := appServices.Environment.GetEnvironmentByID(ctx, envID)
+ if err != nil {
+ return "", err
+ }
+ if env == nil {
+ return "", nil
+ }
+ return env.Name, nil
+ })
server.SetEventCallback(eventCallback)
+ server.SetEnrollmentCallback(func(ctx context.Context, envID, remoteAddr string, certIssued bool, caGenerated bool, reenrolled bool) {
+ if appServices.Event == nil {
+ return
+ }
+ envName := ""
+ if env, err := appServices.Environment.GetEnvironmentByID(ctx, envID); err == nil && env != nil {
+ envName = env.Name
+ }
+ resourceType := "environment"
+ envIDCopy := envID
+ envNameCopy := envName
+ _, _ = appServices.Event.CreateEvent(ctx, services.CreateEventRequest{
+ Type: models.EventTypeEnvironmentMTLSEnroll,
+ Severity: edgeMTLSEnrollmentSeverityInternal(reenrolled),
+ Title: "Edge mTLS enrollment",
+ Description: fmt.Sprintf("Edge agent completed mTLS enrollment from %s", remoteAddr),
+ ResourceType: &resourceType,
+ ResourceID: &envIDCopy,
+ ResourceName: &envNameCopy,
+ EnvironmentID: &envIDCopy,
+ Metadata: models.JSON{"remoteAddr": remoteAddr, "reenrollment": reenrolled},
+ })
+ createEdgeMTLSIssueEventsInternal(ctx, appServices.Event, envIDCopy, envNameCopy, remoteAddr, certIssued, caGenerated, reenrolled)
+ })
go server.StartCleanupLoop(ctx)
apiGroup.POST("/tunnel/poll", server.HandlePoll)
- apiGroup.GET("/tunnel/connect", server.HandleConnect)
+ // Rate-limit agent mTLS enrollment per-IP. Enrollment is authenticated
+ // only by the agent token, so we cap bursts to mitigate brute-force or
+ // token-abuse attempts without impacting normal agent lifecycles.
+ apiGroup.POST("/tunnel/mtls/enroll", middleware.PerIPRateLimit(10, 3), middleware.PerAgentTokenRateLimit(10, 3), server.HandleMTLSEnroll)
+ apiGroup.GET("/tunnel/connect", middleware.PerIPRateLimit(60, 30), middleware.PerAgentTokenRateLimit(10, 3), server.HandleConnect)
slog.InfoContext(ctx, "Configured edge tunnel server",
"poll_enabled", true,
"grpc_enabled", !cfg.AgentMode,
@@ -94,6 +143,49 @@ func registerEdgeTunnelRoutes(
return server
}
+func createEdgeMTLSIssueEventsInternal(ctx context.Context, eventService *services.EventService, envID string, envName string, remoteAddr string, certIssued bool, caGenerated bool, reenrolled bool) {
+ if eventService == nil {
+ return
+ }
+ if caGenerated {
+ _, _ = eventService.CreateEvent(ctx, services.CreateEventRequest{
+ Type: models.EventTypeEnvironmentMTLSCAGenerated,
+ Severity: models.EventSeverityInfo,
+ Title: "Edge mTLS CA generated",
+ Description: "Arcane generated a new edge mTLS certificate authority",
+ Metadata: models.JSON{"remoteAddr": remoteAddr, "kind": "ca"},
+ })
+ }
+ if certIssued {
+ resourceType := "environment"
+ _, _ = eventService.CreateEvent(ctx, services.CreateEventRequest{
+ Type: models.EventTypeEnvironmentMTLSCertIssued,
+ Severity: edgeMTLSCertIssuedSeverityInternal(reenrolled),
+ Title: "Edge mTLS certificate issued",
+ Description: fmt.Sprintf("Arcane issued an edge mTLS client certificate for environment '%s'", envName),
+ ResourceType: &resourceType,
+ ResourceID: &envID,
+ ResourceName: &envName,
+ EnvironmentID: &envID,
+ Metadata: models.JSON{"remoteAddr": remoteAddr, "kind": "client", "reenrollment": reenrolled},
+ })
+ }
+}
+
+func edgeMTLSEnrollmentSeverityInternal(reenrolled bool) models.EventSeverity {
+ if reenrolled {
+ return models.EventSeverityWarning
+ }
+ return models.EventSeverityInfo
+}
+
+func edgeMTLSCertIssuedSeverityInternal(reenrolled bool) models.EventSeverity {
+ if reenrolled {
+ return models.EventSeverityWarning
+ }
+ return models.EventSeverityInfo
+}
+
func optionalStringPtr(value string) *string {
if value == "" {
return nil
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index 107fc3df9..d8b6d9670 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -71,6 +71,12 @@ type Config struct {
EdgeAgent bool `env:"EDGE_AGENT" default:"false"`
EdgeTransport string `env:"EDGE_TRANSPORT" default:"auto" options:"toLower"`
EdgeReconnectInterval int `env:"EDGE_RECONNECT_INTERVAL" default:"5"` // seconds
+ EdgeMTLSMode string `env:"EDGE_MTLS_MODE" default:"disabled" options:"toLower"`
+ EdgeMTLSCAFile string `env:"EDGE_MTLS_CA_FILE" default:""`
+ EdgeMTLSCertFile string `env:"EDGE_MTLS_CERT_FILE" default:""`
+ EdgeMTLSKeyFile string `env:"EDGE_MTLS_KEY_FILE" default:""`
+ EdgeMTLSServerName string `env:"EDGE_MTLS_SERVER_NAME" default:""`
+ EdgeMTLSAssetsDir string `env:"EDGE_MTLS_ASSETS_DIR" default:""`
FilePerm os.FileMode `env:"FILE_PERM" default:"0644"`
DirPerm os.FileMode `env:"DIR_PERM" default:"0755"`
diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go
index f55150a54..60ae6e174 100644
--- a/backend/internal/config/config_test.go
+++ b/backend/internal/config/config_test.go
@@ -238,8 +238,10 @@ func TestConfig_DockerSecretsFileSupport(t *testing.T) {
func TestConfig_OptionsToLower(t *testing.T) {
origLogLevel := os.Getenv("LOG_LEVEL")
origEdgeTransport := os.Getenv("EDGE_TRANSPORT")
+ origEdgeMTLSMode := os.Getenv("EDGE_MTLS_MODE")
defer restoreEnv("LOG_LEVEL", origLogLevel)
defer restoreEnv("EDGE_TRANSPORT", origEdgeTransport)
+ defer restoreEnv("EDGE_MTLS_MODE", origEdgeMTLSMode)
t.Run("LogLevel is converted to lowercase", func(t *testing.T) {
setEnv(t, "LOG_LEVEL", "DEBUG")
@@ -268,6 +270,20 @@ func TestConfig_OptionsToLower(t *testing.T) {
cfg := Load()
assert.Equal(t, "auto", cfg.EdgeTransport)
})
+
+ t.Run("EdgeMTLSMode is converted to lowercase", func(t *testing.T) {
+ setEnv(t, "EDGE_MTLS_MODE", "REQUIRED")
+
+ cfg := Load()
+ assert.Equal(t, "required", cfg.EdgeMTLSMode)
+ })
+
+ t.Run("EdgeMTLSMode defaults to disabled", func(t *testing.T) {
+ unsetEnv(t, "EDGE_MTLS_MODE")
+
+ cfg := Load()
+ assert.Equal(t, "disabled", cfg.EdgeMTLSMode)
+ })
}
func TestConfig_AllowDowngrade(t *testing.T) {
diff --git a/backend/internal/configschema/schema_test.go b/backend/internal/configschema/schema_test.go
index 3c26ca650..14264c5c8 100644
--- a/backend/internal/configschema/schema_test.go
+++ b/backend/internal/configschema/schema_test.go
@@ -201,6 +201,12 @@ var expectedEnvConfigVars = []string{
"DOCKER_HOST",
"DOCKER_IMAGE_PULL_TIMEOUT",
"EDGE_AGENT",
+ "EDGE_MTLS_ASSETS_DIR",
+ "EDGE_MTLS_CA_FILE",
+ "EDGE_MTLS_CERT_FILE",
+ "EDGE_MTLS_KEY_FILE",
+ "EDGE_MTLS_MODE",
+ "EDGE_MTLS_SERVER_NAME",
"EDGE_RECONNECT_INTERVAL",
"EDGE_TRANSPORT",
"ENCRYPTION_KEY",
diff --git a/backend/internal/huma/handlers/edge_mtls_ca.go b/backend/internal/huma/handlers/edge_mtls_ca.go
new file mode 100644
index 000000000..dbc595ce8
--- /dev/null
+++ b/backend/internal/huma/handlers/edge_mtls_ca.go
@@ -0,0 +1,118 @@
+package handlers
+
+import (
+ "crypto/x509"
+ "encoding/pem"
+ "fmt"
+ "math"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
+ typesenvironment "github.com/getarcaneapp/arcane/types/environment"
+)
+
+const edgeMTLSCertificateExpiryWarningWindow = 30 * 24 * time.Hour
+
+func generatedEdgeMTLSCAPathInternal(cfg *config.Config) (string, error) {
+ if cfg == nil {
+ return "", fmt.Errorf("config not available")
+ }
+ if edge.NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode) == edge.EdgeMTLSModeDisabled {
+ return "", fmt.Errorf("edge mTLS is disabled")
+ }
+
+ edgeCfg := &edge.Config{
+ EdgeMTLSMode: cfg.EdgeMTLSMode,
+ EdgeMTLSCAFile: cfg.EdgeMTLSCAFile,
+ EdgeMTLSAssetsDir: cfg.EdgeMTLSAssetsDir,
+ AppURL: cfg.GetAppURL(),
+ }
+ caPath, err := edge.GeneratedManagerMTLSCAPath(edgeCfg)
+ if err != nil {
+ return "", fmt.Errorf("resolve edge mTLS CA path: %w", err)
+ }
+ if _, err := os.Stat(caPath); err != nil {
+ return "", fmt.Errorf("stat edge mTLS CA: %w", err)
+ }
+
+ return caPath, nil
+}
+
+func hasGeneratedEdgeMTLSCAInternal(cfg *config.Config) bool {
+ _, err := generatedEdgeMTLSCAPathInternal(cfg)
+ return err == nil
+}
+
+func generatedEdgeMTLSClientCertPathInternal(cfg *config.Config, envID string) (string, error) {
+ if cfg == nil {
+ return "", fmt.Errorf("config not available")
+ }
+ if edge.NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode) == edge.EdgeMTLSModeDisabled {
+ return "", fmt.Errorf("edge mTLS is disabled")
+ }
+
+ edgeCfg := &edge.Config{
+ EdgeMTLSAssetsDir: cfg.EdgeMTLSAssetsDir,
+ }
+
+ certPath, err := edge.GeneratedManagerClientMTLSCertPath(edgeCfg, envID)
+ if err != nil {
+ return "", fmt.Errorf("resolve generated edge mTLS client certificate path: %w", err)
+ }
+ if _, err := os.Stat(certPath); err != nil {
+ return "", fmt.Errorf("stat generated edge mTLS client certificate: %w", err)
+ }
+
+ return certPath, nil
+}
+
+func readGeneratedEdgeMTLSCertificateInfoInternal(cfg *config.Config, envID string) (*typesenvironment.EdgeMTLSCertificate, error) {
+ certPath, err := generatedEdgeMTLSClientCertPathInternal(cfg, envID)
+ if err != nil {
+ return nil, err
+ }
+
+ certPEM, err := os.ReadFile(certPath)
+ if err != nil {
+ return nil, fmt.Errorf("read generated edge mTLS client certificate: %w", err)
+ }
+
+ block, _ := pem.Decode(certPEM)
+ if block == nil {
+ return nil, fmt.Errorf("decode generated edge mTLS client certificate PEM")
+ }
+
+ cert, err := x509.ParseCertificate(block.Bytes)
+ if err != nil {
+ return nil, fmt.Errorf("parse generated edge mTLS client certificate: %w", err)
+ }
+
+ expiresAt := cert.NotAfter.UTC()
+ now := time.Now().UTC()
+ remaining := expiresAt.Sub(now)
+ daysRemaining := edgeMTLSCertificateDaysRemainingInternal(now, expiresAt)
+
+ info := &typesenvironment.EdgeMTLSCertificate{
+ ExpiresAt: &expiresAt,
+ DaysRemaining: &daysRemaining,
+ Expired: now.After(expiresAt),
+ ExpiringSoon: now.Before(expiresAt) && remaining <= edgeMTLSCertificateExpiryWarningWindow,
+ }
+
+ if commonName := strings.TrimSpace(cert.Subject.CommonName); commonName != "" {
+ info.CommonName = &commonName
+ }
+
+ return info, nil
+}
+
+func edgeMTLSCertificateDaysRemainingInternal(now time.Time, expiresAt time.Time) int {
+ remaining := expiresAt.Sub(now)
+ if remaining <= 0 {
+ return 0
+ }
+ return int(math.Ceil(remaining.Hours() / 24))
+}
diff --git a/backend/internal/huma/handlers/edge_mtls_ca_test.go b/backend/internal/huma/handlers/edge_mtls_ca_test.go
new file mode 100644
index 000000000..37fd3f6d8
--- /dev/null
+++ b/backend/internal/huma/handlers/edge_mtls_ca_test.go
@@ -0,0 +1,117 @@
+package handlers
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ libcrypto "github.com/getarcaneapp/arcane/backend/pkg/libarcane/crypto"
+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
+ "github.com/stretchr/testify/require"
+)
+
+func TestMain(m *testing.M) {
+ libcrypto.InitEncryption(&libcrypto.Config{
+ EncryptionKey: "test-encryption-key-for-edge-mtls-32bytes-min",
+ Environment: "test",
+ })
+ os.Exit(m.Run())
+}
+
+func TestGeneratedEdgeMTLSCAPath(t *testing.T) {
+ t.Run("returns error when edge mTLS is disabled", func(t *testing.T) {
+ cfg := &config.Config{EdgeMTLSMode: edge.EdgeMTLSModeDisabled}
+
+ _, err := generatedEdgeMTLSCAPathInternal(cfg)
+
+ require.Error(t, err)
+ })
+
+ t.Run("returns configured CA path when CA is externally managed", func(t *testing.T) {
+ caPath := t.TempDir() + "/custom-ca.crt"
+ require.NoError(t, os.WriteFile(caPath, []byte("pem"), 0o644))
+
+ cfg := &config.Config{
+ EdgeMTLSMode: edge.EdgeMTLSModeRequired,
+ EdgeMTLSCAFile: caPath,
+ }
+
+ path, err := generatedEdgeMTLSCAPathInternal(cfg)
+
+ require.NoError(t, err)
+ require.Equal(t, caPath, path)
+ })
+
+ t.Run("returns generated CA path when Arcane manages the CA", func(t *testing.T) {
+ cfg := &config.Config{
+ EdgeMTLSMode: edge.EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ }
+ require.NoError(t, edge.PrepareManagerMTLSAssetsWithContext(context.Background(), &edge.Config{
+ EdgeMTLSMode: cfg.EdgeMTLSMode,
+ EdgeMTLSAssetsDir: cfg.EdgeMTLSAssetsDir,
+ AppURL: cfg.GetAppURL(),
+ }))
+
+ path, err := generatedEdgeMTLSCAPathInternal(cfg)
+
+ require.NoError(t, err)
+ require.FileExists(t, path)
+
+ pemBytes, readErr := os.ReadFile(path)
+ require.NoError(t, readErr)
+ require.Contains(t, string(pemBytes), "BEGIN CERTIFICATE")
+ })
+
+ t.Run("does not generate missing Arcane-managed CA", func(t *testing.T) {
+ cfg := &config.Config{
+ EdgeMTLSMode: edge.EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ }
+
+ _, err := generatedEdgeMTLSCAPathInternal(cfg)
+
+ require.Error(t, err)
+ require.NoFileExists(t, filepath.Join(cfg.EdgeMTLSAssetsDir, "ca.crt"))
+ require.NoFileExists(t, filepath.Join(cfg.EdgeMTLSAssetsDir, "ca.key"))
+ })
+}
+
+func TestReadGeneratedEdgeMTLSCertificateInfo(t *testing.T) {
+ cfg := &config.Config{
+ EdgeMTLSMode: edge.EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ }
+
+ _, err := edge.GenerateManagerClientMTLSAssetsWithContext(context.Background(), &edge.Config{
+ EdgeMTLSMode: cfg.EdgeMTLSMode,
+ EdgeMTLSAssetsDir: cfg.EdgeMTLSAssetsDir,
+ AppURL: cfg.GetAppURL(),
+ }, "env-123", "Lab Server")
+ require.NoError(t, err)
+
+ info, err := readGeneratedEdgeMTLSCertificateInfoInternal(cfg, "env-123")
+
+ require.NoError(t, err)
+ require.NotNil(t, info)
+ require.NotNil(t, info.CommonName)
+ require.Equal(t, "Lab-Server-env-123", *info.CommonName)
+ require.NotNil(t, info.ExpiresAt)
+ require.True(t, info.ExpiresAt.After(time.Now().UTC()))
+ require.NotNil(t, info.DaysRemaining)
+ require.True(t, *info.DaysRemaining > 0)
+ require.False(t, info.Expired)
+ require.False(t, info.ExpiringSoon)
+}
+
+func TestEdgeMTLSCertificateDaysRemaining(t *testing.T) {
+ now := time.Date(2026, 4, 30, 12, 0, 0, 0, time.UTC)
+
+ require.Equal(t, 2, edgeMTLSCertificateDaysRemainingInternal(now, now.Add(48*time.Hour)))
+ require.Equal(t, 3, edgeMTLSCertificateDaysRemainingInternal(now, now.Add(48*time.Hour+time.Second)))
+ require.Equal(t, 0, edgeMTLSCertificateDaysRemainingInternal(now, now))
+ require.Equal(t, 0, edgeMTLSCertificateDaysRemainingInternal(now, now.Add(-time.Second)))
+}
diff --git a/backend/internal/huma/handlers/environments.go b/backend/internal/huma/handlers/environments.go
index 7906d7b1d..3f4a127e5 100644
--- a/backend/internal/huma/handlers/environments.go
+++ b/backend/internal/huma/handlers/environments.go
@@ -1,11 +1,16 @@
package handlers
import (
+ "archive/zip"
+ "bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
+ "os"
+ "path/filepath"
+ "strconv"
"strings"
"time"
@@ -139,8 +144,25 @@ type PairEnvironmentOutput struct {
}
type DeploymentSnippet struct {
- DockerRun string `json:"dockerRun" doc:"Docker run command snippet"`
- DockerCompose string `json:"dockerCompose" doc:"Docker compose YAML snippet"`
+ DockerRun string `json:"dockerRun" doc:"Docker run command snippet"`
+ DockerCompose string `json:"dockerCompose" doc:"Docker compose YAML snippet"`
+ MTLS *DeploymentSnippetMTLS `json:"mtls,omitempty" doc:"Optional Arcane-generated mTLS deployment assets for edge agents"`
+}
+
+type DeploymentSnippetFile struct {
+ Name string `json:"name" doc:"Suggested filename"`
+ Content string `json:"content,omitempty" doc:"PEM file contents. Omitted for sensitive files such as private keys; use downloadUrl instead."`
+ DownloadURL string `json:"downloadUrl,omitempty" doc:"Admin-only endpoint to download this file when content is withheld"`
+ Sensitive bool `json:"sensitive,omitempty" doc:"True when this file is sensitive and must be fetched via downloadUrl"`
+ ContainerPath string `json:"containerPath" doc:"Container mount path expected by the mTLS snippet"`
+ Permissions string `json:"permissions" doc:"Suggested file mode"`
+}
+
+type DeploymentSnippetMTLS struct {
+ DockerRun string `json:"dockerRun" doc:"Docker run snippet using Arcane-generated mTLS assets"`
+ DockerCompose string `json:"dockerCompose" doc:"Docker compose snippet using Arcane-generated mTLS assets"`
+ Files []DeploymentSnippetFile `json:"files" doc:"Generated PEM files to place on the edge host"`
+ HostDirHint string `json:"hostDirHint" doc:"Suggested host directory containing the generated PEM files"`
}
type GetDeploymentSnippetsInput struct {
@@ -159,6 +181,17 @@ type GetEnvironmentVersionOutput struct {
Body base.ApiResponse[version.Info]
}
+type DownloadEdgeMTLSCAInput struct{}
+
+type DownloadEnvironmentMTLSBundleInput struct {
+ ID string `path:"id" doc:"Environment ID"`
+}
+
+type DownloadEnvironmentMTLSFileInput struct {
+ ID string `path:"id" doc:"Environment ID"`
+ FileName string `path:"fileName" doc:"mTLS asset filename"`
+}
+
// ============================================================================
// Registration
// ============================================================================
@@ -314,6 +347,32 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
},
}, h.GetDeploymentSnippets)
+ huma.Register(api, huma.Operation{
+ OperationID: "downloadEnvironmentMTLSBundle",
+ Method: "GET",
+ Path: "/environments/{id}/deployment/mtls/bundle",
+ Summary: "Download environment mTLS bundle",
+ Description: "Download the generated mTLS client certificate bundle for an edge environment",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DownloadEnvironmentMTLSBundle)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "downloadEnvironmentMTLSFile",
+ Method: "GET",
+ Path: "/environments/{id}/deployment/mtls/{fileName}",
+ Summary: "Download environment mTLS asset",
+ Description: "Download an individual generated mTLS client certificate asset for an edge environment",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DownloadEnvironmentMTLSFile)
+
huma.Register(api, huma.Operation{
OperationID: "getEnvironmentVersion",
Method: "GET",
@@ -326,6 +385,19 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"ApiKeyAuth": {}},
},
}, h.GetEnvironmentVersion)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "downloadEdgeMTLSCA",
+ Method: "GET",
+ Path: "/edge-mtls/ca",
+ Summary: "Download Arcane-generated edge mTLS CA",
+ Description: "Download the Arcane-managed certificate authority used for generated edge mTLS client certificates",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DownloadEdgeMTLSCA)
}
// ============================================================================
@@ -516,6 +588,11 @@ func (h *EnvironmentHandler) GetEnvironment(ctx context.Context, input *GetEnvir
return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())
}
h.applyEdgeRuntimeState(&out)
+ if env.IsEdge {
+ if certInfo, certErr := readGeneratedEdgeMTLSCertificateInfoInternal(h.cfg, env.ID); certErr == nil {
+ out.EdgeMTLSCertificate = certInfo
+ }
+ }
return &GetEnvironmentOutput{
Body: base.ApiResponse[environment.Environment]{
@@ -946,7 +1023,12 @@ func (h *EnvironmentHandler) GetDeploymentSnippets(ctx context.Context, input *G
// Use edge snippets for edge environments
var snippets *services.DeploymentSnippets
if env.IsEdge {
- snippets, err = h.environmentService.GenerateEdgeDeploymentSnippets(ctx, env.ID, h.cfg.GetAppURL(), *env.AccessToken)
+ snippets, err = h.environmentService.GenerateEdgeDeploymentSnippets(ctx, env.ID, h.cfg.GetAppURL(), *env.AccessToken, &edge.Config{
+ EdgeMTLSMode: h.cfg.EdgeMTLSMode,
+ EdgeMTLSCAFile: h.cfg.EdgeMTLSCAFile,
+ EdgeMTLSAssetsDir: h.cfg.EdgeMTLSAssetsDir,
+ AppURL: h.cfg.GetAppURL(),
+ })
} else {
snippets, err = h.environmentService.GenerateDeploymentSnippets(ctx, env.ID, h.cfg.GetAppURL(), *env.AccessToken)
}
@@ -955,12 +1037,39 @@ func (h *EnvironmentHandler) GetDeploymentSnippets(ctx context.Context, input *G
return nil, huma.Error500InternalServerError("Failed to generate deployment snippets")
}
+ var mtls *DeploymentSnippetMTLS
+ if snippets.MTLS != nil {
+ files := make([]DeploymentSnippetFile, 0, len(snippets.MTLS.Files))
+ for _, file := range snippets.MTLS.Files {
+ sensitive := isSensitiveMTLSAssetNameInternal(file.Name)
+ entry := DeploymentSnippetFile{
+ Name: file.Name,
+ ContainerPath: file.ContainerPath,
+ Permissions: file.Permissions,
+ DownloadURL: fmt.Sprintf("/api/environments/%s/deployment/mtls/%s", env.ID, file.Name),
+ }
+ if sensitive {
+ entry.Sensitive = true
+ } else {
+ entry.Content = file.Content
+ }
+ files = append(files, entry)
+ }
+ mtls = &DeploymentSnippetMTLS{
+ DockerRun: snippets.MTLS.DockerRun,
+ DockerCompose: snippets.MTLS.DockerCompose,
+ Files: files,
+ HostDirHint: snippets.MTLS.HostDirHint,
+ }
+ }
+
return &GetDeploymentSnippetsOutput{
Body: base.ApiResponse[DeploymentSnippet]{
Success: true,
Data: DeploymentSnippet{
DockerRun: snippets.DockerRun,
DockerCompose: snippets.DockerCompose,
+ MTLS: mtls,
},
},
}, nil
@@ -1038,3 +1147,314 @@ func (h *EnvironmentHandler) GetEnvironmentVersion(ctx context.Context, input *G
},
}, nil
}
+
+// DownloadEdgeMTLSCA downloads the Arcane-managed edge mTLS CA certificate.
+func (h *EnvironmentHandler) DownloadEdgeMTLSCA(ctx context.Context, _ *DownloadEdgeMTLSCAInput) (*huma.StreamResponse, error) {
+ if err := checkAdmin(ctx); err != nil {
+ return nil, err
+ }
+
+ caPath, err := generatedEdgeMTLSCAPathInternal(h.cfg)
+ if err != nil {
+ return nil, huma.Error404NotFound("Arcane-managed edge mTLS CA is not available")
+ }
+
+ caPEM, err := os.ReadFile(caPath)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to read generated edge mTLS CA", "path", caPath, "error", err.Error())
+ return nil, huma.Error500InternalServerError("Failed to read Arcane-generated edge mTLS CA")
+ }
+
+ fileName := filepath.Base(caPath)
+ if strings.TrimSpace(fileName) == "" {
+ fileName = "ca.crt"
+ }
+
+ return &huma.StreamResponse{
+ Body: func(humaCtx huma.Context) { //nolint:contextcheck // context is obtained from humaCtx.Context()
+ humaCtx.SetHeader("Content-Type", "application/x-pem-file")
+ humaCtx.SetHeader("Content-Disposition", fmt.Sprintf("attachment; filename=%q", fileName))
+ humaCtx.SetHeader("Content-Length", strconv.Itoa(len(caPEM)))
+
+ if written, writeErr := humaCtx.BodyWriter().Write(bytes.Clone(caPEM)); writeErr != nil || written != len(caPEM) {
+ slog.WarnContext(humaCtx.Context(), "Failed to stream edge mTLS CA download", "fileName", fileName, "bytesWritten", written, "bytesExpected", len(caPEM), "error", writeErr)
+ return
+ }
+ h.logMTLSAuditEvent(humaCtx.Context(), nil, models.EventTypeEnvironmentMTLSDownload,
+ "mTLS CA downloaded",
+ fmt.Sprintf("Administrator downloaded edge mTLS CA %q", fileName),
+ models.JSON{
+ "fileName": fileName,
+ "kind": "ca",
+ })
+ },
+ }, nil
+}
+
+func (h *EnvironmentHandler) DownloadEnvironmentMTLSBundle(ctx context.Context, input *DownloadEnvironmentMTLSBundleInput) (*huma.StreamResponse, error) {
+ if err := checkAdmin(ctx); err != nil {
+ return nil, err
+ }
+
+ env, files, err := h.loadEnvironmentMTLSFiles(ctx, input.ID)
+ if err != nil {
+ return nil, err
+ }
+
+ var archive bytes.Buffer
+ zipWriter := zip.NewWriter(&archive)
+
+ for _, file := range files {
+ downloadName := environmentMTLSAssetDownloadNameInternal(env, file.Name)
+ header := &zip.FileHeader{
+ Name: downloadName,
+ Method: zip.Deflate,
+ }
+ header.SetMode(environmentMTLSAssetFileModeInternal(file))
+
+ entry, createErr := zipWriter.CreateHeader(header)
+ if createErr != nil {
+ slog.ErrorContext(ctx, "Failed to create mTLS bundle entry", "environmentID", input.ID, "fileName", downloadName, "error", createErr.Error())
+ return nil, huma.Error500InternalServerError("Failed to build mTLS bundle")
+ }
+
+ if _, writeErr := entry.Write([]byte(file.Content)); writeErr != nil {
+ slog.ErrorContext(ctx, "Failed to write mTLS bundle entry", "environmentID", input.ID, "fileName", downloadName, "error", writeErr.Error())
+ return nil, huma.Error500InternalServerError("Failed to build mTLS bundle")
+ }
+ }
+
+ if err := zipWriter.Close(); err != nil {
+ slog.ErrorContext(ctx, "Failed to finalize mTLS bundle", "environmentID", input.ID, "error", err.Error())
+ return nil, huma.Error500InternalServerError("Failed to build mTLS bundle")
+ }
+
+ fileName := environmentMTLSDownloadBaseNameInternal(env) + "-mtls.zip"
+
+ return &huma.StreamResponse{
+ Body: func(humaCtx huma.Context) { //nolint:contextcheck // context is obtained from humaCtx.Context()
+ humaCtx.SetHeader("Content-Type", "application/zip")
+ humaCtx.SetHeader("Content-Disposition", fmt.Sprintf("attachment; filename=%q", fileName))
+ humaCtx.SetHeader("Content-Length", strconv.Itoa(archive.Len()))
+
+ if written, writeErr := humaCtx.BodyWriter().Write(archive.Bytes()); writeErr != nil || written != archive.Len() {
+ slog.WarnContext(humaCtx.Context(), "Failed to stream edge mTLS bundle download", "environmentID", input.ID, "fileName", fileName, "bytesWritten", written, "bytesExpected", archive.Len(), "error", writeErr)
+ return
+ }
+ h.logMTLSAuditEvent(humaCtx.Context(), env, models.EventTypeEnvironmentMTLSDownload,
+ "mTLS bundle downloaded",
+ fmt.Sprintf("Administrator downloaded edge mTLS bundle %q (%d files)", fileName, len(files)),
+ models.JSON{
+ "fileName": fileName,
+ "kind": "bundle",
+ "fileCount": len(files),
+ })
+ },
+ }, nil
+}
+
+func (h *EnvironmentHandler) DownloadEnvironmentMTLSFile(ctx context.Context, input *DownloadEnvironmentMTLSFileInput) (*huma.StreamResponse, error) {
+ if err := checkAdmin(ctx); err != nil {
+ return nil, err
+ }
+
+ env, file, err := h.loadEnvironmentMTLSFile(ctx, input.ID, input.FileName)
+ if err != nil {
+ return nil, err
+ }
+
+ fileContent := []byte(file.Content)
+ downloadName := environmentMTLSAssetDownloadNameInternal(env, file.Name)
+
+ return &huma.StreamResponse{
+ Body: func(humaCtx huma.Context) { //nolint:contextcheck // context is obtained from humaCtx.Context()
+ humaCtx.SetHeader("Content-Type", "application/x-pem-file")
+ humaCtx.SetHeader("Content-Disposition", fmt.Sprintf("attachment; filename=%q", downloadName))
+ humaCtx.SetHeader("Content-Length", strconv.Itoa(len(fileContent)))
+
+ if written, writeErr := humaCtx.BodyWriter().Write(fileContent); writeErr != nil || written != len(fileContent) {
+ slog.WarnContext(humaCtx.Context(), "Failed to stream edge mTLS asset download", "environmentID", input.ID, "fileName", file.Name, "bytesWritten", written, "bytesExpected", len(fileContent), "error", writeErr)
+ return
+ }
+ h.logMTLSAuditEvent(humaCtx.Context(), env, models.EventTypeEnvironmentMTLSDownload,
+ "mTLS asset downloaded",
+ fmt.Sprintf("Administrator downloaded edge mTLS asset %q", file.Name),
+ models.JSON{
+ "fileName": file.Name,
+ "kind": "file",
+ "sensitive": isSensitiveMTLSAssetNameInternal(file.Name),
+ })
+ },
+ }, nil
+}
+
+func (h *EnvironmentHandler) loadEnvironmentMTLSEnvironmentInternal(ctx context.Context, environmentID string) (*models.Environment, error) {
+ if h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ env, err := h.environmentService.GetEnvironmentByID(ctx, environmentID)
+ if err != nil {
+ return nil, huma.Error404NotFound("Environment not found")
+ }
+
+ if !env.IsEdge {
+ return nil, huma.Error400BadRequest("Environment is not an edge agent")
+ }
+
+ if env.ApiKeyID == nil {
+ return nil, huma.Error400BadRequest("Environment does not have an API key configured")
+ }
+
+ if env.AccessToken == nil || *env.AccessToken == "" {
+ return nil, huma.Error400BadRequest("Environment is missing access token")
+ }
+
+ return env, nil
+}
+
+func (h *EnvironmentHandler) loadEnvironmentMTLSFiles(ctx context.Context, environmentID string) (*models.Environment, []services.DeploymentSnippetFile, error) {
+ env, err := h.loadEnvironmentMTLSEnvironmentInternal(ctx, environmentID)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ snippets, err := h.environmentService.GenerateEdgeDeploymentSnippets(ctx, env.ID, h.cfg.GetAppURL(), *env.AccessToken, &edge.Config{
+ EdgeMTLSMode: h.cfg.EdgeMTLSMode,
+ EdgeMTLSCAFile: h.cfg.EdgeMTLSCAFile,
+ EdgeMTLSAssetsDir: h.cfg.EdgeMTLSAssetsDir,
+ AppURL: h.cfg.GetAppURL(),
+ })
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to generate environment mTLS assets", "environmentID", environmentID, "error", err.Error())
+ return nil, nil, huma.Error500InternalServerError("Failed to generate environment mTLS assets")
+ }
+
+ if snippets.MTLS == nil || len(snippets.MTLS.Files) == 0 {
+ return nil, nil, huma.Error404NotFound("mTLS assets are not available for this environment")
+ }
+
+ return env, snippets.MTLS.Files, nil
+}
+
+func (h *EnvironmentHandler) loadEnvironmentMTLSFile(ctx context.Context, environmentID string, fileName string) (*models.Environment, services.DeploymentSnippetFile, error) {
+ env, files, err := h.loadEnvironmentMTLSFiles(ctx, environmentID)
+ if err != nil {
+ return nil, services.DeploymentSnippetFile{}, err
+ }
+
+ for _, file := range files {
+ if file.Name == fileName {
+ return env, file, nil
+ }
+ }
+
+ return nil, services.DeploymentSnippetFile{}, huma.Error404NotFound("Requested mTLS asset was not found")
+}
+
+// isSensitiveMTLSAssetNameInternal reports whether the given generated asset
+// filename contains secret material (currently just the agent private key).
+// Sensitive asset contents must not be returned inline in JSON responses; the
+// client should fetch them via the admin-only download endpoint instead.
+func isSensitiveMTLSAssetNameInternal(fileName string) bool {
+ name := strings.ToLower(strings.TrimSpace(fileName))
+ return strings.HasSuffix(name, ".key") || strings.HasSuffix(name, "-key.pem") || strings.HasSuffix(name, "_key.pem")
+}
+
+func environmentMTLSDownloadBaseNameInternal(env *models.Environment) string {
+ base := strings.TrimSpace(env.Name)
+ if base == "" {
+ base = "environment"
+ }
+
+ base = strings.Map(func(r rune) rune {
+ switch {
+ case r >= 'a' && r <= 'z':
+ return r
+ case r >= 'A' && r <= 'Z':
+ return r
+ case r >= '0' && r <= '9':
+ return r
+ default:
+ return '-'
+ }
+ }, base)
+
+ base = strings.Trim(base, "-")
+ if base == "" {
+ base = "environment"
+ }
+
+ return base + "-" + env.ID
+}
+
+func environmentMTLSAssetDownloadNameInternal(env *models.Environment, fileName string) string {
+ base := environmentMTLSDownloadBaseNameInternal(env)
+
+ switch fileName {
+ case "agent.crt":
+ return base + ".pem"
+ case "agent.key":
+ return base + ".key"
+ default:
+ return fileName
+ }
+}
+
+func environmentMTLSAssetFileModeInternal(file services.DeploymentSnippetFile) os.FileMode {
+ if parsed, err := strconv.ParseUint(strings.TrimSpace(file.Permissions), 8, 32); err == nil && parsed != 0 {
+ return os.FileMode(parsed)
+ }
+ if isSensitiveMTLSAssetNameInternal(file.Name) {
+ return 0o600
+ }
+ return 0o644
+}
+
+// logMTLSAuditEvent records an audit event for administrator-triggered
+// edge mTLS actions (downloads, bundle exports). Must never include raw
+// certificate content or private key material.
+func (h *EnvironmentHandler) logMTLSAuditEvent(ctx context.Context, env *models.Environment, eventType models.EventType, title, description string, extra models.JSON) {
+ if h == nil || h.eventService == nil {
+ return
+ }
+
+ user, _ := humamw.GetCurrentUserFromContext(ctx)
+ var userID, username *string
+ if user != nil {
+ uid := user.ID
+ uname := user.Username
+ userID = &uid
+ username = &uname
+ }
+
+ if extra == nil {
+ extra = models.JSON{}
+ }
+ if remoteAddr := strings.TrimSpace(humamw.GetRemoteAddrFromContext(ctx)); remoteAddr != "" {
+ extra["remoteAddr"] = remoteAddr
+ }
+
+ req := services.CreateEventRequest{
+ Type: eventType,
+ Severity: models.EventSeverityInfo,
+ Title: title,
+ Description: description,
+ UserID: userID,
+ Username: username,
+ Metadata: extra,
+ }
+ if env != nil {
+ envID := env.ID
+ envName := env.Name
+ resourceType := "environment"
+ req.ResourceType = &resourceType
+ req.ResourceID = &envID
+ req.ResourceName = &envName
+ req.EnvironmentID = &envID
+ }
+
+ if _, err := h.eventService.CreateEvent(ctx, req); err != nil {
+ slog.WarnContext(ctx, "Failed to record mTLS audit event", "type", string(eventType), "error", err)
+ }
+}
diff --git a/backend/internal/huma/handlers/environments_test.go b/backend/internal/huma/handlers/environments_test.go
index dfb96d63c..c05daef36 100644
--- a/backend/internal/huma/handlers/environments_test.go
+++ b/backend/internal/huma/handlers/environments_test.go
@@ -1,15 +1,39 @@
package handlers
import (
+ "os"
"testing"
"time"
"github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
envtypes "github.com/getarcaneapp/arcane/types/environment"
"github.com/stretchr/testify/assert"
)
+func TestEnvironmentMTLSAssetDownloadName(t *testing.T) {
+ env := &models.Environment{Name: "Lab Server"}
+ env.ID = "env-123"
+
+ assert.Equal(t, "Lab-Server-env-123.pem", environmentMTLSAssetDownloadNameInternal(env, "agent.crt"))
+ assert.Equal(t, "Lab-Server-env-123.key", environmentMTLSAssetDownloadNameInternal(env, "agent.key"))
+ assert.Equal(t, "ca.crt", environmentMTLSAssetDownloadNameInternal(env, "ca.crt"))
+}
+
+func TestEnvironmentMTLSAssetFileModeInternal(t *testing.T) {
+ assert.Equal(t, os.FileMode(0o600), environmentMTLSAssetFileModeInternal(services.DeploymentSnippetFile{
+ Name: "agent.key",
+ Permissions: "0600",
+ }))
+ assert.Equal(t, os.FileMode(0o644), environmentMTLSAssetFileModeInternal(services.DeploymentSnippetFile{
+ Name: "ca.crt",
+ }))
+ assert.Equal(t, os.FileMode(0o600), environmentMTLSAssetFileModeInternal(services.DeploymentSnippetFile{
+ Name: "agent.key",
+ }))
+}
+
func TestEnvironmentHandlerApplyEdgeRuntimeState(t *testing.T) {
t.Run("leaves non-edge environments unchanged", func(t *testing.T) {
handler := &EnvironmentHandler{}
@@ -23,6 +47,10 @@ func TestEnvironmentHandlerApplyEdgeRuntimeState(t *testing.T) {
assert.Equal(t, string(models.EnvironmentStatusOnline), env.Status)
assert.Nil(t, env.EdgeTransport)
+ assert.Nil(t, env.EdgeSecurityMode)
+ assert.Nil(t, env.EdgeSessionID)
+ assert.Nil(t, env.EdgeAgentInstance)
+ assert.Nil(t, env.EdgeCapabilities)
assert.Nil(t, env.Connected)
assert.Nil(t, env.ConnectedAt)
assert.Nil(t, env.LastHeartbeat)
@@ -44,6 +72,10 @@ func TestEnvironmentHandlerApplyEdgeRuntimeState(t *testing.T) {
assert.Equal(t, string(models.EnvironmentStatusOffline), env.Status)
assert.Nil(t, env.EdgeTransport)
+ assert.Nil(t, env.EdgeSecurityMode)
+ assert.Nil(t, env.EdgeSessionID)
+ assert.Nil(t, env.EdgeAgentInstance)
+ assert.Nil(t, env.EdgeCapabilities)
if assert.NotNil(t, env.Connected) {
assert.False(t, *env.Connected)
}
@@ -67,6 +99,10 @@ func TestEnvironmentHandlerApplyEdgeRuntimeState(t *testing.T) {
assert.Equal(t, string(models.EnvironmentStatusPending), env.Status)
assert.Nil(t, env.EdgeTransport)
+ assert.Nil(t, env.EdgeSecurityMode)
+ assert.Nil(t, env.EdgeSessionID)
+ assert.Nil(t, env.EdgeAgentInstance)
+ assert.Nil(t, env.EdgeCapabilities)
if assert.NotNil(t, env.Connected) {
assert.False(t, *env.Connected)
}
@@ -81,6 +117,10 @@ func TestEnvironmentHandlerApplyEdgeRuntimeState(t *testing.T) {
t.Cleanup(func() { edge.GetRegistry().Unregister(envID) })
tunnel := edge.NewAgentTunnelWithConn(envID, edge.NewGRPCManagerTunnelConn(nil))
+ tunnel.SessionID = "session-live"
+ tunnel.AgentInstance = "agent-live"
+ tunnel.SecurityMode = "mtls"
+ tunnel.Capabilities = []string{"container.list", "container.inspect"}
edge.GetRegistry().Register(envID, tunnel)
env := envtypes.Environment{
@@ -95,6 +135,16 @@ func TestEnvironmentHandlerApplyEdgeRuntimeState(t *testing.T) {
if assert.NotNil(t, env.EdgeTransport) {
assert.Equal(t, edge.EdgeTransportGRPC, *env.EdgeTransport)
}
+ if assert.NotNil(t, env.EdgeSecurityMode) {
+ assert.Equal(t, "mtls", *env.EdgeSecurityMode)
+ }
+ if assert.NotNil(t, env.EdgeSessionID) {
+ assert.Equal(t, "session-live", *env.EdgeSessionID)
+ }
+ if assert.NotNil(t, env.EdgeAgentInstance) {
+ assert.Equal(t, "agent-live", *env.EdgeAgentInstance)
+ }
+ assert.Equal(t, []string{"container.list", "container.inspect"}, env.EdgeCapabilities)
if assert.NotNil(t, env.Connected) {
assert.True(t, *env.Connected)
}
@@ -123,6 +173,10 @@ func TestEnvironmentHandlerApplyEdgeRuntimeState(t *testing.T) {
assert.False(t, *env.Connected)
}
assert.Nil(t, env.EdgeTransport)
+ assert.Nil(t, env.EdgeSecurityMode)
+ assert.Nil(t, env.EdgeSessionID)
+ assert.Nil(t, env.EdgeAgentInstance)
+ assert.Nil(t, env.EdgeCapabilities)
assert.Nil(t, env.ConnectedAt)
assert.Nil(t, env.LastHeartbeat)
assert.NotNil(t, env.LastPollAt)
diff --git a/backend/internal/huma/handlers/settings.go b/backend/internal/huma/handlers/settings.go
index 9e8668467..38119943a 100644
--- a/backend/internal/huma/handlers/settings.go
+++ b/backend/internal/huma/handlers/settings.go
@@ -183,6 +183,50 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s
}, h.GetCategories)
}
+func (h *SettingsHandler) appendRuntimeSettingsInternal(settingsDto []settings.PublicSetting, includeAuthenticatedOnly bool) []settings.PublicSetting {
+ if !includeAuthenticatedOnly {
+ return settingsDto
+ }
+
+ uiConfigDisabled := false
+ if h.cfg != nil {
+ uiConfigDisabled = h.cfg.UIConfigurationDisabled
+ }
+ settingsDto = append(settingsDto, settings.PublicSetting{
+ Key: "uiConfigDisabled",
+ Value: strconv.FormatBool(uiConfigDisabled),
+ Type: "boolean",
+ })
+
+ backupVolumeName := "arcane-backups"
+ if h.cfg != nil && strings.TrimSpace(h.cfg.BackupVolumeName) != "" {
+ backupVolumeName = h.cfg.BackupVolumeName
+ }
+ settingsDto = append(settingsDto, settings.PublicSetting{
+ Key: "backupVolumeName",
+ Value: backupVolumeName,
+ Type: "string",
+ })
+
+ settingsDto = append(settingsDto, settings.PublicSetting{
+ Key: "edgeMTLSManagerCAAvailable",
+ Value: strconv.FormatBool(hasGeneratedEdgeMTLSCAInternal(h.cfg)),
+ Type: "boolean",
+ })
+
+ if h.settingsService != nil {
+ cfg := h.settingsService.GetSettingsConfig()
+ depotConfigured := strings.TrimSpace(cfg.DepotProjectId.Value) != "" && strings.TrimSpace(cfg.DepotToken.Value) != ""
+ settingsDto = append(settingsDto, settings.PublicSetting{
+ Key: "depotConfigured",
+ Value: strconv.FormatBool(depotConfigured),
+ Type: "boolean",
+ })
+ }
+
+ return settingsDto
+}
+
// GetPublicSettings returns public settings for an environment.
func (h *SettingsHandler) GetPublicSettings(ctx context.Context, input *GetPublicSettingsInput) (*GetPublicSettingsOutput, error) {
if h.settingsService == nil {
@@ -214,7 +258,7 @@ func (h *SettingsHandler) GetPublicSettings(ctx context.Context, input *GetPubli
return nil, huma.Error500InternalServerError((&common.SettingsMappingError{Err: err}).Error())
}
- return &GetPublicSettingsOutput{Body: h.appendRuntimeSettings(settingsDto, false)}, nil
+ return &GetPublicSettingsOutput{Body: h.appendRuntimeSettingsInternal(settingsDto, false)}, nil
}
// GetSettings returns all settings for an environment.
@@ -254,43 +298,7 @@ func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInp
return nil, huma.Error500InternalServerError((&common.SettingsMappingError{Err: err}).Error())
}
- return &GetSettingsOutput{Body: h.appendRuntimeSettings(settingsDto, true)}, nil
-}
-
-func (h *SettingsHandler) appendRuntimeSettings(settingsDto []settings.PublicSetting, includeAuthenticatedOnly bool) []settings.PublicSetting {
- uiConfigDisabled := false
- if includeAuthenticatedOnly && h.cfg != nil {
- uiConfigDisabled = h.cfg.UIConfigurationDisabled
- }
- if includeAuthenticatedOnly {
- settingsDto = append(settingsDto, settings.PublicSetting{
- Key: "uiConfigDisabled",
- Value: strconv.FormatBool(uiConfigDisabled),
- Type: "boolean",
- })
-
- backupVolumeName := "arcane-backups"
- if h.cfg != nil && strings.TrimSpace(h.cfg.BackupVolumeName) != "" {
- backupVolumeName = h.cfg.BackupVolumeName
- }
- settingsDto = append(settingsDto, settings.PublicSetting{
- Key: "backupVolumeName",
- Value: backupVolumeName,
- Type: "string",
- })
-
- if h.settingsService != nil {
- cfg := h.settingsService.GetSettingsConfig()
- depotConfigured := strings.TrimSpace(cfg.DepotProjectId.Value) != "" && strings.TrimSpace(cfg.DepotToken.Value) != ""
- settingsDto = append(settingsDto, settings.PublicSetting{
- Key: "depotConfigured",
- Value: strconv.FormatBool(depotConfigured),
- Type: "boolean",
- })
- }
- }
-
- return settingsDto
+ return &GetSettingsOutput{Body: h.appendRuntimeSettingsInternal(settingsDto, true)}, nil
}
// UpdateSettings updates settings for an environment.
diff --git a/backend/internal/huma/handlers/settings_test.go b/backend/internal/huma/handlers/settings_test.go
index 65ea3682d..677148ac5 100644
--- a/backend/internal/huma/handlers/settings_test.go
+++ b/backend/internal/huma/handlers/settings_test.go
@@ -1,9 +1,11 @@
package handlers
import (
+ "path/filepath"
"testing"
"github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
apitypes "github.com/getarcaneapp/arcane/types/settings"
"github.com/stretchr/testify/require"
)
@@ -16,18 +18,38 @@ func TestSettingsHandler_AppendRuntimeSettings(t *testing.T) {
},
}
- publicSettings := handler.appendRuntimeSettings(nil, false)
+ publicSettings := handler.appendRuntimeSettingsInternal(nil, false)
publicKeys := runtimeSettingKeysInternal(publicSettings)
require.NotContains(t, publicKeys, "uiConfigDisabled")
require.NotContains(t, publicKeys, "backupVolumeName")
require.NotContains(t, publicKeys, "depotConfigured")
+ require.NotContains(t, publicKeys, "edgeMTLSManagerCAAvailable")
- authenticatedSettings := handler.appendRuntimeSettings(nil, true)
+ authenticatedSettings := handler.appendRuntimeSettingsInternal(nil, true)
authenticatedKeys := runtimeSettingKeysInternal(authenticatedSettings)
require.Contains(t, authenticatedKeys, "uiConfigDisabled")
require.Contains(t, authenticatedKeys, "backupVolumeName")
+ require.Contains(t, authenticatedKeys, "edgeMTLSManagerCAAvailable")
require.Equal(t, "true", authenticatedKeys["uiConfigDisabled"])
require.Equal(t, "custom-backups", authenticatedKeys["backupVolumeName"])
+ require.Equal(t, "false", authenticatedKeys["edgeMTLSManagerCAAvailable"])
+}
+
+func TestSettingsHandler_AppendRuntimeSettings_DoesNotGenerateEdgeMTLSCA(t *testing.T) {
+ assetsDir := t.TempDir()
+ handler := &SettingsHandler{
+ cfg: &config.Config{
+ EdgeMTLSMode: edge.EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: assetsDir,
+ },
+ }
+
+ authenticatedSettings := handler.appendRuntimeSettingsInternal(nil, true)
+ authenticatedKeys := runtimeSettingKeysInternal(authenticatedSettings)
+
+ require.Equal(t, "false", authenticatedKeys["edgeMTLSManagerCAAvailable"])
+ require.NoFileExists(t, filepath.Join(assetsDir, "ca.crt"))
+ require.NoFileExists(t, filepath.Join(assetsDir, "ca.key"))
}
func runtimeSettingKeysInternal(settings []apitypes.PublicSetting) map[string]string {
diff --git a/backend/internal/huma/handlers/swarm.go b/backend/internal/huma/handlers/swarm.go
index 3731c76f9..60c996db7 100644
--- a/backend/internal/huma/handlers/swarm.go
+++ b/backend/internal/huma/handlers/swarm.go
@@ -15,6 +15,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/types/base"
swarmtypes "github.com/getarcaneapp/arcane/types/swarm"
@@ -907,7 +908,12 @@ func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwa
return nil, huma.Error500InternalServerError(err.Error())
}
- snippets, err := h.environmentService.GenerateEdgeDeploymentSnippets(ctx, env.ID, h.cfg.GetAppURL(), apiKey)
+ snippets, err := h.environmentService.GenerateEdgeDeploymentSnippets(ctx, env.ID, h.cfg.GetAppURL(), apiKey, &edge.Config{
+ EdgeMTLSMode: h.cfg.EdgeMTLSMode,
+ EdgeMTLSCAFile: h.cfg.EdgeMTLSCAFile,
+ EdgeMTLSAssetsDir: h.cfg.EdgeMTLSAssetsDir,
+ AppURL: h.cfg.GetAppURL(),
+ })
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
diff --git a/backend/internal/huma/middleware/auth.go b/backend/internal/huma/middleware/auth.go
index 8b4fe61d7..cc3963ba0 100644
--- a/backend/internal/huma/middleware/auth.go
+++ b/backend/internal/huma/middleware/auth.go
@@ -29,6 +29,8 @@ const (
ContextKeyCurrentUser ContextKey = "currentUser"
// ContextKeyUserIsAdmin is the context key for whether the user is an admin.
ContextKeyUserIsAdmin ContextKey = "userIsAdmin"
+ // ContextKeyRemoteAddr is the context key for the request remote address.
+ ContextKeyRemoteAddr ContextKey = "remoteAddr"
)
// GetUserIDFromContext retrieves the user ID from the context.
@@ -49,6 +51,12 @@ func IsAdminFromContext(ctx context.Context) bool {
return ok && isAdmin
}
+// GetRemoteAddrFromContext retrieves the request remote address from context.
+func GetRemoteAddrFromContext(ctx context.Context) string {
+ remoteAddr, _ := ctx.Value(ContextKeyRemoteAddr).(string)
+ return remoteAddr
+}
+
// securityRequirements holds parsed security requirements from an operation.
type securityRequirements struct {
isRequired bool
@@ -191,6 +199,7 @@ func createEnvironmentSudoUser(env *models.Environment) *models.User {
// enforces security requirements defined on operations.
func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyService *services.ApiKeyService, envTokenResolver environmentAccessTokenResolver, cfg *config.Config) func(ctx huma.Context, next func(huma.Context)) {
return func(ctx huma.Context, next func(huma.Context)) {
+ ctx = huma.WithContext(ctx, context.WithValue(ctx.Context(), ContextKeyRemoteAddr, ctx.RemoteAddr()))
if authService == nil {
next(ctx)
return
diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.go
index 80775a6cd..18064fbd8 100644
--- a/backend/internal/middleware/environment_middleware.go
+++ b/backend/internal/middleware/environment_middleware.go
@@ -234,6 +234,10 @@ func isManagementPathInternal(suffix string) bool {
return true
}
+ if strings.HasPrefix(suffix, "/deployment/mtls/") {
+ return true
+ }
+
_, isManagement := managementEndpointSet[suffix]
return isManagement
}
diff --git a/backend/internal/middleware/environment_middleware_test.go b/backend/internal/middleware/environment_middleware_test.go
index 3d522e17e..fc24c65a0 100644
--- a/backend/internal/middleware/environment_middleware_test.go
+++ b/backend/internal/middleware/environment_middleware_test.go
@@ -101,6 +101,30 @@ func TestEnvironmentMiddleware_KeepsEdgeManagementEndpointsLocal(t *testing.T) {
assert.True(t, localHandlerHit)
}
+func TestEnvironmentMiddleware_KeepsEdgeMTLSDownloadEndpointsLocal(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ middleware := newTestEnvironmentMiddleware()
+ router := gin.New()
+ api := router.Group("/api")
+ api.Use(middleware.Handle)
+
+ localHandlerHit := false
+ api.GET("/environments/:id/deployment/mtls/bundle", func(c *gin.Context) {
+ localHandlerHit = true
+ c.JSON(http.StatusOK, gin.H{"success": true})
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/deployment/mtls/bundle", nil)
+ recorder := httptest.NewRecorder()
+
+ router.ServeHTTP(recorder, req)
+
+ assert.Equal(t, http.StatusOK, recorder.Code)
+ assert.Contains(t, recorder.Body.String(), "\"success\":true")
+ assert.True(t, localHandlerHit)
+}
+
func TestEnvironmentMiddleware_KeepsNotificationEndpointsLocal(t *testing.T) {
gin.SetMode(gin.TestMode)
diff --git a/backend/internal/middleware/rate_limit_middleware.go b/backend/internal/middleware/rate_limit_middleware.go
new file mode 100644
index 000000000..a11eb628e
--- /dev/null
+++ b/backend/internal/middleware/rate_limit_middleware.go
@@ -0,0 +1,182 @@
+package middleware
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "net"
+ "net/http"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "golang.org/x/time/rate"
+)
+
+// ipRateLimiter tracks per-client token bucket limiters keyed by client IP.
+type ipRateLimiter struct {
+ mu sync.Mutex
+ limiters map[string]*limiterEntry
+ rate rate.Limit
+ burst int
+ ttl time.Duration
+ lastSweep time.Time
+ maxEntries int
+}
+
+type limiterEntry struct {
+ limiter *rate.Limiter
+ seen time.Time
+}
+
+func newIPRateLimiterInternal(r rate.Limit, burst int) *ipRateLimiter {
+ return &ipRateLimiter{
+ limiters: make(map[string]*limiterEntry),
+ rate: r,
+ burst: burst,
+ ttl: 10 * time.Minute,
+ maxEntries: 10000,
+ }
+}
+
+func (l *ipRateLimiter) allow(key string) bool {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ now := time.Now()
+ if now.Sub(l.lastSweep) > time.Minute || len(l.limiters) > l.maxEntries {
+ for k, e := range l.limiters {
+ if now.Sub(e.seen) > l.ttl {
+ delete(l.limiters, k)
+ }
+ }
+ l.trimToMaxEntriesInternal(key)
+ l.lastSweep = now
+ }
+
+ entry, ok := l.limiters[key]
+ if !ok {
+ l.trimForNewEntryInternal(key)
+ entry = &limiterEntry{limiter: rate.NewLimiter(l.rate, l.burst)}
+ l.limiters[key] = entry
+ }
+ entry.seen = now
+ return entry.limiter.Allow()
+}
+
+func (l *ipRateLimiter) trimForNewEntryInternal(key string) {
+ if l.maxEntries <= 0 || len(l.limiters) < l.maxEntries {
+ return
+ }
+ l.evictOldestEntriesInternal(len(l.limiters)-l.maxEntries+1, key)
+}
+
+func (l *ipRateLimiter) trimToMaxEntriesInternal(protectedKey string) {
+ if l.maxEntries <= 0 || len(l.limiters) <= l.maxEntries {
+ return
+ }
+ l.evictOldestEntriesInternal(len(l.limiters)-l.maxEntries, protectedKey)
+}
+
+func (l *ipRateLimiter) evictOldestEntriesInternal(count int, protectedKey string) {
+ if count <= 0 {
+ return
+ }
+
+ entries := make([]struct {
+ key string
+ seen time.Time
+ }, 0, len(l.limiters))
+ for key, entry := range l.limiters {
+ if key == protectedKey {
+ continue
+ }
+ entries = append(entries, struct {
+ key string
+ seen time.Time
+ }{key: key, seen: entry.seen})
+ }
+
+ sort.Slice(entries, func(i, j int) bool {
+ return entries[i].seen.Before(entries[j].seen)
+ })
+
+ for i := 0; i < count && i < len(entries); i++ {
+ delete(l.limiters, entries[i].key)
+ }
+}
+
+// PerIPRateLimit returns a Gin middleware that limits requests per client IP
+// to the given rate and burst. It responds with 429 when the limit is
+// exceeded. It is intended for public unauthenticated or weakly-authenticated
+// endpoints such as agent mTLS enrollment.
+func PerIPRateLimit(perMinute int, burst int) gin.HandlerFunc {
+ if perMinute <= 0 {
+ perMinute = 10
+ }
+ if burst <= 0 {
+ burst = perMinute
+ }
+ limiter := newIPRateLimiterInternal(rate.Every(time.Minute/time.Duration(perMinute)), burst)
+
+ return func(c *gin.Context) {
+ key := clientIPForRateLimitInternal(c)
+ if !limiter.allow(key) {
+ c.Header("Retry-After", "60")
+ c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "rate limit exceeded"})
+ return
+ }
+ c.Next()
+ }
+}
+
+// PerAgentTokenRateLimit returns a Gin middleware that limits requests per
+// edge agent token to the given rate and burst. Requests without a token pass
+// through so endpoint authentication can return the canonical auth error.
+// This is a token-scoped limiter only; enrollment and tunnel routes must also
+// stack PerIPRateLimit before it to provide IP-level back-pressure when tokens
+// are missing, invalid, rotated, or stolen.
+func PerAgentTokenRateLimit(perMinute int, burst int) gin.HandlerFunc {
+ if perMinute <= 0 {
+ perMinute = 10
+ }
+ if burst <= 0 {
+ burst = perMinute
+ }
+ limiter := newIPRateLimiterInternal(rate.Every(time.Minute/time.Duration(perMinute)), burst)
+
+ return func(c *gin.Context) {
+ key := strings.TrimSpace(c.GetHeader("X-Arcane-Agent-Token"))
+ if key == "" {
+ key = strings.TrimSpace(c.GetHeader("X-API-Key"))
+ }
+ if key == "" {
+ c.Next()
+ return
+ }
+ if !limiter.allow(agentTokenRateLimitKeyInternal(key)) {
+ c.Header("Retry-After", "60")
+ c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "rate limit exceeded"})
+ return
+ }
+ c.Next()
+ }
+}
+
+func agentTokenRateLimitKeyInternal(token string) string {
+ sum := sha256.Sum256([]byte(token))
+ return hex.EncodeToString(sum[:])
+}
+
+func clientIPForRateLimitInternal(c *gin.Context) string {
+ // Prefer the Gin-resolved client IP, which respects trusted proxy config.
+ if ip := strings.TrimSpace(c.ClientIP()); ip != "" {
+ return ip
+ }
+ host, _, err := net.SplitHostPort(c.Request.RemoteAddr)
+ if err != nil {
+ return c.Request.RemoteAddr
+ }
+ return host
+}
diff --git a/backend/internal/middleware/rate_limit_middleware_test.go b/backend/internal/middleware/rate_limit_middleware_test.go
new file mode 100644
index 000000000..565e661b9
--- /dev/null
+++ b/backend/internal/middleware/rate_limit_middleware_test.go
@@ -0,0 +1,109 @@
+package middleware
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "golang.org/x/time/rate"
+)
+
+func TestPerIPRateLimit_AllowsUnderBurstAndBlocksOver(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ router := gin.New()
+ router.POST("/t", PerIPRateLimit(60, 2), func(c *gin.Context) {
+ c.Status(http.StatusOK)
+ })
+
+ doReq := func() int {
+ req := httptest.NewRequest(http.MethodPost, "/t", nil)
+ req.RemoteAddr = "192.0.2.10:4000"
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, req)
+ return rec.Code
+ }
+
+ // Burst of 2 must succeed, the third immediate request must be throttled.
+ require.Equal(t, http.StatusOK, doReq())
+ require.Equal(t, http.StatusOK, doReq())
+ require.Equal(t, http.StatusTooManyRequests, doReq())
+}
+
+func TestPerIPRateLimit_TracksDistinctClients(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ router := gin.New()
+ router.POST("/t", PerIPRateLimit(60, 1), func(c *gin.Context) {
+ c.Status(http.StatusOK)
+ })
+
+ doReqFrom := func(addr string) int {
+ req := httptest.NewRequest(http.MethodPost, "/t", nil)
+ req.RemoteAddr = addr
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, req)
+ return rec.Code
+ }
+
+ require.Equal(t, http.StatusOK, doReqFrom("192.0.2.10:1000"))
+ require.Equal(t, http.StatusTooManyRequests, doReqFrom("192.0.2.10:1000"))
+ // Distinct client must not be affected by the first client's throttling.
+ require.Equal(t, http.StatusOK, doReqFrom("192.0.2.11:1000"))
+}
+
+func TestStackedAgentEnrollmentRateLimits_KeepIPBackPressure(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ router := gin.New()
+ router.POST("/t", PerIPRateLimit(60, 1), PerAgentTokenRateLimit(60, 10), func(c *gin.Context) {
+ c.Status(http.StatusOK)
+ })
+
+ doReq := func(token string) int {
+ req := httptest.NewRequest(http.MethodPost, "/t", nil)
+ req.RemoteAddr = "192.0.2.10:4000"
+ req.Header.Set("X-Arcane-Agent-Token", token)
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, req)
+ return rec.Code
+ }
+
+ require.Equal(t, http.StatusOK, doReq("token-a"))
+ require.Equal(t, http.StatusTooManyRequests, doReq("token-b"))
+}
+
+func TestIPRateLimiter_EnforcesMaxEntriesForRecentClients(t *testing.T) {
+ limiter := newIPRateLimiterInternal(1, 1)
+ limiter.maxEntries = 3
+
+ require.True(t, limiter.allow("client-1"))
+ require.True(t, limiter.allow("client-2"))
+ require.True(t, limiter.allow("client-3"))
+ require.True(t, limiter.allow("client-4"))
+
+ require.LessOrEqual(t, len(limiter.limiters), limiter.maxEntries)
+ require.Contains(t, limiter.limiters, "client-4")
+}
+
+func TestIPRateLimiter_ProtectsCurrentKeyDuringSweep(t *testing.T) {
+ limiter := newIPRateLimiterInternal(rate.Every(time.Hour), 1)
+ limiter.maxEntries = 1
+
+ exhausted := rate.NewLimiter(rate.Every(time.Hour), 1)
+ require.True(t, exhausted.Allow())
+
+ now := time.Now()
+ limiter.limiters["current"] = &limiterEntry{
+ limiter: exhausted,
+ seen: now.Add(-time.Minute),
+ }
+ limiter.limiters["other"] = &limiterEntry{
+ limiter: rate.NewLimiter(rate.Every(time.Hour), 1),
+ seen: now,
+ }
+
+ require.False(t, limiter.allow("current"))
+ require.Contains(t, limiter.limiters, "current")
+ require.NotContains(t, limiter.limiters, "other")
+}
diff --git a/backend/internal/models/event.go b/backend/internal/models/event.go
index 78e0dc815..a00f84083 100644
--- a/backend/internal/models/event.go
+++ b/backend/internal/models/event.go
@@ -78,6 +78,10 @@ const (
EventTypeEnvironmentUpdate EventType = "environment.update"
EventTypeEnvironmentDelete EventType = "environment.delete"
EventTypeEnvironmentApiKeyRegenerated EventType = "environment.api_key.regenerated"
+ EventTypeEnvironmentMTLSCAGenerated EventType = "environment.mtls.ca_generated"
+ EventTypeEnvironmentMTLSCertIssued EventType = "environment.mtls.cert_issued"
+ EventTypeEnvironmentMTLSEnroll EventType = "environment.mtls.enroll"
+ EventTypeEnvironmentMTLSDownload EventType = "environment.mtls.download"
EventTypeWebhookCreate EventType = "webhook.create"
EventTypeWebhookUpdate EventType = "webhook.update"
diff --git a/backend/internal/services/environment_runtime_state.go b/backend/internal/services/environment_runtime_state.go
index 7f62abd0e..9b203f930 100644
--- a/backend/internal/services/environment_runtime_state.go
+++ b/backend/internal/services/environment_runtime_state.go
@@ -21,6 +21,10 @@ func ApplyEnvironmentRuntimeState(env *environmenttypes.Environment) {
env.LastHeartbeat = nil
env.LastPollAt = nil
env.EdgeTransport = nil
+ env.EdgeSecurityMode = nil
+ env.EdgeSessionID = nil
+ env.EdgeAgentInstance = nil
+ env.EdgeCapabilities = nil
if pollState, ok := edge.GetPollRuntimeRegistry().Get(env.ID, time.Now()); ok {
env.LastPollAt = pollState.LastPollAt
@@ -32,6 +36,18 @@ func ApplyEnvironmentRuntimeState(env *environmenttypes.Environment) {
env.Status = string(models.EnvironmentStatusOnline)
env.ConnectedAt = runtimeState.ConnectedAt
env.LastHeartbeat = runtimeState.LastHeartbeat
+ if runtimeState.SecurityMode != "" {
+ env.EdgeSecurityMode = &runtimeState.SecurityMode
+ }
+ if runtimeState.SessionID != "" {
+ env.EdgeSessionID = &runtimeState.SessionID
+ }
+ if runtimeState.AgentInstance != "" {
+ env.EdgeAgentInstance = &runtimeState.AgentInstance
+ }
+ if len(runtimeState.Capabilities) > 0 {
+ env.EdgeCapabilities = append([]string(nil), runtimeState.Capabilities...)
+ }
if transport, ok := edge.GetActiveTunnelTransport(env.ID); ok {
env.EdgeTransport = &transport
} else if runtimeState.Transport != "" {
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index 578a95ce1..7bfbca3d7 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -895,9 +895,27 @@ func (s *EnvironmentService) GetEnabledRegistryCredentials(ctx context.Context)
type DeploymentSnippets struct {
DockerRun string
DockerCompose string
+ MTLS *DeploymentSnippetMTLS
}
-const deploymentSnippetsDataPath = "/app/data"
+type DeploymentSnippetFile struct {
+ Name string
+ Content string
+ ContainerPath string
+ Permissions string
+}
+
+type DeploymentSnippetMTLS struct {
+ DockerRun string
+ DockerCompose string
+ Files []DeploymentSnippetFile
+ HostDirHint string
+}
+
+const (
+ deploymentSnippetsDataPath = "/app/data"
+ deploymentSnippetsMTLSPath = "/app/data/edge-mtls-agent"
+)
// GenerateDeploymentSnippets generates Docker deployment snippets for an environment.
func (s *EnvironmentService) GenerateDeploymentSnippets(ctx context.Context, envID string, envAddress string, apiKey string) (*DeploymentSnippets, error) {
@@ -946,7 +964,7 @@ func (s *EnvironmentService) GenerateDeploymentSnippets(ctx context.Context, env
// GenerateEdgeDeploymentSnippets generates Docker deployment snippets for an edge agent.
// Edge agents connect outbound to the manager and don't require exposed ports.
-func (s *EnvironmentService) GenerateEdgeDeploymentSnippets(ctx context.Context, envID string, managerURL string, apiKey string) (*DeploymentSnippets, error) {
+func (s *EnvironmentService) GenerateEdgeDeploymentSnippets(ctx context.Context, envID string, managerURL string, apiKey string, edgeCfg *edge.Config) (*DeploymentSnippets, error) {
managerURL = strings.TrimRight(managerURL, "/")
dockerRun := strings.Join([]string{
@@ -982,10 +1000,128 @@ func (s *EnvironmentService) GenerateEdgeDeploymentSnippets(ctx context.Context,
" arcane-data:",
}, "\n")
- return &DeploymentSnippets{
+ snippets := &DeploymentSnippets{
DockerRun: dockerRun,
DockerCompose: dockerCompose,
- }, nil
+ }
+
+ envName := ""
+ if s != nil && s.db != nil {
+ if env, getErr := s.GetEnvironmentByID(ctx, envID); getErr == nil && env != nil {
+ envName = env.Name
+ }
+ }
+ if edgeCfg != nil && strings.TrimSpace(edgeCfg.AppURL) == "" {
+ edgeCfg.AppURL = managerURL
+ }
+
+ generatedAssets, err := edge.GenerateManagerClientMTLSAssetsWithContext(ctx, edgeCfg, envID, envName)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to generate edge mTLS assets; returning basic snippets only", "environment_id", envID, "error", err)
+ return snippets, nil
+ }
+ if generatedAssets == nil {
+ return snippets, nil
+ }
+ s.logGeneratedMTLSEventsInternal(ctx, envID, envName, generatedAssets)
+
+ snippets.MTLS = buildMTLSDeploymentSnippetInternal(managerURL, apiKey, generatedAssets)
+ return snippets, nil
+}
+
+func (s *EnvironmentService) logGeneratedMTLSEventsInternal(ctx context.Context, envID string, envName string, assets *edge.GeneratedMTLSAssets) {
+ if s == nil || s.eventService == nil || assets == nil {
+ return
+ }
+ if assets.CAGenerated {
+ if _, err := s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: models.EventTypeEnvironmentMTLSCAGenerated,
+ Severity: models.EventSeverityInfo,
+ Title: "Edge mTLS CA generated",
+ Description: "Arcane generated a new edge mTLS certificate authority",
+ Metadata: models.JSON{"kind": "ca"},
+ }); err != nil {
+ slog.WarnContext(ctx, "Failed to create edge mTLS CA generation event", "error", err)
+ }
+ }
+ if assets.CertIssued {
+ resourceType := "environment"
+ envIDCopy := envID
+ envNameCopy := envName
+ if _, err := s.eventService.CreateEvent(ctx, CreateEventRequest{
+ Type: models.EventTypeEnvironmentMTLSCertIssued,
+ Severity: models.EventSeverityInfo,
+ Title: "Edge mTLS certificate issued",
+ Description: fmt.Sprintf("Arcane issued an edge mTLS client certificate for environment '%s'", envName),
+ ResourceType: &resourceType,
+ ResourceID: &envIDCopy,
+ ResourceName: &envNameCopy,
+ EnvironmentID: &envIDCopy,
+ Metadata: models.JSON{"kind": "client"},
+ }); err != nil {
+ slog.WarnContext(ctx, "Failed to create edge mTLS certificate issuance event", "environment_id", envID, "error", err)
+ }
+ }
+}
+
+func buildMTLSDeploymentSnippetInternal(managerURL string, apiKey string, generatedAssets *edge.GeneratedMTLSAssets) *DeploymentSnippetMTLS {
+ if generatedAssets == nil {
+ return nil
+ }
+
+ mtlsDockerRun := strings.Join([]string{
+ "docker run -d \\",
+ " --name arcane-edge-agent \\",
+ " --restart unless-stopped \\",
+ " -e EDGE_AGENT=true \\",
+ " -e EDGE_TRANSPORT=poll \\",
+ " -e EDGE_MTLS_MODE=required \\",
+ fmt.Sprintf(" -e EDGE_MTLS_ASSETS_DIR=%s \\", deploymentSnippetsMTLSPath),
+ fmt.Sprintf(" -e AGENT_TOKEN=%s \\", apiKey),
+ fmt.Sprintf(" -e MANAGER_API_URL=%s \\", managerURL),
+ " -v /var/run/docker.sock:/var/run/docker.sock \\",
+ fmt.Sprintf(" -v arcane-data:%s \\", deploymentSnippetsDataPath),
+ " ghcr.io/getarcaneapp/arcane-headless:latest",
+ }, "\n")
+
+ mtlsDockerCompose := strings.Join([]string{
+ "# Edge agent with automatic mTLS enrollment",
+ "services:",
+ " arcane-edge-agent:",
+ " image: ghcr.io/getarcaneapp/arcane-headless:latest",
+ " container_name: arcane-edge-agent",
+ " restart: unless-stopped",
+ " environment:",
+ " - EDGE_AGENT=true",
+ " - EDGE_TRANSPORT=poll",
+ " - EDGE_MTLS_MODE=required",
+ fmt.Sprintf(" - EDGE_MTLS_ASSETS_DIR=%s", deploymentSnippetsMTLSPath),
+ fmt.Sprintf(" - AGENT_TOKEN=%s", apiKey),
+ fmt.Sprintf(" - MANAGER_API_URL=%s", managerURL),
+ " volumes:",
+ " - /var/run/docker.sock:/var/run/docker.sock",
+ fmt.Sprintf(" - arcane-data:%s", deploymentSnippetsDataPath),
+ "",
+ "volumes:",
+ " arcane-data:",
+ }, "\n")
+
+ files := make([]DeploymentSnippetFile, 0, len(generatedAssets.Files))
+ for _, file := range generatedAssets.Files {
+ files = append(files, DeploymentSnippetFile{
+ Name: file.Name,
+ Content: file.Content,
+ ContainerPath: file.ContainerPath,
+ Permissions: file.Permissions,
+ })
+ }
+
+ return &DeploymentSnippetMTLS{
+ DockerRun: mtlsDockerRun,
+ DockerCompose: mtlsDockerCompose,
+ Files: files,
+ HostDirHint: strings.TrimSpace(generatedAssets.HostDirHint),
+ }
}
// SyncRegistriesToEnvironment syncs all registries from this manager to a remote environment
diff --git a/backend/internal/services/environment_service_test.go b/backend/internal/services/environment_service_test.go
index 6289dfae9..a2e39ec08 100644
--- a/backend/internal/services/environment_service_test.go
+++ b/backend/internal/services/environment_service_test.go
@@ -6,6 +6,8 @@ import (
"fmt"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"strings"
"sync/atomic"
"testing"
@@ -19,6 +21,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/crypto"
+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/types/containerregistry"
)
@@ -473,7 +476,7 @@ func TestEnvironmentService_GenerateDeploymentSnippets_ExplicitlyUsePollTranspor
require.Contains(t, standard.DockerCompose, "- arcane-data:/app/data")
require.NotContains(t, standard.DockerRun, "-v arcane-data:/data")
- edgeSnippets, err := svc.GenerateEdgeDeploymentSnippets(context.Background(), "env-2", "https://manager.example.com", "token-456")
+ edgeSnippets, err := svc.GenerateEdgeDeploymentSnippets(context.Background(), "env-2", "https://manager.example.com", "token-456", nil)
require.NoError(t, err)
require.NotNil(t, edgeSnippets)
require.NotContains(t, edgeSnippets.DockerRun, "EDGE_TRANSPORT=websocket")
@@ -592,3 +595,57 @@ func TestEnvironmentService_ListMethods_ExcludeHiddenEnvironments(t *testing.T)
require.Len(t, remoteEnvironments, 1)
require.Equal(t, "env-visible", remoteEnvironments[0].ID)
}
+
+func TestEnvironmentService_GenerateEdgeDeploymentSnippets_WithAutoGeneratedMTLS(t *testing.T) {
+ crypto.InitEncryption(&crypto.Config{
+ EncryptionKey: "test-encryption-key-for-testing-32bytes-min",
+ Environment: "test",
+ })
+ svc := NewEnvironmentService(nil, nil, nil, nil, nil, nil)
+
+ assetsDir := filepath.Join(t.TempDir(), "edge-mtls")
+ snippets, err := svc.GenerateEdgeDeploymentSnippets(context.Background(), "env-mtls", "https://manager.example.com", "token-789", &edge.Config{
+ EdgeMTLSMode: edge.EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: assetsDir,
+ })
+ require.NoError(t, err)
+ require.NotNil(t, snippets)
+ require.NotNil(t, snippets.MTLS)
+ require.Contains(t, snippets.MTLS.DockerRun, "EDGE_MTLS_MODE=required")
+ require.Contains(t, snippets.MTLS.DockerRun, "EDGE_MTLS_ASSETS_DIR=/app/data/edge-mtls-agent")
+ require.NotContains(t, snippets.MTLS.DockerRun, "EDGE_MTLS_CA_FILE")
+ require.NotContains(t, snippets.MTLS.DockerRun, "EDGE_MTLS_CERT_FILE")
+ require.NotContains(t, snippets.MTLS.DockerRun, "EDGE_MTLS_KEY_FILE")
+ require.NotContains(t, snippets.MTLS.DockerRun, "./arcane-edge-certs:/app/data/edge-mtls-agent:ro")
+ require.Contains(t, snippets.MTLS.DockerCompose, "EDGE_MTLS_ASSETS_DIR=/app/data/edge-mtls-agent")
+ require.NotContains(t, snippets.MTLS.DockerCompose, "EDGE_MTLS_CA_FILE")
+ require.NotContains(t, snippets.MTLS.DockerCompose, "EDGE_MTLS_CERT_FILE")
+ require.NotContains(t, snippets.MTLS.DockerCompose, "EDGE_MTLS_KEY_FILE")
+ require.NotContains(t, snippets.MTLS.DockerCompose, "./arcane-edge-certs:/app/data/edge-mtls-agent:ro")
+ require.Equal(t, "./arcane-edge-certs", snippets.MTLS.HostDirHint)
+ require.Len(t, snippets.MTLS.Files, 3)
+ require.Equal(t, "ca.crt", snippets.MTLS.Files[0].Name)
+ require.Equal(t, "/app/data/edge-mtls-agent/ca.crt", snippets.MTLS.Files[0].ContainerPath)
+ require.Contains(t, snippets.MTLS.Files[0].Content, "BEGIN CERTIFICATE")
+ require.Equal(t, "agent.key", snippets.MTLS.Files[2].Name)
+ require.Equal(t, "/app/data/edge-mtls-agent/agent.key", snippets.MTLS.Files[2].ContainerPath)
+ require.Contains(t, snippets.MTLS.Files[2].Content, "BEGIN EC PRIVATE KEY")
+}
+
+func TestEnvironmentService_GenerateEdgeDeploymentSnippets_ReturnsBasicSnippetsWhenMTLSGenerationFails(t *testing.T) {
+ svc := NewEnvironmentService(nil, nil, nil, nil, nil, nil)
+
+ assetsPath := filepath.Join(t.TempDir(), "edge-mtls-file")
+ require.NoError(t, os.WriteFile(assetsPath, []byte("not a directory"), 0o600))
+
+ snippets, err := svc.GenerateEdgeDeploymentSnippets(context.Background(), "env-mtls", "https://manager.example.com", "token-789", &edge.Config{
+ EdgeMTLSMode: edge.EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: assetsPath,
+ })
+
+ require.NoError(t, err)
+ require.NotNil(t, snippets)
+ require.Nil(t, snippets.MTLS)
+ require.Contains(t, snippets.DockerRun, "EDGE_TRANSPORT=poll")
+ require.Contains(t, snippets.DockerCompose, "MANAGER_API_URL=https://manager.example.com")
+}
diff --git a/backend/internal/services/notification_service_test.go b/backend/internal/services/notification_service_test.go
index 3811fb61d..ed674855b 100644
--- a/backend/internal/services/notification_service_test.go
+++ b/backend/internal/services/notification_service_test.go
@@ -423,7 +423,7 @@ func TestNotificationService_DispatchNotification_UnsupportedKindReturnsSentinel
require.Error(t, err)
require.ErrorIs(t, err, ErrUnsupportedDispatchKind)
- var unsupportedErr error = ErrUnsupportedDispatchKind
+ var unsupportedErr = ErrUnsupportedDispatchKind
require.True(t, errors.Is(err, unsupportedErr))
require.Contains(t, err.Error(), "bogus_kind")
}
diff --git a/backend/internal/services/project_service_test.go b/backend/internal/services/project_service_test.go
index 0c7e05f00..6f4e2f302 100644
--- a/backend/internal/services/project_service_test.go
+++ b/backend/internal/services/project_service_test.go
@@ -72,7 +72,7 @@ func newProjectImagePullServer(t *testing.T, inspectByRef map[string]dockertypes
}
w.Header().Set("Content-Type", "application/json")
- _, _ = io.WriteString(w, `{"status":"Pulled"}`+"\n")
+ _, _ = io.WriteString(w, fmt.Sprintf(`{"status":"Pulled","id":%q}`+"\n", fullRef))
return
case strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json"):
path := r.URL.Path
diff --git a/backend/internal/services/template_service.go b/backend/internal/services/template_service.go
index 63ab6aef8..77ddc5a4b 100644
--- a/backend/internal/services/template_service.go
+++ b/backend/internal/services/template_service.go
@@ -1118,7 +1118,9 @@ func (s *TemplateService) UpdateGlobalVariables(ctx context.Context, vars []env.
var builder strings.Builder
builder.WriteString("# Global Environment Variables\n")
builder.WriteString("# These variables are available to all projects\n")
- builder.WriteString("# Last updated: " + time.Now().Format(time.RFC3339) + "\n\n")
+ builder.WriteString("# Last updated: ")
+ builder.WriteString(time.Now().Format(time.RFC3339))
+ builder.WriteString("\n\n")
for _, v := range vars {
if strings.TrimSpace(v.Key) == "" {
diff --git a/backend/pkg/fswatch/watcher.go b/backend/pkg/fswatch/watcher.go
index 9b7602f96..a661f18d3 100644
--- a/backend/pkg/fswatch/watcher.go
+++ b/backend/pkg/fswatch/watcher.go
@@ -27,6 +27,7 @@ type Watcher struct {
mu sync.Mutex
started bool
stopped bool
+ stopOnce sync.Once
stopErr error
}
@@ -92,29 +93,28 @@ func (fw *Watcher) Start(ctx context.Context) error {
}
func (fw *Watcher) Stop() error {
- fw.mu.Lock()
- if fw.stopped {
- err := fw.stopErr
+ fw.stopOnce.Do(func() {
+ fw.mu.Lock()
+ fw.stopped = true
+ started := fw.started
fw.mu.Unlock()
- return err
- }
- fw.stopped = true
- started := fw.started
- fw.mu.Unlock()
+ if started {
+ close(fw.stopCh)
+ <-fw.stoppedCh // Wait for watchLoop to finish
+ }
- if started {
- close(fw.stopCh)
- <-fw.stoppedCh // Wait for watchLoop to finish
- }
+ err := fw.watcher.Close()
- err := fw.watcher.Close()
+ fw.mu.Lock()
+ fw.stopErr = err
+ fw.mu.Unlock()
+ })
fw.mu.Lock()
- fw.stopErr = err
- fw.mu.Unlock()
+ defer fw.mu.Unlock()
- return err
+ return fw.stopErr
}
func (fw *Watcher) watchLoop(ctx context.Context) {
diff --git a/backend/pkg/libarcane/edge/client.go b/backend/pkg/libarcane/edge/client.go
index ce48bdc62..e3f6303a0 100644
--- a/backend/pkg/libarcane/edge/client.go
+++ b/backend/pkg/libarcane/edge/client.go
@@ -30,6 +30,7 @@ const (
// DefaultWebSocketPreferenceTTL keeps websocket as the preferred transport
// for a short period after a successful auto-mode fallback.
DefaultWebSocketPreferenceTTL = 2 * time.Minute
+ defaultCommandChunkSize = 256 * 1024
)
// activeWSStream tracks an active WebSocket stream on the agent side.
@@ -64,6 +65,8 @@ type TunnelClient struct {
activeStreams sync.Map // map[string]*activeWSStream
transportPreferenceMu sync.RWMutex
preferWebSocketUntil time.Time
+ agentInstanceID string
+ sessionID string
}
// NewTunnelClient creates a new tunnel client
@@ -99,18 +102,13 @@ func NewTunnelClient(cfg *Config, handler http.Handler) *TunnelClient {
httpClient: &http.Client{},
stopCh: make(chan struct{}),
requestTimeout: DefaultRequestTimeout,
+ agentInstanceID: uuid.NewString(),
}
}
// StartWithErrorChan runs the tunnel client and optionally emits connection errors.
func (c *TunnelClient) StartWithErrorChan(ctx context.Context, errCh chan error) {
- transport := NormalizeEdgeTransport(c.cfg.EdgeTransport)
- slog.InfoContext(ctx, "Starting edge tunnel client",
- "transport_mode", transport,
- "attempt_grpc", c.shouldAttemptGRPCTunnelInternal(),
- "attempt_websocket", c.shouldAttemptWebSocketTunnelInternal(),
- "manager_url", c.managerURL,
- )
+ slog.InfoContext(ctx, "Starting edge agent session client", StartupLogAttrs(c.cfg)...)
if errCh != nil {
defer close(errCh)
}
@@ -148,6 +146,47 @@ func (c *TunnelClient) StartWithErrorChan(ctx context.Context, errCh chan error)
}
}
+func StartupLogAttrs(cfg *Config) []any {
+ if cfg == nil {
+ return []any{
+ "control_plane", "unknown",
+ "managed_session_transports", []string{},
+ "security_mode", NormalizeEdgeMTLSMode(""),
+ }
+ }
+
+ controlPlane := "managed"
+ if UsePollEdgeTransport(cfg) {
+ controlPlane = EdgeTransportPoll
+ }
+
+ managedSessionTransports := make([]string, 0, 2)
+ if UseGRPCEdgeTransport(cfg) || (UsePollEdgeTransport(cfg) && strings.TrimSpace(cfg.GetManagerGRPCAddr()) != "") {
+ managedSessionTransports = append(managedSessionTransports, EdgeTransportGRPC)
+ }
+ if UseWebSocketEdgeTransport(cfg) || (UsePollEdgeTransport(cfg) && strings.TrimSpace(cfg.GetManagerBaseURL()) != "") {
+ managedSessionTransports = append(managedSessionTransports, EdgeTransportWebSocket)
+ }
+
+ attrs := []any{
+ "control_plane", controlPlane,
+ "managed_session_transports", managedSessionTransports,
+ "security_mode", NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode),
+ }
+
+ if managerAPIURL := strings.TrimSpace(cfg.ManagerApiUrl); managerAPIURL != "" {
+ attrs = append(attrs, "manager_api_url", managerAPIURL)
+ }
+ if managerGRPCAddr := strings.TrimSpace(cfg.GetManagerGRPCAddr()); managerGRPCAddr != "" {
+ attrs = append(attrs, "manager_grpc_addr", managerGRPCAddr)
+ }
+ if managerBaseURL := strings.TrimSpace(cfg.GetManagerBaseURL()); managerBaseURL != "" {
+ attrs = append(attrs, "manager_base_url", managerBaseURL)
+ }
+
+ return attrs
+}
+
// connectAndServe establishes a connection and handles messages.
func (c *TunnelClient) connectAndServe(ctx context.Context) error {
if UsePollEdgeTransport(c.cfg) {
@@ -283,6 +322,62 @@ func (c *TunnelClient) markTransportConnectedInternal(transport string) {
}
}
+func (c *TunnelClient) registerMessageInternal() *TunnelMessage {
+ return &TunnelMessage{
+ Type: MessageTypeRegister,
+ AgentToken: c.cfg.AgentToken,
+ AgentInstance: c.agentInstanceID,
+ Capabilities: AdvertisedEdgeCommands(),
+ ResumeSession: c.sessionID,
+ }
+}
+
+func (c *TunnelClient) awaitRegistrationInternal(ctx context.Context) (*TunnelMessage, error) {
+ if c == nil || c.conn == nil {
+ return nil, fmt.Errorf("edge tunnel connection is not initialized")
+ }
+ conn := c.conn
+
+ type registrationResult struct {
+ msg *TunnelMessage
+ err error
+ }
+
+ timeout := c.grpcRegistrationTimeoutInternal()
+ recvCh := make(chan registrationResult, 1)
+ go func() {
+ msg, err := conn.Receive()
+ recvCh <- registrationResult{msg: msg, err: err}
+ }()
+
+ timer := time.NewTimer(timeout)
+ defer timer.Stop()
+
+ select {
+ case <-ctx.Done():
+ _ = conn.Close()
+ return nil, ctx.Err()
+ case <-timer.C:
+ _ = conn.Close()
+ return nil, fmt.Errorf("timed out waiting for tunnel registration response after %s", timeout)
+ case result := <-recvCh:
+ if result.err != nil {
+ return nil, fmt.Errorf("failed to receive tunnel registration response: %w", result.err)
+ }
+ if result.msg == nil {
+ return nil, fmt.Errorf("received empty tunnel registration response")
+ }
+ if result.msg.Type != MessageTypeRegisterResponse {
+ return nil, fmt.Errorf("unexpected first tunnel message: %s", result.msg.Type)
+ }
+ if !result.msg.Accepted {
+ return nil, fmt.Errorf("manager rejected tunnel registration: %s", result.msg.Error)
+ }
+ c.sessionID = result.msg.SessionID
+ return result.msg, nil
+ }
+}
+
// heartbeatLoop sends periodic heartbeats
func (c *TunnelClient) heartbeatLoop(ctx context.Context) {
ticker := time.NewTicker(c.heartbeatInterval)
@@ -330,13 +425,23 @@ func (c *TunnelClient) messageLoop(ctx context.Context) error {
switch msg.Type {
case MessageTypeRequest:
go c.handleRequest(ctx, msg)
+ case MessageTypeCommandRequest:
+ go c.handleCommandRequest(ctx, msg)
case MessageTypeWebSocketStart:
c.handleWebSocketStart(ctx, msg)
+ case MessageTypeStreamOpen:
+ c.handleStreamOpen(ctx, msg)
case MessageTypeWebSocketData:
c.handleWebSocketData(ctx, msg)
+ case MessageTypeStreamData:
+ c.handleStreamData(ctx, msg)
case MessageTypeWebSocketClose:
c.handleWebSocketClose(ctx, msg)
- case MessageTypeResponse, MessageTypeHeartbeat, MessageTypeStreamData, MessageTypeStreamEnd, MessageTypeEvent:
+ case MessageTypeStreamClose:
+ c.handleStreamClose(ctx, msg)
+ case MessageTypeCancelRequest:
+ slog.DebugContext(ctx, "Ignoring edge cancel request on agent", "id", msg.ID)
+ case MessageTypeResponse, MessageTypeHeartbeat, MessageTypeStreamEnd, MessageTypeEvent, MessageTypeCommandAck, MessageTypeCommandOutput, MessageTypeCommandComplete, MessageTypeFileChunk:
slog.DebugContext(ctx, "Ignoring message type on agent", "type", msg.Type)
case MessageTypeHeartbeatAck:
slog.DebugContext(ctx, "Received heartbeat ack")
@@ -357,6 +462,67 @@ func (c *TunnelClient) messageLoop(ctx context.Context) error {
}
}
+func (c *TunnelClient) handleCommandRequest(ctx context.Context, msg *TunnelMessage) {
+ if !ValidateEdgeCommand(msg.Command, msg.Method, msg.Path, false) {
+ c.sendCommandComplete(msg.ID, http.StatusBadRequest, nil, nil, "unsupported edge command", false)
+ return
+ }
+ if err := c.conn.Send(&TunnelMessage{ID: msg.ID, Type: MessageTypeCommandAck, Command: msg.Command}); err != nil {
+ slog.WarnContext(ctx, "Failed to acknowledge edge command", "id", msg.ID, "command", msg.Command, "error", err)
+ return
+ }
+
+ reqCtx, cancel := context.WithTimeout(ctx, c.requestTimeout)
+ defer cancel()
+
+ req, err := c.buildLocalHTTPRequest(reqCtx, msg)
+ if err != nil {
+ c.sendCommandComplete(msg.ID, http.StatusInternalServerError, nil, nil, fmt.Sprintf("failed to create request: %v", err), false)
+ return
+ }
+
+ recorder := newCommandResponseRecorderInternal(msg.ID, msg.Command, c.conn)
+ c.handler.ServeHTTP(recorder, req)
+ if err := recorder.Close(); err != nil {
+ slog.WarnContext(reqCtx, "Failed to finalize command response", "id", msg.ID, "command", msg.Command, "error", err)
+ }
+}
+
+func (c *TunnelClient) buildLocalHTTPRequest(ctx context.Context, msg *TunnelMessage) (*http.Request, error) {
+ var body io.Reader
+ var bodyBytes []byte
+ if len(msg.Body) > 0 {
+ bodyBytes = append([]byte(nil), msg.Body...)
+ body = bytes.NewReader(bodyBytes)
+ }
+
+ path := msg.Path
+ if msg.Query != "" {
+ path = path + "?" + msg.Query
+ }
+
+ req, err := http.NewRequestWithContext(ctx, msg.Method, path, body)
+ if err != nil {
+ return nil, err
+ }
+
+ if bodyBytes != nil {
+ req.GetBody = func() (io.ReadCloser, error) {
+ return io.NopCloser(bytes.NewReader(bodyBytes)), nil
+ }
+ }
+
+ for k, v := range msg.Headers {
+ if http.CanonicalHeaderKey(k) == "Host" {
+ req.Host = v
+ continue
+ }
+ req.Header.Set(k, v)
+ }
+
+ return req, nil
+}
+
// handleRequest processes an incoming request and sends back a response
func (c *TunnelClient) handleRequest(ctx context.Context, msg *TunnelMessage) {
if c.isGRPCConnectionInternal() {
@@ -496,6 +662,11 @@ func (c *TunnelClient) handleRequestStreaming(ctx context.Context, msg *TunnelMe
// handleWebSocketStart handles a WebSocket stream start request from the manager.
func (c *TunnelClient) handleWebSocketStart(ctx context.Context, msg *TunnelMessage) {
+ if msg.Command == "" {
+ if commandName, ok := ResolveEdgeCommandName(http.MethodGet, msg.Path, true); ok {
+ msg.Command = commandName
+ }
+ }
streamID := msg.ID
slog.DebugContext(ctx, "Starting WebSocket stream", "stream_id", streamID, "path", msg.Path)
@@ -530,6 +701,22 @@ func (c *TunnelClient) handleWebSocketStart(ctx context.Context, msg *TunnelMess
go c.startLocalWebSocketWriteLoop(ctx, streamCtx, ws, stream, cancel)
}
+func (c *TunnelClient) handleStreamOpen(ctx context.Context, msg *TunnelMessage) {
+ if !ValidateEdgeCommand(msg.Command, http.MethodGet, msg.Path, true) {
+ c.sendStreamCloseMessage(msg.ID, "unsupported edge stream")
+ return
+ }
+
+ c.handleWebSocketStart(ctx, &TunnelMessage{
+ ID: msg.ID,
+ Type: MessageTypeWebSocketStart,
+ Command: msg.Command,
+ Path: msg.Path,
+ Query: msg.Query,
+ Headers: msg.Headers,
+ })
+}
+
func (c *TunnelClient) buildLocalWebSocketURLInternal(msg *TunnelMessage) string {
path := msg.Path
if msg.Query != "" {
@@ -579,6 +766,7 @@ var localDialSkipHeaders = map[string]bool{
"Sec-Websocket-Extensions": true,
"Upgrade": true,
"Connection": true,
+ "Host": true,
// Browser headers forwarded through the tunnel that are invalid
// for a server-to-server local dial.
@@ -708,15 +896,24 @@ func (c *TunnelClient) sendWebSocketData(streamID string, msgType int, data []by
}
func (c *TunnelClient) sendWebSocketClose(streamID string) {
+ c.sendStreamCloseMessage(streamID, "")
+}
+
+func (c *TunnelClient) sendStreamCloseMessage(streamID string, message string) {
closeMsg := &TunnelMessage{
- ID: streamID,
- Type: MessageTypeWebSocketClose,
+ ID: streamID,
+ Type: MessageTypeStreamClose,
+ Error: message,
}
_ = c.conn.Send(closeMsg)
}
// handleWebSocketData handles incoming WebSocket data from the manager.
func (c *TunnelClient) handleWebSocketData(ctx context.Context, msg *TunnelMessage) {
+ c.handleStreamData(ctx, msg)
+}
+
+func (c *TunnelClient) handleStreamData(ctx context.Context, msg *TunnelMessage) {
streamRaw, ok := c.activeStreams.Load(msg.ID)
if !ok {
slog.DebugContext(ctx, "Received WebSocket data for unknown stream", "stream_id", msg.ID)
@@ -740,6 +937,10 @@ func (c *TunnelClient) handleWebSocketData(ctx context.Context, msg *TunnelMessa
// handleWebSocketClose handles WebSocket close from the manager.
func (c *TunnelClient) handleWebSocketClose(ctx context.Context, msg *TunnelMessage) {
+ c.handleStreamClose(ctx, msg)
+}
+
+func (c *TunnelClient) handleStreamClose(ctx context.Context, msg *TunnelMessage) {
streamRaw, ok := c.activeStreams.Load(msg.ID)
if !ok {
return
@@ -760,6 +961,18 @@ func (c *TunnelClient) sendErrorResponse(requestID string, status int, message s
_ = c.conn.Send(resp)
}
+func (c *TunnelClient) sendCommandComplete(commandID string, status int, headers map[string]string, body []byte, message string, streaming bool) {
+ _ = c.conn.Send(&TunnelMessage{
+ ID: commandID,
+ Type: MessageTypeCommandComplete,
+ Status: status,
+ Headers: headers,
+ Body: body,
+ Error: message,
+ Streaming: streaming,
+ })
+}
+
// responseRecorder captures HTTP responses
type responseRecorder struct {
headers http.Header
@@ -767,6 +980,160 @@ type responseRecorder struct {
statusCode int
}
+type commandResponseRecorder struct {
+ commandID string
+ commandName string
+ conn TunnelConnection
+ headers http.Header
+ statusCode int
+ buffer bytes.Buffer
+ wroteHeader bool
+ streaming bool
+ sequence int64
+ closed bool
+ mu sync.Mutex
+}
+
+func newCommandResponseRecorderInternal(commandID, commandName string, conn TunnelConnection) *commandResponseRecorder {
+ return &commandResponseRecorder{
+ commandID: commandID,
+ commandName: commandName,
+ conn: conn,
+ headers: make(http.Header),
+ statusCode: http.StatusOK,
+ }
+}
+
+func (r *commandResponseRecorder) Header() http.Header {
+ return r.headers
+}
+
+func (r *commandResponseRecorder) Write(b []byte) (int, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ originalLen := len(b)
+
+ if len(b) == 0 {
+ return 0, nil
+ }
+
+ if !r.streaming && r.buffer.Len()+len(b) <= defaultCommandChunkSize {
+ return r.buffer.Write(b)
+ }
+
+ r.streaming = true
+ if err := r.flushBufferLocked(); err != nil {
+ return 0, err
+ }
+
+ for len(b) > 0 {
+ chunk := b
+ if len(chunk) > defaultCommandChunkSize {
+ chunk = chunk[:defaultCommandChunkSize]
+ }
+ if err := r.conn.Send(&TunnelMessage{
+ ID: r.commandID,
+ Type: MessageTypeCommandOutput,
+ Body: append([]byte(nil), chunk...),
+ Sequence: r.sequence,
+ Command: r.commandName,
+ }); err != nil {
+ return 0, err
+ }
+ r.sequence++
+ b = b[len(chunk):]
+ }
+
+ return originalLen, nil
+}
+
+func (r *commandResponseRecorder) WriteHeader(statusCode int) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.statusCode = statusCode
+ r.wroteHeader = true
+}
+
+func (r *commandResponseRecorder) Flush() {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.streaming = true
+ _ = r.flushBufferLocked()
+}
+
+func (r *commandResponseRecorder) Close() error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.closed {
+ return nil
+ }
+
+ if !r.streaming {
+ err := r.conn.Send(&TunnelMessage{
+ ID: r.commandID,
+ Type: MessageTypeCommandComplete,
+ Status: r.statusCode,
+ Headers: flattenResponseHeadersInternal(r.headers),
+ Body: append([]byte(nil), r.buffer.Bytes()...),
+ Streaming: false,
+ Command: r.commandName,
+ })
+ if err != nil {
+ return err
+ }
+ r.closed = true
+ return nil
+ }
+
+ if err := r.flushBufferLocked(); err != nil {
+ return err
+ }
+ if err := r.conn.Send(&TunnelMessage{
+ ID: r.commandID,
+ Type: MessageTypeCommandComplete,
+ Status: r.statusCode,
+ Headers: flattenResponseHeadersInternal(r.headers),
+ Streaming: true,
+ Command: r.commandName,
+ }); err != nil {
+ return err
+ }
+
+ r.closed = true
+ return nil
+}
+
+func (r *commandResponseRecorder) flushBufferLocked() error {
+ if r.buffer.Len() == 0 {
+ return nil
+ }
+ if err := r.conn.Send(&TunnelMessage{
+ ID: r.commandID,
+ Type: MessageTypeCommandOutput,
+ Body: append([]byte(nil), r.buffer.Bytes()...),
+ Sequence: r.sequence,
+ Command: r.commandName,
+ }); err != nil {
+ return err
+ }
+ r.sequence++
+ r.buffer.Reset()
+ return nil
+}
+
+func flattenResponseHeadersInternal(headers http.Header) map[string]string {
+ if len(headers) == 0 {
+ return nil
+ }
+ out := make(map[string]string, len(headers))
+ for k, vs := range headers {
+ if len(vs) > 0 {
+ out[k] = vs[0]
+ }
+ }
+ return out
+}
+
func (r *responseRecorder) Header() http.Header {
return r.headers
}
@@ -918,6 +1285,13 @@ func StartTunnelClientWithErrors(ctx context.Context, cfg *Config, handler http.
return nil, fmt.Errorf("AGENT_TOKEN is required")
}
+ if err := EnsureAgentMTLSAssets(ctx, cfg); err != nil {
+ return nil, err
+ }
+ if err := ValidateAgentMTLSConfig(cfg); err != nil {
+ return nil, err
+ }
+
client := NewTunnelClient(cfg, handler)
errCh := make(chan error, 1)
go client.StartWithErrorChan(ctx, errCh)
diff --git a/backend/pkg/libarcane/edge/client_grpc_test.go b/backend/pkg/libarcane/edge/client_grpc_test.go
index fec27c5c6..485b5a7bf 100644
--- a/backend/pkg/libarcane/edge/client_grpc_test.go
+++ b/backend/pkg/libarcane/edge/client_grpc_test.go
@@ -7,7 +7,6 @@ import (
"net"
"net/http"
"net/http/httptest"
- "net/url"
"strings"
"sync"
"sync/atomic"
@@ -30,17 +29,25 @@ type stallingTunnelService struct {
}
type blockingRegistrationConn struct {
- closeCount atomic.Int32
- closedCh chan struct{}
+ closeCount atomic.Int32
+ closedCh chan struct{}
+ receiveStarted chan struct{}
+ receiveStartOnce sync.Once
}
func newBlockingRegistrationConn() *blockingRegistrationConn {
- return &blockingRegistrationConn{closedCh: make(chan struct{})}
+ return &blockingRegistrationConn{
+ closedCh: make(chan struct{}),
+ receiveStarted: make(chan struct{}),
+ }
}
func (c *blockingRegistrationConn) Send(*TunnelMessage) error { return nil }
func (c *blockingRegistrationConn) Receive() (*TunnelMessage, error) {
+ c.receiveStartOnce.Do(func() {
+ close(c.receiveStarted)
+ })
<-c.closedCh
return nil, io.EOF
}
@@ -102,7 +109,7 @@ func TestTunnelClient_GRPC_EndToEnd(t *testing.T) {
defer stopManager()
localHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/local/health" {
+ if r.URL.Path != "/api/health" {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte("not found"))
return
@@ -134,7 +141,7 @@ func TestTunnelClient_GRPC_EndToEnd(t *testing.T) {
proxyCtx, proxyCancel := context.WithTimeout(ctx, 5*time.Second)
defer proxyCancel()
- status, headers, body, err := ProxyRequest(proxyCtx, tunnel, http.MethodGet, "/local/health", "", map[string]string{"Accept": "text/plain"}, nil)
+ status, headers, body, err := ProxyRequest(proxyCtx, tunnel, http.MethodGet, "/api/health", "", map[string]string{"Accept": "text/plain"}, nil)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, status)
assert.Equal(t, "text/plain", headers["Content-Type"])
@@ -196,6 +203,30 @@ func TestStartTunnelClientWithErrors_GRPCValidation(t *testing.T) {
require.Error(t, err)
assert.Contains(t, err.Error(), "AGENT_TOKEN is required")
})
+
+ t.Run("mtls requires https manager url", func(t *testing.T) {
+ _, err := StartTunnelClientWithErrors(ctx, &Config{
+ EdgeAgent: true,
+ EdgeTransport: EdgeTransportGRPC,
+ ManagerApiUrl: "http://manager.example.com/api",
+ AgentToken: "token",
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ }, http.NotFoundHandler())
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "MANAGER_API_URL to use https")
+ })
+
+ t.Run("required mtls auto-enrollment failure surfaces", func(t *testing.T) {
+ _, err := StartTunnelClientWithErrors(ctx, &Config{
+ EdgeAgent: true,
+ EdgeTransport: EdgeTransportGRPC,
+ ManagerApiUrl: "https://127.0.0.1:1/api",
+ AgentToken: "token",
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ }, http.NotFoundHandler())
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "edge mTLS enrollment request failed")
+ })
}
func TestTunnelClient_connectAndServeGRPC_EmptyManagerAddress(t *testing.T) {
@@ -264,7 +295,7 @@ func TestTunnelClient_connectAndServeGRPC_TimesOutWithoutRegisterResponse(t *tes
err := client.connectAndServeGRPC(ctx)
require.Error(t, err)
- assert.Contains(t, err.Error(), "timed out waiting for gRPC tunnel registration response")
+ assert.Contains(t, err.Error(), "timed out waiting for tunnel registration response")
assert.EqualValues(t, 1, service.connectCount.Load())
assert.True(t, client.conn == nil || client.conn.IsClosed())
}
@@ -286,6 +317,55 @@ func TestTunnelClient_awaitGRPCRegistrationInternal_ClosesConnOnContextDone(t *t
assert.EqualValues(t, 1, conn.closeCount.Load())
}
+func TestTunnelClient_awaitGRPCRegistrationInternal_ClosesAttemptConnWhenClientConnChanges(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ firstConn := newBlockingRegistrationConn()
+ secondConn := newBlockingRegistrationConn()
+ t.Cleanup(func() {
+ _ = firstConn.Close()
+ _ = secondConn.Close()
+ })
+
+ client := &TunnelClient{
+ conn: firstConn,
+ grpcRegistrationTimeout: time.Second,
+ }
+
+ type registrationResult struct {
+ msg *TunnelMessage
+ err error
+ }
+ resultCh := make(chan registrationResult, 1)
+ go func() {
+ msg, err := client.awaitGRPCRegistrationInternal(ctx)
+ resultCh <- registrationResult{msg: msg, err: err}
+ }()
+
+ select {
+ case <-firstConn.receiveStarted:
+ case <-time.After(time.Second):
+ t.Fatal("registration receive did not start")
+ }
+
+ client.conn = secondConn
+ cancel()
+
+ select {
+ case result := <-resultCh:
+ require.Nil(t, result.msg)
+ require.ErrorIs(t, result.err, context.Canceled)
+ case <-time.After(time.Second):
+ t.Fatal("registration did not exit after cancellation")
+ }
+
+ assert.True(t, firstConn.IsClosed())
+ assert.EqualValues(t, 1, firstConn.closeCount.Load())
+ assert.False(t, secondConn.IsClosed())
+ assert.EqualValues(t, 0, secondConn.closeCount.Load())
+}
+
func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -312,18 +392,33 @@ func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
headerTokenCh := make(chan string, 1)
queryCh := make(chan string, 1)
+ pathCh := make(chan string, 1)
receivedMsgCh := make(chan string, 1)
+ upgradeErrCh := make(chan string, 1)
localWSServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/local/ws" {
- w.WriteHeader(http.StatusNotFound)
- return
+ select {
+ case pathCh <- r.URL.Path:
+ default:
+ }
+ select {
+ case headerTokenCh <- r.Header.Get(HeaderAPIKey):
+ default:
+ }
+ select {
+ case queryCh <- r.URL.RawQuery:
+ default:
}
- headerTokenCh <- r.Header.Get(HeaderAPIKey)
- queryCh <- r.URL.RawQuery
-
- upgrader := websocket.Upgrader{}
+ upgrader := websocket.Upgrader{
+ CheckOrigin: func(*http.Request) bool { return true },
+ Error: func(_ http.ResponseWriter, _ *http.Request, status int, reason error) {
+ select {
+ case upgradeErrCh <- reason.Error():
+ default:
+ }
+ },
+ }
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
@@ -335,7 +430,10 @@ func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
if err != nil {
return
}
- receivedMsgCh <- string(data)
+ select {
+ case receivedMsgCh <- string(data):
+ default:
+ }
if err := conn.WriteMessage(mt, append([]byte("local echo: "), data...)); err != nil {
return
}
@@ -343,16 +441,16 @@ func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
}))
defer localWSServer.Close()
- parsedLocalURL, err := url.Parse(localWSServer.URL)
- require.NoError(t, err)
- _, localPort, err := net.SplitHostPort(parsedLocalURL.Host)
+ localHost, localPort, err := net.SplitHostPort(localWSServer.Listener.Addr().String())
require.NoError(t, err)
+ localHost = strings.Trim(localHost, "[]")
cfg := &Config{
EdgeTransport: EdgeTransportGRPC,
ManagerApiUrl: managerURL,
AgentToken: "valid-token",
EdgeReconnectInterval: 1,
+ Listen: localHost,
Port: localPort,
}
@@ -373,7 +471,7 @@ func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
c.AbortWithStatus(http.StatusServiceUnavailable)
return
}
- ProxyWebSocketRequest(c, tunnel, "/local/ws")
+ ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats")
})
proxyServer := httptest.NewServer(router)
@@ -390,10 +488,22 @@ func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
require.NoError(t, proxyConn.WriteMessage(websocket.TextMessage, []byte("hello-grpc-ws")))
msgType, payload, err := proxyConn.ReadMessage()
+ select {
+ case upgradeErr := <-upgradeErrCh:
+ t.Fatalf("local websocket upgrade failed: %s", upgradeErr)
+ default:
+ }
require.NoError(t, err)
assert.Equal(t, websocket.TextMessage, msgType)
assert.Equal(t, "local echo: hello-grpc-ws", string(payload))
+ select {
+ case got := <-pathCh:
+ assert.Equal(t, "/api/environments/0/ws/system/stats", got)
+ case <-time.After(2 * time.Second):
+ t.Fatal("timeout waiting for forwarded websocket path")
+ }
+
select {
case got := <-headerTokenCh:
assert.Equal(t, "valid-token", got)
diff --git a/backend/pkg/libarcane/edge/client_test.go b/backend/pkg/libarcane/edge/client_test.go
index f750b835b..5159b0815 100644
--- a/backend/pkg/libarcane/edge/client_test.go
+++ b/backend/pkg/libarcane/edge/client_test.go
@@ -37,6 +37,17 @@ func TestTunnelClient_HandleRequest(t *testing.T) {
conn, _ := upgrader.Upgrade(w, r, nil)
defer func() { _ = conn.Close() }()
+ _, registerData, _ := conn.ReadMessage()
+ var registerMsg TunnelMessage
+ _ = json.Unmarshal(registerData, &registerMsg)
+ assert.Equal(t, MessageTypeRegister, registerMsg.Type)
+ registerResp, _ := json.Marshal(&TunnelMessage{
+ Type: MessageTypeRegisterResponse,
+ Accepted: true,
+ SessionID: "session-1",
+ })
+ _ = conn.WriteMessage(websocket.TextMessage, registerResp)
+
// Send a request to the agent
reqMsg := &TunnelMessage{
ID: "req-1",
@@ -110,6 +121,17 @@ func TestTunnelClient_WebSocketProxy(t *testing.T) {
conn, _ := upgrader.Upgrade(w, r, nil)
defer func() { _ = conn.Close() }()
+ _, registerData, _ := conn.ReadMessage()
+ var registerMsg TunnelMessage
+ _ = json.Unmarshal(registerData, &registerMsg)
+ assert.Equal(t, MessageTypeRegister, registerMsg.Type)
+ registerResp, _ := json.Marshal(&TunnelMessage{
+ Type: MessageTypeRegisterResponse,
+ Accepted: true,
+ SessionID: "session-1",
+ })
+ _ = conn.WriteMessage(websocket.TextMessage, registerResp)
+
// Send WS Start
startMsg := &TunnelMessage{
ID: "ws-1",
@@ -163,6 +185,17 @@ func TestTunnelClient_HandleRequest_Errors(t *testing.T) {
conn, _ := upgrader.Upgrade(w, r, nil)
defer func() { _ = conn.Close() }()
+ _, registerData, _ := conn.ReadMessage()
+ var registerMsg TunnelMessage
+ _ = json.Unmarshal(registerData, &registerMsg)
+ assert.Equal(t, MessageTypeRegister, registerMsg.Type)
+ registerResp, _ := json.Marshal(&TunnelMessage{
+ Type: MessageTypeRegisterResponse,
+ Accepted: true,
+ SessionID: "session-1",
+ })
+ _ = conn.WriteMessage(websocket.TextMessage, registerResp)
+
// 1. Send request with invalid URL to trigger error
reqMsg := &TunnelMessage{
ID: "req-err",
@@ -454,6 +487,7 @@ func TestTunnelClient_DialLocalWebSocket_StripsForwardedBrowserHeaders(t *testin
msg := &TunnelMessage{
Path: "/",
Headers: map[string]string{
+ "Host": "manager.example.com",
"Origin": "https://public.browser.example.com",
"Cookie": "session=browser-cookie",
"Authorization": "Bearer browser-token",
@@ -464,6 +498,7 @@ func TestTunnelClient_DialLocalWebSocket_StripsForwardedBrowserHeaders(t *testin
}
headers := client.buildLocalWebSocketHeadersInternal(msg)
+ assert.Empty(t, headers.Get("Host"))
assert.Empty(t, headers.Get("Origin"))
assert.Empty(t, headers.Get("Cookie"))
assert.Empty(t, headers.Get("Authorization"))
diff --git a/backend/pkg/libarcane/edge/client_transport_grpc.go b/backend/pkg/libarcane/edge/client_transport_grpc.go
index 2c49543e6..5b58ead99 100644
--- a/backend/pkg/libarcane/edge/client_transport_grpc.go
+++ b/backend/pkg/libarcane/edge/client_transport_grpc.go
@@ -42,9 +42,14 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {
}
if c.useTLSForManagerGRPC() {
- dialOpts = append(dialOpts, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{ //nolint:gosec
- MinVersion: tls.VersionTLS12,
- })))
+ tlsConfig, err := buildManagerClientTLSConfigInternal(c.cfg)
+ if err != nil {
+ return fmt.Errorf("failed to configure edge gRPC TLS: %w", err)
+ }
+ if tlsConfig == nil {
+ tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12} //nolint:gosec
+ }
+ dialOpts = append(dialOpts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
} else {
dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
@@ -72,10 +77,7 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {
c.conn = NewGRPCAgentTunnelConn(stream, streamCancel)
setActiveAgentTunnelConn(c.conn)
defer clearActiveAgentTunnelConn(c.conn)
- if err := c.conn.Send(&TunnelMessage{
- Type: MessageTypeRegister,
- AgentToken: c.cfg.AgentToken,
- }); err != nil {
+ if err := c.conn.Send(c.registerMessageInternal()); err != nil {
return fmt.Errorf("failed to send register message: %w", err)
}
@@ -97,58 +99,6 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {
return c.messageLoop(ctx)
}
-func (c *TunnelClient) awaitGRPCRegistrationInternal(ctx context.Context) (*TunnelMessage, error) {
- if c == nil || c.conn == nil {
- return nil, fmt.Errorf("gRPC tunnel connection is not initialized")
- }
-
- type registrationResult struct {
- msg *TunnelMessage
- err error
- }
-
- timeout := c.grpcRegistrationTimeoutInternal()
- recvCh := make(chan registrationResult, 1)
- go func() {
- msg, err := c.conn.Receive()
- recvCh <- registrationResult{msg: msg, err: err}
- }()
-
- timer := time.NewTimer(timeout)
- defer timer.Stop()
-
- select {
- case <-ctx.Done():
- if err := c.conn.Close(); err != nil {
- slog.DebugContext(ctx, "Failed to close gRPC edge tunnel after context cancellation", "error", err)
- }
- return nil, ctx.Err()
- case <-timer.C:
- slog.WarnContext(ctx, "Timed out waiting for gRPC edge tunnel registration response",
- "manager_addr", c.managerGRPCAddr,
- "timeout", timeout,
- )
- if err := c.conn.Close(); err != nil {
- slog.DebugContext(ctx, "Failed to close gRPC edge tunnel after registration timeout", "error", err)
- }
- return nil, fmt.Errorf("timed out waiting for gRPC tunnel registration response after %s", timeout)
- case result := <-recvCh:
- if result.err != nil {
- return nil, fmt.Errorf("failed to receive gRPC tunnel registration response: %w", result.err)
- }
- if result.msg == nil {
- return nil, fmt.Errorf("received empty gRPC tunnel registration response")
- }
- if result.msg.Type != MessageTypeRegisterResponse {
- return nil, fmt.Errorf("unexpected first gRPC tunnel message: %s", result.msg.Type)
- }
- if !result.msg.Accepted {
- return nil, fmt.Errorf("manager rejected tunnel registration: %s", result.msg.Error)
- }
- return result.msg, nil
- }
-}
-
func (c *TunnelClient) openTunnelConnectStreamInternal(
ctx context.Context,
conn *grpc.ClientConn,
@@ -165,6 +115,10 @@ func (c *TunnelClient) grpcConnectMethodInternal() string {
return "/api/tunnel/connect"
}
+func (c *TunnelClient) awaitGRPCRegistrationInternal(ctx context.Context) (*TunnelMessage, error) {
+ return c.awaitRegistrationInternal(ctx)
+}
+
func (c *TunnelClient) useTLSForManagerGRPC() bool {
baseURL := strings.TrimSpace(c.cfg.GetManagerBaseURL())
if baseURL == "" {
diff --git a/backend/pkg/libarcane/edge/client_transport_poll.go b/backend/pkg/libarcane/edge/client_transport_poll.go
index eb536268f..aaef4a507 100644
--- a/backend/pkg/libarcane/edge/client_transport_poll.go
+++ b/backend/pkg/libarcane/edge/client_transport_poll.go
@@ -27,6 +27,11 @@ func (c *TunnelClient) connectAndServePoll(ctx context.Context) error {
if managerBaseURL == "" {
return fmt.Errorf("manager base URL is empty")
}
+ httpClient, err := NewManagerHTTPClient(c.cfg, 0)
+ if err != nil {
+ return fmt.Errorf("failed to configure edge poll client: %w", err)
+ }
+ c.httpClient = httpClient
pollURL := managerBaseURL + "/api/tunnel/poll"
interval := DefaultTunnelPollInterval
diff --git a/backend/pkg/libarcane/edge/client_transport_websocket.go b/backend/pkg/libarcane/edge/client_transport_websocket.go
index 8a006daeb..1662309dd 100644
--- a/backend/pkg/libarcane/edge/client_transport_websocket.go
+++ b/backend/pkg/libarcane/edge/client_transport_websocket.go
@@ -6,6 +6,7 @@ import (
"io"
"log/slog"
"net/http"
+ "strings"
"time"
"github.com/gorilla/websocket"
@@ -22,6 +23,13 @@ func (c *TunnelClient) connectAndServeWebSocket(ctx context.Context) error {
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: 30 * time.Second,
}
+ if strings.HasPrefix(strings.ToLower(managerWSURL), "wss://") {
+ tlsConfig, err := buildManagerClientTLSConfigInternal(c.cfg)
+ if err != nil {
+ return fmt.Errorf("failed to configure edge websocket TLS: %w", err)
+ }
+ dialer.TLSClientConfig = tlsConfig
+ }
headers := http.Header{}
headers.Set(HeaderAgentToken, c.cfg.AgentToken)
@@ -43,7 +51,18 @@ func (c *TunnelClient) connectAndServeWebSocket(ctx context.Context) error {
c.conn = NewTunnelConn(conn)
setActiveAgentTunnelConn(c.conn)
defer clearActiveAgentTunnelConn(c.conn)
+ if err := c.conn.Send(c.registerMessageInternal()); err != nil {
+ return fmt.Errorf("failed to send websocket register message: %w", err)
+ }
+ registerMsg, err := c.awaitRegistrationInternal(ctx)
+ if err != nil {
+ return err
+ }
slog.InfoContext(ctx, "WebSocket edge tunnel connected to manager", "manager_url", managerWSURL)
+ slog.InfoContext(ctx, "Edge websocket tunnel registered",
+ "environment_id", registerMsg.EnvironmentID,
+ "session_id", registerMsg.SessionID,
+ )
c.markTransportConnectedInternal(EdgeTransportWebSocket)
heartbeatCtx, heartbeatCancel := context.WithCancel(ctx)
diff --git a/backend/pkg/libarcane/edge/command_client.go b/backend/pkg/libarcane/edge/command_client.go
new file mode 100644
index 000000000..5b8ca9b61
--- /dev/null
+++ b/backend/pkg/libarcane/edge/command_client.go
@@ -0,0 +1,149 @@
+package edge
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+type CommandRequest struct {
+ ID string
+ Command string
+ Method string
+ Path string
+ Query string
+ Headers map[string]string
+ Body []byte
+ TimeoutMillis int64
+}
+
+type CommandResult struct {
+ Status int
+ Headers map[string]string
+ Body []byte
+}
+
+type CommandClient struct{}
+
+func NewCommandClient() *CommandClient {
+ return &CommandClient{}
+}
+
+func (c *CommandClient) Execute(ctx context.Context, tunnel *AgentTunnel, req *CommandRequest) (*CommandResult, error) {
+ if ctx == nil {
+ return nil, fmt.Errorf("context is required")
+ }
+ if err := validateConnectedTunnelInternal(tunnel); err != nil {
+ return nil, err
+ }
+ if req == nil {
+ return nil, fmt.Errorf("command request is required")
+ }
+
+ commandName := req.Command
+ if commandName == "" {
+ resolved, ok := ResolveEdgeCommandName(req.Method, req.Path, false)
+ if !ok {
+ return nil, fmt.Errorf("unsupported edge command for %s %s", req.Method, req.Path)
+ }
+ commandName = resolved
+ }
+
+ requestID := req.ID
+ if requestID == "" {
+ requestID = uuid.New().String()
+ }
+
+ timeoutMillis := req.TimeoutMillis
+ if timeoutMillis <= 0 {
+ timeoutMillis = int64(DefaultProxyTimeout / time.Millisecond)
+ }
+
+ msg := &TunnelMessage{
+ ID: requestID,
+ Type: MessageTypeCommandRequest,
+ Command: commandName,
+ Method: req.Method,
+ Path: req.Path,
+ Query: req.Query,
+ Headers: req.Headers,
+ Body: req.Body,
+ TimeoutMillis: timeoutMillis,
+ SessionID: tunnel.SessionID,
+ AgentInstance: tunnel.AgentInstance,
+ }
+
+ respCh, err := registerPendingRequestInternal(tunnel, requestID)
+ if err != nil {
+ return nil, err
+ }
+ defer tunnel.Pending.Delete(requestID)
+
+ if err := tunnel.Conn.Send(msg); err != nil {
+ return nil, fmt.Errorf("tunnel request failed: %w", err)
+ }
+
+ status, headers, body, err := collectCommandResponseInternal(ctx, respCh, req.Method)
+ if err != nil {
+ return nil, err
+ }
+
+ return &CommandResult{
+ Status: status,
+ Headers: headers,
+ Body: body,
+ }, nil
+}
+
+func (c *CommandClient) OpenStream(ctx context.Context, tunnel *AgentTunnel, req *CommandRequest) error {
+ if ctx == nil {
+ return fmt.Errorf("context is required")
+ }
+ if err := validateConnectedTunnelInternal(tunnel); err != nil {
+ return err
+ }
+ if req == nil {
+ return fmt.Errorf("command request is required")
+ }
+ if req.ID == "" {
+ return fmt.Errorf("stream ID is required")
+ }
+
+ commandName := req.Command
+ if commandName == "" {
+ resolved, ok := ResolveEdgeCommandName(http.MethodGet, req.Path, true)
+ if !ok {
+ return fmt.Errorf("unsupported edge stream target %q", req.Path)
+ }
+ commandName = resolved
+ }
+
+ msg := &TunnelMessage{
+ ID: req.ID,
+ Type: MessageTypeStreamOpen,
+ Command: commandName,
+ Path: req.Path,
+ Query: req.Query,
+ Headers: req.Headers,
+ SessionID: tunnel.SessionID,
+ }
+
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ return tunnel.Conn.Send(msg)
+ }
+}
+
+var DefaultCommandClient = NewCommandClient()
+
+func validateConnectedTunnelInternal(tunnel *AgentTunnel) error {
+ if tunnel == nil || tunnel.Conn == nil || tunnel.Conn.IsClosed() {
+ return fmt.Errorf("edge tunnel is not connected")
+ }
+ return nil
+}
diff --git a/backend/pkg/libarcane/edge/commands.go b/backend/pkg/libarcane/edge/commands.go
new file mode 100644
index 000000000..ed37905d8
--- /dev/null
+++ b/backend/pkg/libarcane/edge/commands.go
@@ -0,0 +1,312 @@
+package edge
+
+import (
+ "net/http"
+ "strings"
+)
+
+type commandRoute struct {
+ Method string
+ PathPattern string
+ CommandName string
+ Stream bool
+}
+
+var commandRoutes = []commandRoute{
+ {Method: http.MethodGet, PathPattern: "/api/health", CommandName: "system.health"},
+ {Method: http.MethodHead, PathPattern: "/api/health", CommandName: "system.health"},
+ {Method: http.MethodGet, PathPattern: "/api/app-version", CommandName: "system.version"},
+ {Method: http.MethodPost, PathPattern: "/api/container-registries/sync", CommandName: "container_registry.sync"},
+ {Method: http.MethodPost, PathPattern: "/api/git-repositories/sync", CommandName: "git_repository.sync"},
+
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/containers", CommandName: "container.list"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/containers/counts", CommandName: "container.counts"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/containers", CommandName: "container.create"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/containers/{containerId}", CommandName: "container.inspect"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/containers/{containerId}/start", CommandName: "container.start"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/containers/{containerId}/stop", CommandName: "container.stop"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/containers/{containerId}/restart", CommandName: "container.restart"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/containers/{containerId}/redeploy", CommandName: "container.redeploy"},
+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/containers/{containerId}", CommandName: "container.delete"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/containers/{containerId}/update", CommandName: "container.update"},
+
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/images", CommandName: "image.list"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/images/counts", CommandName: "image.counts"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/images/{imageId}", CommandName: "image.inspect"},
+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/images/{imageId}", CommandName: "image.delete"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/images/pull", CommandName: "image.pull"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/images/build", CommandName: "image.build.start"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/images/builds", CommandName: "image.build.list"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/images/builds/{buildId}", CommandName: "image.build.inspect"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/images/prune", CommandName: "image.prune"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/images/upload", CommandName: "image.upload"},
+
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/image-updates/check", CommandName: "image_update.check"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/image-updates/check/{imageId}", CommandName: "image_update.check_one"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/image-updates/check/{imageId}", CommandName: "image_update.check_one"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/image-updates/check-batch", CommandName: "image_update.check_batch"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/image-updates/check-all", CommandName: "image_update.check_all"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/image-updates/summary", CommandName: "image_update.summary"},
+
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/images/{imageId}/vulnerabilities/scan", CommandName: "vulnerability.scan"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/images/{imageId}/vulnerabilities", CommandName: "vulnerability.list"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/images/{imageId}/vulnerabilities/summary", CommandName: "vulnerability.summary"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/images/vulnerabilities/summaries", CommandName: "vulnerability.summary"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/images/{imageId}/vulnerabilities/list", CommandName: "vulnerability.list"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/scanner-status", CommandName: "vulnerability.scanner_status"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/summary", CommandName: "vulnerability.summary"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/all", CommandName: "vulnerability.all"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/image-options", CommandName: "vulnerability.image_options"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/vulnerabilities/ignore", CommandName: "vulnerability.ignore.create"},
+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/vulnerabilities/ignore/{ignoreId}", CommandName: "vulnerability.ignore.delete"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/vulnerabilities/ignored", CommandName: "vulnerability.ignore.list"},
+
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/projects", CommandName: "project.list"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/projects/counts", CommandName: "project.counts"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/projects/{projectId}/up", CommandName: "project.up"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/projects/{projectId}/down", CommandName: "project.down"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/projects", CommandName: "project.create"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/projects/{projectId}", CommandName: "project.inspect"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/projects/{projectId}/redeploy", CommandName: "project.redeploy"},
+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/projects/{projectId}/destroy", CommandName: "project.destroy"},
+ {Method: http.MethodPut, PathPattern: "/api/environments/{id}/projects/{projectId}", CommandName: "project.update"},
+ {Method: http.MethodPut, PathPattern: "/api/environments/{id}/projects/{projectId}/includes", CommandName: "project.includes"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/projects/{projectId}/restart", CommandName: "project.restart"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/projects/{projectId}/pull", CommandName: "project.pull"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/projects/{projectId}/build", CommandName: "project.build"},
+
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/gitops-syncs", CommandName: "gitops_sync.list"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/gitops-syncs", CommandName: "gitops_sync.create"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/gitops-syncs/import", CommandName: "gitops_sync.import"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/gitops-syncs/{syncId}", CommandName: "gitops_sync.inspect"},
+ {Method: http.MethodPut, PathPattern: "/api/environments/{id}/gitops-syncs/{syncId}", CommandName: "gitops_sync.update"},
+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/gitops-syncs/{syncId}", CommandName: "gitops_sync.delete"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/gitops-syncs/{syncId}/sync", CommandName: "gitops_sync.run"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/gitops-syncs/{syncId}/status", CommandName: "gitops_sync.status"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/gitops-syncs/{syncId}/files", CommandName: "gitops_sync.files"},
+
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/counts", CommandName: "volume.counts"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes", CommandName: "volume.list"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}", CommandName: "volume.inspect"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes", CommandName: "volume.create"},
+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/volumes/{volumeName}", CommandName: "volume.delete"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes/prune", CommandName: "volume.prune"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/usage", CommandName: "volume.usage"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/sizes", CommandName: "volume.sizes"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/browse", CommandName: "volume.browse.list"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/browse/content", CommandName: "volume.browse.read_file"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/browse/download", CommandName: "volume.browse.download"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes/{volumeName}/browse/upload", CommandName: "volume.browse.upload"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes/{volumeName}/browse/mkdir", CommandName: "volume.browse.mkdir"},
+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/volumes/{volumeName}/browse", CommandName: "volume.browse.delete"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/{volumeName}/backups", CommandName: "volume.backup.list"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes/{volumeName}/backups", CommandName: "volume.backup.create"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes/{volumeName}/backups/{backupId}/restore", CommandName: "volume.backup.restore"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes/{volumeName}/backups/{backupId}/restore-files", CommandName: "volume.backup.restore_files"},
+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/volumes/backups/{backupId}", CommandName: "volume.backup.delete"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/backups/{backupId}/download", CommandName: "volume.backup.download"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/backups/{backupId}/has-path", CommandName: "volume.backup.has_path"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/volumes/backups/{backupId}/files", CommandName: "volume.backup.files"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/volumes/{volumeName}/backups/upload", CommandName: "volume.backup.upload"},
+
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/builds/browse", CommandName: "build_workspace.browse.list"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/builds/browse/content", CommandName: "build_workspace.browse.read_file"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/builds/browse/download", CommandName: "build_workspace.browse.download"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/builds/browse/upload", CommandName: "build_workspace.browse.upload"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/builds/browse/mkdir", CommandName: "build_workspace.browse.mkdir"},
+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/builds/browse", CommandName: "build_workspace.browse.delete"},
+
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/networks", CommandName: "network.list"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/networks/counts", CommandName: "network.counts"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/networks", CommandName: "network.create"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/networks/{networkId}", CommandName: "network.inspect"},
+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/networks/{networkId}", CommandName: "network.delete"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/networks/prune", CommandName: "network.prune"},
+
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/settings/public", CommandName: "settings.public.get"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/settings", CommandName: "settings.get"},
+ {Method: http.MethodPut, PathPattern: "/api/environments/{id}/settings", CommandName: "settings.update"},
+
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/job-schedules", CommandName: "job_schedule.list"},
+ {Method: http.MethodPut, PathPattern: "/api/environments/{id}/job-schedules", CommandName: "job_schedule.upsert"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/jobs", CommandName: "job.list"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/jobs/{jobId}/run", CommandName: "job.run"},
+
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/notifications/settings", CommandName: "notification.settings.list"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/notifications/settings/{provider}", CommandName: "notification.settings.get"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/notifications/settings", CommandName: "notification.settings.upsert"},
+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/notifications/settings/{provider}", CommandName: "notification.settings.delete"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/notifications/test/{provider}", CommandName: "notification.test"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/notifications/apprise", CommandName: "notification.apprise.get"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/notifications/apprise", CommandName: "notification.apprise.upsert"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/notifications/apprise/test", CommandName: "notification.apprise.test"},
+
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/dashboard", CommandName: "dashboard.snapshot"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/dashboard/action-items", CommandName: "dashboard.action_items"},
+
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/updater/run", CommandName: "updater.run"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/updater/status", CommandName: "updater.status"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/updater/history", CommandName: "updater.history"},
+
+ {Method: http.MethodHead, PathPattern: "/api/environments/{id}/system/health", CommandName: "system.health"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/system/docker/info", CommandName: "system.docker_info"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/system/prune", CommandName: "system.prune"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/system/containers/start-all", CommandName: "system.containers.start_all"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/system/containers/start-stopped", CommandName: "system.containers.start_stopped"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/system/containers/stop-all", CommandName: "system.containers.stop_all"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/system/convert", CommandName: "system.convert"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/system/upgrade/check", CommandName: "system.upgrade.check"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/system/upgrade", CommandName: "system.upgrade.run"},
+
+ {PathPattern: "/api/environments/{id}/ws/projects/{projectId}/logs", CommandName: "project.logs.stream", Stream: true},
+ {PathPattern: "/api/environments/{id}/ws/containers/{containerId}/logs", CommandName: "container.logs.stream", Stream: true},
+ {PathPattern: "/api/environments/{id}/ws/containers/{containerId}/stats", CommandName: "container.stats.stream", Stream: true},
+ {PathPattern: "/api/environments/{id}/ws/containers/{containerId}/terminal", CommandName: "container.exec.stream", Stream: true},
+ {PathPattern: "/api/environments/{id}/ws/system/stats", CommandName: "system.stats.stream", Stream: true},
+}
+
+type commandRouteKey struct {
+ Method string
+ Stream bool
+}
+
+type commandRouteNode struct {
+ static map[string]*commandRouteNode
+ param *commandRouteNode
+ route *commandRoute
+}
+
+type commandRouteIndexInternal struct {
+ roots map[commandRouteKey]*commandRouteNode
+}
+
+var commandRoutesIndex = buildCommandRouteIndexInternal(commandRoutes)
+
+func ResolveEdgeCommandName(method, requestPath string, stream bool) (string, bool) {
+ method = strings.ToUpper(strings.TrimSpace(method))
+ requestPath = normalizeCommandPathInternal(requestPath)
+
+ route, ok := commandRoutesIndex.resolveInternal(method, requestPath, stream)
+ if !ok {
+ return "", false
+ }
+
+ return route.CommandName, true
+}
+
+func ValidateEdgeCommand(commandName, method, requestPath string, stream bool) bool {
+ resolved, ok := ResolveEdgeCommandName(method, requestPath, stream)
+ return ok && resolved == strings.TrimSpace(commandName)
+}
+
+func AdvertisedEdgeCommands() []string {
+ seen := make(map[string]struct{}, len(commandRoutes))
+ commands := make([]string, 0, len(commandRoutes))
+ for _, route := range commandRoutes {
+ if _, ok := seen[route.CommandName]; ok {
+ continue
+ }
+ seen[route.CommandName] = struct{}{}
+ commands = append(commands, route.CommandName)
+ }
+ return commands
+}
+
+func normalizeCommandPathInternal(requestPath string) string {
+ if idx := strings.IndexByte(requestPath, '?'); idx >= 0 {
+ requestPath = requestPath[:idx]
+ }
+ requestPath = strings.TrimSpace(requestPath)
+ if requestPath == "" {
+ return "/"
+ }
+ if requestPath[0] != '/' {
+ return "/" + requestPath
+ }
+ return requestPath
+}
+
+func splitCommandPathInternal(p string) []string {
+ trimmed := strings.Trim(p, "/")
+ if trimmed == "" {
+ return nil
+ }
+ return strings.Split(trimmed, "/")
+}
+
+func isCommandParamInternal(segment string) bool {
+ return strings.HasPrefix(segment, "{") && strings.HasSuffix(segment, "}")
+}
+
+func buildCommandRouteIndexInternal(routes []commandRoute) commandRouteIndexInternal {
+ index := commandRouteIndexInternal{roots: make(map[commandRouteKey]*commandRouteNode)}
+
+ for i := range routes {
+ route := &routes[i]
+ key := commandRouteLookupKeyInternal(route.Method, route.Stream)
+ root := index.roots[key]
+ if root == nil {
+ root = &commandRouteNode{}
+ index.roots[key] = root
+ }
+ root.insertInternal(route)
+ }
+
+ return index
+}
+
+func commandRouteLookupKeyInternal(method string, stream bool) commandRouteKey {
+ if stream {
+ return commandRouteKey{Stream: true}
+ }
+ return commandRouteKey{Method: strings.ToUpper(strings.TrimSpace(method))}
+}
+
+func (n *commandRouteNode) insertInternal(route *commandRoute) {
+ current := n
+ for _, part := range splitCommandPathInternal(route.PathPattern) {
+ if isCommandParamInternal(part) {
+ if current.param == nil {
+ current.param = &commandRouteNode{}
+ }
+ current = current.param
+ continue
+ }
+ if current.static == nil {
+ current.static = make(map[string]*commandRouteNode)
+ }
+ next := current.static[part]
+ if next == nil {
+ next = &commandRouteNode{}
+ current.static[part] = next
+ }
+ current = next
+ }
+ if current.route != nil {
+ panic("duplicate edge command route: " + route.PathPattern)
+ }
+ current.route = route
+}
+
+func (i commandRouteIndexInternal) resolveInternal(method string, requestPath string, stream bool) (*commandRoute, bool) {
+ root := i.roots[commandRouteLookupKeyInternal(method, stream)]
+ if root == nil {
+ return nil, false
+ }
+
+ current := root
+ for _, part := range splitCommandPathInternal(requestPath) {
+ if next := current.static[part]; next != nil {
+ current = next
+ continue
+ }
+ if current.param == nil || part == "" {
+ return nil, false
+ }
+ current = current.param
+ }
+ if current.route == nil {
+ return nil, false
+ }
+ return current.route, true
+}
diff --git a/backend/pkg/libarcane/edge/commands_test.go b/backend/pkg/libarcane/edge/commands_test.go
new file mode 100644
index 000000000..dea914c7a
--- /dev/null
+++ b/backend/pkg/libarcane/edge/commands_test.go
@@ -0,0 +1,68 @@
+package edge
+
+import (
+ "context"
+ "net/http"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestResolveEdgeCommandName(t *testing.T) {
+ t.Parallel()
+
+ testCases := []struct {
+ name string
+ method string
+ path string
+ stream bool
+ command string
+ shouldHit bool
+ }{
+ {name: "container list", method: "GET", path: "/api/environments/0/containers", command: "container.list", shouldHit: true},
+ {name: "container start", method: "POST", path: "/api/environments/0/containers/abc/start", command: "container.start", shouldHit: true},
+ {name: "volume browse download", method: "GET", path: "/api/environments/0/volumes/data/browse/download", command: "volume.browse.download", shouldHit: true},
+ {name: "project logs stream", method: "GET", path: "/api/environments/0/ws/projects/p1/logs", stream: true, command: "project.logs.stream", shouldHit: true},
+ {name: "health", method: "HEAD", path: "/api/environments/0/system/health", command: "system.health", shouldHit: true},
+ {name: "unknown", method: "PATCH", path: "/api/environments/0/containers", shouldHit: false},
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+
+ command, ok := ResolveEdgeCommandName(tc.method, tc.path, tc.stream)
+ require.Equal(t, tc.shouldHit, ok)
+ if tc.shouldHit {
+ require.Equal(t, tc.command, command)
+ require.True(t, ValidateEdgeCommand(tc.command, tc.method, tc.path, tc.stream))
+ }
+ })
+ }
+}
+
+func TestBuildCommandRouteIndexInternalPanicsOnDuplicateRoute(t *testing.T) {
+ t.Parallel()
+
+ require.Panics(t, func() {
+ buildCommandRouteIndexInternal([]commandRoute{
+ {Method: http.MethodGet, PathPattern: "/api/test/{id}", CommandName: "test.one"},
+ {Method: http.MethodGet, PathPattern: "/api/test/{id}", CommandName: "test.two"},
+ })
+ })
+}
+
+func TestCollectCommandResponse(t *testing.T) {
+ t.Parallel()
+
+ respCh := make(chan *TunnelMessage, 4)
+ respCh <- &TunnelMessage{ID: "cmd-1", Type: MessageTypeCommandAck}
+ respCh <- &TunnelMessage{ID: "cmd-1", Type: MessageTypeCommandOutput, Body: []byte("hello ")}
+ respCh <- &TunnelMessage{ID: "cmd-1", Type: MessageTypeCommandComplete, Status: 200, Headers: map[string]string{"Content-Type": "text/plain"}, Body: []byte("world")}
+
+ status, headers, body, err := collectCommandResponseInternal(context.Background(), respCh, "")
+ require.NoError(t, err)
+ require.Equal(t, 200, status)
+ require.Equal(t, "text/plain", headers["Content-Type"])
+ require.Equal(t, "hello world", string(body))
+}
diff --git a/backend/pkg/libarcane/edge/grpc_tunnel_integration_test.go b/backend/pkg/libarcane/edge/grpc_tunnel_integration_test.go
index 7f6777248..5cf549878 100644
--- a/backend/pkg/libarcane/edge/grpc_tunnel_integration_test.go
+++ b/backend/pkg/libarcane/edge/grpc_tunnel_integration_test.go
@@ -70,14 +70,21 @@ func TestGRPCTunnel_RequestResponse(t *testing.T) {
return
}
- req := msg.GetHttpRequest()
+ req := msg.GetCommandRequest()
if req == nil {
- agentErrCh <- errors.New("expected http request")
+ agentErrCh <- errors.New("expected command request")
return
}
- agentErrCh <- stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_HttpResponse{HttpResponse: &tunnelpb.HttpResponse{
- RequestId: req.GetRequestId(),
+ if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
+ CommandId: req.GetCommandId(),
+ }}}); err != nil {
+ agentErrCh <- err
+ return
+ }
+
+ agentErrCh <- stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandComplete{CommandComplete: &tunnelpb.CommandComplete{
+ CommandId: req.GetCommandId(),
Status: 200,
Headers: map[string]string{"Content-Type": "text/plain"},
Body: []byte("ok"),
@@ -149,39 +156,44 @@ func TestGRPCTunnel_RequestResponseStreamingChunks(t *testing.T) {
return
}
- req := msg.GetHttpRequest()
+ req := msg.GetCommandRequest()
if req == nil {
- agentErrCh <- errors.New("expected http request")
+ agentErrCh <- errors.New("expected command request")
return
}
- if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_HttpResponse{HttpResponse: &tunnelpb.HttpResponse{
- RequestId: req.GetRequestId(),
- Status: 200,
- Headers: map[string]string{"Content-Type": "text/plain", "X-Arcane-Tunnel-Stream": "1"},
+ if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
+ CommandId: req.GetCommandId(),
}}}); err != nil {
agentErrCh <- err
return
}
- if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_StreamData{StreamData: &tunnelpb.StreamData{
- RequestId: req.GetRequestId(),
+ if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandOutput{CommandOutput: &tunnelpb.CommandOutput{
+ CommandId: req.GetCommandId(),
Data: []byte("hello "),
+ Sequence: 0,
}}}); err != nil {
agentErrCh <- err
return
}
- if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_StreamData{StreamData: &tunnelpb.StreamData{
- RequestId: req.GetRequestId(),
+ if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandOutput{CommandOutput: &tunnelpb.CommandOutput{
+ CommandId: req.GetCommandId(),
Data: []byte("world"),
+ Sequence: 1,
}}}); err != nil {
agentErrCh <- err
return
}
- agentErrCh <- stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_StreamEnd{StreamEnd: &tunnelpb.StreamEnd{
- RequestId: req.GetRequestId(),
+ time.Sleep(10 * time.Millisecond)
+
+ agentErrCh <- stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandComplete{CommandComplete: &tunnelpb.CommandComplete{
+ CommandId: req.GetCommandId(),
+ Status: 200,
+ Headers: map[string]string{"Content-Type": "text/plain", "X-Arcane-Tunnel-Stream": "1"},
+ Streaming: true,
}}})
}()
diff --git a/backend/pkg/libarcane/edge/http_client_test.go b/backend/pkg/libarcane/edge/http_client_test.go
index 627059705..fdd33eb29 100644
--- a/backend/pkg/libarcane/edge/http_client_test.go
+++ b/backend/pkg/libarcane/edge/http_client_test.go
@@ -40,8 +40,8 @@ func TestEdgeAwareClient_DoForEnvironment_EdgeWithTunnel(t *testing.T) {
envID,
true, // isEdge
"GET",
- "http://ignored/api/path",
- "/api/path",
+ "http://ignored/api/health",
+ "/api/health",
map[string]string{"X-H": "v"},
nil,
)
@@ -59,8 +59,8 @@ func TestEdgeAwareClient_DoForEnvironment_EdgeNoTunnel(t *testing.T) {
"env-edge-missing",
true, // isEdge
"GET",
- "http://ignored/api/path",
- "/api/path",
+ "http://ignored/api/health",
+ "/api/health",
nil,
nil,
)
@@ -167,9 +167,9 @@ func TestEdgeAwareClient_DoForEnvironment_EdgeWithGRPCTunnel(t *testing.T) {
return
}
- req := msg.GetHttpRequest()
+ req := msg.GetCommandRequest()
if req == nil {
- agentErrCh <- errors.New("expected http request")
+ agentErrCh <- errors.New("expected command request")
return
}
@@ -177,7 +177,7 @@ func TestEdgeAwareClient_DoForEnvironment_EdgeWithGRPCTunnel(t *testing.T) {
agentErrCh <- errors.New("unexpected method")
return
}
- if req.GetPath() != "/api/path" {
+ if req.GetPath() != "/api/environments/0/projects" {
agentErrCh <- errors.New("unexpected path")
return
}
@@ -194,8 +194,15 @@ func TestEdgeAwareClient_DoForEnvironment_EdgeWithGRPCTunnel(t *testing.T) {
return
}
- agentErrCh <- stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_HttpResponse{HttpResponse: &tunnelpb.HttpResponse{
- RequestId: req.GetRequestId(),
+ if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
+ CommandId: req.GetCommandId(),
+ }}}); err != nil {
+ agentErrCh <- err
+ return
+ }
+
+ agentErrCh <- stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandComplete{CommandComplete: &tunnelpb.CommandComplete{
+ CommandId: req.GetCommandId(),
Status: http.StatusCreated,
Headers: map[string]string{"Content-Type": "application/json"},
Body: []byte(`{"ok":true}`),
@@ -213,8 +220,8 @@ func TestEdgeAwareClient_DoForEnvironment_EdgeWithGRPCTunnel(t *testing.T) {
envID,
true,
http.MethodPost,
- "http://ignored/api/path",
- "/api/path",
+ "http://ignored/api/environments/0/projects",
+ "/api/environments/0/projects",
map[string]string{"X-H": "v", "Content-Type": "application/json"},
[]byte(`{"edge":true}`),
)
diff --git a/backend/pkg/libarcane/edge/poll_control.go b/backend/pkg/libarcane/edge/poll_control.go
index 1b95347d1..b6e55d7c2 100644
--- a/backend/pkg/libarcane/edge/poll_control.go
+++ b/backend/pkg/libarcane/edge/poll_control.go
@@ -266,6 +266,12 @@ func (s *TunnelServer) pollStatusInternal(envID string) TunnelPollResponse {
func (s *TunnelServer) HandlePoll(c *gin.Context) {
ctx := c.Request.Context()
+ if err := s.requireClientCertificateInternal(c.Request); err != nil {
+ slog.WarnContext(ctx, "Rejected edge poll request without required client certificate", "error", err)
+ c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
+ return
+ }
+
if _, err := decodeTunnelPollRequestInternal(c); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid poll payload"})
return
@@ -287,6 +293,11 @@ func (s *TunnelServer) HandlePoll(c *gin.Context) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid agent token"})
return
}
+ if err := s.requireCertificateIdentityInternal(c.Request.TLS, envID); err != nil {
+ slog.WarnContext(ctx, "Rejected edge poll request with mismatched client certificate", "environment_id", envID, "error", err)
+ c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
+ return
+ }
pollInterval := DefaultTunnelPollInterval
GetPollRuntimeRegistry().Update(envID, pollInterval, time.Now())
diff --git a/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel.pb.go b/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel.pb.go
index f20150ce2..5ba8320ef 100644
--- a/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel.pb.go
+++ b/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel.pb.go
@@ -7,12 +7,11 @@
package tunnelpb
import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
-
- protoreflect "google.golang.org/protobuf/reflect/protoreflect"
- protoimpl "google.golang.org/protobuf/runtime/protoimpl"
)
const (
@@ -35,6 +34,11 @@ type AgentMessage struct {
// *AgentMessage_StreamEnd
// *AgentMessage_Register
// *AgentMessage_Event
+ // *AgentMessage_CommandAck
+ // *AgentMessage_CommandOutput
+ // *AgentMessage_CommandComplete
+ // *AgentMessage_FileChunk
+ // *AgentMessage_StreamClose
Payload isAgentMessage_Payload `protobuf_oneof:"payload"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
@@ -149,6 +153,51 @@ func (x *AgentMessage) GetEvent() *EventLog {
return nil
}
+func (x *AgentMessage) GetCommandAck() *CommandAck {
+ if x != nil {
+ if x, ok := x.Payload.(*AgentMessage_CommandAck); ok {
+ return x.CommandAck
+ }
+ }
+ return nil
+}
+
+func (x *AgentMessage) GetCommandOutput() *CommandOutput {
+ if x != nil {
+ if x, ok := x.Payload.(*AgentMessage_CommandOutput); ok {
+ return x.CommandOutput
+ }
+ }
+ return nil
+}
+
+func (x *AgentMessage) GetCommandComplete() *CommandComplete {
+ if x != nil {
+ if x, ok := x.Payload.(*AgentMessage_CommandComplete); ok {
+ return x.CommandComplete
+ }
+ }
+ return nil
+}
+
+func (x *AgentMessage) GetFileChunk() *FileChunk {
+ if x != nil {
+ if x, ok := x.Payload.(*AgentMessage_FileChunk); ok {
+ return x.FileChunk
+ }
+ }
+ return nil
+}
+
+func (x *AgentMessage) GetStreamClose() *StreamClose {
+ if x != nil {
+ if x, ok := x.Payload.(*AgentMessage_StreamClose); ok {
+ return x.StreamClose
+ }
+ }
+ return nil
+}
+
type isAgentMessage_Payload interface {
isAgentMessage_Payload()
}
@@ -185,6 +234,26 @@ type AgentMessage_Event struct {
Event *EventLog `protobuf:"bytes,8,opt,name=event,proto3,oneof"`
}
+type AgentMessage_CommandAck struct {
+ CommandAck *CommandAck `protobuf:"bytes,9,opt,name=command_ack,json=commandAck,proto3,oneof"`
+}
+
+type AgentMessage_CommandOutput struct {
+ CommandOutput *CommandOutput `protobuf:"bytes,10,opt,name=command_output,json=commandOutput,proto3,oneof"`
+}
+
+type AgentMessage_CommandComplete struct {
+ CommandComplete *CommandComplete `protobuf:"bytes,11,opt,name=command_complete,json=commandComplete,proto3,oneof"`
+}
+
+type AgentMessage_FileChunk struct {
+ FileChunk *FileChunk `protobuf:"bytes,12,opt,name=file_chunk,json=fileChunk,proto3,oneof"`
+}
+
+type AgentMessage_StreamClose struct {
+ StreamClose *StreamClose `protobuf:"bytes,13,opt,name=stream_close,json=streamClose,proto3,oneof"`
+}
+
func (*AgentMessage_HttpResponse) isAgentMessage_Payload() {}
func (*AgentMessage_HeartbeatPing) isAgentMessage_Payload() {}
@@ -201,37 +270,740 @@ func (*AgentMessage_Register) isAgentMessage_Payload() {}
func (*AgentMessage_Event) isAgentMessage_Payload() {}
-// Messages sent from the manager to the agent.
-type ManagerMessage struct {
- state protoimpl.MessageState `protogen:"open.v1"`
- // Types that are valid to be assigned to Payload:
- //
- // *ManagerMessage_HttpRequest
- // *ManagerMessage_HeartbeatPong
- // *ManagerMessage_WsStart
- // *ManagerMessage_WsData
- // *ManagerMessage_WsClose
- // *ManagerMessage_RegisterResponse
- Payload isManagerMessage_Payload `protobuf_oneof:"payload"`
+func (*AgentMessage_CommandAck) isAgentMessage_Payload() {}
+
+func (*AgentMessage_CommandOutput) isAgentMessage_Payload() {}
+
+func (*AgentMessage_CommandComplete) isAgentMessage_Payload() {}
+
+func (*AgentMessage_FileChunk) isAgentMessage_Payload() {}
+
+func (*AgentMessage_StreamClose) isAgentMessage_Payload() {}
+
+// Messages sent from the manager to the agent.
+type ManagerMessage struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ // Types that are valid to be assigned to Payload:
+ //
+ // *ManagerMessage_HttpRequest
+ // *ManagerMessage_HeartbeatPong
+ // *ManagerMessage_WsStart
+ // *ManagerMessage_WsData
+ // *ManagerMessage_WsClose
+ // *ManagerMessage_RegisterResponse
+ // *ManagerMessage_CommandRequest
+ // *ManagerMessage_StreamOpen
+ // *ManagerMessage_StreamClose
+ // *ManagerMessage_CancelRequest
+ // *ManagerMessage_FileChunk
+ Payload isManagerMessage_Payload `protobuf_oneof:"payload"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ManagerMessage) Reset() {
+ *x = ManagerMessage{}
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ManagerMessage) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ManagerMessage) ProtoMessage() {}
+
+func (x *ManagerMessage) ProtoReflect() protoreflect.Message {
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[1]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ManagerMessage.ProtoReflect.Descriptor instead.
+func (*ManagerMessage) Descriptor() ([]byte, []int) {
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *ManagerMessage) GetPayload() isManagerMessage_Payload {
+ if x != nil {
+ return x.Payload
+ }
+ return nil
+}
+
+func (x *ManagerMessage) GetHttpRequest() *HttpRequest {
+ if x != nil {
+ if x, ok := x.Payload.(*ManagerMessage_HttpRequest); ok {
+ return x.HttpRequest
+ }
+ }
+ return nil
+}
+
+func (x *ManagerMessage) GetHeartbeatPong() *HeartbeatPong {
+ if x != nil {
+ if x, ok := x.Payload.(*ManagerMessage_HeartbeatPong); ok {
+ return x.HeartbeatPong
+ }
+ }
+ return nil
+}
+
+func (x *ManagerMessage) GetWsStart() *WebSocketStart {
+ if x != nil {
+ if x, ok := x.Payload.(*ManagerMessage_WsStart); ok {
+ return x.WsStart
+ }
+ }
+ return nil
+}
+
+func (x *ManagerMessage) GetWsData() *WebSocketData {
+ if x != nil {
+ if x, ok := x.Payload.(*ManagerMessage_WsData); ok {
+ return x.WsData
+ }
+ }
+ return nil
+}
+
+func (x *ManagerMessage) GetWsClose() *WebSocketClose {
+ if x != nil {
+ if x, ok := x.Payload.(*ManagerMessage_WsClose); ok {
+ return x.WsClose
+ }
+ }
+ return nil
+}
+
+func (x *ManagerMessage) GetRegisterResponse() *RegisterResponse {
+ if x != nil {
+ if x, ok := x.Payload.(*ManagerMessage_RegisterResponse); ok {
+ return x.RegisterResponse
+ }
+ }
+ return nil
+}
+
+func (x *ManagerMessage) GetCommandRequest() *CommandRequest {
+ if x != nil {
+ if x, ok := x.Payload.(*ManagerMessage_CommandRequest); ok {
+ return x.CommandRequest
+ }
+ }
+ return nil
+}
+
+func (x *ManagerMessage) GetStreamOpen() *StreamOpen {
+ if x != nil {
+ if x, ok := x.Payload.(*ManagerMessage_StreamOpen); ok {
+ return x.StreamOpen
+ }
+ }
+ return nil
+}
+
+func (x *ManagerMessage) GetStreamClose() *StreamClose {
+ if x != nil {
+ if x, ok := x.Payload.(*ManagerMessage_StreamClose); ok {
+ return x.StreamClose
+ }
+ }
+ return nil
+}
+
+func (x *ManagerMessage) GetCancelRequest() *CancelRequest {
+ if x != nil {
+ if x, ok := x.Payload.(*ManagerMessage_CancelRequest); ok {
+ return x.CancelRequest
+ }
+ }
+ return nil
+}
+
+func (x *ManagerMessage) GetFileChunk() *FileChunk {
+ if x != nil {
+ if x, ok := x.Payload.(*ManagerMessage_FileChunk); ok {
+ return x.FileChunk
+ }
+ }
+ return nil
+}
+
+type isManagerMessage_Payload interface {
+ isManagerMessage_Payload()
+}
+
+type ManagerMessage_HttpRequest struct {
+ HttpRequest *HttpRequest `protobuf:"bytes,1,opt,name=http_request,json=httpRequest,proto3,oneof"`
+}
+
+type ManagerMessage_HeartbeatPong struct {
+ HeartbeatPong *HeartbeatPong `protobuf:"bytes,2,opt,name=heartbeat_pong,json=heartbeatPong,proto3,oneof"`
+}
+
+type ManagerMessage_WsStart struct {
+ WsStart *WebSocketStart `protobuf:"bytes,3,opt,name=ws_start,json=wsStart,proto3,oneof"`
+}
+
+type ManagerMessage_WsData struct {
+ WsData *WebSocketData `protobuf:"bytes,4,opt,name=ws_data,json=wsData,proto3,oneof"`
+}
+
+type ManagerMessage_WsClose struct {
+ WsClose *WebSocketClose `protobuf:"bytes,5,opt,name=ws_close,json=wsClose,proto3,oneof"`
+}
+
+type ManagerMessage_RegisterResponse struct {
+ RegisterResponse *RegisterResponse `protobuf:"bytes,6,opt,name=register_response,json=registerResponse,proto3,oneof"`
+}
+
+type ManagerMessage_CommandRequest struct {
+ CommandRequest *CommandRequest `protobuf:"bytes,7,opt,name=command_request,json=commandRequest,proto3,oneof"`
+}
+
+type ManagerMessage_StreamOpen struct {
+ StreamOpen *StreamOpen `protobuf:"bytes,8,opt,name=stream_open,json=streamOpen,proto3,oneof"`
+}
+
+type ManagerMessage_StreamClose struct {
+ StreamClose *StreamClose `protobuf:"bytes,9,opt,name=stream_close,json=streamClose,proto3,oneof"`
+}
+
+type ManagerMessage_CancelRequest struct {
+ CancelRequest *CancelRequest `protobuf:"bytes,10,opt,name=cancel_request,json=cancelRequest,proto3,oneof"`
+}
+
+type ManagerMessage_FileChunk struct {
+ FileChunk *FileChunk `protobuf:"bytes,11,opt,name=file_chunk,json=fileChunk,proto3,oneof"`
+}
+
+func (*ManagerMessage_HttpRequest) isManagerMessage_Payload() {}
+
+func (*ManagerMessage_HeartbeatPong) isManagerMessage_Payload() {}
+
+func (*ManagerMessage_WsStart) isManagerMessage_Payload() {}
+
+func (*ManagerMessage_WsData) isManagerMessage_Payload() {}
+
+func (*ManagerMessage_WsClose) isManagerMessage_Payload() {}
+
+func (*ManagerMessage_RegisterResponse) isManagerMessage_Payload() {}
+
+func (*ManagerMessage_CommandRequest) isManagerMessage_Payload() {}
+
+func (*ManagerMessage_StreamOpen) isManagerMessage_Payload() {}
+
+func (*ManagerMessage_StreamClose) isManagerMessage_Payload() {}
+
+func (*ManagerMessage_CancelRequest) isManagerMessage_Payload() {}
+
+func (*ManagerMessage_FileChunk) isManagerMessage_Payload() {}
+
+type RegisterRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ AgentToken string `protobuf:"bytes,1,opt,name=agent_token,json=agentToken,proto3" json:"agent_token,omitempty"`
+ AgentInstanceId string `protobuf:"bytes,2,opt,name=agent_instance_id,json=agentInstanceId,proto3" json:"agent_instance_id,omitempty"`
+ Capabilities []string `protobuf:"bytes,3,rep,name=capabilities,proto3" json:"capabilities,omitempty"`
+ ResumeSessionId string `protobuf:"bytes,4,opt,name=resume_session_id,json=resumeSessionId,proto3" json:"resume_session_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RegisterRequest) Reset() {
+ *x = RegisterRequest{}
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[2]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RegisterRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RegisterRequest) ProtoMessage() {}
+
+func (x *RegisterRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[2]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use RegisterRequest.ProtoReflect.Descriptor instead.
+func (*RegisterRequest) Descriptor() ([]byte, []int) {
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{2}
+}
+
+func (x *RegisterRequest) GetAgentToken() string {
+ if x != nil {
+ return x.AgentToken
+ }
+ return ""
+}
+
+func (x *RegisterRequest) GetAgentInstanceId() string {
+ if x != nil {
+ return x.AgentInstanceId
+ }
+ return ""
+}
+
+func (x *RegisterRequest) GetCapabilities() []string {
+ if x != nil {
+ return x.Capabilities
+ }
+ return nil
+}
+
+func (x *RegisterRequest) GetResumeSessionId() string {
+ if x != nil {
+ return x.ResumeSessionId
+ }
+ return ""
+}
+
+type RegisterResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Accepted bool `protobuf:"varint,1,opt,name=accepted,proto3" json:"accepted,omitempty"`
+ EnvironmentId string `protobuf:"bytes,2,opt,name=environment_id,json=environmentId,proto3" json:"environment_id,omitempty"`
+ Error string `protobuf:"bytes,3,opt,name=error,proto3" json:"error,omitempty"`
+ SessionId string `protobuf:"bytes,4,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ SecurityMode string `protobuf:"bytes,5,opt,name=security_mode,json=securityMode,proto3" json:"security_mode,omitempty"`
+ Capabilities []string `protobuf:"bytes,6,rep,name=capabilities,proto3" json:"capabilities,omitempty"`
+ DrainPrevious bool `protobuf:"varint,7,opt,name=drain_previous,json=drainPrevious,proto3" json:"drain_previous,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RegisterResponse) Reset() {
+ *x = RegisterResponse{}
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[3]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RegisterResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RegisterResponse) ProtoMessage() {}
+
+func (x *RegisterResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[3]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use RegisterResponse.ProtoReflect.Descriptor instead.
+func (*RegisterResponse) Descriptor() ([]byte, []int) {
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{3}
+}
+
+func (x *RegisterResponse) GetAccepted() bool {
+ if x != nil {
+ return x.Accepted
+ }
+ return false
+}
+
+func (x *RegisterResponse) GetEnvironmentId() string {
+ if x != nil {
+ return x.EnvironmentId
+ }
+ return ""
+}
+
+func (x *RegisterResponse) GetError() string {
+ if x != nil {
+ return x.Error
+ }
+ return ""
+}
+
+func (x *RegisterResponse) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *RegisterResponse) GetSecurityMode() string {
+ if x != nil {
+ return x.SecurityMode
+ }
+ return ""
+}
+
+func (x *RegisterResponse) GetCapabilities() []string {
+ if x != nil {
+ return x.Capabilities
+ }
+ return nil
+}
+
+func (x *RegisterResponse) GetDrainPrevious() bool {
+ if x != nil {
+ return x.DrainPrevious
+ }
+ return false
+}
+
+type CommandRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ CommandId string `protobuf:"bytes,1,opt,name=command_id,json=commandId,proto3" json:"command_id,omitempty"`
+ CommandName string `protobuf:"bytes,2,opt,name=command_name,json=commandName,proto3" json:"command_name,omitempty"`
+ Method string `protobuf:"bytes,3,opt,name=method,proto3" json:"method,omitempty"`
+ Path string `protobuf:"bytes,4,opt,name=path,proto3" json:"path,omitempty"`
+ Query string `protobuf:"bytes,5,opt,name=query,proto3" json:"query,omitempty"`
+ Headers map[string]string `protobuf:"bytes,6,rep,name=headers,proto3" json:"headers,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Body []byte `protobuf:"bytes,7,opt,name=body,proto3" json:"body,omitempty"`
+ TimeoutMillis int64 `protobuf:"varint,8,opt,name=timeout_millis,json=timeoutMillis,proto3" json:"timeout_millis,omitempty"`
+ SessionId string `protobuf:"bytes,9,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ AgentInstanceId string `protobuf:"bytes,10,opt,name=agent_instance_id,json=agentInstanceId,proto3" json:"agent_instance_id,omitempty"`
+ Metadata map[string]string `protobuf:"bytes,11,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *CommandRequest) Reset() {
+ *x = CommandRequest{}
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[4]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *CommandRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CommandRequest) ProtoMessage() {}
+
+func (x *CommandRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[4]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use CommandRequest.ProtoReflect.Descriptor instead.
+func (*CommandRequest) Descriptor() ([]byte, []int) {
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{4}
+}
+
+func (x *CommandRequest) GetCommandId() string {
+ if x != nil {
+ return x.CommandId
+ }
+ return ""
+}
+
+func (x *CommandRequest) GetCommandName() string {
+ if x != nil {
+ return x.CommandName
+ }
+ return ""
+}
+
+func (x *CommandRequest) GetMethod() string {
+ if x != nil {
+ return x.Method
+ }
+ return ""
+}
+
+func (x *CommandRequest) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
+func (x *CommandRequest) GetQuery() string {
+ if x != nil {
+ return x.Query
+ }
+ return ""
+}
+
+func (x *CommandRequest) GetHeaders() map[string]string {
+ if x != nil {
+ return x.Headers
+ }
+ return nil
+}
+
+func (x *CommandRequest) GetBody() []byte {
+ if x != nil {
+ return x.Body
+ }
+ return nil
+}
+
+func (x *CommandRequest) GetTimeoutMillis() int64 {
+ if x != nil {
+ return x.TimeoutMillis
+ }
+ return 0
+}
+
+func (x *CommandRequest) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *CommandRequest) GetAgentInstanceId() string {
+ if x != nil {
+ return x.AgentInstanceId
+ }
+ return ""
+}
+
+func (x *CommandRequest) GetMetadata() map[string]string {
+ if x != nil {
+ return x.Metadata
+ }
+ return nil
+}
+
+type CommandAck struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ CommandId string `protobuf:"bytes,1,opt,name=command_id,json=commandId,proto3" json:"command_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *CommandAck) Reset() {
+ *x = CommandAck{}
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[5]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *CommandAck) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CommandAck) ProtoMessage() {}
+
+func (x *CommandAck) ProtoReflect() protoreflect.Message {
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[5]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use CommandAck.ProtoReflect.Descriptor instead.
+func (*CommandAck) Descriptor() ([]byte, []int) {
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{5}
+}
+
+func (x *CommandAck) GetCommandId() string {
+ if x != nil {
+ return x.CommandId
+ }
+ return ""
+}
+
+type CommandOutput struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ CommandId string `protobuf:"bytes,1,opt,name=command_id,json=commandId,proto3" json:"command_id,omitempty"`
+ Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
+ Sequence int64 `protobuf:"varint,3,opt,name=sequence,proto3" json:"sequence,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *CommandOutput) Reset() {
+ *x = CommandOutput{}
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[6]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *CommandOutput) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CommandOutput) ProtoMessage() {}
+
+func (x *CommandOutput) ProtoReflect() protoreflect.Message {
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[6]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use CommandOutput.ProtoReflect.Descriptor instead.
+func (*CommandOutput) Descriptor() ([]byte, []int) {
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{6}
+}
+
+func (x *CommandOutput) GetCommandId() string {
+ if x != nil {
+ return x.CommandId
+ }
+ return ""
+}
+
+func (x *CommandOutput) GetData() []byte {
+ if x != nil {
+ return x.Data
+ }
+ return nil
+}
+
+func (x *CommandOutput) GetSequence() int64 {
+ if x != nil {
+ return x.Sequence
+ }
+ return 0
+}
+
+type CommandComplete struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ CommandId string `protobuf:"bytes,1,opt,name=command_id,json=commandId,proto3" json:"command_id,omitempty"`
+ Status int32 `protobuf:"varint,2,opt,name=status,proto3" json:"status,omitempty"`
+ Headers map[string]string `protobuf:"bytes,3,rep,name=headers,proto3" json:"headers,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Body []byte `protobuf:"bytes,4,opt,name=body,proto3" json:"body,omitempty"`
+ Error string `protobuf:"bytes,5,opt,name=error,proto3" json:"error,omitempty"`
+ Streaming bool `protobuf:"varint,6,opt,name=streaming,proto3" json:"streaming,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *CommandComplete) Reset() {
+ *x = CommandComplete{}
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[7]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *CommandComplete) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CommandComplete) ProtoMessage() {}
+
+func (x *CommandComplete) ProtoReflect() protoreflect.Message {
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[7]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use CommandComplete.ProtoReflect.Descriptor instead.
+func (*CommandComplete) Descriptor() ([]byte, []int) {
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{7}
+}
+
+func (x *CommandComplete) GetCommandId() string {
+ if x != nil {
+ return x.CommandId
+ }
+ return ""
+}
+
+func (x *CommandComplete) GetStatus() int32 {
+ if x != nil {
+ return x.Status
+ }
+ return 0
+}
+
+func (x *CommandComplete) GetHeaders() map[string]string {
+ if x != nil {
+ return x.Headers
+ }
+ return nil
+}
+
+func (x *CommandComplete) GetBody() []byte {
+ if x != nil {
+ return x.Body
+ }
+ return nil
+}
+
+func (x *CommandComplete) GetError() string {
+ if x != nil {
+ return x.Error
+ }
+ return ""
+}
+
+func (x *CommandComplete) GetStreaming() bool {
+ if x != nil {
+ return x.Streaming
+ }
+ return false
+}
+
+type FileChunk struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ TransferId string `protobuf:"bytes,1,opt,name=transfer_id,json=transferId,proto3" json:"transfer_id,omitempty"`
+ Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
+ Sequence int64 `protobuf:"varint,3,opt,name=sequence,proto3" json:"sequence,omitempty"`
+ Eof bool `protobuf:"varint,4,opt,name=eof,proto3" json:"eof,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
-func (x *ManagerMessage) Reset() {
- *x = ManagerMessage{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[1]
+func (x *FileChunk) Reset() {
+ *x = FileChunk{}
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
-func (x *ManagerMessage) String() string {
+func (x *FileChunk) String() string {
return protoimpl.X.MessageStringOf(x)
}
-func (*ManagerMessage) ProtoMessage() {}
+func (*FileChunk) ProtoMessage() {}
-func (x *ManagerMessage) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[1]
+func (x *FileChunk) ProtoReflect() protoreflect.Message {
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[8]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -242,134 +1014,146 @@ func (x *ManagerMessage) ProtoReflect() protoreflect.Message {
return mi.MessageOf(x)
}
-// Deprecated: Use ManagerMessage.ProtoReflect.Descriptor instead.
-func (*ManagerMessage) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{1}
+// Deprecated: Use FileChunk.ProtoReflect.Descriptor instead.
+func (*FileChunk) Descriptor() ([]byte, []int) {
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{8}
}
-func (x *ManagerMessage) GetPayload() isManagerMessage_Payload {
+func (x *FileChunk) GetTransferId() string {
if x != nil {
- return x.Payload
+ return x.TransferId
}
- return nil
+ return ""
}
-func (x *ManagerMessage) GetHttpRequest() *HttpRequest {
+func (x *FileChunk) GetData() []byte {
if x != nil {
- if x, ok := x.Payload.(*ManagerMessage_HttpRequest); ok {
- return x.HttpRequest
- }
+ return x.Data
}
return nil
}
-func (x *ManagerMessage) GetHeartbeatPong() *HeartbeatPong {
+func (x *FileChunk) GetSequence() int64 {
if x != nil {
- if x, ok := x.Payload.(*ManagerMessage_HeartbeatPong); ok {
- return x.HeartbeatPong
- }
+ return x.Sequence
}
- return nil
+ return 0
}
-func (x *ManagerMessage) GetWsStart() *WebSocketStart {
+func (x *FileChunk) GetEof() bool {
if x != nil {
- if x, ok := x.Payload.(*ManagerMessage_WsStart); ok {
- return x.WsStart
- }
+ return x.Eof
}
- return nil
+ return false
}
-func (x *ManagerMessage) GetWsData() *WebSocketData {
- if x != nil {
- if x, ok := x.Payload.(*ManagerMessage_WsData); ok {
- return x.WsData
- }
- }
- return nil
+type StreamOpen struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ StreamId string `protobuf:"bytes,1,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"`
+ CommandName string `protobuf:"bytes,2,opt,name=command_name,json=commandName,proto3" json:"command_name,omitempty"`
+ Path string `protobuf:"bytes,3,opt,name=path,proto3" json:"path,omitempty"`
+ Query string `protobuf:"bytes,4,opt,name=query,proto3" json:"query,omitempty"`
+ Headers map[string]string `protobuf:"bytes,5,rep,name=headers,proto3" json:"headers,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ SessionId string `protobuf:"bytes,6,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
-func (x *ManagerMessage) GetWsClose() *WebSocketClose {
- if x != nil {
- if x, ok := x.Payload.(*ManagerMessage_WsClose); ok {
- return x.WsClose
- }
- }
- return nil
+func (x *StreamOpen) Reset() {
+ *x = StreamOpen{}
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[9]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
}
-func (x *ManagerMessage) GetRegisterResponse() *RegisterResponse {
+func (x *StreamOpen) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*StreamOpen) ProtoMessage() {}
+
+func (x *StreamOpen) ProtoReflect() protoreflect.Message {
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[9]
if x != nil {
- if x, ok := x.Payload.(*ManagerMessage_RegisterResponse); ok {
- return x.RegisterResponse
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
}
+ return ms
}
- return nil
+ return mi.MessageOf(x)
}
-type isManagerMessage_Payload interface {
- isManagerMessage_Payload()
+// Deprecated: Use StreamOpen.ProtoReflect.Descriptor instead.
+func (*StreamOpen) Descriptor() ([]byte, []int) {
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{9}
}
-type ManagerMessage_HttpRequest struct {
- HttpRequest *HttpRequest `protobuf:"bytes,1,opt,name=http_request,json=httpRequest,proto3,oneof"`
+func (x *StreamOpen) GetStreamId() string {
+ if x != nil {
+ return x.StreamId
+ }
+ return ""
}
-type ManagerMessage_HeartbeatPong struct {
- HeartbeatPong *HeartbeatPong `protobuf:"bytes,2,opt,name=heartbeat_pong,json=heartbeatPong,proto3,oneof"`
+func (x *StreamOpen) GetCommandName() string {
+ if x != nil {
+ return x.CommandName
+ }
+ return ""
}
-type ManagerMessage_WsStart struct {
- WsStart *WebSocketStart `protobuf:"bytes,3,opt,name=ws_start,json=wsStart,proto3,oneof"`
+func (x *StreamOpen) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
}
-type ManagerMessage_WsData struct {
- WsData *WebSocketData `protobuf:"bytes,4,opt,name=ws_data,json=wsData,proto3,oneof"`
+func (x *StreamOpen) GetQuery() string {
+ if x != nil {
+ return x.Query
+ }
+ return ""
}
-type ManagerMessage_WsClose struct {
- WsClose *WebSocketClose `protobuf:"bytes,5,opt,name=ws_close,json=wsClose,proto3,oneof"`
+func (x *StreamOpen) GetHeaders() map[string]string {
+ if x != nil {
+ return x.Headers
+ }
+ return nil
}
-type ManagerMessage_RegisterResponse struct {
- RegisterResponse *RegisterResponse `protobuf:"bytes,6,opt,name=register_response,json=registerResponse,proto3,oneof"`
+func (x *StreamOpen) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
}
-func (*ManagerMessage_HttpRequest) isManagerMessage_Payload() {}
-
-func (*ManagerMessage_HeartbeatPong) isManagerMessage_Payload() {}
-
-func (*ManagerMessage_WsStart) isManagerMessage_Payload() {}
-
-func (*ManagerMessage_WsData) isManagerMessage_Payload() {}
-
-func (*ManagerMessage_WsClose) isManagerMessage_Payload() {}
-
-func (*ManagerMessage_RegisterResponse) isManagerMessage_Payload() {}
-
-type RegisterRequest struct {
+type StreamClose struct {
state protoimpl.MessageState `protogen:"open.v1"`
- AgentToken string `protobuf:"bytes,1,opt,name=agent_token,json=agentToken,proto3" json:"agent_token,omitempty"`
+ StreamId string `protobuf:"bytes,1,opt,name=stream_id,json=streamId,proto3" json:"stream_id,omitempty"`
+ Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
-func (x *RegisterRequest) Reset() {
- *x = RegisterRequest{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[2]
+func (x *StreamClose) Reset() {
+ *x = StreamClose{}
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[10]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
-func (x *RegisterRequest) String() string {
+func (x *StreamClose) String() string {
return protoimpl.X.MessageStringOf(x)
}
-func (*RegisterRequest) ProtoMessage() {}
+func (*StreamClose) ProtoMessage() {}
-func (x *RegisterRequest) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[2]
+func (x *StreamClose) ProtoReflect() protoreflect.Message {
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[10]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -380,42 +1164,47 @@ func (x *RegisterRequest) ProtoReflect() protoreflect.Message {
return mi.MessageOf(x)
}
-// Deprecated: Use RegisterRequest.ProtoReflect.Descriptor instead.
-func (*RegisterRequest) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{2}
+// Deprecated: Use StreamClose.ProtoReflect.Descriptor instead.
+func (*StreamClose) Descriptor() ([]byte, []int) {
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{10}
}
-func (x *RegisterRequest) GetAgentToken() string {
+func (x *StreamClose) GetStreamId() string {
if x != nil {
- return x.AgentToken
+ return x.StreamId
}
return ""
}
-type RegisterResponse struct {
+func (x *StreamClose) GetError() string {
+ if x != nil {
+ return x.Error
+ }
+ return ""
+}
+
+type CancelRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
- Accepted bool `protobuf:"varint,1,opt,name=accepted,proto3" json:"accepted,omitempty"`
- EnvironmentId string `protobuf:"bytes,2,opt,name=environment_id,json=environmentId,proto3" json:"environment_id,omitempty"`
- Error string `protobuf:"bytes,3,opt,name=error,proto3" json:"error,omitempty"`
+ CommandId string `protobuf:"bytes,1,opt,name=command_id,json=commandId,proto3" json:"command_id,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
-func (x *RegisterResponse) Reset() {
- *x = RegisterResponse{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[3]
+func (x *CancelRequest) Reset() {
+ *x = CancelRequest{}
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[11]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
-func (x *RegisterResponse) String() string {
+func (x *CancelRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
-func (*RegisterResponse) ProtoMessage() {}
+func (*CancelRequest) ProtoMessage() {}
-func (x *RegisterResponse) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[3]
+func (x *CancelRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[11]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -426,28 +1215,14 @@ func (x *RegisterResponse) ProtoReflect() protoreflect.Message {
return mi.MessageOf(x)
}
-// Deprecated: Use RegisterResponse.ProtoReflect.Descriptor instead.
-func (*RegisterResponse) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{3}
-}
-
-func (x *RegisterResponse) GetAccepted() bool {
- if x != nil {
- return x.Accepted
- }
- return false
-}
-
-func (x *RegisterResponse) GetEnvironmentId() string {
- if x != nil {
- return x.EnvironmentId
- }
- return ""
+// Deprecated: Use CancelRequest.ProtoReflect.Descriptor instead.
+func (*CancelRequest) Descriptor() ([]byte, []int) {
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{11}
}
-func (x *RegisterResponse) GetError() string {
+func (x *CancelRequest) GetCommandId() string {
if x != nil {
- return x.Error
+ return x.CommandId
}
return ""
}
@@ -466,7 +1241,7 @@ type HttpRequest struct {
func (x *HttpRequest) Reset() {
*x = HttpRequest{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[4]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[12]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -478,7 +1253,7 @@ func (x *HttpRequest) String() string {
func (*HttpRequest) ProtoMessage() {}
func (x *HttpRequest) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[4]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[12]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -491,7 +1266,7 @@ func (x *HttpRequest) ProtoReflect() protoreflect.Message {
// Deprecated: Use HttpRequest.ProtoReflect.Descriptor instead.
func (*HttpRequest) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{4}
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{12}
}
func (x *HttpRequest) GetRequestId() string {
@@ -548,7 +1323,7 @@ type HttpResponse struct {
func (x *HttpResponse) Reset() {
*x = HttpResponse{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[5]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[13]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -560,7 +1335,7 @@ func (x *HttpResponse) String() string {
func (*HttpResponse) ProtoMessage() {}
func (x *HttpResponse) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[5]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[13]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -573,7 +1348,7 @@ func (x *HttpResponse) ProtoReflect() protoreflect.Message {
// Deprecated: Use HttpResponse.ProtoReflect.Descriptor instead.
func (*HttpResponse) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{5}
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{13}
}
func (x *HttpResponse) GetRequestId() string {
@@ -609,13 +1384,14 @@ type StreamData struct {
state protoimpl.MessageState `protogen:"open.v1"`
RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"`
Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"`
+ MessageType int32 `protobuf:"varint,3,opt,name=message_type,json=messageType,proto3" json:"message_type,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *StreamData) Reset() {
*x = StreamData{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[6]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -627,7 +1403,7 @@ func (x *StreamData) String() string {
func (*StreamData) ProtoMessage() {}
func (x *StreamData) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[6]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[14]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -640,7 +1416,7 @@ func (x *StreamData) ProtoReflect() protoreflect.Message {
// Deprecated: Use StreamData.ProtoReflect.Descriptor instead.
func (*StreamData) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{6}
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{14}
}
func (x *StreamData) GetRequestId() string {
@@ -657,6 +1433,13 @@ func (x *StreamData) GetData() []byte {
return nil
}
+func (x *StreamData) GetMessageType() int32 {
+ if x != nil {
+ return x.MessageType
+ }
+ return 0
+}
+
type StreamEnd struct {
state protoimpl.MessageState `protogen:"open.v1"`
RequestId string `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"`
@@ -666,7 +1449,7 @@ type StreamEnd struct {
func (x *StreamEnd) Reset() {
*x = StreamEnd{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[7]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[15]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -678,7 +1461,7 @@ func (x *StreamEnd) String() string {
func (*StreamEnd) ProtoMessage() {}
func (x *StreamEnd) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[7]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[15]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -691,7 +1474,7 @@ func (x *StreamEnd) ProtoReflect() protoreflect.Message {
// Deprecated: Use StreamEnd.ProtoReflect.Descriptor instead.
func (*StreamEnd) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{7}
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{15}
}
func (x *StreamEnd) GetRequestId() string {
@@ -709,7 +1492,7 @@ type HeartbeatPing struct {
func (x *HeartbeatPing) Reset() {
*x = HeartbeatPing{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[8]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -721,7 +1504,7 @@ func (x *HeartbeatPing) String() string {
func (*HeartbeatPing) ProtoMessage() {}
func (x *HeartbeatPing) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[8]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[16]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -734,7 +1517,7 @@ func (x *HeartbeatPing) ProtoReflect() protoreflect.Message {
// Deprecated: Use HeartbeatPing.ProtoReflect.Descriptor instead.
func (*HeartbeatPing) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{8}
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{16}
}
type HeartbeatPong struct {
@@ -745,7 +1528,7 @@ type HeartbeatPong struct {
func (x *HeartbeatPong) Reset() {
*x = HeartbeatPong{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[9]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[17]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -757,7 +1540,7 @@ func (x *HeartbeatPong) String() string {
func (*HeartbeatPong) ProtoMessage() {}
func (x *HeartbeatPong) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[9]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[17]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -770,7 +1553,7 @@ func (x *HeartbeatPong) ProtoReflect() protoreflect.Message {
// Deprecated: Use HeartbeatPong.ProtoReflect.Descriptor instead.
func (*HeartbeatPong) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{9}
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{17}
}
type WebSocketStart struct {
@@ -785,7 +1568,7 @@ type WebSocketStart struct {
func (x *WebSocketStart) Reset() {
*x = WebSocketStart{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[10]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[18]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -797,7 +1580,7 @@ func (x *WebSocketStart) String() string {
func (*WebSocketStart) ProtoMessage() {}
func (x *WebSocketStart) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[10]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[18]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -810,7 +1593,7 @@ func (x *WebSocketStart) ProtoReflect() protoreflect.Message {
// Deprecated: Use WebSocketStart.ProtoReflect.Descriptor instead.
func (*WebSocketStart) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{10}
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{18}
}
func (x *WebSocketStart) GetStreamId() string {
@@ -852,7 +1635,7 @@ type WebSocketData struct {
func (x *WebSocketData) Reset() {
*x = WebSocketData{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[11]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[19]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -864,7 +1647,7 @@ func (x *WebSocketData) String() string {
func (*WebSocketData) ProtoMessage() {}
func (x *WebSocketData) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[11]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[19]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -877,7 +1660,7 @@ func (x *WebSocketData) ProtoReflect() protoreflect.Message {
// Deprecated: Use WebSocketData.ProtoReflect.Descriptor instead.
func (*WebSocketData) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{11}
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{19}
}
func (x *WebSocketData) GetStreamId() string {
@@ -910,7 +1693,7 @@ type WebSocketClose struct {
func (x *WebSocketClose) Reset() {
*x = WebSocketClose{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[12]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[20]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -922,7 +1705,7 @@ func (x *WebSocketClose) String() string {
func (*WebSocketClose) ProtoMessage() {}
func (x *WebSocketClose) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[12]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[20]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -935,7 +1718,7 @@ func (x *WebSocketClose) ProtoReflect() protoreflect.Message {
// Deprecated: Use WebSocketClose.ProtoReflect.Descriptor instead.
func (*WebSocketClose) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{12}
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{20}
}
func (x *WebSocketClose) GetStreamId() string {
@@ -964,7 +1747,7 @@ type EventLog struct {
func (x *EventLog) Reset() {
*x = EventLog{}
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[13]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[21]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
@@ -976,7 +1759,7 @@ func (x *EventLog) String() string {
func (*EventLog) ProtoMessage() {}
func (x *EventLog) ProtoReflect() protoreflect.Message {
- mi := &file_tunnel_v1_tunnel_proto_msgTypes[13]
+ mi := &file_tunnel_v1_tunnel_proto_msgTypes[21]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -989,7 +1772,7 @@ func (x *EventLog) ProtoReflect() protoreflect.Message {
// Deprecated: Use EventLog.ProtoReflect.Descriptor instead.
func (*EventLog) Descriptor() ([]byte, []int) {
- return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{13}
+ return file_tunnel_v1_tunnel_proto_rawDescGZIP(), []int{21}
}
func (x *EventLog) GetType() string {
@@ -1066,7 +1849,7 @@ var File_tunnel_v1_tunnel_proto protoreflect.FileDescriptor
const file_tunnel_v1_tunnel_proto_rawDesc = "" +
"\n" +
- "\x16tunnel/v1/tunnel.proto\x12\ttunnel.v1\"\xe1\x03\n" +
+ "\x16tunnel/v1/tunnel.proto\x12\ttunnel.v1\"\x9b\x06\n" +
"\fAgentMessage\x12>\n" +
"\rhttp_response\x18\x01 \x01(\v2\x17.tunnel.v1.HttpResponseH\x00R\fhttpResponse\x12A\n" +
"\x0eheartbeat_ping\x18\x02 \x01(\v2\x18.tunnel.v1.HeartbeatPingH\x00R\rheartbeatPing\x123\n" +
@@ -1077,23 +1860,112 @@ const file_tunnel_v1_tunnel_proto_rawDesc = "" +
"\n" +
"stream_end\x18\x06 \x01(\v2\x14.tunnel.v1.StreamEndH\x00R\tstreamEnd\x128\n" +
"\bregister\x18\a \x01(\v2\x1a.tunnel.v1.RegisterRequestH\x00R\bregister\x12+\n" +
- "\x05event\x18\b \x01(\v2\x13.tunnel.v1.EventLogH\x00R\x05eventB\t\n" +
- "\apayload\"\x8c\x03\n" +
+ "\x05event\x18\b \x01(\v2\x13.tunnel.v1.EventLogH\x00R\x05event\x128\n" +
+ "\vcommand_ack\x18\t \x01(\v2\x15.tunnel.v1.CommandAckH\x00R\n" +
+ "commandAck\x12A\n" +
+ "\x0ecommand_output\x18\n" +
+ " \x01(\v2\x18.tunnel.v1.CommandOutputH\x00R\rcommandOutput\x12G\n" +
+ "\x10command_complete\x18\v \x01(\v2\x1a.tunnel.v1.CommandCompleteH\x00R\x0fcommandComplete\x125\n" +
+ "\n" +
+ "file_chunk\x18\f \x01(\v2\x14.tunnel.v1.FileChunkH\x00R\tfileChunk\x12;\n" +
+ "\fstream_close\x18\r \x01(\v2\x16.tunnel.v1.StreamCloseH\x00R\vstreamCloseB\t\n" +
+ "\apayload\"\xc3\x05\n" +
"\x0eManagerMessage\x12;\n" +
"\fhttp_request\x18\x01 \x01(\v2\x16.tunnel.v1.HttpRequestH\x00R\vhttpRequest\x12A\n" +
"\x0eheartbeat_pong\x18\x02 \x01(\v2\x18.tunnel.v1.HeartbeatPongH\x00R\rheartbeatPong\x126\n" +
"\bws_start\x18\x03 \x01(\v2\x19.tunnel.v1.WebSocketStartH\x00R\awsStart\x123\n" +
"\aws_data\x18\x04 \x01(\v2\x18.tunnel.v1.WebSocketDataH\x00R\x06wsData\x126\n" +
"\bws_close\x18\x05 \x01(\v2\x19.tunnel.v1.WebSocketCloseH\x00R\awsClose\x12J\n" +
- "\x11register_response\x18\x06 \x01(\v2\x1b.tunnel.v1.RegisterResponseH\x00R\x10registerResponseB\t\n" +
- "\apayload\"2\n" +
+ "\x11register_response\x18\x06 \x01(\v2\x1b.tunnel.v1.RegisterResponseH\x00R\x10registerResponse\x12D\n" +
+ "\x0fcommand_request\x18\a \x01(\v2\x19.tunnel.v1.CommandRequestH\x00R\x0ecommandRequest\x128\n" +
+ "\vstream_open\x18\b \x01(\v2\x15.tunnel.v1.StreamOpenH\x00R\n" +
+ "streamOpen\x12;\n" +
+ "\fstream_close\x18\t \x01(\v2\x16.tunnel.v1.StreamCloseH\x00R\vstreamClose\x12A\n" +
+ "\x0ecancel_request\x18\n" +
+ " \x01(\v2\x18.tunnel.v1.CancelRequestH\x00R\rcancelRequest\x125\n" +
+ "\n" +
+ "file_chunk\x18\v \x01(\v2\x14.tunnel.v1.FileChunkH\x00R\tfileChunkB\t\n" +
+ "\apayload\"\xae\x01\n" +
"\x0fRegisterRequest\x12\x1f\n" +
"\vagent_token\x18\x01 \x01(\tR\n" +
- "agentToken\"k\n" +
+ "agentToken\x12*\n" +
+ "\x11agent_instance_id\x18\x02 \x01(\tR\x0fagentInstanceId\x12\"\n" +
+ "\fcapabilities\x18\x03 \x03(\tR\fcapabilities\x12*\n" +
+ "\x11resume_session_id\x18\x04 \x01(\tR\x0fresumeSessionId\"\xfa\x01\n" +
"\x10RegisterResponse\x12\x1a\n" +
"\baccepted\x18\x01 \x01(\bR\baccepted\x12%\n" +
"\x0eenvironment_id\x18\x02 \x01(\tR\renvironmentId\x12\x14\n" +
- "\x05error\x18\x03 \x01(\tR\x05error\"\xfd\x01\n" +
+ "\x05error\x18\x03 \x01(\tR\x05error\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x04 \x01(\tR\tsessionId\x12#\n" +
+ "\rsecurity_mode\x18\x05 \x01(\tR\fsecurityMode\x12\"\n" +
+ "\fcapabilities\x18\x06 \x03(\tR\fcapabilities\x12%\n" +
+ "\x0edrain_previous\x18\a \x01(\bR\rdrainPrevious\"\x9a\x04\n" +
+ "\x0eCommandRequest\x12\x1d\n" +
+ "\n" +
+ "command_id\x18\x01 \x01(\tR\tcommandId\x12!\n" +
+ "\fcommand_name\x18\x02 \x01(\tR\vcommandName\x12\x16\n" +
+ "\x06method\x18\x03 \x01(\tR\x06method\x12\x12\n" +
+ "\x04path\x18\x04 \x01(\tR\x04path\x12\x14\n" +
+ "\x05query\x18\x05 \x01(\tR\x05query\x12@\n" +
+ "\aheaders\x18\x06 \x03(\v2&.tunnel.v1.CommandRequest.HeadersEntryR\aheaders\x12\x12\n" +
+ "\x04body\x18\a \x01(\fR\x04body\x12%\n" +
+ "\x0etimeout_millis\x18\b \x01(\x03R\rtimeoutMillis\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\t \x01(\tR\tsessionId\x12*\n" +
+ "\x11agent_instance_id\x18\n" +
+ " \x01(\tR\x0fagentInstanceId\x12C\n" +
+ "\bmetadata\x18\v \x03(\v2'.tunnel.v1.CommandRequest.MetadataEntryR\bmetadata\x1a:\n" +
+ "\fHeadersEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1a;\n" +
+ "\rMetadataEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"+\n" +
+ "\n" +
+ "CommandAck\x12\x1d\n" +
+ "\n" +
+ "command_id\x18\x01 \x01(\tR\tcommandId\"^\n" +
+ "\rCommandOutput\x12\x1d\n" +
+ "\n" +
+ "command_id\x18\x01 \x01(\tR\tcommandId\x12\x12\n" +
+ "\x04data\x18\x02 \x01(\fR\x04data\x12\x1a\n" +
+ "\bsequence\x18\x03 \x01(\x03R\bsequence\"\x8f\x02\n" +
+ "\x0fCommandComplete\x12\x1d\n" +
+ "\n" +
+ "command_id\x18\x01 \x01(\tR\tcommandId\x12\x16\n" +
+ "\x06status\x18\x02 \x01(\x05R\x06status\x12A\n" +
+ "\aheaders\x18\x03 \x03(\v2'.tunnel.v1.CommandComplete.HeadersEntryR\aheaders\x12\x12\n" +
+ "\x04body\x18\x04 \x01(\fR\x04body\x12\x14\n" +
+ "\x05error\x18\x05 \x01(\tR\x05error\x12\x1c\n" +
+ "\tstreaming\x18\x06 \x01(\bR\tstreaming\x1a:\n" +
+ "\fHeadersEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"n\n" +
+ "\tFileChunk\x12\x1f\n" +
+ "\vtransfer_id\x18\x01 \x01(\tR\n" +
+ "transferId\x12\x12\n" +
+ "\x04data\x18\x02 \x01(\fR\x04data\x12\x1a\n" +
+ "\bsequence\x18\x03 \x01(\x03R\bsequence\x12\x10\n" +
+ "\x03eof\x18\x04 \x01(\bR\x03eof\"\x8f\x02\n" +
+ "\n" +
+ "StreamOpen\x12\x1b\n" +
+ "\tstream_id\x18\x01 \x01(\tR\bstreamId\x12!\n" +
+ "\fcommand_name\x18\x02 \x01(\tR\vcommandName\x12\x12\n" +
+ "\x04path\x18\x03 \x01(\tR\x04path\x12\x14\n" +
+ "\x05query\x18\x04 \x01(\tR\x05query\x12<\n" +
+ "\aheaders\x18\x05 \x03(\v2\".tunnel.v1.StreamOpen.HeadersEntryR\aheaders\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x06 \x01(\tR\tsessionId\x1a:\n" +
+ "\fHeadersEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"@\n" +
+ "\vStreamClose\x12\x1b\n" +
+ "\tstream_id\x18\x01 \x01(\tR\bstreamId\x12\x14\n" +
+ "\x05error\x18\x02 \x01(\tR\x05error\".\n" +
+ "\rCancelRequest\x12\x1d\n" +
+ "\n" +
+ "command_id\x18\x01 \x01(\tR\tcommandId\"\xfd\x01\n" +
"\vHttpRequest\x12\x1d\n" +
"\n" +
"request_id\x18\x01 \x01(\tR\trequestId\x12\x16\n" +
@@ -1113,12 +1985,13 @@ const file_tunnel_v1_tunnel_proto_rawDesc = "" +
"\x04body\x18\x04 \x01(\fR\x04body\x1a:\n" +
"\fHeadersEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
- "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"?\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"b\n" +
"\n" +
"StreamData\x12\x1d\n" +
"\n" +
"request_id\x18\x01 \x01(\tR\trequestId\x12\x12\n" +
- "\x04data\x18\x02 \x01(\fR\x04data\"*\n" +
+ "\x04data\x18\x02 \x01(\fR\x04data\x12!\n" +
+ "\fmessage_type\x18\x03 \x01(\x05R\vmessageType\"*\n" +
"\tStreamEnd\x12\x1d\n" +
"\n" +
"request_id\x18\x01 \x01(\tR\trequestId\"\x0f\n" +
@@ -1166,51 +2039,77 @@ func file_tunnel_v1_tunnel_proto_rawDescGZIP() []byte {
return file_tunnel_v1_tunnel_proto_rawDescData
}
-var file_tunnel_v1_tunnel_proto_msgTypes = make([]protoimpl.MessageInfo, 17)
+var file_tunnel_v1_tunnel_proto_msgTypes = make([]protoimpl.MessageInfo, 29)
var file_tunnel_v1_tunnel_proto_goTypes = []any{
(*AgentMessage)(nil), // 0: tunnel.v1.AgentMessage
(*ManagerMessage)(nil), // 1: tunnel.v1.ManagerMessage
(*RegisterRequest)(nil), // 2: tunnel.v1.RegisterRequest
(*RegisterResponse)(nil), // 3: tunnel.v1.RegisterResponse
- (*HttpRequest)(nil), // 4: tunnel.v1.HttpRequest
- (*HttpResponse)(nil), // 5: tunnel.v1.HttpResponse
- (*StreamData)(nil), // 6: tunnel.v1.StreamData
- (*StreamEnd)(nil), // 7: tunnel.v1.StreamEnd
- (*HeartbeatPing)(nil), // 8: tunnel.v1.HeartbeatPing
- (*HeartbeatPong)(nil), // 9: tunnel.v1.HeartbeatPong
- (*WebSocketStart)(nil), // 10: tunnel.v1.WebSocketStart
- (*WebSocketData)(nil), // 11: tunnel.v1.WebSocketData
- (*WebSocketClose)(nil), // 12: tunnel.v1.WebSocketClose
- (*EventLog)(nil), // 13: tunnel.v1.EventLog
- nil, // 14: tunnel.v1.HttpRequest.HeadersEntry
- nil, // 15: tunnel.v1.HttpResponse.HeadersEntry
- nil, // 16: tunnel.v1.WebSocketStart.HeadersEntry
+ (*CommandRequest)(nil), // 4: tunnel.v1.CommandRequest
+ (*CommandAck)(nil), // 5: tunnel.v1.CommandAck
+ (*CommandOutput)(nil), // 6: tunnel.v1.CommandOutput
+ (*CommandComplete)(nil), // 7: tunnel.v1.CommandComplete
+ (*FileChunk)(nil), // 8: tunnel.v1.FileChunk
+ (*StreamOpen)(nil), // 9: tunnel.v1.StreamOpen
+ (*StreamClose)(nil), // 10: tunnel.v1.StreamClose
+ (*CancelRequest)(nil), // 11: tunnel.v1.CancelRequest
+ (*HttpRequest)(nil), // 12: tunnel.v1.HttpRequest
+ (*HttpResponse)(nil), // 13: tunnel.v1.HttpResponse
+ (*StreamData)(nil), // 14: tunnel.v1.StreamData
+ (*StreamEnd)(nil), // 15: tunnel.v1.StreamEnd
+ (*HeartbeatPing)(nil), // 16: tunnel.v1.HeartbeatPing
+ (*HeartbeatPong)(nil), // 17: tunnel.v1.HeartbeatPong
+ (*WebSocketStart)(nil), // 18: tunnel.v1.WebSocketStart
+ (*WebSocketData)(nil), // 19: tunnel.v1.WebSocketData
+ (*WebSocketClose)(nil), // 20: tunnel.v1.WebSocketClose
+ (*EventLog)(nil), // 21: tunnel.v1.EventLog
+ nil, // 22: tunnel.v1.CommandRequest.HeadersEntry
+ nil, // 23: tunnel.v1.CommandRequest.MetadataEntry
+ nil, // 24: tunnel.v1.CommandComplete.HeadersEntry
+ nil, // 25: tunnel.v1.StreamOpen.HeadersEntry
+ nil, // 26: tunnel.v1.HttpRequest.HeadersEntry
+ nil, // 27: tunnel.v1.HttpResponse.HeadersEntry
+ nil, // 28: tunnel.v1.WebSocketStart.HeadersEntry
}
var file_tunnel_v1_tunnel_proto_depIdxs = []int32{
- 5, // 0: tunnel.v1.AgentMessage.http_response:type_name -> tunnel.v1.HttpResponse
- 8, // 1: tunnel.v1.AgentMessage.heartbeat_ping:type_name -> tunnel.v1.HeartbeatPing
- 11, // 2: tunnel.v1.AgentMessage.ws_data:type_name -> tunnel.v1.WebSocketData
- 12, // 3: tunnel.v1.AgentMessage.ws_close:type_name -> tunnel.v1.WebSocketClose
- 6, // 4: tunnel.v1.AgentMessage.stream_data:type_name -> tunnel.v1.StreamData
- 7, // 5: tunnel.v1.AgentMessage.stream_end:type_name -> tunnel.v1.StreamEnd
+ 13, // 0: tunnel.v1.AgentMessage.http_response:type_name -> tunnel.v1.HttpResponse
+ 16, // 1: tunnel.v1.AgentMessage.heartbeat_ping:type_name -> tunnel.v1.HeartbeatPing
+ 19, // 2: tunnel.v1.AgentMessage.ws_data:type_name -> tunnel.v1.WebSocketData
+ 20, // 3: tunnel.v1.AgentMessage.ws_close:type_name -> tunnel.v1.WebSocketClose
+ 14, // 4: tunnel.v1.AgentMessage.stream_data:type_name -> tunnel.v1.StreamData
+ 15, // 5: tunnel.v1.AgentMessage.stream_end:type_name -> tunnel.v1.StreamEnd
2, // 6: tunnel.v1.AgentMessage.register:type_name -> tunnel.v1.RegisterRequest
- 13, // 7: tunnel.v1.AgentMessage.event:type_name -> tunnel.v1.EventLog
- 4, // 8: tunnel.v1.ManagerMessage.http_request:type_name -> tunnel.v1.HttpRequest
- 9, // 9: tunnel.v1.ManagerMessage.heartbeat_pong:type_name -> tunnel.v1.HeartbeatPong
- 10, // 10: tunnel.v1.ManagerMessage.ws_start:type_name -> tunnel.v1.WebSocketStart
- 11, // 11: tunnel.v1.ManagerMessage.ws_data:type_name -> tunnel.v1.WebSocketData
- 12, // 12: tunnel.v1.ManagerMessage.ws_close:type_name -> tunnel.v1.WebSocketClose
- 3, // 13: tunnel.v1.ManagerMessage.register_response:type_name -> tunnel.v1.RegisterResponse
- 14, // 14: tunnel.v1.HttpRequest.headers:type_name -> tunnel.v1.HttpRequest.HeadersEntry
- 15, // 15: tunnel.v1.HttpResponse.headers:type_name -> tunnel.v1.HttpResponse.HeadersEntry
- 16, // 16: tunnel.v1.WebSocketStart.headers:type_name -> tunnel.v1.WebSocketStart.HeadersEntry
- 0, // 17: tunnel.v1.TunnelService.Connect:input_type -> tunnel.v1.AgentMessage
- 1, // 18: tunnel.v1.TunnelService.Connect:output_type -> tunnel.v1.ManagerMessage
- 18, // [18:19] is the sub-list for method output_type
- 17, // [17:18] is the sub-list for method input_type
- 17, // [17:17] is the sub-list for extension type_name
- 17, // [17:17] is the sub-list for extension extendee
- 0, // [0:17] is the sub-list for field type_name
+ 21, // 7: tunnel.v1.AgentMessage.event:type_name -> tunnel.v1.EventLog
+ 5, // 8: tunnel.v1.AgentMessage.command_ack:type_name -> tunnel.v1.CommandAck
+ 6, // 9: tunnel.v1.AgentMessage.command_output:type_name -> tunnel.v1.CommandOutput
+ 7, // 10: tunnel.v1.AgentMessage.command_complete:type_name -> tunnel.v1.CommandComplete
+ 8, // 11: tunnel.v1.AgentMessage.file_chunk:type_name -> tunnel.v1.FileChunk
+ 10, // 12: tunnel.v1.AgentMessage.stream_close:type_name -> tunnel.v1.StreamClose
+ 12, // 13: tunnel.v1.ManagerMessage.http_request:type_name -> tunnel.v1.HttpRequest
+ 17, // 14: tunnel.v1.ManagerMessage.heartbeat_pong:type_name -> tunnel.v1.HeartbeatPong
+ 18, // 15: tunnel.v1.ManagerMessage.ws_start:type_name -> tunnel.v1.WebSocketStart
+ 19, // 16: tunnel.v1.ManagerMessage.ws_data:type_name -> tunnel.v1.WebSocketData
+ 20, // 17: tunnel.v1.ManagerMessage.ws_close:type_name -> tunnel.v1.WebSocketClose
+ 3, // 18: tunnel.v1.ManagerMessage.register_response:type_name -> tunnel.v1.RegisterResponse
+ 4, // 19: tunnel.v1.ManagerMessage.command_request:type_name -> tunnel.v1.CommandRequest
+ 9, // 20: tunnel.v1.ManagerMessage.stream_open:type_name -> tunnel.v1.StreamOpen
+ 10, // 21: tunnel.v1.ManagerMessage.stream_close:type_name -> tunnel.v1.StreamClose
+ 11, // 22: tunnel.v1.ManagerMessage.cancel_request:type_name -> tunnel.v1.CancelRequest
+ 8, // 23: tunnel.v1.ManagerMessage.file_chunk:type_name -> tunnel.v1.FileChunk
+ 22, // 24: tunnel.v1.CommandRequest.headers:type_name -> tunnel.v1.CommandRequest.HeadersEntry
+ 23, // 25: tunnel.v1.CommandRequest.metadata:type_name -> tunnel.v1.CommandRequest.MetadataEntry
+ 24, // 26: tunnel.v1.CommandComplete.headers:type_name -> tunnel.v1.CommandComplete.HeadersEntry
+ 25, // 27: tunnel.v1.StreamOpen.headers:type_name -> tunnel.v1.StreamOpen.HeadersEntry
+ 26, // 28: tunnel.v1.HttpRequest.headers:type_name -> tunnel.v1.HttpRequest.HeadersEntry
+ 27, // 29: tunnel.v1.HttpResponse.headers:type_name -> tunnel.v1.HttpResponse.HeadersEntry
+ 28, // 30: tunnel.v1.WebSocketStart.headers:type_name -> tunnel.v1.WebSocketStart.HeadersEntry
+ 0, // 31: tunnel.v1.TunnelService.Connect:input_type -> tunnel.v1.AgentMessage
+ 1, // 32: tunnel.v1.TunnelService.Connect:output_type -> tunnel.v1.ManagerMessage
+ 32, // [32:33] is the sub-list for method output_type
+ 31, // [31:32] is the sub-list for method input_type
+ 31, // [31:31] is the sub-list for extension type_name
+ 31, // [31:31] is the sub-list for extension extendee
+ 0, // [0:31] is the sub-list for field type_name
}
func init() { file_tunnel_v1_tunnel_proto_init() }
@@ -1227,6 +2126,11 @@ func file_tunnel_v1_tunnel_proto_init() {
(*AgentMessage_StreamEnd)(nil),
(*AgentMessage_Register)(nil),
(*AgentMessage_Event)(nil),
+ (*AgentMessage_CommandAck)(nil),
+ (*AgentMessage_CommandOutput)(nil),
+ (*AgentMessage_CommandComplete)(nil),
+ (*AgentMessage_FileChunk)(nil),
+ (*AgentMessage_StreamClose)(nil),
}
file_tunnel_v1_tunnel_proto_msgTypes[1].OneofWrappers = []any{
(*ManagerMessage_HttpRequest)(nil),
@@ -1235,6 +2139,11 @@ func file_tunnel_v1_tunnel_proto_init() {
(*ManagerMessage_WsData)(nil),
(*ManagerMessage_WsClose)(nil),
(*ManagerMessage_RegisterResponse)(nil),
+ (*ManagerMessage_CommandRequest)(nil),
+ (*ManagerMessage_StreamOpen)(nil),
+ (*ManagerMessage_StreamClose)(nil),
+ (*ManagerMessage_CancelRequest)(nil),
+ (*ManagerMessage_FileChunk)(nil),
}
type x struct{}
out := protoimpl.TypeBuilder{
@@ -1242,7 +2151,7 @@ func file_tunnel_v1_tunnel_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_tunnel_v1_tunnel_proto_rawDesc), len(file_tunnel_v1_tunnel_proto_rawDesc)),
NumEnums: 0,
- NumMessages: 17,
+ NumMessages: 29,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel.proto b/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel.proto
index 9e81047d7..c7cedc235 100644
--- a/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel.proto
+++ b/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel.proto
@@ -21,6 +21,11 @@ message AgentMessage {
StreamEnd stream_end = 6;
RegisterRequest register = 7;
EventLog event = 8;
+ CommandAck command_ack = 9;
+ CommandOutput command_output = 10;
+ CommandComplete command_complete = 11;
+ FileChunk file_chunk = 12;
+ StreamClose stream_close = 13;
}
}
@@ -33,17 +38,87 @@ message ManagerMessage {
WebSocketData ws_data = 4;
WebSocketClose ws_close = 5;
RegisterResponse register_response = 6;
+ CommandRequest command_request = 7;
+ StreamOpen stream_open = 8;
+ StreamClose stream_close = 9;
+ CancelRequest cancel_request = 10;
+ FileChunk file_chunk = 11;
}
}
message RegisterRequest {
string agent_token = 1;
+ string agent_instance_id = 2;
+ repeated string capabilities = 3;
+ string resume_session_id = 4;
}
message RegisterResponse {
bool accepted = 1;
string environment_id = 2;
string error = 3;
+ string session_id = 4;
+ string security_mode = 5;
+ repeated string capabilities = 6;
+ bool drain_previous = 7;
+}
+
+message CommandRequest {
+ string command_id = 1;
+ string command_name = 2;
+ string method = 3;
+ string path = 4;
+ string query = 5;
+ map<string, string> headers = 6;
+ bytes body = 7;
+ int64 timeout_millis = 8;
+ string session_id = 9;
+ string agent_instance_id = 10;
+ map<string, string> metadata = 11;
+}
+
+message CommandAck {
+ string command_id = 1;
+}
+
+message CommandOutput {
+ string command_id = 1;
+ bytes data = 2;
+ int64 sequence = 3;
+}
+
+message CommandComplete {
+ string command_id = 1;
+ int32 status = 2;
+ map<string, string> headers = 3;
+ bytes body = 4;
+ string error = 5;
+ bool streaming = 6;
+}
+
+message FileChunk {
+ string transfer_id = 1;
+ bytes data = 2;
+ int64 sequence = 3;
+ bool eof = 4;
+}
+
+message StreamOpen {
+ string stream_id = 1;
+ string command_name = 2;
+ string path = 3;
+ string query = 4;
+ map<string, string> headers = 5;
+ string session_id = 6;
+}
+
+message StreamClose {
+ string stream_id = 1;
+ string error = 2;
+}
+
+message CancelRequest {
+ string command_id = 1;
}
message HttpRequest {
@@ -66,6 +141,7 @@ message HttpResponse {
message StreamData {
string request_id = 1;
bytes data = 2;
+ int32 message_type = 3;
}
message StreamEnd {
diff --git a/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel_grpc.pb.go b/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel_grpc.pb.go
index ffd4eb2d6..4f7424980 100644
--- a/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel_grpc.pb.go
+++ b/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel_grpc.pb.go
@@ -8,7 +8,6 @@ package tunnelpb
import (
context "context"
-
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
diff --git a/backend/pkg/libarcane/edge/proxy.go b/backend/pkg/libarcane/edge/proxy.go
index 1b145ea05..a50f1199f 100644
--- a/backend/pkg/libarcane/edge/proxy.go
+++ b/backend/pkg/libarcane/edge/proxy.go
@@ -3,6 +3,7 @@ package edge
import (
"bytes"
"context"
+ "errors"
"fmt"
"io"
"log/slog"
@@ -10,7 +11,6 @@ import (
"time"
"github.com/gin-gonic/gin"
- "github.com/google/uuid"
)
const (
@@ -30,50 +30,34 @@ func DefaultTunnelAcquireTimeout() time.Duration {
// ProxyRequest sends an HTTP request through an edge tunnel
// Returns the response status, headers, and body
func ProxyRequest(ctx context.Context, tunnel *AgentTunnel, method, path, query string, headers map[string]string, body []byte) (int, map[string]string, []byte, error) {
- requestID := uuid.New().String()
-
- msg := &TunnelMessage{
- ID: requestID,
- Type: MessageTypeRequest,
+ result, err := DefaultCommandClient.Execute(ctx, tunnel, &CommandRequest{
Method: method,
Path: path,
Query: query,
Headers: headers,
Body: body,
+ })
+ if err != nil {
+ return 0, nil, nil, err
}
- // Keep request/response flow compatibility for WebSocket transport.
- if _, isGRPC := tunnel.Conn.(*GRPCManagerTunnelConn); !isGRPC {
- return proxyRequestLegacy(ctx, tunnel, msg)
- }
-
- return proxyRequestGRPC(ctx, tunnel, method, requestID, msg)
+ return result.Status, result.Headers, result.Body, nil
}
-func proxyRequestLegacy(ctx context.Context, tunnel *AgentTunnel, msg *TunnelMessage) (int, map[string]string, []byte, error) {
- resp, err := tunnel.Conn.SendRequest(ctx, msg, &tunnel.Pending)
- if err != nil {
- return 0, nil, nil, fmt.Errorf("tunnel request failed: %w", err)
+func registerPendingRequestInternal(tunnel *AgentTunnel, requestID string) (<-chan *TunnelMessage, error) {
+ if requestID == "" {
+ return nil, fmt.Errorf("request ID is required")
}
- return resp.Status, resp.Headers, resp.Body, nil
-}
-func proxyRequestGRPC(ctx context.Context, tunnel *AgentTunnel, method, requestID string, msg *TunnelMessage) (int, map[string]string, []byte, error) {
respCh := make(chan *TunnelMessage, 256)
tunnel.Pending.Store(requestID, &PendingRequest{
ResponseCh: respCh,
CreatedAt: time.Now(),
})
- defer tunnel.Pending.Delete(requestID)
-
- if err := tunnel.Conn.Send(msg); err != nil {
- return 0, nil, nil, fmt.Errorf("tunnel request failed: %w", err)
- }
-
- return collectGRPCResponse(ctx, method, respCh)
+ return respCh, nil
}
-func collectGRPCResponse(ctx context.Context, method string, respCh <-chan *TunnelMessage) (int, map[string]string, []byte, error) {
+func collectCommandResponseInternal(ctx context.Context, respCh <-chan *TunnelMessage, method string) (int, map[string]string, []byte, error) {
state := &grpcResponseState{}
for {
@@ -90,18 +74,28 @@ func collectGRPCResponse(ctx context.Context, method string, respCh <-chan *Tunn
if done, status, headers, body := state.handleResponse(method, incoming); done {
return status, headers, body, nil
}
- case MessageTypeStreamData:
+ case MessageTypeCommandAck:
+ continue
+ case MessageTypeCommandOutput, MessageTypeStreamData, MessageTypeFileChunk:
state.handleStreamData(incoming)
+ case MessageTypeCommandComplete:
+ if done, status, headers, body, err := state.handleCommandComplete(incoming); done {
+ return status, headers, body, err
+ }
case MessageTypeStreamEnd:
if done, status, headers, body := state.handleStreamEnd(); done {
return status, headers, body, nil
}
case MessageTypeRequest,
+ MessageTypeCommandRequest,
MessageTypeHeartbeat,
MessageTypeHeartbeatAck,
MessageTypeWebSocketStart,
MessageTypeWebSocketData,
MessageTypeWebSocketClose,
+ MessageTypeStreamOpen,
+ MessageTypeStreamClose,
+ MessageTypeCancelRequest,
MessageTypeRegister,
MessageTypeRegisterResponse,
MessageTypeEvent:
@@ -145,10 +139,6 @@ func (s *grpcResponseState) handleResponse(method string, incoming *TunnelMessag
}
func (s *grpcResponseState) handleStreamData(incoming *TunnelMessage) {
- if !s.gotResponse {
- // Ignore out-of-order stream chunks until the response envelope arrives.
- return
- }
if len(incoming.Body) > 0 {
s.respBody.Write(incoming.Body)
}
@@ -161,6 +151,21 @@ func (s *grpcResponseState) handleStreamEnd() (bool, int, map[string]string, []b
return true, s.status, stripInternalTunnelHeaders(s.respHeaders), s.respBody.Bytes()
}
+func (s *grpcResponseState) handleCommandComplete(incoming *TunnelMessage) (bool, int, map[string]string, []byte, error) {
+ if !s.gotResponse {
+ s.gotResponse = true
+ s.status = incoming.Status
+ s.respHeaders = incoming.Headers
+ }
+ if len(incoming.Body) > 0 {
+ s.respBody.Write(incoming.Body)
+ }
+ if incoming.Error != "" && incoming.Status >= http.StatusBadRequest {
+ return true, incoming.Status, stripInternalTunnelHeaders(s.respHeaders), s.respBody.Bytes(), errors.New(incoming.Error)
+ }
+ return true, incoming.Status, stripInternalTunnelHeaders(s.respHeaders), s.respBody.Bytes(), nil
+}
+
// ProxyHTTPRequest is a helper that proxies a gin context through a tunnel
func ProxyHTTPRequest(c *gin.Context, tunnel *AgentTunnel, targetPath string) {
ctx := c.Request.Context()
diff --git a/backend/pkg/libarcane/edge/proxy_headers_test.go b/backend/pkg/libarcane/edge/proxy_headers_test.go
index d7919f6c9..b84aa8f87 100644
--- a/backend/pkg/libarcane/edge/proxy_headers_test.go
+++ b/backend/pkg/libarcane/edge/proxy_headers_test.go
@@ -304,7 +304,7 @@ func TestProxyHTTPRequest_BodyPreservation_WebSocket(t *testing.T) {
var msg TunnelMessage
_ = json.Unmarshal(data, &msg)
- if msg.Type == MessageTypeRequest {
+ if msg.Type == MessageTypeRequest || msg.Type == MessageTypeCommandRequest {
receivedBody = string(msg.Body)
resp := &TunnelMessage{
ID: msg.ID,
@@ -327,7 +327,7 @@ func TestProxyHTTPRequest_BodyPreservation_WebSocket(t *testing.T) {
defer func() { _ = resp.Body.Close() }()
}
- tunnel := NewAgentTunnel("env-body-test", wsConn)
+ tunnel := newWebSocketAgentTunnel("env-body-test", wsConn)
defer func() { _ = tunnel.Close() }()
go func() {
diff --git a/backend/pkg/libarcane/edge/proxy_test.go b/backend/pkg/libarcane/edge/proxy_test.go
index 482478a26..2142513a0 100644
--- a/backend/pkg/libarcane/edge/proxy_test.go
+++ b/backend/pkg/libarcane/edge/proxy_test.go
@@ -41,7 +41,7 @@ func setupMockAgentServer(t *testing.T, handler func(*TunnelMessage) *TunnelMess
var msg TunnelMessage
_ = json.Unmarshal(data, &msg)
- if msg.Type == MessageTypeRequest {
+ if msg.Type == MessageTypeRequest || msg.Type == MessageTypeCommandRequest {
resp := handler(&msg)
respData, _ := json.Marshal(resp)
_ = conn.WriteMessage(websocket.TextMessage, respData)
@@ -56,7 +56,7 @@ func setupMockAgentServer(t *testing.T, handler func(*TunnelMessage) *TunnelMess
defer func() { _ = resp.Body.Close() }()
}
- tunnel := NewAgentTunnel("env-1", conn)
+ tunnel := newWebSocketAgentTunnel("env-1", conn)
// We need a loop to read responses from the tunnel and dispatch them to pending
go func() {
@@ -91,7 +91,7 @@ func TestProxyRequest(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
- status, headers, body, err := ProxyRequest(ctx, tunnel, "GET", "/api/test", "", nil, nil)
+ status, headers, body, err := ProxyRequest(ctx, tunnel, http.MethodGet, "/api/health", "", nil, nil)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, status)
@@ -120,7 +120,7 @@ func TestProxyHTTPRequest(t *testing.T) {
c.Request = httptest.NewRequest(http.MethodPost, "/test", bytes.NewBufferString("request body"))
c.Request.Header.Set("X-Custom", "header")
- ProxyHTTPRequest(c, tunnel, "/target/path")
+ ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
assert.Equal(t, http.StatusCreated, w.Code)
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
@@ -176,9 +176,9 @@ func TestProxyHTTPRequest_GRPCTunnel(t *testing.T) {
return
}
- req := msg.GetHttpRequest()
+ req := msg.GetCommandRequest()
if req == nil {
- agentErrCh <- errors.New("expected http request")
+ agentErrCh <- errors.New("expected command request")
return
}
@@ -186,7 +186,7 @@ func TestProxyHTTPRequest_GRPCTunnel(t *testing.T) {
agentErrCh <- errors.New("unexpected method")
return
}
- if req.GetPath() != "/target/path" {
+ if req.GetPath() != "/api/environments/0/projects" {
agentErrCh <- errors.New("unexpected path")
return
}
@@ -207,8 +207,15 @@ func TestProxyHTTPRequest_GRPCTunnel(t *testing.T) {
return
}
- agentErrCh <- stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_HttpResponse{HttpResponse: &tunnelpb.HttpResponse{
- RequestId: req.GetRequestId(),
+ if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
+ CommandId: req.GetCommandId(),
+ }}}); err != nil {
+ agentErrCh <- err
+ return
+ }
+
+ agentErrCh <- stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandComplete{CommandComplete: &tunnelpb.CommandComplete{
+ CommandId: req.GetCommandId(),
Status: http.StatusCreated,
Headers: map[string]string{"Content-Type": "application/json"},
Body: []byte(`{"success":true}`),
@@ -228,7 +235,7 @@ func TestProxyHTTPRequest_GRPCTunnel(t *testing.T) {
c.Request.Header.Set("X-Custom", "header")
c.Request.Header.Set("Connection", "keep-alive")
- ProxyHTTPRequest(c, tunnel, "/target/path")
+ ProxyHTTPRequest(c, tunnel, "/api/environments/0/projects")
assert.Equal(t, http.StatusCreated, w.Code)
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
@@ -255,7 +262,7 @@ func TestDoRequest(t *testing.T) {
defer registry.Unregister("env-do-req")
ctx := context.Background()
- status, body, err := DoRequest(ctx, "env-do-req", "GET", "/path", nil)
+ status, body, err := DoRequest(ctx, "env-do-req", "GET", "/api/health", nil)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, status)
@@ -271,7 +278,7 @@ func TestDoRequest_NoTunnel(t *testing.T) {
func TestHasActiveTunnel(t *testing.T) {
conn := createTestConn(t)
defer func() { _ = conn.Close() }()
- tunnel := NewAgentTunnel("env-active", conn)
+ tunnel := newWebSocketAgentTunnel("env-active", conn)
registry := GetRegistry()
registry.Register("env-active", tunnel)
diff --git a/backend/pkg/libarcane/edge/registry.go b/backend/pkg/libarcane/edge/registry.go
index 1a9735724..25cf9fefe 100644
--- a/backend/pkg/libarcane/edge/registry.go
+++ b/backend/pkg/libarcane/edge/registry.go
@@ -4,8 +4,6 @@ import (
"log/slog"
"sync"
"time"
-
- "github.com/gorilla/websocket"
)
// AgentTunnel represents an active tunnel connection from an edge agent
@@ -15,14 +13,16 @@ type AgentTunnel struct {
Pending sync.Map // map[string]*PendingRequest
ConnectedAt time.Time
LastHeartbeat time.Time
+ SessionID string
+ AgentInstance string
+ Transport string
+ SecurityMode string
+ Capabilities []string
+ State string
+ DisconnectErr string
mu sync.RWMutex
}
-// NewAgentTunnel creates a new agent tunnel.
-func NewAgentTunnel(envID string, conn *websocket.Conn) *AgentTunnel {
- return NewAgentTunnelWithConn(envID, NewTunnelConn(conn))
-}
-
// NewAgentTunnelWithConn creates a new agent tunnel from a transport-agnostic connection.
func NewAgentTunnelWithConn(envID string, conn TunnelConnection) *AgentTunnel {
now := time.Now()
@@ -31,6 +31,7 @@ func NewAgentTunnelWithConn(envID string, conn TunnelConnection) *AgentTunnel {
Conn: conn,
ConnectedAt: now,
LastHeartbeat: now,
+ State: "connected",
}
}
@@ -50,6 +51,17 @@ func (t *AgentTunnel) GetLastHeartbeat() time.Time {
// Close closes the tunnel connection
func (t *AgentTunnel) Close() error {
+ return t.CloseWithReason("")
+}
+
+// CloseWithReason closes the tunnel connection and records the disconnect reason.
+func (t *AgentTunnel) CloseWithReason(reason string) error {
+ t.mu.Lock()
+ t.State = "closed"
+ if reason != "" {
+ t.DisconnectErr = reason
+ }
+ t.mu.Unlock()
return t.Conn.Close()
}
@@ -89,6 +101,44 @@ func (r *TunnelRegistry) Register(envID string, tunnel *AgentTunnel) {
slog.Info("Edge agent tunnel registered")
}
+// RegisterSession adds a tunnel with duplicate-session handling.
+func (r *TunnelRegistry) RegisterSession(tunnel *AgentTunnel, staleAfter time.Duration) (accepted bool, drainPrevious bool, reason string) {
+ if r == nil || tunnel == nil {
+ return false, false, "tunnel is required"
+ }
+
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ envID := tunnel.EnvironmentID
+ if envID == "" {
+ return false, false, "environment ID is required"
+ }
+
+ if existing, ok := r.tunnels[envID]; ok && existing != nil {
+ if existing == tunnel {
+ return true, false, ""
+ }
+
+ existingStale := staleAfter > 0 && time.Since(existing.GetLastHeartbeat()) > staleAfter
+ sameAgentInstance := existing.AgentInstance != "" && tunnel.AgentInstance != "" && existing.AgentInstance == tunnel.AgentInstance
+ legacyReplace := existing.AgentInstance == "" || tunnel.AgentInstance == ""
+
+ if existing.Conn == nil || existing.Conn.IsClosed() || existingStale || sameAgentInstance || legacyReplace {
+ if sameAgentInstance {
+ drainPrevious = true
+ }
+ _ = existing.CloseWithReason("replaced by newer edge tunnel session")
+ } else {
+ return false, false, "another edge agent session is already active"
+ }
+ }
+
+ r.tunnels[envID] = tunnel
+ slog.Info("Edge agent tunnel registered", "environment_id", envID, "session_id", tunnel.SessionID, "security_mode", tunnel.SecurityMode)
+ return true, drainPrevious, ""
+}
+
// Unregister removes a tunnel from the registry
func (r *TunnelRegistry) Unregister(envID string) {
r.mu.Lock()
@@ -101,6 +151,31 @@ func (r *TunnelRegistry) Unregister(envID string) {
}
}
+// UnregisterCurrent removes the active tunnel only when it still matches the
+// provided tunnel reference. It reports whether the tunnel was removed and
+// whether another active session for the environment is already present.
+func (r *TunnelRegistry) UnregisterCurrent(envID string, current *AgentTunnel) (removed bool, activeReplacement bool) {
+ if r == nil || current == nil {
+ return false, false
+ }
+
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ existing, ok := r.tunnels[envID]
+ if !ok || existing != current {
+ if ok && existing != nil && !existing.Conn.IsClosed() {
+ return false, true
+ }
+ return false, false
+ }
+
+ _ = existing.Close()
+ delete(r.tunnels, envID)
+ slog.Info("Edge agent tunnel unregistered", "environment_id", envID, "session_id", current.SessionID)
+ return true, false
+}
+
// CleanupStale removes tunnels that haven't had a heartbeat within the given duration
func (r *TunnelRegistry) CleanupStale(maxAge time.Duration) int {
r.mu.Lock()
diff --git a/backend/pkg/libarcane/edge/registry_test.go b/backend/pkg/libarcane/edge/registry_test.go
index 05fa5884c..e33724bb7 100644
--- a/backend/pkg/libarcane/edge/registry_test.go
+++ b/backend/pkg/libarcane/edge/registry_test.go
@@ -35,7 +35,7 @@ func TestTunnelRegistry(t *testing.T) {
// Create a tunnel
conn := createTestConn(t)
defer func() { _ = conn.Close() }()
- tunnel := NewAgentTunnel(envID, conn)
+ tunnel := newWebSocketAgentTunnel(envID, conn)
// Register
r.Register(envID, tunnel)
@@ -60,12 +60,12 @@ func TestTunnelRegistry_RegisterReplace(t *testing.T) {
conn1 := createTestConn(t)
defer func() { _ = conn1.Close() }()
- tunnel1 := NewAgentTunnel(envID, conn1)
+ tunnel1 := newWebSocketAgentTunnel(envID, conn1)
r.Register(envID, tunnel1)
conn2 := createTestConn(t)
defer func() { _ = conn2.Close() }()
- tunnel2 := NewAgentTunnel(envID, conn2)
+ tunnel2 := newWebSocketAgentTunnel(envID, conn2)
// Register replacement
r.Register(envID, tunnel2)
@@ -80,13 +80,75 @@ func TestTunnelRegistry_RegisterReplace(t *testing.T) {
assert.False(t, tunnel2.Conn.IsClosed())
}
+func TestTunnelRegistry_RegisterSessionRejectsCompetingAgent(t *testing.T) {
+ r := NewTunnelRegistry()
+ envID := "env-session-reject"
+
+ conn1 := createTestConn(t)
+ defer func() { _ = conn1.Close() }()
+ tunnel1 := newWebSocketAgentTunnel(envID, conn1)
+ tunnel1.AgentInstance = "agent-a"
+ tunnel1.SessionID = "session-a"
+
+ accepted, drainPrevious, reason := r.RegisterSession(tunnel1, TunnelStaleTimeout)
+ assert.True(t, accepted)
+ assert.False(t, drainPrevious)
+ assert.Equal(t, "", reason)
+
+ conn2 := createTestConn(t)
+ defer func() { _ = conn2.Close() }()
+ tunnel2 := newWebSocketAgentTunnel(envID, conn2)
+ tunnel2.AgentInstance = "agent-b"
+ tunnel2.SessionID = "session-b"
+
+ accepted, drainPrevious, reason = r.RegisterSession(tunnel2, TunnelStaleTimeout)
+ assert.False(t, accepted)
+ assert.False(t, drainPrevious)
+ assert.Equal(t, "another edge agent session is already active", reason)
+
+ got, ok := r.Get(envID)
+ assert.True(t, ok)
+ assert.Equal(t, tunnel1, got)
+ assert.False(t, tunnel1.Conn.IsClosed())
+}
+
+func TestTunnelRegistry_RegisterSessionReplacesSameAgentInstance(t *testing.T) {
+ r := NewTunnelRegistry()
+ envID := "env-session-replace"
+
+ conn1 := createTestConn(t)
+ defer func() { _ = conn1.Close() }()
+ tunnel1 := newWebSocketAgentTunnel(envID, conn1)
+ tunnel1.AgentInstance = "agent-a"
+ tunnel1.SessionID = "session-a"
+ accepted, drainPrevious, reason := r.RegisterSession(tunnel1, TunnelStaleTimeout)
+ assert.True(t, accepted)
+ assert.False(t, drainPrevious)
+ assert.Equal(t, "", reason)
+
+ conn2 := createTestConn(t)
+ defer func() { _ = conn2.Close() }()
+ tunnel2 := newWebSocketAgentTunnel(envID, conn2)
+ tunnel2.AgentInstance = "agent-a"
+ tunnel2.SessionID = "session-b"
+ accepted, drainPrevious, reason = r.RegisterSession(tunnel2, TunnelStaleTimeout)
+ assert.True(t, accepted)
+ assert.True(t, drainPrevious)
+ assert.Equal(t, "", reason)
+ assert.True(t, tunnel1.Conn.IsClosed())
+
+ got, ok := r.Get(envID)
+ assert.True(t, ok)
+ assert.Equal(t, tunnel2, got)
+}
+
func TestTunnelRegistry_CleanupStale(t *testing.T) {
r := NewTunnelRegistry()
envID := "env-1"
conn := createTestConn(t)
defer func() { _ = conn.Close() }()
- tunnel := NewAgentTunnel(envID, conn)
+ tunnel := newWebSocketAgentTunnel(envID, conn)
// Manually set last heartbeat to past
tunnel.mu.Lock()
@@ -113,7 +175,7 @@ func TestGetRegistry(t *testing.T) {
func TestAgentTunnel_Heartbeat(t *testing.T) {
conn := createTestConn(t)
defer func() { _ = conn.Close() }()
- tunnel := NewAgentTunnel("env-1", conn)
+ tunnel := newWebSocketAgentTunnel("env-1", conn)
initial := tunnel.GetLastHeartbeat()
time.Sleep(10 * time.Millisecond)
diff --git a/backend/pkg/libarcane/edge/server.go b/backend/pkg/libarcane/edge/server.go
index 37fea405f..203847cdd 100644
--- a/backend/pkg/libarcane/edge/server.go
+++ b/backend/pkg/libarcane/edge/server.go
@@ -2,6 +2,7 @@ package edge
import (
"context"
+ "crypto/tls"
"errors"
"io"
"log/slog"
@@ -12,10 +13,13 @@ import (
tunnelpb "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge/proto/tunnel/v1"
"github.com/gin-gonic/gin"
+ "github.com/google/uuid"
"github.com/gorilla/websocket"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
@@ -37,6 +41,9 @@ var tunnelUpgrader = websocket.Upgrader{
// EnvironmentResolver resolves an agent token to an environment ID.
type EnvironmentResolver func(ctx context.Context, token string) (environmentID string, err error)
+// EnvironmentNameResolver resolves a display name for an environment ID.
+type EnvironmentNameResolver func(ctx context.Context, environmentID string) (environmentName string, err error)
+
// StatusUpdateCallback is called when an edge agent connects or disconnects.
// The connected parameter is true on connect, false on disconnect.
type StatusUpdateCallback func(ctx context.Context, environmentID string, connected bool)
@@ -44,13 +51,23 @@ type StatusUpdateCallback func(ctx context.Context, environmentID string, connec
// EventCallback is called when an edge agent publishes an event.
type EventCallback func(ctx context.Context, environmentID string, event *TunnelEvent) error
+// EnrollmentCallback is called after a successful manager-side mTLS enrollment
+// of an edge agent, allowing the host to record audit events or metrics.
+// remoteAddr is the client socket address as seen by the manager.
+// reenrolled is true when an environment that had already enrolled receives
+// assets again after the enrollment cooldown.
+type EnrollmentCallback func(ctx context.Context, environmentID, remoteAddr string, certIssued bool, caGenerated bool, reenrolled bool)
+
// TunnelServer handles incoming edge agent connections on the manager side.
type TunnelServer struct {
- registry *TunnelRegistry
- resolver EnvironmentResolver
- statusCallback StatusUpdateCallback
- eventCallback EventCallback
- cleanupDone chan struct{}
+ registry *TunnelRegistry
+ resolver EnvironmentResolver
+ nameResolver EnvironmentNameResolver
+ statusCallback StatusUpdateCallback
+ eventCallback EventCallback
+ enrollmentCallback EnrollmentCallback
+ cleanupDone chan struct{}
+ cfg *Config
}
// NewTunnelServer creates a new tunnel server.
@@ -72,6 +89,14 @@ func NewTunnelServerWithRegistry(registry *TunnelRegistry, resolver EnvironmentR
}
}
+// SetEnvironmentNameResolver configures environment name lookup for manager-generated assets.
+func (s *TunnelServer) SetEnvironmentNameResolver(resolver EnvironmentNameResolver) {
+ if s == nil {
+ return
+ }
+ s.nameResolver = resolver
+}
+
type resolvedEnvironmentIDKey struct{}
// GRPCServerOptions returns the stream interceptor chain used by the tunnel service.
@@ -91,40 +116,169 @@ func (s *TunnelServer) SetEventCallback(callback EventCallback) {
s.eventCallback = callback
}
+// SetEnrollmentCallback configures the manager callback invoked after
+// a successful edge mTLS enrollment. Passing nil clears the callback.
+func (s *TunnelServer) SetEnrollmentCallback(callback EnrollmentCallback) {
+ if s == nil {
+ return
+ }
+ s.enrollmentCallback = callback
+}
+
+// SetConfig attaches edge tunnel runtime config to the manager-side server.
+func (s *TunnelServer) SetConfig(cfg *Config) {
+ s.cfg = cfg
+}
+
// HandleConnect is the WebSocket handler for edge agent connections.
// This is registered at /api/tunnel/connect.
func (s *TunnelServer) HandleConnect(c *gin.Context) {
ctx := c.Request.Context()
callbackCtx := context.WithoutCancel(ctx)
- // Get agent token from headers.
- token := c.GetHeader(HeaderAgentToken)
+ if err := s.requireClientCertificateInternal(c.Request); err != nil {
+ slog.WarnContext(ctx, "Rejected websocket edge tunnel without required client certificate", "error", err)
+ c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
+ return
+ }
+
+ // Upgrade to WebSocket.
+ conn, err := tunnelUpgrader.Upgrade(c.Writer, c.Request, nil)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to upgrade edge tunnel connection", "error", err)
+ return
+ }
+
+ tunnelConn := NewTunnelConn(conn)
+ firstMsg, err := tunnelConn.Receive()
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to receive websocket edge tunnel registration", "error", err)
+ _ = tunnelConn.Close()
+ return
+ }
+ if firstMsg == nil || firstMsg.Type != MessageTypeRegister {
+ slog.WarnContext(ctx, "Websocket edge tunnel missing register message")
+ _ = tunnelConn.Close()
+ return
+ }
+
+ token := tokenFromHeadersInternal(c.Request)
if token == "" {
- token = c.GetHeader(HeaderAPIKey)
+ // Header auth can be unavailable after the WebSocket upgrade path, so
+ // the register message remains a fallback token source. Treat it only
+ // as an auth claim; mTLS identity is verified separately below against
+ // the environment resolved from this token.
+ token = strings.TrimSpace(firstMsg.AgentToken)
}
if token == "" {
slog.WarnContext(ctx, "Edge tunnel connection attempt without token")
- c.JSON(http.StatusUnauthorized, gin.H{"error": "agent token required"})
+ _ = tunnelConn.Send(&TunnelMessage{Type: MessageTypeRegisterResponse, Accepted: false, Error: "agent token required"})
+ _ = tunnelConn.Close()
return
}
- // Resolve token to environment ID.
envID, err := s.resolveEnvironment(ctx, token)
if err != nil {
slog.WarnContext(ctx, "Failed to resolve agent token", "error", err)
+ _ = tunnelConn.Send(&TunnelMessage{Type: MessageTypeRegisterResponse, Accepted: false, Error: "invalid agent token"})
+ _ = tunnelConn.Close()
+ return
+ }
+ if err := s.requireCertificateIdentityInternal(c.Request.TLS, envID); err != nil {
+ slog.WarnContext(ctx, "Rejected websocket edge tunnel with mismatched client certificate", "environment_id", envID, "error", err)
+ _ = tunnelConn.Send(&TunnelMessage{Type: MessageTypeRegisterResponse, Accepted: false, Error: "client certificate does not match environment"})
+ _ = tunnelConn.Close()
+ return
+ }
+
+ tunnel := NewAgentTunnelWithConn(envID, tunnelConn)
+ s.populateSessionMetadata(tunnel, firstMsg, requestSecurityModeInternal(c.Request))
+ s.manageConnectedTunnel(ctx, callbackCtx, tunnel)
+}
+
+// HandleMTLSEnroll returns manager-generated edge client certificates for the
+// calling environment when generated edge mTLS is enabled. The response includes
+// private key material, so response-body logging must not be enabled here.
+func (s *TunnelServer) HandleMTLSEnroll(c *gin.Context) {
+ ctx := c.Request.Context()
+ c.Header("Cache-Control", "no-store")
+ c.Header("Pragma", "no-cache")
+
+ if s == nil || s.cfg == nil || !shouldUseGeneratedManagerCAInternal(s.cfg) {
+ c.JSON(http.StatusNotFound, gin.H{"error": "edge mTLS enrollment is not available"})
+ return
+ }
+
+ token := tokenFromHeadersInternal(c.Request)
+ if token == "" {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "agent token required"})
+ return
+ }
+
+ envID, err := s.resolveEnvironment(ctx, token)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to resolve edge token for mTLS enrollment", "error", err)
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid agent token"})
return
}
- // Upgrade to WebSocket.
- conn, err := tunnelUpgrader.Upgrade(c.Writer, c.Request, nil)
+ envName := ""
+ if s.nameResolver != nil {
+ resolvedName, resolveErr := s.nameResolver(ctx, envID)
+ if resolveErr != nil {
+ slog.WarnContext(ctx, "Failed to resolve environment name for edge mTLS enrollment", "environment_id", envID, "error", resolveErr)
+ } else {
+ envName = resolvedName
+ }
+ }
+
+ now := time.Now()
+ previouslyEnrolled, enrollmentLimited, err := managerMTLSEnrollmentStateInternal(s.cfg, envID, now)
if err != nil {
- slog.ErrorContext(ctx, "Failed to upgrade edge tunnel connection", "error", err)
+ slog.ErrorContext(ctx, "Failed to read edge mTLS enrollment state", "environment_id", envID, "error", err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read edge mTLS enrollment state"})
+ return
+ }
+ if enrollmentLimited {
+ cachedAssets, cacheErr := GenerateManagerClientMTLSAssetsWithContext(ctx, s.cfg, envID, envName)
+ if cacheErr == nil && cachedAssets != nil {
+ slog.InfoContext(ctx, "Served cached edge mTLS enrollment during cooldown", "environment_id", envID, "remote_addr", c.ClientIP())
+ c.JSON(http.StatusOK, enrollMTLSResponse{Files: cachedAssets.Files})
+ return
+ }
+ if cacheErr != nil {
+ slog.WarnContext(ctx, "Failed to re-serve cached edge mTLS enrollment during cooldown", "environment_id", envID, "error", cacheErr)
+ }
+ slog.WarnContext(ctx, "Rejected repeated edge mTLS enrollment during cooldown", "environment_id", envID, "remote_addr", c.ClientIP())
+ c.JSON(http.StatusTooManyRequests, gin.H{"error": "edge mTLS enrollment was recently completed; retry later"})
return
}
- tunnel := NewAgentTunnel(envID, conn)
- s.manageConnectedTunnel(ctx, callbackCtx, tunnel)
+ assets, err := GenerateManagerClientMTLSAssetsWithContext(ctx, s.cfg, envID, envName)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to generate edge mTLS enrollment assets", "environment_id", envID, "error", err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate edge mTLS assets"})
+ return
+ }
+ if assets == nil {
+ c.JSON(http.StatusNotFound, gin.H{"error": "edge mTLS enrollment assets unavailable"})
+ return
+ }
+ assets.Reenrolled = previouslyEnrolled
+ if err := recordManagerMTLSEnrollmentInternal(s.cfg, envID, now); err != nil {
+ slog.ErrorContext(ctx, "Failed to record edge mTLS enrollment state", "environment_id", envID, "error", err)
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to record edge mTLS enrollment state"})
+ return
+ }
+ if assets.Reenrolled {
+ slog.WarnContext(ctx, "Edge mTLS certificate assets re-enrolled", "environment_id", envID, "remote_addr", c.ClientIP(), "cert_issued", assets.CertIssued)
+ }
+
+ if s.enrollmentCallback != nil {
+ s.enrollmentCallback(context.WithoutCancel(ctx), envID, c.ClientIP(), assets.CertIssued, assets.CAGenerated, assets.Reenrolled)
+ }
+
+ c.JSON(http.StatusOK, enrollMTLSResponse{Files: assets.Files})
}
// Connect is the gRPC bidi stream handler for edge agent connections.
@@ -163,12 +317,43 @@ func (s *TunnelServer) Connect(stream grpc.BidiStreamingServer[tunnelpb.AgentMes
return status.Error(codes.Unauthenticated, "invalid agent token")
}
}
+ if err := s.requireCertificateIdentityFromContextInternal(ctx, envID); err != nil {
+ return status.Error(codes.Unauthenticated, err.Error())
+ }
tunnel := NewAgentTunnelWithConn(envID, NewGRPCManagerTunnelConn(stream))
+ s.populateSessionMetadata(tunnel, &TunnelMessage{
+ AgentInstance: register.GetAgentInstanceId(),
+ Capabilities: append([]string(nil), register.GetCapabilities()...),
+ ResumeSession: register.GetResumeSessionId(),
+ }, securityModeFromGRPCContextInternal(ctx))
s.manageConnectedTunnel(ctx, callbackCtx, tunnel)
return nil
}
+func (s *TunnelServer) populateSessionMetadata(tunnel *AgentTunnel, registerMsg *TunnelMessage, securityMode string) {
+ if tunnel == nil {
+ return
+ }
+
+ tunnel.SessionID = uuid.NewString()
+ tunnel.SecurityMode = securityMode
+ if tunnel.SecurityMode == "" {
+ tunnel.SecurityMode = "token"
+ }
+ if registerMsg != nil {
+ tunnel.AgentInstance = strings.TrimSpace(registerMsg.AgentInstance)
+ tunnel.Capabilities = append([]string(nil), registerMsg.Capabilities...)
+ }
+
+ switch tunnel.Conn.(type) {
+ case *GRPCManagerTunnelConn:
+ tunnel.Transport = EdgeTransportGRPC
+ default:
+ tunnel.Transport = EdgeTransportWebSocket
+ }
+}
+
func (s *TunnelServer) resolveEnvironment(ctx context.Context, token string) (string, error) {
if s.resolver == nil {
return "", errors.New("edge resolver is not configured")
@@ -200,31 +385,68 @@ func tokenFromMetadata(ctx context.Context) string {
return ""
}
-func (s *TunnelServer) manageConnectedTunnel(ctx context.Context, callbackCtx context.Context, tunnel *AgentTunnel) {
- slog.InfoContext(ctx, "Edge agent connected", "environment_id", tunnel.EnvironmentID)
+func tokenFromHeadersInternal(req *http.Request) string {
+ if req == nil {
+ return ""
+ }
+ for _, header := range []string{HeaderAgentToken, HeaderAPIKey} {
+ if token := strings.TrimSpace(req.Header.Get(header)); token != "" {
+ return token
+ }
+ }
+ return ""
+}
- if _, ok := tunnel.Conn.(*GRPCManagerTunnelConn); ok {
- if err := tunnel.Conn.Send(&TunnelMessage{
+func (s *TunnelServer) manageConnectedTunnel(ctx context.Context, callbackCtx context.Context, tunnel *AgentTunnel) {
+ accepted, drainPrevious, rejectReason := s.registry.RegisterSession(tunnel, TunnelStaleTimeout)
+ if !accepted {
+ slog.WarnContext(ctx, "Rejected duplicate edge agent session",
+ "environment_id", tunnel.EnvironmentID,
+ "agent_instance_id", tunnel.AgentInstance,
+ "reason", rejectReason,
+ )
+ _ = tunnel.Conn.Send(&TunnelMessage{
Type: MessageTypeRegisterResponse,
- Accepted: true,
+ Accepted: false,
EnvironmentID: tunnel.EnvironmentID,
- }); err != nil {
- slog.WarnContext(ctx, "Failed to send register response", "environment_id", tunnel.EnvironmentID, "error", err)
- _ = tunnel.Close()
- return
- }
+ Error: rejectReason,
+ })
+ _ = tunnel.CloseWithReason(rejectReason)
+ return
}
- s.registry.Register(tunnel.EnvironmentID, tunnel)
+ slog.InfoContext(ctx, "Edge agent connected",
+ "environment_id", tunnel.EnvironmentID,
+ "session_id", tunnel.SessionID,
+ "security_mode", tunnel.SecurityMode,
+ )
+
+ if err := tunnel.Conn.Send(&TunnelMessage{
+ Type: MessageTypeRegisterResponse,
+ Accepted: true,
+ EnvironmentID: tunnel.EnvironmentID,
+ SessionID: tunnel.SessionID,
+ SecurityMode: tunnel.SecurityMode,
+ Capabilities: append([]string(nil), tunnel.Capabilities...),
+ DrainPrevious: drainPrevious,
+ }); err != nil {
+ slog.WarnContext(ctx, "Failed to send register response", "environment_id", tunnel.EnvironmentID, "error", err)
+ _ = tunnel.Close()
+ _, _ = s.registry.UnregisterCurrent(tunnel.EnvironmentID, tunnel)
+ return
+ }
if s.statusCallback != nil {
s.statusCallback(callbackCtx, tunnel.EnvironmentID, true)
}
defer func() {
- s.registry.Unregister(tunnel.EnvironmentID)
- slog.InfoContext(ctx, "Edge agent disconnected", "environment_id", tunnel.EnvironmentID)
- if s.statusCallback != nil {
+ removed, active := s.registry.UnregisterCurrent(tunnel.EnvironmentID, tunnel)
+ if !removed {
+ return
+ }
+ slog.InfoContext(ctx, "Edge agent disconnected", "environment_id", tunnel.EnvironmentID, "session_id", tunnel.SessionID)
+ if s.statusCallback != nil && !active {
s.statusCallback(callbackCtx, tunnel.EnvironmentID, false)
}
}()
@@ -258,11 +480,13 @@ func (s *TunnelServer) handleTunnelMessage(ctx context.Context, tunnel *AgentTun
s.handleHeartbeat(ctx, tunnel, msg)
case MessageTypeResponse:
s.deliverResponse(ctx, tunnel, msg)
+ case MessageTypeCommandAck, MessageTypeCommandOutput, MessageTypeCommandComplete, MessageTypeFileChunk:
+ s.deliverResponse(ctx, tunnel, msg)
case MessageTypeEvent:
s.handleEvent(ctx, tunnel, msg)
- case MessageTypeStreamData, MessageTypeStreamEnd, MessageTypeWebSocketData, MessageTypeWebSocketClose:
+ case MessageTypeStreamData, MessageTypeStreamEnd, MessageTypeWebSocketData, MessageTypeWebSocketClose, MessageTypeStreamClose:
s.deliverStream(ctx, tunnel, msg)
- case MessageTypeRequest, MessageTypeHeartbeatAck, MessageTypeWebSocketStart, MessageTypeRegisterResponse:
+ case MessageTypeRequest, MessageTypeHeartbeatAck, MessageTypeWebSocketStart, MessageTypeRegisterResponse, MessageTypeCommandRequest, MessageTypeStreamOpen, MessageTypeCancelRequest:
slog.DebugContext(ctx, "Ignoring message type from agent", "type", msg.Type, "environment_id", tunnel.EnvironmentID)
case MessageTypeRegister:
slog.DebugContext(ctx, "Ignoring duplicate register message from agent", "environment_id", tunnel.EnvironmentID)
@@ -357,17 +581,26 @@ func (s *TunnelServer) WaitForCleanupDone() {
func (s *TunnelServer) authStreamInterceptorInternal(ctx context.Context) grpc.StreamServerInterceptor {
_ = ctx
+ // TunnelService currently exposes only Connect. Keep this explicit method
+ // gate aligned with tunnel.proto if new RPCs are added.
//nolint:contextcheck // Stream interceptors receive request-scoped context from grpc.ServerStream.
return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if info == nil || info.FullMethod != tunnelpb.TunnelService_Connect_FullMethodName {
return handler(srv, ss)
}
+ if err := s.requireClientCertificateFromContextInternal(ss.Context()); err != nil {
+ return status.Error(codes.Unauthenticated, err.Error())
+ }
+
token := tokenFromMetadata(ss.Context())
envID, err := s.resolveEnvironment(ss.Context(), token)
if err != nil {
return status.Error(codes.Unauthenticated, "invalid agent token")
}
+ if err := s.requireCertificateIdentityFromContextInternal(ss.Context(), envID); err != nil {
+ return status.Error(codes.Unauthenticated, err.Error())
+ }
ctx := context.WithValue(ss.Context(), resolvedEnvironmentIDKey{}, envID)
return handler(srv, &contextualServerStream{ServerStream: ss, ctx: ctx})
@@ -434,3 +667,65 @@ func resolvedEnvironmentIDFromContextInternal(ctx context.Context) (string, bool
return envID, true
}
+
+func (s *TunnelServer) requireClientCertificateInternal(req *http.Request) error {
+ if NormalizeEdgeMTLSMode(s.edgeMTLSModeInternal()) != EdgeMTLSModeRequired {
+ return nil
+ }
+ if hasVerifiedPeerCertificateInternal(req.TLS) {
+ return nil
+ }
+ return errors.New("verified client certificate required")
+}
+
+func (s *TunnelServer) requireClientCertificateFromContextInternal(ctx context.Context) error {
+ if NormalizeEdgeMTLSMode(s.edgeMTLSModeInternal()) != EdgeMTLSModeRequired {
+ return nil
+ }
+
+ p, ok := peer.FromContext(ctx)
+ if !ok {
+ return errors.New("verified client certificate required")
+ }
+ if tlsInfo, ok := p.AuthInfo.(credentials.TLSInfo); ok && hasVerifiedPeerCertificateInternal(&tlsInfo.State) {
+ return nil
+ }
+ return errors.New("verified client certificate required")
+}
+
+func (s *TunnelServer) requireCertificateIdentityInternal(state *tls.ConnectionState, envID string) error {
+ if NormalizeEdgeMTLSMode(s.edgeMTLSModeInternal()) == EdgeMTLSModeDisabled {
+ return nil
+ }
+ return verifiedPeerCertificateEnvironmentIDMatchesInternal(state, envID, edgeMTLSTrustDomainInternal(s.cfg))
+}
+
+func (s *TunnelServer) requireCertificateIdentityFromContextInternal(ctx context.Context, envID string) error {
+ if NormalizeEdgeMTLSMode(s.edgeMTLSModeInternal()) == EdgeMTLSModeDisabled {
+ return nil
+ }
+ p, ok := peer.FromContext(ctx)
+ if !ok {
+ return nil
+ }
+ tlsInfo, ok := p.AuthInfo.(credentials.TLSInfo)
+ if !ok {
+ return nil
+ }
+ return verifiedPeerCertificateEnvironmentIDMatchesInternal(&tlsInfo.State, envID, edgeMTLSTrustDomainInternal(s.cfg))
+}
+
+func (s *TunnelServer) edgeMTLSModeInternal() string {
+ if s == nil || s.cfg == nil {
+ return EdgeMTLSModeDisabled
+ }
+ return s.cfg.EdgeMTLSMode
+}
+
+func securityModeFromGRPCContextInternal(ctx context.Context) string {
+ p, ok := peer.FromContext(ctx)
+ if !ok {
+ return "token"
+ }
+ return grpcContextSecurityModeInternal(*p)
+}
diff --git a/backend/pkg/libarcane/edge/server_test.go b/backend/pkg/libarcane/edge/server_test.go
index 56b7e7a9b..1daf9bce9 100644
--- a/backend/pkg/libarcane/edge/server_test.go
+++ b/backend/pkg/libarcane/edge/server_test.go
@@ -2,10 +2,14 @@ package edge
import (
"context"
+ "crypto/x509"
+ "encoding/json"
+ "encoding/pem"
"errors"
"io"
"net/http"
"net/http/httptest"
+ "os"
"strings"
"sync"
"testing"
@@ -62,14 +66,28 @@ func TestTunnelServer_HandleConnect(t *testing.T) {
assert.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode)
+ err = conn.WriteJSON(&TunnelMessage{
+ Type: MessageTypeRegister,
+ AgentToken: "valid-token",
+ AgentInstance: "agent-connected",
+ })
+ require.NoError(t, err)
+
+ var registerResp TunnelMessage
+ err = conn.ReadJSON(&registerResp)
+ require.NoError(t, err)
+ assert.Equal(t, MessageTypeRegisterResponse, registerResp.Type)
+ assert.True(t, registerResp.Accepted)
+
// Check registry
reg := GetRegistry()
var tunnel *AgentTunnel
require.Eventually(t, func() bool {
var ok bool
tunnel, ok = reg.Get("env-connected")
- return ok && tunnel != nil
+ return ok && tunnel != nil && tunnel.SessionID != ""
}, time.Second, 10*time.Millisecond)
+ assert.Equal(t, "agent-connected", tunnel.AgentInstance)
select {
case <-statusCallbackCalled:
@@ -170,12 +188,67 @@ func TestTunnelServer_HandleConnect_InvalidToken(t *testing.T) {
headers := http.Header{}
headers.Set(HeaderAgentToken, "bad-token")
- _, resp, err := websocket.DefaultDialer.Dial(url, headers)
- require.Error(t, err)
+ conn, resp, err := websocket.DefaultDialer.Dial(url, headers)
+ require.NoError(t, err)
if resp != nil {
defer func() { _ = resp.Body.Close() }()
}
- assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
+ defer func() { _ = conn.Close() }()
+ assert.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode)
+
+ err = conn.WriteJSON(&TunnelMessage{Type: MessageTypeRegister, AgentToken: "bad-token"})
+ require.NoError(t, err)
+
+ var registerResp TunnelMessage
+ err = conn.ReadJSON(&registerResp)
+ require.NoError(t, err)
+ assert.Equal(t, MessageTypeRegisterResponse, registerResp.Type)
+ assert.False(t, registerResp.Accepted)
+ assert.Equal(t, "invalid agent token", registerResp.Error)
+}
+
+func TestTunnelServer_HandleConnect_PrefersHeaderTokenOverRegisterMessage(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ var resolvedToken string
+ resolver := func(ctx context.Context, token string) (string, error) {
+ resolvedToken = token
+ if token == "valid-token" {
+ return "env-header-token", nil
+ }
+ return "", errors.New("invalid token")
+ }
+
+ server := NewTunnelServer(resolver, nil)
+ router := gin.New()
+ router.GET("/connect", server.HandleConnect)
+
+ ts := httptest.NewServer(router)
+ defer ts.Close()
+
+ url := "ws" + strings.TrimPrefix(ts.URL, "http") + "/connect"
+ headers := http.Header{}
+ headers.Set(HeaderAgentToken, "valid-token")
+
+ conn, resp, err := websocket.DefaultDialer.Dial(url, headers)
+ require.NoError(t, err)
+ if resp != nil {
+ defer func() { _ = resp.Body.Close() }()
+ }
+ defer func() { _ = conn.Close() }()
+ require.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode)
+
+ err = conn.WriteJSON(&TunnelMessage{Type: MessageTypeRegister, AgentToken: "bad-token"})
+ require.NoError(t, err)
+
+ var registerResp TunnelMessage
+ err = conn.ReadJSON(&registerResp)
+ require.NoError(t, err)
+ require.Equal(t, MessageTypeRegisterResponse, registerResp.Type)
+ require.True(t, registerResp.Accepted)
+ require.Equal(t, "valid-token", resolvedToken)
+
+ GetRegistry().Unregister("env-header-token")
}
func TestTunnelServer_HandleConnect_NoToken(t *testing.T) {
@@ -188,12 +261,23 @@ func TestTunnelServer_HandleConnect_NoToken(t *testing.T) {
url := "ws" + strings.TrimPrefix(ts.URL, "http") + "/connect"
- _, resp, err := websocket.DefaultDialer.Dial(url, nil)
- require.Error(t, err)
+ conn, resp, err := websocket.DefaultDialer.Dial(url, nil)
+ require.NoError(t, err)
if resp != nil {
defer func() { _ = resp.Body.Close() }()
}
- assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
+ defer func() { _ = conn.Close() }()
+ assert.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode)
+
+ err = conn.WriteJSON(&TunnelMessage{Type: MessageTypeRegister})
+ require.NoError(t, err)
+
+ var registerResp TunnelMessage
+ err = conn.ReadJSON(&registerResp)
+ require.NoError(t, err)
+ require.Equal(t, MessageTypeRegisterResponse, registerResp.Type)
+ require.False(t, registerResp.Accepted)
+ require.Equal(t, "agent token required", registerResp.Error)
}
func TestTunnelConnectRouteRegistration(t *testing.T) {
@@ -209,8 +293,136 @@ func TestTunnelConnectRouteRegistration(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/tunnel/connect", nil)
router.ServeHTTP(w, req)
- // Should be 401 because no token, which means the handler was reached
- assert.Equal(t, http.StatusUnauthorized, w.Code)
+ // Plain HTTP requests hit the route but fail websocket upgrade.
+ assert.Equal(t, http.StatusBadRequest, w.Code)
+}
+
+func TestTunnelServer_HandleMTLSEnroll(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ server := NewTunnelServer(func(ctx context.Context, token string) (string, error) {
+ if token != "valid-token" {
+ return "", errors.New("invalid token")
+ }
+ return "env-mtls", nil
+ }, nil)
+ server.SetEnvironmentNameResolver(func(ctx context.Context, environmentID string) (string, error) {
+ require.Equal(t, "env-mtls", environmentID)
+ return "Lab Server", nil
+ })
+ server.SetConfig(&Config{
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ })
+
+ router := gin.New()
+ router.POST("/enroll", server.HandleMTLSEnroll)
+
+ req := httptest.NewRequest(http.MethodPost, "/enroll", nil)
+ req.Header.Set(HeaderAgentToken, "valid-token")
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+
+ require.Equal(t, http.StatusOK, w.Code)
+ require.Equal(t, "no-store", w.Header().Get("Cache-Control"))
+ require.Equal(t, "no-cache", w.Header().Get("Pragma"))
+
+ var resp enrollMTLSResponse
+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
+ require.Len(t, resp.Files, 3)
+ assert.Equal(t, "ca.crt", resp.Files[0].Name)
+ assert.Contains(t, resp.Files[0].Content, "BEGIN CERTIFICATE")
+ assert.Equal(t, "agent.key", resp.Files[2].Name)
+ assert.Contains(t, resp.Files[2].Content, "BEGIN EC PRIVATE KEY")
+
+ certBlock, _ := pem.Decode([]byte(resp.Files[1].Content))
+ require.NotNil(t, certBlock)
+
+ cert, err := x509.ParseCertificate(certBlock.Bytes)
+ require.NoError(t, err)
+ assert.Equal(t, "Lab-Server-env-mtls", cert.Subject.CommonName)
+}
+
+func TestTunnelServer_HandleMTLSEnroll_ServesCachedAssetsDuringCooldown(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ server := NewTunnelServer(func(ctx context.Context, token string) (string, error) {
+ if token != "valid-token" {
+ return "", errors.New("invalid token")
+ }
+ return "env-repeat", nil
+ }, nil)
+ server.SetConfig(&Config{
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ })
+
+ router := gin.New()
+ router.POST("/enroll", server.HandleMTLSEnroll)
+
+ req := httptest.NewRequest(http.MethodPost, "/enroll", nil)
+ req.Header.Set(HeaderAgentToken, "valid-token")
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ require.Equal(t, http.StatusOK, w.Code)
+
+ var firstResp enrollMTLSResponse
+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &firstResp))
+ require.Len(t, firstResp.Files, 3)
+
+ req = httptest.NewRequest(http.MethodPost, "/enroll", nil)
+ req.Header.Set(HeaderAgentToken, "valid-token")
+ w = httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ require.Equal(t, http.StatusOK, w.Code)
+
+ var secondResp enrollMTLSResponse
+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &secondResp))
+ require.Equal(t, firstResp.Files, secondResp.Files)
+}
+
+func TestTunnelServer_HandleMTLSEnroll_AllowsRepeatAfterCooldownAndMarksReenrollment(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ cfg := &Config{
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ }
+ server := NewTunnelServer(func(ctx context.Context, token string) (string, error) {
+ if token != "valid-token" {
+ return "", errors.New("invalid token")
+ }
+ return "env-repeat-old", nil
+ }, nil)
+ server.SetConfig(cfg)
+
+ reenrolled := make(chan bool, 2)
+ server.SetEnrollmentCallback(func(ctx context.Context, environmentID, remoteAddr string, certIssued bool, caGenerated bool, wasReenrolled bool) {
+ require.Equal(t, "env-repeat-old", environmentID)
+ reenrolled <- wasReenrolled
+ })
+
+ router := gin.New()
+ router.POST("/enroll", server.HandleMTLSEnroll)
+
+ req := httptest.NewRequest(http.MethodPost, "/enroll", nil)
+ req.Header.Set(HeaderAgentToken, "valid-token")
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ require.Equal(t, http.StatusOK, w.Code)
+ require.False(t, <-reenrolled)
+
+ markerPath, err := managerMTLSEnrollmentMarkerPathInternal(cfg, "env-repeat-old")
+ require.NoError(t, err)
+ oldEnrollment := time.Now().Add(-(managerMTLSReenrollCooldown + time.Minute)).UTC().Format(time.RFC3339Nano) + "\n"
+ require.NoError(t, os.WriteFile(markerPath, []byte(oldEnrollment), 0o600))
+
+ req = httptest.NewRequest(http.MethodPost, "/enroll", nil)
+ req.Header.Set(HeaderAgentToken, "valid-token")
+ w = httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ require.Equal(t, http.StatusOK, w.Code)
+ require.True(t, <-reenrolled)
}
func TestTunnelServer_CleanupLoop(t *testing.T) {
@@ -389,7 +601,7 @@ func (f *registerResponseOrderConn) SendRequest(ctx context.Context, msg *Tunnel
return nil, errors.New("not implemented")
}
-func TestTunnelServer_ManageConnectedTunnel_SendsGRPCRegisterResponseBeforeRegistering(t *testing.T) {
+func TestTunnelServer_ManageConnectedTunnel_RegistersBeforeSendingGRPCRegisterResponse(t *testing.T) {
server := NewTunnelServer(nil, nil)
envID := "env-grpc-register-order"
server.registry.Unregister(envID)
@@ -399,7 +611,7 @@ func TestTunnelServer_ManageConnectedTunnel_SendsGRPCRegisterResponseBeforeRegis
conn.sendHook = func(msg *TunnelMessage) error {
require.Equal(t, MessageTypeRegisterResponse, msg.Type)
_, ok := server.registry.Get(envID)
- assert.False(t, ok, "gRPC tunnel should not be routable before register response is sent")
+ assert.True(t, ok, "gRPC tunnel should already be registered when the register response is sent")
return nil
}
diff --git a/backend/pkg/libarcane/edge/tls.go b/backend/pkg/libarcane/edge/tls.go
new file mode 100644
index 000000000..3509b5693
--- /dev/null
+++ b/backend/pkg/libarcane/edge/tls.go
@@ -0,0 +1,1319 @@
+package edge
+
+import (
+ "bytes"
+ "context"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/json"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ libcrypto "github.com/getarcaneapp/arcane/backend/pkg/libarcane/crypto"
+ certgen "github.com/getarcaneapp/arcane/cli/pkg/generate"
+ "google.golang.org/grpc/credentials"
+ "google.golang.org/grpc/peer"
+)
+
+const (
+ defaultGeneratedMTLSDir = "data/edge-mtls"
+ defaultAgentMTLSDir = "data/edge-mtls-agent"
+ generatedMTLSContainerDir = "/app/data/edge-mtls-agent"
+ generatedMTLSCertValidity = 5 * 365 * 24 * time.Hour
+ generatedClientMTLSSubdir = "clients"
+ generatedMTLSCACertFileName = "ca.crt"
+ generatedMTLSCAKeyFileName = "ca.key"
+ generatedMTLSClientCertName = "agent.crt"
+ generatedMTLSClientKeyName = "agent.key"
+ generatedMTLSEnrolledName = ".enrolled"
+ managerMTLSReenrollCooldown = 15 * time.Minute
+ agentMTLSRenewBefore = 30 * 24 * time.Hour
+ maxEnrollResponseBytes = 1 << 20
+ managerCALockTimeout = 2 * time.Minute
+ managerCALockPollInterval = 100 * time.Millisecond
+)
+
+var generatedAssetNameSanitizer = regexp.MustCompile(`[^a-zA-Z0-9._-]+`)
+
+var managerCALocks sync.Map
+
+// GeneratedMTLSFile describes a generated file that should be copied to the edge agent host.
+type GeneratedMTLSFile struct {
+ Name string `json:"name"`
+ Content string `json:"content"`
+ ContainerPath string `json:"containerPath"`
+ Permissions string `json:"permissions"`
+}
+
+// GeneratedMTLSAssets contains manager-generated edge client certificates and snippet metadata.
+type GeneratedMTLSAssets struct {
+ Files []GeneratedMTLSFile `json:"files"`
+ HostDirHint string `json:"hostDirHint"`
+ CertIssued bool `json:"-"`
+ CAGenerated bool `json:"-"`
+ Reenrolled bool `json:"-"`
+}
+
+type enrollMTLSResponse struct {
+ Files []GeneratedMTLSFile `json:"files"`
+}
+
+// BuildManagerServerTLSConfig returns the manager TLS configuration needed to
+// support optional edge mTLS on the shared Arcane listener.
+func BuildManagerServerTLSConfig(cfg *Config) (*tls.Config, error) {
+ if cfg == nil || NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode) == EdgeMTLSModeDisabled {
+ return nil, nil
+ }
+
+ caPool, err := loadCertPoolInternal(strings.TrimSpace(cfg.EdgeMTLSCAFile))
+ if err != nil {
+ return nil, fmt.Errorf("failed to load edge mTLS CA file: %w", err)
+ }
+
+ // ClientAuth is intentionally VerifyClientCertIfGiven even when
+ // EdgeMTLSMode is "required". Enforcement of "required" mode is done
+ // per-request at the application layer (see TunnelServer.requireClientCertificate*
+ // in server.go) so that the mTLS enrollment endpoint, which agents must
+ // reach before they own a client certificate, remains accessible. If the
+ // handshake were set to RequireAndVerifyClientCert, bootstrap would fail.
+ // TODO: reload ClientCAs when CA rotation support is added.
+ return &tls.Config{
+ MinVersion: tls.VersionTLS12,
+ ClientAuth: tls.VerifyClientCertIfGiven,
+ ClientCAs: caPool,
+ }, nil
+}
+
+// NewManagerHTTPClient creates an HTTP client for agent-to-manager requests,
+// applying edge TLS settings when the manager URL uses HTTPS.
+func NewManagerHTTPClient(cfg *Config, timeout time.Duration) (*http.Client, error) {
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ tlsConfig, err := buildManagerClientTLSConfigInternal(cfg)
+ if err != nil {
+ return nil, err
+ }
+ if tlsConfig != nil {
+ transport.TLSClientConfig = tlsConfig
+ }
+
+ client := &http.Client{Transport: transport}
+ if timeout > 0 {
+ client.Timeout = timeout
+ }
+ return client, nil
+}
+
+// PrepareManagerMTLSAssetsWithContext ensures Arcane-managed edge mTLS assets exist when
+// edge mTLS is enabled and no explicit manager CA file is configured.
+func PrepareManagerMTLSAssetsWithContext(ctx context.Context, cfg *Config) error {
+ if !shouldAutoGenerateManagerCAInternal(cfg) {
+ return nil
+ }
+
+ assetsDir, err := edgeMTLSAssetsDirInternal(cfg)
+ if err != nil {
+ return err
+ }
+
+ if _, _, _, err := ensureManagerCAInternal(ctx, assetsDir); err != nil {
+ return err
+ }
+
+ cfg.EdgeMTLSCAFile = filepath.Join(assetsDir, generatedMTLSCACertFileName)
+ return nil
+}
+
+// GeneratedManagerMTLSCAPath returns the configured or Arcane-managed manager CA path without creating assets.
+func GeneratedManagerMTLSCAPath(cfg *Config) (string, error) {
+ if cfg == nil {
+ return "", fmt.Errorf("edge config is required")
+ }
+ if configured := strings.TrimSpace(cfg.EdgeMTLSCAFile); configured != "" {
+ return configured, nil
+ }
+ assetsDir, err := edgeMTLSAssetsDirInternal(cfg)
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(assetsDir, generatedMTLSCACertFileName), nil
+}
+
+// GenerateManagerClientMTLSAssetsWithContext creates or loads the generated CA and per-environment client certificate bundle.
+func GenerateManagerClientMTLSAssetsWithContext(ctx context.Context, cfg *Config, envID string, envName string) (*GeneratedMTLSAssets, error) {
+ if !shouldUseGeneratedManagerCAInternal(cfg) {
+ return nil, nil
+ }
+ if strings.TrimSpace(envID) == "" {
+ return nil, fmt.Errorf("environment ID is required")
+ }
+
+ assetsDir, err := edgeMTLSAssetsDirInternal(cfg)
+ if err != nil {
+ return nil, err
+ }
+ caCertPath, _, caGenerated, err := ensureManagerCAInternal(ctx, assetsDir)
+ if err != nil {
+ return nil, err
+ }
+ appURL := edgeMTLSAppURLInternal(cfg)
+ clientCertPath, clientKeyPath, certIssued, err := ensureClientCertificateInternal(ctx, assetsDir, envID, envName, appURL)
+ if err != nil {
+ return nil, err
+ }
+
+ caPEM, err := os.ReadFile(caCertPath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read generated CA certificate: %w", err)
+ }
+ clientCertPEM, err := os.ReadFile(clientCertPath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read generated client certificate: %w", err)
+ }
+ clientKeyPEM, err := os.ReadFile(clientKeyPath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read generated client key: %w", err)
+ }
+
+ return &GeneratedMTLSAssets{
+ HostDirHint: "./arcane-edge-certs",
+ CertIssued: certIssued,
+ CAGenerated: caGenerated,
+ Files: []GeneratedMTLSFile{
+ {Name: generatedMTLSCACertFileName, Content: string(caPEM), ContainerPath: filepath.ToSlash(filepath.Join(generatedMTLSContainerDir, generatedMTLSCACertFileName)), Permissions: "0644"},
+ {Name: generatedMTLSClientCertName, Content: string(clientCertPEM), ContainerPath: filepath.ToSlash(filepath.Join(generatedMTLSContainerDir, generatedMTLSClientCertName)), Permissions: "0644"},
+ {Name: generatedMTLSClientKeyName, Content: string(clientKeyPEM), ContainerPath: filepath.ToSlash(filepath.Join(generatedMTLSContainerDir, generatedMTLSClientKeyName)), Permissions: "0600"},
+ },
+ }, nil
+}
+
+func managerMTLSEnrollmentStateInternal(cfg *Config, envID string, now time.Time) (bool, bool, error) {
+ markerPath, err := managerMTLSEnrollmentMarkerPathInternal(cfg, envID)
+ if err != nil {
+ return false, false, err
+ }
+ enrolledAt, err := readMTLSEnrollmentMarkerInternal(markerPath)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return false, false, nil
+ }
+ return false, false, err
+ }
+ if now.IsZero() {
+ now = time.Now()
+ }
+ if enrolledAt.IsZero() {
+ return true, false, nil
+ }
+ return true, now.Sub(enrolledAt) < managerMTLSReenrollCooldown, nil
+}
+
+func recordManagerMTLSEnrollmentInternal(cfg *Config, envID string, now time.Time) error {
+ markerPath, err := managerMTLSEnrollmentMarkerPathInternal(cfg, envID)
+ if err != nil {
+ return err
+ }
+ if now.IsZero() {
+ now = time.Now()
+ }
+ return writeFileAtomicInternal(markerPath, []byte(now.UTC().Format(time.RFC3339Nano)+"\n"), 0o600)
+}
+
+func managerMTLSEnrollmentMarkerPathInternal(cfg *Config, envID string) (string, error) {
+ assetsDir, err := edgeMTLSAssetsDirInternal(cfg)
+ if err != nil {
+ return "", err
+ }
+ safeEnvID := generatedAssetNameSanitizer.ReplaceAllString(strings.TrimSpace(envID), "_")
+ if safeEnvID == "" {
+ return "", fmt.Errorf("environment ID is required")
+ }
+ return filepath.Join(assetsDir, generatedClientMTLSSubdir, safeEnvID, generatedMTLSEnrolledName), nil
+}
+
+func readMTLSEnrollmentMarkerInternal(path string) (time.Time, error) {
+ content, err := os.ReadFile(path)
+ if err != nil {
+ return time.Time{}, err
+ }
+ trimmed := strings.TrimSpace(string(content))
+ if trimmed == "" {
+ return time.Time{}, nil
+ }
+ enrolledAt, err := time.Parse(time.RFC3339Nano, trimmed)
+ if err != nil {
+ return time.Time{}, fmt.Errorf("failed to parse edge mTLS enrollment marker %s: %w", path, err)
+ }
+ return enrolledAt, nil
+}
+
+// GeneratedManagerClientMTLSCertPath returns the manager-side generated client certificate path for an environment.
+func GeneratedManagerClientMTLSCertPath(cfg *Config, envID string) (string, error) {
+ assetsDir, err := edgeMTLSAssetsDirInternal(cfg)
+ if err != nil {
+ return "", err
+ }
+
+ safeEnvID := generatedAssetNameSanitizer.ReplaceAllString(strings.TrimSpace(envID), "_")
+ if safeEnvID == "" {
+ return "", fmt.Errorf("environment ID is required")
+ }
+
+ return filepath.Join(assetsDir, "clients", safeEnvID, generatedMTLSClientCertName), nil
+}
+
+// EnsureAgentMTLSAssets downloads manager-generated client certificates when
+// edge mTLS is enabled and explicit client cert/key files are not configured.
+func EnsureAgentMTLSAssets(ctx context.Context, cfg *Config) error {
+ if !shouldAutoEnrollAgentMTLSInternal(cfg) {
+ return nil
+ }
+ if hasClientCertificateInternal(cfg) {
+ return nil
+ }
+
+ assetsDir, err := edgeAgentMTLSAssetsDirInternal(cfg)
+ if err != nil {
+ return err
+ }
+ certPath := filepath.Join(assetsDir, generatedMTLSClientCertName)
+ keyPath := filepath.Join(assetsDir, generatedMTLSClientKeyName)
+ if fileExistsInternal(certPath) && fileExistsInternal(keyPath) {
+ needsEnrollment, reason := agentMTLSAssetsNeedEnrollmentInternal(certPath, keyPath, time.Now())
+ if !needsEnrollment {
+ if !fileExistsInternal(filepath.Join(assetsDir, generatedMTLSEnrolledName)) {
+ if err := writeFileAtomicInternal(filepath.Join(assetsDir, generatedMTLSEnrolledName), []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), 0o600); err != nil {
+ return fmt.Errorf("failed to write edge mTLS enrollment marker: %w", err)
+ }
+ }
+ setAgentMTLSAssetPathsInternal(cfg, assetsDir)
+ return nil
+ }
+ slog.WarnContext(ctx, "Existing edge mTLS assets need renewal; enrolling new assets", "reason", reason, "cert_path", certPath)
+ }
+
+ if err := enrollAgentMTLSAssetsInternal(ctx, cfg, assetsDir, certPath, keyPath); err != nil {
+ if NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode) != EdgeMTLSModeRequired {
+ slog.WarnContext(ctx, "Edge mTLS enrollment failed; proceeding without client certificate", "error", err)
+ return nil
+ }
+ return err
+ }
+ return nil
+}
+
+func enrollAgentMTLSAssetsInternal(ctx context.Context, cfg *Config, assetsDir, certPath, keyPath string) error {
+ managerBaseURL := strings.TrimRight(strings.TrimSpace(cfg.GetManagerBaseURL()), "/")
+ if managerBaseURL == "" {
+ return fmt.Errorf("MANAGER_API_URL is required to enroll edge mTLS assets")
+ }
+ if !managerUsesTLSInternal(cfg) {
+ return fmt.Errorf("EDGE_MTLS_MODE requires MANAGER_API_URL to use https for certificate enrollment")
+ }
+
+ httpClient, err := NewManagerHTTPClient(cfg, 30*time.Second)
+ if err != nil {
+ return fmt.Errorf("failed to configure edge mTLS enrollment client: %w", err)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, managerBaseURL+"/api/tunnel/mtls/enroll", nil)
+ if err != nil {
+ return fmt.Errorf("failed to create edge mTLS enrollment request: %w", err)
+ }
+ req.Header.Set(HeaderAgentToken, cfg.AgentToken)
+ req.Header.Set(HeaderAPIKey, cfg.AgentToken)
+
+ resp, err := httpClient.Do(req) //nolint:gosec // intentional request to configured manager endpoint
+ if err != nil {
+ return fmt.Errorf("edge mTLS enrollment request failed: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, maxEnrollResponseBytes))
+ return fmt.Errorf("edge mTLS enrollment failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
+ }
+
+ var enrollResp enrollMTLSResponse
+ if err := json.NewDecoder(io.LimitReader(resp.Body, maxEnrollResponseBytes)).Decode(&enrollResp); err != nil {
+ return fmt.Errorf("failed to decode edge mTLS enrollment response: %w", err)
+ }
+ if len(enrollResp.Files) == 0 {
+ return fmt.Errorf("edge mTLS enrollment response did not include any files")
+ }
+
+ if err := os.MkdirAll(assetsDir, common.DirPerm); err != nil {
+ return fmt.Errorf("failed to create edge mTLS asset dir: %w", err)
+ }
+ for _, file := range enrollResp.Files {
+ fileName := filepath.Base(file.Name)
+ targetPath := filepath.Join(assetsDir, fileName)
+ perm := common.FilePerm
+ if strings.TrimSpace(file.Permissions) == "0600" {
+ perm = 0o600
+ }
+ if err := writeFileAtomicInternal(targetPath, []byte(file.Content), perm); err != nil {
+ return fmt.Errorf("failed to write edge mTLS asset %s: %w", file.Name, err)
+ }
+ }
+ needsEnrollment, reason := agentMTLSAssetsNeedEnrollmentInternal(certPath, keyPath, time.Now())
+ if needsEnrollment {
+ return fmt.Errorf("edge mTLS enrollment wrote unusable assets: %s", reason)
+ }
+ if err := writeFileAtomicInternal(filepath.Join(assetsDir, generatedMTLSEnrolledName), []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), 0o600); err != nil {
+ return fmt.Errorf("failed to write edge mTLS enrollment marker: %w", err)
+ }
+
+ setAgentMTLSAssetPathsInternal(cfg, assetsDir)
+ return nil
+}
+
+func buildManagerClientTLSConfigInternal(cfg *Config) (*tls.Config, error) {
+ if cfg == nil || !managerUsesTLSInternal(cfg) {
+ return nil, nil
+ }
+
+ tlsConfig := &tls.Config{
+ MinVersion: tls.VersionTLS12,
+ }
+
+ if serverName := strings.TrimSpace(cfg.EdgeMTLSServerName); serverName != "" {
+ tlsConfig.ServerName = serverName
+ }
+
+ if caFile := strings.TrimSpace(cfg.EdgeMTLSCAFile); caFile != "" {
+ pool, err := loadSystemOrCustomCertPoolInternal(caFile)
+ if err != nil {
+ return nil, fmt.Errorf("failed to load edge mTLS CA file: %w", err)
+ }
+ tlsConfig.RootCAs = pool
+ }
+
+ if hasClientCertificateInternal(cfg) {
+ mode := NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode)
+ certPath := strings.TrimSpace(cfg.EdgeMTLSCertFile)
+ keyPath := strings.TrimSpace(cfg.EdgeMTLSKeyFile)
+ needsEnrollment, reason := agentMTLSAssetsNeedEnrollmentInternal(certPath, keyPath, time.Now())
+ if needsEnrollment {
+ err := fmt.Errorf("edge mTLS client certificate is unusable: %s", reason)
+ if mode == EdgeMTLSModeOptional {
+ slog.Warn("Ignoring unusable optional edge mTLS client certificate; falling back to token auth", "cert_path", certPath, "error", err.Error())
+ return tlsConfig, nil
+ }
+ return nil, err
+ }
+ cert, err := tls.LoadX509KeyPair(certPath, keyPath)
+ if err != nil {
+ if mode == EdgeMTLSModeOptional {
+ slog.Warn("Failed to load optional edge mTLS client certificate; falling back to token auth", "cert_path", certPath, "error", err.Error())
+ return tlsConfig, nil
+ }
+ return nil, fmt.Errorf("failed to load edge mTLS client certificate: %w", err)
+ }
+ tlsConfig.Certificates = []tls.Certificate{cert}
+ }
+
+ return tlsConfig, nil
+}
+
+// ValidateAgentMTLSConfig validates the edge agent TLS configuration before the
+// reverse tunnel client starts.
+func ValidateAgentMTLSConfig(cfg *Config) error {
+ if cfg == nil {
+ return nil
+ }
+
+ mode := NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode)
+ if mode == EdgeMTLSModeDisabled {
+ return nil
+ }
+
+ if !managerUsesTLSInternal(cfg) {
+ return fmt.Errorf("EDGE_MTLS_MODE requires MANAGER_API_URL to use https")
+ }
+
+ _, err := buildManagerClientTLSConfigInternal(cfg)
+ return err
+}
+
+// ValidateManagerMTLSConfig validates the manager-side mTLS configuration used
+// by edge tunnel endpoints.
+func ValidateManagerMTLSConfig(cfg *Config, managerTLSEnabled bool) error {
+ if cfg == nil {
+ return nil
+ }
+
+ mode := NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode)
+ if mode == EdgeMTLSModeDisabled {
+ return nil
+ }
+ if !managerTLSEnabled {
+ return fmt.Errorf("EDGE_MTLS_MODE requires TLS_ENABLED=true on the manager")
+ }
+
+ if strings.TrimSpace(cfg.EdgeMTLSCAFile) == "" {
+ return fmt.Errorf("EDGE_MTLS_MODE=%s requires EDGE_MTLS_CA_FILE on the manager", mode)
+ }
+
+ _, err := BuildManagerServerTLSConfig(cfg)
+ return err
+}
+
+func loadCertPoolInternal(caFile string) (*x509.CertPool, error) {
+ caFile = strings.TrimSpace(caFile)
+ if caFile == "" {
+ return nil, fmt.Errorf("CA file is required")
+ }
+
+ pemBytes, err := os.ReadFile(caFile)
+ if err != nil {
+ return nil, err
+ }
+
+ pool := x509.NewCertPool()
+ if !pool.AppendCertsFromPEM(pemBytes) {
+ return nil, fmt.Errorf("failed to parse PEM certificates")
+ }
+
+ return pool, nil
+}
+
+func loadSystemOrCustomCertPoolInternal(caFile string) (*x509.CertPool, error) {
+ pool, err := x509.SystemCertPool()
+ if err != nil || pool == nil {
+ slog.Warn("Failed to load system certificate pool; falling back to configured edge mTLS CA only", "error", err)
+ pool = x509.NewCertPool()
+ }
+
+ caFile = strings.TrimSpace(caFile)
+ if caFile == "" {
+ return pool, nil
+ }
+
+ pemBytes, err := os.ReadFile(caFile)
+ if err != nil {
+ return nil, err
+ }
+ if !pool.AppendCertsFromPEM(pemBytes) {
+ return nil, fmt.Errorf("failed to parse PEM certificates")
+ }
+ return pool, nil
+}
+
+func hasClientCertificateInternal(cfg *Config) bool {
+ if cfg == nil {
+ return false
+ }
+
+ return strings.TrimSpace(cfg.EdgeMTLSCertFile) != "" && strings.TrimSpace(cfg.EdgeMTLSKeyFile) != ""
+}
+
+func managerUsesTLSInternal(cfg *Config) bool {
+ if cfg == nil {
+ return false
+ }
+
+ baseURL := strings.TrimSpace(cfg.GetManagerBaseURL())
+ return strings.HasPrefix(strings.ToLower(baseURL), "https://")
+}
+
+func shouldAutoGenerateManagerCAInternal(cfg *Config) bool {
+ if cfg == nil {
+ return false
+ }
+
+ return NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode) != EdgeMTLSModeDisabled &&
+ strings.TrimSpace(cfg.EdgeMTLSCAFile) == ""
+}
+
+func shouldUseGeneratedManagerCAInternal(cfg *Config) bool {
+ if cfg == nil {
+ return false
+ }
+ if NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode) == EdgeMTLSModeDisabled {
+ return false
+ }
+ configuredCA := strings.TrimSpace(cfg.EdgeMTLSCAFile)
+ if configuredCA == "" {
+ return true
+ }
+ assetsDir, err := edgeMTLSAssetsDirInternal(cfg)
+ if err != nil {
+ return false
+ }
+ generatedCA := filepath.Join(assetsDir, generatedMTLSCACertFileName)
+ return filepath.Clean(configuredCA) == filepath.Clean(generatedCA)
+}
+
+func shouldAutoEnrollAgentMTLSInternal(cfg *Config) bool {
+ if cfg == nil {
+ return false
+ }
+
+ return NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode) != EdgeMTLSModeDisabled &&
+ !hasClientCertificateInternal(cfg)
+}
+
+func setAgentMTLSAssetPathsInternal(cfg *Config, assetsDir string) {
+ if cfg == nil {
+ return
+ }
+
+ cfg.EdgeMTLSCertFile = filepath.Join(assetsDir, generatedMTLSClientCertName)
+ cfg.EdgeMTLSKeyFile = filepath.Join(assetsDir, generatedMTLSClientKeyName)
+
+ caPath := filepath.Join(assetsDir, generatedMTLSCACertFileName)
+ if fileExistsInternal(caPath) && strings.TrimSpace(cfg.EdgeMTLSCAFile) == "" {
+ cfg.EdgeMTLSCAFile = caPath
+ }
+}
+
+func requestSecurityModeInternal(req *http.Request) string {
+ if req == nil || req.TLS == nil {
+ return "token"
+ }
+
+ if hasVerifiedPeerCertificateInternal(req.TLS) {
+ return "mtls"
+ }
+
+ return "token"
+}
+
+func grpcContextSecurityModeInternal(pctx peer.Peer) string {
+ if tlsInfo, ok := pctx.AuthInfo.(credentials.TLSInfo); ok && hasVerifiedPeerCertificateInternal(&tlsInfo.State) {
+ return "mtls"
+ }
+ return "token"
+}
+
+func hasVerifiedPeerCertificateInternal(state *tls.ConnectionState) bool {
+ if state == nil {
+ return false
+ }
+ return len(state.PeerCertificates) > 0 && len(state.VerifiedChains) > 0
+}
+
+func verifiedPeerCertificateEnvironmentIDMatchesInternal(state *tls.ConnectionState, envID string, trustDomain string) error {
+ if !hasVerifiedPeerCertificateInternal(state) {
+ return nil
+ }
+ expectedPath := expectedEdgeMTLSURIPathInternal(envID)
+ if expectedPath == "" {
+ return fmt.Errorf("environment ID is required for edge mTLS certificate identity check")
+ }
+ trustDomain = strings.TrimSpace(strings.ToLower(strings.TrimSuffix(trustDomain, ".")))
+ if trustDomain == "" {
+ return fmt.Errorf("edge mTLS trust domain is required for certificate identity check")
+ }
+ leaf := state.VerifiedChains[0][0]
+ for _, uri := range leaf.URIs {
+ if uri == nil {
+ continue
+ }
+ if uri.Scheme == "spiffe" && strings.EqualFold(strings.TrimSuffix(uri.Host, "."), trustDomain) && uri.Path == expectedPath {
+ return nil
+ }
+ }
+ return fmt.Errorf("verified edge mTLS client certificate does not match environment %s", strings.TrimSpace(envID))
+}
+
+func edgeMTLSAppURLInternal(cfg *Config) string {
+ if cfg == nil {
+ return ""
+ }
+ if appURL := strings.TrimSpace(cfg.AppURL); appURL != "" {
+ return appURL
+ }
+ return strings.TrimSpace(cfg.GetManagerBaseURL())
+}
+
+func edgeMTLSTrustDomainInternal(cfg *Config) string {
+ return certgen.EdgeMTLSTrustDomain(edgeMTLSAppURLInternal(cfg))
+}
+
+func expectedEdgeMTLSURIPathInternal(envID string) string {
+ safeEnvID := generatedAssetNameSanitizer.ReplaceAllString(strings.TrimSpace(envID), "_")
+ if safeEnvID == "" {
+ return ""
+ }
+ return "/edge/" + safeEnvID
+}
+
+func edgeMTLSAssetsDirInternal(cfg *Config) (string, error) {
+ if cfg == nil {
+ return "", fmt.Errorf("edge config is required")
+ }
+
+ if configured := strings.TrimSpace(cfg.EdgeMTLSAssetsDir); configured != "" {
+ return configured, nil
+ }
+
+ baseDir := defaultGeneratedMTLSDir
+ if _, err := os.Stat("/app/data"); err == nil {
+ baseDir = "/app/data/edge-mtls"
+ }
+
+ resolved, err := filepath.Abs(baseDir)
+ if err != nil {
+ return "", fmt.Errorf("failed to resolve edge mTLS assets dir: %w", err)
+ }
+ return resolved, nil
+}
+
+func edgeAgentMTLSAssetsDirInternal(cfg *Config) (string, error) {
+ if cfg == nil {
+ return "", fmt.Errorf("edge config is required")
+ }
+ if configured := strings.TrimSpace(cfg.EdgeMTLSAssetsDir); configured != "" {
+ return configured, nil
+ }
+
+ baseDir := defaultAgentMTLSDir
+ if _, err := os.Stat("/app/data"); err == nil {
+ baseDir = "/app/data/edge-mtls-agent"
+ }
+
+ resolved, err := filepath.Abs(baseDir)
+ if err != nil {
+ return "", fmt.Errorf("failed to resolve edge agent mTLS assets dir: %w", err)
+ }
+ return resolved, nil
+}
+
+func ensureManagerCAInternal(ctx context.Context, assetsDir string) (string, string, bool, error) {
+ if err := os.MkdirAll(assetsDir, common.DirPerm); err != nil {
+ return "", "", false, fmt.Errorf("failed to create edge mTLS assets dir: %w", err)
+ }
+
+ unlock, err := lockEdgeMTLSPathInternal(ctx, assetsDir, ".ca.lock")
+ if err != nil {
+ return "", "", false, err
+ }
+ defer unlock()
+
+ caCertPath := filepath.Join(assetsDir, generatedMTLSCACertFileName)
+ caKeyPath := filepath.Join(assetsDir, generatedMTLSCAKeyFileName)
+ if generatedCAReadyInternal(caCertPath, caKeyPath) {
+ if err := migratePlainCAKeyInternal(caKeyPath); err != nil {
+ return "", "", false, err
+ }
+ return caCertPath, caKeyPath, false, nil
+ }
+ _ = os.Remove(caCertPath)
+ _ = os.Remove(caKeyPath)
+
+ privateKey, err := certgen.GenerateP384PrivateKey()
+ if err != nil {
+ return "", "", false, fmt.Errorf("failed to generate CA private key: %w", err)
+ }
+
+ template, err := certgen.NewEdgeMTLSCATemplate()
+ if err != nil {
+ return "", "", false, err
+ }
+
+ certDER, err := x509.CreateCertificate(rand.Reader, template, template, &privateKey.PublicKey, privateKey)
+ if err != nil {
+ return "", "", false, fmt.Errorf("failed to create CA certificate: %w", err)
+ }
+
+ if err := writePEMFileInternal(caCertPath, "CERTIFICATE", certDER, common.FilePerm); err != nil {
+ return "", "", false, err
+ }
+ caKeyDER, err := x509.MarshalECPrivateKey(privateKey)
+ if err != nil {
+ return "", "", false, fmt.Errorf("failed to marshal CA private key: %w", err)
+ }
+ if err := writeCAKeyFileInternal(caKeyPath, caKeyDER); err != nil {
+ return "", "", false, err
+ }
+
+ slog.Info("generated edge mTLS CA", "cert_path", caCertPath)
+ return caCertPath, caKeyPath, true, nil
+}
+
+func generatedCAReadyInternal(caCertPath string, caKeyPath string) bool {
+ if !fileExistsInternal(caCertPath) || !fileExistsInternal(caKeyPath) {
+ return false
+ }
+ if err := validateGeneratedCAInternal(caCertPath, caKeyPath); err != nil {
+ return false
+ }
+ return true
+}
+
+func migratePlainCAKeyInternal(caKeyPath string) error {
+ if isCAKeyEncryptedOnDiskInternal(caKeyPath) {
+ return nil
+ }
+ keyPEM, err := os.ReadFile(caKeyPath)
+ if err != nil {
+ return fmt.Errorf("failed to read legacy plain edge mTLS CA key for migration: %w", err)
+ }
+ block, _ := pem.Decode(keyPEM)
+ if block == nil {
+ return fmt.Errorf("failed to decode legacy plain edge mTLS CA key for migration")
+ }
+ if err := writeCAKeyFileInternal(caKeyPath, block.Bytes); err != nil {
+ return fmt.Errorf("failed to migrate edge mTLS CA key to encrypted format: %w", err)
+ }
+ slog.Info("migrated edge mTLS CA key to encrypted format", "path", caKeyPath)
+ return nil
+}
+
+func ensureClientCertificateInternal(ctx context.Context, assetsDir string, envID string, envName string, appURL string) (string, string, bool, error) {
+ caCertPath, caKeyPath, _, err := ensureManagerCAInternal(ctx, assetsDir)
+ if err != nil {
+ return "", "", false, err
+ }
+
+ caCertPEM, err := os.ReadFile(caCertPath)
+ if err != nil {
+ return "", "", false, fmt.Errorf("failed to read CA certificate: %w", err)
+ }
+ caKeyPEM, err := readCAKeyPEMInternal(caKeyPath)
+ if err != nil {
+ return "", "", false, err
+ }
+
+ caCertBlock, _ := pem.Decode(caCertPEM)
+ if caCertBlock == nil {
+ return "", "", false, fmt.Errorf("failed to parse CA certificate PEM")
+ }
+ caCert, err := x509.ParseCertificate(caCertBlock.Bytes)
+ if err != nil {
+ return "", "", false, fmt.Errorf("failed to parse CA certificate: %w", err)
+ }
+
+ caKeyBlock, _ := pem.Decode(caKeyPEM)
+ if caKeyBlock == nil {
+ return "", "", false, fmt.Errorf("failed to parse CA private key PEM")
+ }
+ caKey, err := x509.ParseECPrivateKey(caKeyBlock.Bytes)
+ if err != nil {
+ return "", "", false, fmt.Errorf("failed to parse CA private key: %w", err)
+ }
+
+ safeEnvID := generatedAssetNameSanitizer.ReplaceAllString(strings.TrimSpace(envID), "_")
+ clientDir := filepath.Join(assetsDir, generatedClientMTLSSubdir, safeEnvID)
+ if err := os.MkdirAll(clientDir, common.DirPerm); err != nil {
+ return "", "", false, fmt.Errorf("failed to create client cert dir: %w", err)
+ }
+ unlock, err := lockEdgeMTLSPathInternal(ctx, clientDir, ".client.lock")
+ if err != nil {
+ return "", "", false, err
+ }
+ defer unlock()
+
+ clientCertPath := filepath.Join(clientDir, generatedMTLSClientCertName)
+ clientKeyPath := filepath.Join(clientDir, generatedMTLSClientKeyName)
+ expectedCommonName := buildGeneratedClientCommonNameInternal(envName, safeEnvID)
+ expectedURISAN := certgen.BuildEdgeMTLSURISAN(appURL, safeEnvID)
+ if fileExistsInternal(clientCertPath) && fileExistsInternal(clientKeyPath) {
+ // The URI SAN is the stable edge identity. Common Name is display metadata
+ // for newly issued certs only, so environment renames must not rotate keys.
+ if err := validateGeneratedClientCertificateInternal(clientCertPath, clientKeyPath, "", expectedURISAN); err == nil {
+ return clientCertPath, clientKeyPath, false, nil
+ }
+ _ = os.Remove(clientCertPath)
+ _ = os.Remove(clientKeyPath)
+ }
+
+ privateKey, err := certgen.GenerateP384PrivateKey()
+ if err != nil {
+ return "", "", false, fmt.Errorf("failed to generate client private key: %w", err)
+ }
+ uriSAN, dnsSANs := buildGeneratedClientSANsInternal(envName, safeEnvID, appURL)
+ template, err := certgen.NewEdgeMTLSClientTemplate(expectedCommonName, uriSAN, dnsSANs)
+ if err != nil {
+ return "", "", false, err
+ }
+
+ certDER, err := x509.CreateCertificate(rand.Reader, template, caCert, &privateKey.PublicKey, caKey)
+ if err != nil {
+ return "", "", false, fmt.Errorf("failed to create client certificate: %w", err)
+ }
+
+ if err := writePEMFileInternal(clientCertPath, "CERTIFICATE", certDER, common.FilePerm); err != nil {
+ return "", "", false, err
+ }
+ clientKeyDER, err := x509.MarshalECPrivateKey(privateKey)
+ if err != nil {
+ return "", "", false, fmt.Errorf("failed to marshal client private key: %w", err)
+ }
+ if err := writePEMFileInternal(clientKeyPath, "EC PRIVATE KEY", clientKeyDER, 0o600); err != nil {
+ return "", "", false, err
+ }
+
+ return clientCertPath, clientKeyPath, true, nil
+}
+
+func buildGeneratedClientCommonNameInternal(envName string, safeEnvID string) string {
+ safeEnvID = strings.TrimSpace(safeEnvID)
+ if safeEnvID == "" {
+ return ""
+ }
+
+ safeEnvName := generatedAssetNameSanitizer.ReplaceAllString(strings.TrimSpace(envName), "-")
+ safeEnvName = strings.Trim(safeEnvName, "-_")
+ if safeEnvName == "" {
+ return safeEnvID
+ }
+
+ const maxCommonNameLength = 64
+
+ maxEnvNameLength := maxCommonNameLength - len(safeEnvID) - 1
+ if maxEnvNameLength <= 0 {
+ return safeEnvID
+ }
+ if len(safeEnvName) > maxEnvNameLength {
+ safeEnvName = strings.Trim(safeEnvName[:maxEnvNameLength], "-_")
+ if safeEnvName == "" {
+ return safeEnvID
+ }
+ }
+
+ return fmt.Sprintf("%s-%s", safeEnvName, safeEnvID)
+}
+
+// buildGeneratedClientSANsInternal returns the URI and DNS Subject Alternative
+// Names to embed in a generated edge agent client certificate. The URI SAN
+// provides a stable machine-readable identity; DNS SANs improve interop with
+// stricter verifiers. Returns a nil URI if safeEnvID is empty.
+func buildGeneratedClientSANsInternal(envName string, safeEnvID string, appURL string) (*url.URL, []string) {
+ safeEnvID = strings.TrimSpace(safeEnvID)
+ if safeEnvID == "" {
+ return nil, nil
+ }
+
+ uriSAN := certgen.BuildEdgeMTLSURISAN(appURL, safeEnvID)
+ trustDomain := certgen.EdgeMTLSTrustDomain(appURL)
+
+ dnsSANs := []string{"arcane-agent"}
+ safeEnvName := generatedAssetNameSanitizer.ReplaceAllString(strings.TrimSpace(envName), "-")
+ safeEnvName = strings.Trim(safeEnvName, "-_.")
+ if safeEnvName != "" && trustDomain != "" {
+ dnsSANs = append(dnsSANs, safeEnvName+".agent."+trustDomain)
+ }
+
+ return uriSAN, dnsSANs
+}
+
+func validateGeneratedCAInternal(certPath, keyPath string) error {
+ cert, err := readCertificateInternal(certPath)
+ if err != nil {
+ return err
+ }
+ if !cert.IsCA {
+ return fmt.Errorf("generated CA certificate is not a CA")
+ }
+ publicKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
+ if !ok || publicKey.Curve != elliptic.P384() {
+ return fmt.Errorf("generated CA certificate is not ECDSA P-384")
+ }
+ keyPEM, err := readCAKeyPEMInternal(keyPath)
+ if err != nil {
+ return err
+ }
+ keyBlock, _ := pem.Decode(keyPEM)
+ if keyBlock == nil {
+ return fmt.Errorf("failed to parse CA private key PEM %s", keyPath)
+ }
+ privateKey, err := x509.ParseECPrivateKey(keyBlock.Bytes)
+ if err != nil {
+ return fmt.Errorf("failed to parse CA private key %s: %w", keyPath, err)
+ }
+ if privateKey.Curve != elliptic.P384() {
+ return fmt.Errorf("generated CA private key is not ECDSA P-384")
+ }
+ if err := validateCertificateKeyPairInternal(cert, privateKey, "generated CA"); err != nil {
+ return err
+ }
+ return nil
+}
+
+func validateGeneratedClientCertificateInternal(certPath, keyPath string, expectedCommonName string, expectedURISAN *url.URL) error {
+ cert, err := readCertificateInternal(certPath)
+ if err != nil {
+ return err
+ }
+ now := time.Now()
+ if now.Before(cert.NotBefore) || !now.Before(cert.NotAfter) {
+ return fmt.Errorf("generated client certificate is not currently valid")
+ }
+ if strings.TrimSpace(expectedCommonName) != "" && cert.Subject.CommonName != expectedCommonName {
+ return fmt.Errorf("generated client certificate common name %q does not match expected %q", cert.Subject.CommonName, expectedCommonName)
+ }
+ if expectedURISAN != nil && !certificateHasURISANInternal(cert, expectedURISAN) {
+ return fmt.Errorf("generated client certificate URI SAN does not match expected %s", expectedURISAN.String())
+ }
+ publicKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
+ if !ok || publicKey.Curve != elliptic.P384() {
+ return fmt.Errorf("generated client certificate is not ECDSA P-384")
+ }
+ privateKey, err := readECPrivateKeyInternal(keyPath)
+ if err != nil {
+ return err
+ }
+ if privateKey.Curve != elliptic.P384() {
+ return fmt.Errorf("generated client private key is not ECDSA P-384")
+ }
+ if err := validateCertificateKeyPairInternal(cert, privateKey, "generated client"); err != nil {
+ return err
+ }
+ return nil
+}
+
+func certificateHasURISANInternal(cert *x509.Certificate, expected *url.URL) bool {
+ if cert == nil || expected == nil {
+ return false
+ }
+ for _, uri := range cert.URIs {
+ if uri == nil {
+ continue
+ }
+ if strings.EqualFold(uri.Scheme, expected.Scheme) &&
+ strings.EqualFold(strings.TrimSuffix(uri.Host, "."), strings.TrimSuffix(expected.Host, ".")) &&
+ uri.Path == expected.Path {
+ return true
+ }
+ }
+ return false
+}
+
+func agentMTLSAssetsNeedEnrollmentInternal(certPath string, keyPath string, now time.Time) (bool, string) {
+ if !fileExistsInternal(certPath) || !fileExistsInternal(keyPath) {
+ return true, "certificate or key is missing"
+ }
+ cert, err := readCertificateInternal(certPath)
+ if err != nil {
+ return true, err.Error()
+ }
+ privateKey, err := readECPrivateKeyInternal(keyPath)
+ if err != nil {
+ return true, err.Error()
+ }
+ if err := validateCertificateKeyPairInternal(cert, privateKey, "edge mTLS client"); err != nil {
+ return true, err.Error()
+ }
+ if now.IsZero() {
+ now = time.Now()
+ }
+ if now.Before(cert.NotBefore) {
+ return true, fmt.Sprintf("certificate is not valid before %s", cert.NotBefore.UTC().Format(time.RFC3339))
+ }
+ if !now.Before(cert.NotAfter) {
+ return true, fmt.Sprintf("certificate expired at %s", cert.NotAfter.UTC().Format(time.RFC3339))
+ }
+ if now.Add(agentMTLSRenewBefore).After(cert.NotAfter) {
+ return true, fmt.Sprintf("certificate expires soon at %s", cert.NotAfter.UTC().Format(time.RFC3339))
+ }
+ return false, ""
+}
+
+func validateCertificateKeyPairInternal(cert *x509.Certificate, privateKey *ecdsa.PrivateKey, label string) error {
+ if cert == nil {
+ return fmt.Errorf("%s certificate is required", label)
+ }
+ if privateKey == nil {
+ return fmt.Errorf("%s private key is required", label)
+ }
+
+ publicKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
+ if !ok {
+ return fmt.Errorf("%s certificate public key is not ECDSA", label)
+ }
+
+ certPublicKeyDER, err := x509.MarshalPKIXPublicKey(publicKey)
+ if err != nil {
+ return fmt.Errorf("failed to marshal %s certificate public key: %w", label, err)
+ }
+ privatePublicKeyDER, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
+ if err != nil {
+ return fmt.Errorf("failed to marshal %s private key public key: %w", label, err)
+ }
+ if !bytes.Equal(certPublicKeyDER, privatePublicKeyDER) {
+ return fmt.Errorf("%s certificate public key does not match private key", label)
+ }
+
+ return nil
+}
+
+func readCertificateInternal(path string) (*x509.Certificate, error) {
+ pemBytes, err := os.ReadFile(path)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read certificate %s: %w", path, err)
+ }
+ block, _ := pem.Decode(pemBytes)
+ if block == nil {
+ return nil, fmt.Errorf("failed to parse certificate PEM %s", path)
+ }
+ cert, err := x509.ParseCertificate(block.Bytes)
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse certificate %s: %w", path, err)
+ }
+ return cert, nil
+}
+
+func readECPrivateKeyInternal(path string) (*ecdsa.PrivateKey, error) {
+ pemBytes, err := os.ReadFile(path)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read private key %s: %w", path, err)
+ }
+ block, _ := pem.Decode(pemBytes)
+ if block == nil {
+ return nil, fmt.Errorf("failed to parse private key PEM %s", path)
+ }
+ privateKey, err := x509.ParseECPrivateKey(block.Bytes)
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse EC private key %s: %w", path, err)
+ }
+ return privateKey, nil
+}
+
+func lockEdgeMTLSPathInternal(ctx context.Context, dir string, lockName string) (func(), error) {
+ absDir, err := filepath.Abs(dir)
+ if err != nil {
+ return nil, fmt.Errorf("failed to resolve edge mTLS lock dir: %w", err)
+ }
+ lockName = strings.TrimSpace(lockName)
+ if lockName == "" {
+ lockName = ".lock"
+ }
+
+ lockPath := filepath.Join(absDir, lockName)
+ muValue, _ := managerCALocks.LoadOrStore(lockPath, &sync.Mutex{})
+ mu := muValue.(*sync.Mutex)
+
+ deadline := time.Now().Add(managerCALockTimeout)
+ for {
+ if !mu.TryLock() {
+ if err := waitForEdgeMTLSLockPollInternal(ctx); err != nil {
+ return nil, err
+ }
+ continue
+ }
+ file, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
+ if err == nil {
+ _, _ = fmt.Fprintf(file, "%d %s\n", os.Getpid(), time.Now().UTC().Format(time.RFC3339Nano))
+ _ = file.Close()
+ return func() {
+ _ = os.Remove(lockPath)
+ mu.Unlock()
+ }, nil
+ }
+ if !os.IsExist(err) {
+ mu.Unlock()
+ return nil, fmt.Errorf("failed to acquire edge mTLS CA lock: %w", err)
+ }
+ if time.Now().After(deadline) {
+ if removeStaleEdgeMTLSLockInternal(lockPath) {
+ deadline = time.Now().Add(managerCALockTimeout)
+ continue
+ }
+ mu.Unlock()
+ return nil, fmt.Errorf("timed out waiting for edge mTLS CA lock %s", lockPath)
+ }
+ mu.Unlock()
+ if err := waitForEdgeMTLSLockPollInternal(ctx); err != nil {
+ return nil, err
+ }
+ }
+}
+
+func waitForEdgeMTLSLockPollInternal(ctx context.Context) error {
+ timer := time.NewTimer(managerCALockPollInterval)
+ defer timer.Stop()
+
+ select {
+ case <-ctx.Done():
+ return fmt.Errorf("cancelled waiting for edge mTLS CA lock: %w", ctx.Err())
+ case <-timer.C:
+ return nil
+ }
+}
+
+func removeStaleEdgeMTLSLockInternal(lockPath string) bool {
+ info, err := readEdgeMTLSLockInfoInternal(lockPath)
+ if err != nil {
+ return false
+ }
+ if !info.createdAt.IsZero() && time.Since(info.createdAt) > 2*managerCALockTimeout {
+ return removeEdgeMTLSLockFileInternal(lockPath)
+ }
+ if edgeMTLSLockPIDAliveInternal(info.pid) {
+ return false
+ }
+ return removeEdgeMTLSLockFileInternal(lockPath)
+}
+
+type edgeMTLSLockInfo struct {
+ pid int
+ createdAt time.Time
+}
+
+func readEdgeMTLSLockInfoInternal(lockPath string) (*edgeMTLSLockInfo, error) {
+ content, err := os.ReadFile(lockPath)
+ if err != nil {
+ return nil, err
+ }
+ fields := strings.Fields(string(content))
+ if len(fields) == 0 {
+ return nil, fmt.Errorf("edge mTLS lock does not contain a PID")
+ }
+ pid, err := strconv.Atoi(fields[0])
+ if err != nil {
+ return nil, fmt.Errorf("parse edge mTLS lock PID: %w", err)
+ }
+ if pid <= 0 {
+ return nil, fmt.Errorf("edge mTLS lock PID must be positive")
+ }
+ info := &edgeMTLSLockInfo{pid: pid}
+ if len(fields) > 1 {
+ createdAt, parseErr := time.Parse(time.RFC3339Nano, fields[1])
+ if parseErr == nil {
+ info.createdAt = createdAt
+ }
+ }
+ return info, nil
+}
+
+func removeEdgeMTLSLockFileInternal(lockPath string) bool {
+ if err := os.Remove(lockPath); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return false
+ }
+ return true
+}
+
+func edgeMTLSLockPIDAliveInternal(pid int) bool {
+ process, err := os.FindProcess(pid)
+ if err != nil {
+ return false
+ }
+ err = process.Signal(syscall.Signal(0))
+ return err == nil || errors.Is(err, syscall.EPERM)
+}
+
+func writePEMFileInternal(path string, blockType string, bytes []byte, perm os.FileMode) error {
+ pemBytes := pem.EncodeToMemory(&pem.Block{Type: blockType, Bytes: bytes})
+ if pemBytes == nil {
+ return fmt.Errorf("failed to encode PEM file %s", path)
+ }
+ return writeFileAtomicInternal(path, pemBytes, perm)
+}
+
+// caKeyEncryptedPrefix marks files written with libcrypto envelope encryption.
+// The payload after the prefix is the base64 ciphertext returned by
+// libcrypto.Encrypt of the plain PEM-encoded CA private key.
+const caKeyEncryptedPrefix = "ARCANE-ENC-V1:"
+
+var caKeyEncryptInternal = libcrypto.Encrypt
+
+// writeCAKeyFileInternal writes the edge CA private key to disk using envelope
+// encryption via libcrypto. The on-disk format is self-describing so
+// readCAKeyPEMInternal can transparently handle encrypted files and legacy
+// plaintext files.
+func writeCAKeyFileInternal(path string, derBytes []byte) error {
+ pemBytes := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: derBytes})
+ if pemBytes == nil {
+ return fmt.Errorf("failed to encode CA private key to PEM")
+ }
+
+ ciphertext, err := caKeyEncryptInternal(string(pemBytes))
+ if err != nil {
+ return fmt.Errorf("failed to encrypt edge mTLS CA private key: %w", err)
+ }
+ if ciphertext == "" {
+ return fmt.Errorf("failed to encrypt edge mTLS CA private key: encrypted payload is empty")
+ }
+
+ return writeFileAtomicInternal(path, []byte(caKeyEncryptedPrefix+ciphertext), 0o600)
+}
+
+// readCAKeyPEMInternal returns the plain PEM bytes of the edge CA private key,
+// accepting either the legacy plain PEM file or a libcrypto-envelope-encrypted
+// file written by writeCAKeyFileInternal.
+func readCAKeyPEMInternal(path string) ([]byte, error) {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read CA private key %s: %w", path, err)
+ }
+ trimmed := strings.TrimSpace(string(raw))
+ if strings.HasPrefix(trimmed, caKeyEncryptedPrefix) {
+ ciphertext := strings.TrimPrefix(trimmed, caKeyEncryptedPrefix)
+ plaintext, err := libcrypto.Decrypt(ciphertext)
+ if err != nil {
+ return nil, fmt.Errorf("failed to decrypt CA private key %s: %w", path, err)
+ }
+ return []byte(plaintext), nil
+ }
+ return raw, nil
+}
+
+// isCAKeyEncryptedOnDiskInternal reports whether the given CA key file is
+// stored in the libcrypto envelope format.
+func isCAKeyEncryptedOnDiskInternal(path string) bool {
+ f, err := os.Open(path)
+ if err != nil {
+ return false
+ }
+ defer func() { _ = f.Close() }()
+ head := make([]byte, len(caKeyEncryptedPrefix))
+ n, _ := io.ReadFull(f, head)
+ return n == len(caKeyEncryptedPrefix) && string(head) == caKeyEncryptedPrefix
+}
+
+// writeFileAtomicInternal writes data to path via a temp file + rename.
+func writeFileAtomicInternal(path string, data []byte, perm os.FileMode) error {
+ dir := filepath.Dir(path)
+ tmp, err := os.CreateTemp(dir, filepath.Base(path)+".tmp-*")
+ if err != nil {
+ return fmt.Errorf("failed to create temp file for %s: %w", path, err)
+ }
+ tmpName := tmp.Name()
+ cleanup := func() { _ = os.Remove(tmpName) }
+ if _, err := tmp.Write(data); err != nil {
+ _ = tmp.Close()
+ cleanup()
+ return fmt.Errorf("failed to write temp file %s: %w", tmpName, err)
+ }
+ if err := tmp.Chmod(perm); err != nil {
+ _ = tmp.Close()
+ cleanup()
+ return fmt.Errorf("failed to chmod temp file %s: %w", tmpName, err)
+ }
+ if err := tmp.Close(); err != nil {
+ cleanup()
+ return fmt.Errorf("failed to close temp file %s: %w", tmpName, err)
+ }
+ if err := os.Rename(tmpName, path); err != nil {
+ cleanup()
+ return fmt.Errorf("failed to rename %s to %s: %w", tmpName, path, err)
+ }
+ return nil
+}
+
+func fileExistsInternal(path string) bool {
+ if strings.TrimSpace(path) == "" {
+ return false
+ }
+ info, err := os.Stat(path)
+ return err == nil && !info.IsDir()
+}
diff --git a/backend/pkg/libarcane/edge/tls_test.go b/backend/pkg/libarcane/edge/tls_test.go
new file mode 100644
index 000000000..869bb4ef6
--- /dev/null
+++ b/backend/pkg/libarcane/edge/tls_test.go
@@ -0,0 +1,510 @@
+package edge
+
+import (
+ "context"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ libcrypto "github.com/getarcaneapp/arcane/backend/pkg/libarcane/crypto"
+ "github.com/stretchr/testify/require"
+)
+
+func TestMain(m *testing.M) {
+ libcrypto.InitEncryption(&libcrypto.Config{
+ EncryptionKey: "test-encryption-key-for-edge-mtls-32bytes-min",
+ Environment: "test",
+ })
+ os.Exit(m.Run())
+}
+
+func initEdgeTestCrypto(t *testing.T) {
+ t.Helper()
+ libcrypto.InitEncryption(&libcrypto.Config{
+ EncryptionKey: "test-encryption-key-for-edge-mtls-32bytes-min",
+ Environment: "test",
+ })
+}
+
+func TestPrepareManagerMTLSAssetsWithContext(t *testing.T) {
+ cfg := &Config{
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ AppURL: "https://manager.example.com",
+ }
+
+ require.NoError(t, PrepareManagerMTLSAssetsWithContext(context.Background(), cfg))
+ require.NotEmpty(t, cfg.EdgeMTLSCAFile)
+ require.FileExists(t, cfg.EdgeMTLSCAFile)
+}
+
+func TestGenerateManagerClientMTLSAssetsWithContext(t *testing.T) {
+ cfg := &Config{
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ AppURL: "https://manager.example.com",
+ }
+
+ assets, err := GenerateManagerClientMTLSAssetsWithContext(context.Background(), cfg, "env-123", "Lab Server")
+ require.NoError(t, err)
+ require.NotNil(t, assets)
+ require.Empty(t, cfg.EdgeMTLSCAFile)
+ clientCertPath, err := GeneratedManagerClientMTLSCertPath(cfg, "env-123")
+ require.NoError(t, err)
+ require.FileExists(t, clientCertPath)
+ require.Equal(t, "./arcane-edge-certs", assets.HostDirHint)
+ require.Len(t, assets.Files, 3)
+ require.Equal(t, "ca.crt", assets.Files[0].Name)
+ require.Contains(t, assets.Files[0].Content, "BEGIN CERTIFICATE")
+ require.Equal(t, "/app/data/edge-mtls-agent/ca.crt", assets.Files[0].ContainerPath)
+ require.Equal(t, "/app/data/edge-mtls-agent/agent.crt", assets.Files[1].ContainerPath)
+ require.Equal(t, "agent.key", assets.Files[2].Name)
+ require.Equal(t, "/app/data/edge-mtls-agent/agent.key", assets.Files[2].ContainerPath)
+ require.Contains(t, assets.Files[2].Content, "BEGIN EC PRIVATE KEY")
+
+ keyBlock, _ := pem.Decode([]byte(assets.Files[2].Content))
+ require.NotNil(t, keyBlock)
+ privateKey, err := x509.ParseECPrivateKey(keyBlock.Bytes)
+ require.NoError(t, err)
+ require.Equal(t, elliptic.P384(), privateKey.Curve)
+
+ certBlock, _ := pem.Decode([]byte(assets.Files[1].Content))
+ require.NotNil(t, certBlock)
+ cert, err := x509.ParseCertificate(certBlock.Bytes)
+ require.NoError(t, err)
+ publicKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
+ require.True(t, ok)
+ require.Equal(t, elliptic.P384(), publicKey.Curve)
+ require.Equal(t, "Lab-Server-env-123", cert.Subject.CommonName)
+ require.Len(t, cert.URIs, 1)
+ require.Equal(t, "spiffe://manager.example.com/edge/env-123", cert.URIs[0].String())
+}
+
+func TestGeneratedClientCertificate_IncludesSANs(t *testing.T) {
+ cfg := &Config{
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ AppURL: "https://manager.example.com",
+ }
+
+ assets, err := GenerateManagerClientMTLSAssetsWithContext(context.Background(), cfg, "env-abc", "Lab Server")
+ require.NoError(t, err)
+ require.NotNil(t, assets)
+
+ var certPEM string
+ for _, file := range assets.Files {
+ if file.Name == generatedMTLSClientCertName {
+ certPEM = file.Content
+ break
+ }
+ }
+ require.NotEmpty(t, certPEM, "agent cert must be in generated assets")
+
+ block, _ := pem.Decode([]byte(certPEM))
+ require.NotNil(t, block)
+ cert, err := x509.ParseCertificate(block.Bytes)
+ require.NoError(t, err)
+
+ require.NotEmpty(t, cert.URIs, "agent cert must include URI SAN for stable identity")
+ uri := cert.URIs[0]
+ require.Equal(t, "spiffe", uri.Scheme)
+ require.Equal(t, "manager.example.com", uri.Host)
+ require.Contains(t, uri.Path, "env-abc")
+
+ require.NotEmpty(t, cert.DNSNames, "agent cert must include at least one DNS SAN")
+ require.Contains(t, cert.DNSNames, "arcane-agent")
+
+ require.True(t, cert.NotBefore.Before(cert.NotAfter))
+ skew := cert.NotAfter.Sub(cert.NotBefore)
+ require.True(t, skew > 0)
+}
+
+func TestEnsureAgentMTLSAssets_RejectsPlainHTTPEnrollment(t *testing.T) {
+ cfg := &Config{
+ ManagerApiUrl: "http://manager.example.com/api",
+ AgentToken: "valid-token",
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ }
+
+ err := EnsureAgentMTLSAssets(context.Background(), cfg)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "MANAGER_API_URL to use https for certificate enrollment")
+}
+
+func TestEnsureAgentMTLSAssets_LimitsEnrollmentErrorBody(t *testing.T) {
+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusInternalServerError)
+ _, _ = w.Write([]byte(strings.Repeat("a", maxEnrollResponseBytes*2)))
+ }))
+ t.Cleanup(server.Close)
+
+ caPath := filepath.Join(t.TempDir(), "manager.crt")
+ require.NoError(t, os.WriteFile(caPath, pem.EncodeToMemory(&pem.Block{
+ Type: "CERTIFICATE",
+ Bytes: server.Certificate().Raw,
+ }), 0o600))
+
+ cfg := &Config{
+ ManagerApiUrl: server.URL + "/api",
+ AgentToken: "valid-token",
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ EdgeMTLSCAFile: caPath,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ }
+
+ err := EnsureAgentMTLSAssets(context.Background(), cfg)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "edge mTLS enrollment failed with status 500")
+ require.LessOrEqual(t, len(err.Error()), maxEnrollResponseBytes+128)
+}
+
+func TestEnsureAgentMTLSAssets_UsesDownloadedCAPathWhenPresent(t *testing.T) {
+ assetsDir := t.TempDir()
+ caPath := filepath.Join(assetsDir, generatedMTLSCACertFileName)
+
+ generated, err := GenerateManagerClientMTLSAssetsWithContext(context.Background(), &Config{
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ AppURL: "https://manager.example.com",
+ }, "env-existing", "Existing")
+ require.NoError(t, err)
+ require.NotNil(t, generated)
+ for _, file := range generated.Files {
+ targetPath := filepath.Join(assetsDir, filepath.Base(file.Name))
+ perm := common.FilePerm
+ if file.Permissions == "0600" {
+ perm = 0o600
+ }
+ require.NoError(t, os.WriteFile(targetPath, []byte(file.Content), perm))
+ }
+
+ cfg := &Config{
+ ManagerApiUrl: "https://manager.example.com/api",
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: assetsDir,
+ }
+
+ require.NoError(t, EnsureAgentMTLSAssets(context.Background(), cfg))
+ require.NotEmpty(t, cfg.EdgeMTLSCertFile)
+ require.NotEmpty(t, cfg.EdgeMTLSKeyFile)
+ require.FileExists(t, cfg.EdgeMTLSCertFile)
+ require.FileExists(t, cfg.EdgeMTLSKeyFile)
+ require.Equal(t, caPath, cfg.EdgeMTLSCAFile)
+}
+
+func TestRemoveStaleEdgeMTLSLockInternal_PreservesLivePID(t *testing.T) {
+ lockPath := filepath.Join(t.TempDir(), ".ca.lock")
+ require.NoError(t, os.WriteFile(lockPath, []byte(fmt.Sprintf("%d %s\n", os.Getpid(), time.Now().UTC().Format(time.RFC3339Nano))), 0o600))
+
+ require.False(t, removeStaleEdgeMTLSLockInternal(lockPath))
+ require.FileExists(t, lockPath)
+}
+
+func TestRemoveStaleEdgeMTLSLockInternal_RemovesOldLockDespiteLivePID(t *testing.T) {
+ lockPath := filepath.Join(t.TempDir(), ".ca.lock")
+ oldTimestamp := time.Now().Add(-(2*managerCALockTimeout + time.Second)).UTC().Format(time.RFC3339Nano)
+ require.NoError(t, os.WriteFile(lockPath, []byte(fmt.Sprintf("%d %s\n", os.Getpid(), oldTimestamp)), 0o600))
+
+ require.True(t, removeStaleEdgeMTLSLockInternal(lockPath))
+ require.NoFileExists(t, lockPath)
+}
+
+func TestBuildManagerClientTLSConfigInternal_OptionalIgnoresBrokenClientCertificate(t *testing.T) {
+ assetsDir := t.TempDir()
+ certPath := filepath.Join(assetsDir, generatedMTLSClientCertName)
+ keyPath := filepath.Join(assetsDir, generatedMTLSClientKeyName)
+ require.NoError(t, os.WriteFile(certPath, []byte("not a cert"), 0o644))
+ require.NoError(t, os.WriteFile(keyPath, []byte("not a key"), 0o600))
+
+ tlsConfig, err := buildManagerClientTLSConfigInternal(&Config{
+ ManagerApiUrl: "https://manager.example.com",
+ EdgeMTLSMode: EdgeMTLSModeOptional,
+ EdgeMTLSCertFile: certPath,
+ EdgeMTLSKeyFile: keyPath,
+ })
+ require.NoError(t, err)
+ require.NotNil(t, tlsConfig)
+ require.Empty(t, tlsConfig.Certificates)
+}
+
+func TestVerifiedPeerCertificateEnvironmentIDMatchesInternal(t *testing.T) {
+ uriSAN, err := url.Parse("spiffe://manager.example.com/edge/env-123")
+ require.NoError(t, err)
+ cert := &x509.Certificate{URIs: []*url.URL{uriSAN}}
+ state := &tls.ConnectionState{
+ PeerCertificates: []*x509.Certificate{cert},
+ VerifiedChains: [][]*x509.Certificate{{cert}},
+ }
+
+ require.NoError(t, verifiedPeerCertificateEnvironmentIDMatchesInternal(state, "env-123", "manager.example.com"))
+ require.Error(t, verifiedPeerCertificateEnvironmentIDMatchesInternal(state, "env-456", "manager.example.com"))
+ require.Error(t, verifiedPeerCertificateEnvironmentIDMatchesInternal(state, "env-123", "other.example.com"))
+}
+
+func TestTunnelServerRequireCertificateIdentityInternal_RejectsWrongEnvironmentURI(t *testing.T) {
+ uriSAN, err := url.Parse("spiffe://manager.example.com/edge/env-a")
+ require.NoError(t, err)
+ cert := &x509.Certificate{URIs: []*url.URL{uriSAN}}
+ state := &tls.ConnectionState{
+ PeerCertificates: []*x509.Certificate{cert},
+ VerifiedChains: [][]*x509.Certificate{{cert}},
+ }
+ server := NewTunnelServer(nil, nil)
+ server.SetConfig(&Config{
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ AppURL: "https://manager.example.com",
+ })
+
+ require.NoError(t, server.requireCertificateIdentityInternal(state, "env-a"))
+ require.Error(t, server.requireCertificateIdentityInternal(state, "env-b"))
+}
+
+func TestAgentMTLSAssetsNeedEnrollmentInternal_RenewsExpiredCertificate(t *testing.T) {
+ assetsDir := t.TempDir()
+ assets, err := GenerateManagerClientMTLSAssetsWithContext(context.Background(), &Config{
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ AppURL: "https://manager.example.com",
+ }, "env-renew", "Renew")
+ require.NoError(t, err)
+
+ for _, file := range assets.Files {
+ targetPath := filepath.Join(assetsDir, filepath.Base(file.Name))
+ perm := common.FilePerm
+ if file.Permissions == "0600" {
+ perm = 0o600
+ }
+ require.NoError(t, os.WriteFile(targetPath, []byte(file.Content), perm))
+ }
+
+ needsEnrollment, reason := agentMTLSAssetsNeedEnrollmentInternal(
+ filepath.Join(assetsDir, generatedMTLSClientCertName),
+ filepath.Join(assetsDir, generatedMTLSClientKeyName),
+ time.Now().Add(generatedMTLSCertValidity+24*time.Hour),
+ )
+ require.True(t, needsEnrollment)
+ require.Contains(t, reason, "expired")
+}
+
+func TestValidateGeneratedClientCertificateInternal_RejectsMismatchedKeyPair(t *testing.T) {
+ assetsDir := t.TempDir()
+
+ clientCertPath, _, _, err := ensureClientCertificateInternal(context.Background(), assetsDir, "env-123", "Lab Server", "https://manager.example.com")
+ require.NoError(t, err)
+
+ replacementKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
+ require.NoError(t, err)
+
+ replacementKeyDER, err := x509.MarshalECPrivateKey(replacementKey)
+ require.NoError(t, err)
+
+ clientKeyPath := filepath.Join(assetsDir, generatedClientMTLSSubdir, "env-123", generatedMTLSClientKeyName)
+ err = writePEMFileInternal(clientKeyPath, "EC PRIVATE KEY", replacementKeyDER, 0o600)
+ require.NoError(t, err)
+
+ expectedURI, err := url.Parse("spiffe://manager.example.com/edge/env-123")
+ require.NoError(t, err)
+
+ err = validateGeneratedClientCertificateInternal(clientCertPath, clientKeyPath, "Lab-Server-env-123", expectedURI)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "does not match private key")
+}
+
+func TestEnsureClientCertificateInternal_PreservesCertificateWhenEnvironmentNameChanges(t *testing.T) {
+ assetsDir := t.TempDir()
+
+ clientCertPath, _, _, err := ensureClientCertificateInternal(context.Background(), assetsDir, "env-123", "", "https://manager.example.com")
+ require.NoError(t, err)
+
+ originalPEM, err := os.ReadFile(clientCertPath)
+ require.NoError(t, err)
+
+ clientCertPath, _, _, err = ensureClientCertificateInternal(context.Background(), assetsDir, "env-123", "Lab Server", "https://manager.example.com")
+ require.NoError(t, err)
+
+ updatedPEM, err := os.ReadFile(clientCertPath)
+ require.NoError(t, err)
+ require.Equal(t, string(originalPEM), string(updatedPEM))
+
+ certBlock, _ := pem.Decode(updatedPEM)
+ require.NotNil(t, certBlock)
+
+ cert, err := x509.ParseCertificate(certBlock.Bytes)
+ require.NoError(t, err)
+ require.Equal(t, "env-123", cert.Subject.CommonName)
+}
+
+func TestCAKey_EncryptedOnDiskWhenCryptoInitialized(t *testing.T) {
+ initEdgeTestCrypto(t)
+
+ assetsDir := t.TempDir()
+ caCertPath, caKeyPath, _, err := ensureManagerCAInternal(context.Background(), assetsDir)
+ require.NoError(t, err)
+ require.FileExists(t, caCertPath)
+ require.FileExists(t, caKeyPath)
+
+ require.True(t, isCAKeyEncryptedOnDiskInternal(caKeyPath),
+ "CA key file must be stored in the encrypted envelope format when libcrypto is initialized")
+
+ raw, err := os.ReadFile(caKeyPath)
+ require.NoError(t, err)
+ require.False(t, strings.Contains(string(raw), "BEGIN EC PRIVATE KEY"),
+ "encrypted CA key file must not contain plain PEM markers")
+
+ pemBytes, err := readCAKeyPEMInternal(caKeyPath)
+ require.NoError(t, err)
+ block, _ := pem.Decode(pemBytes)
+ require.NotNil(t, block)
+ _, err = x509.ParseECPrivateKey(block.Bytes)
+ require.NoError(t, err)
+
+ clientCertPath, clientKeyPath, _, err := ensureClientCertificateInternal(context.Background(), assetsDir, "env-round", "Round Trip", "https://manager.example.com")
+ require.NoError(t, err)
+ require.FileExists(t, clientCertPath)
+ require.FileExists(t, clientKeyPath)
+}
+
+func TestCAKey_MigratesLegacyPlainFile(t *testing.T) {
+ initEdgeTestCrypto(t)
+
+ assetsDir := t.TempDir()
+ _, caKeyPath, _, err := ensureManagerCAInternal(context.Background(), assetsDir)
+ require.NoError(t, err)
+
+ pemBytes, err := readCAKeyPEMInternal(caKeyPath)
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(caKeyPath, pemBytes, 0o600))
+ require.False(t, isCAKeyEncryptedOnDiskInternal(caKeyPath))
+
+ _, caKeyPath2, _, err := ensureManagerCAInternal(context.Background(), assetsDir)
+ require.NoError(t, err)
+ require.Equal(t, caKeyPath, caKeyPath2)
+ require.True(t, isCAKeyEncryptedOnDiskInternal(caKeyPath),
+ "legacy plain CA key file must be migrated to the encrypted envelope format on next load")
+}
+
+func TestCAKey_LegacyPlainMigrationFailureReturnsError(t *testing.T) {
+ initEdgeTestCrypto(t)
+
+ assetsDir := t.TempDir()
+ _, caKeyPath, _, err := ensureManagerCAInternal(context.Background(), assetsDir)
+ require.NoError(t, err)
+
+ pemBytes, err := readCAKeyPEMInternal(caKeyPath)
+ require.NoError(t, err)
+ require.NoError(t, os.WriteFile(caKeyPath, pemBytes, 0o600))
+
+ originalEncrypt := caKeyEncryptInternal
+ t.Cleanup(func() {
+ caKeyEncryptInternal = originalEncrypt
+ })
+ caKeyEncryptInternal = func(string) (string, error) {
+ return "", errors.New("encrypt failed")
+ }
+
+ _, _, _, err = ensureManagerCAInternal(context.Background(), assetsDir)
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "failed to migrate edge mTLS CA key to encrypted format")
+}
+
+func TestCAKey_EncryptionFailureReturnsError(t *testing.T) {
+ originalEncrypt := caKeyEncryptInternal
+ t.Cleanup(func() {
+ caKeyEncryptInternal = originalEncrypt
+ })
+
+ caKeyPath := filepath.Join(t.TempDir(), "ca.key")
+ caKeyEncryptInternal = func(string) (string, error) {
+ return "", errors.New("encrypt failed")
+ }
+
+ err := writeCAKeyFileInternal(caKeyPath, []byte{1, 2, 3})
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "failed to encrypt edge mTLS CA private key")
+ require.NoFileExists(t, caKeyPath)
+}
+
+func TestLockEdgeMTLSPathInternal_ReturnsOnContextCancellation(t *testing.T) {
+ assetsDir := t.TempDir()
+
+ unlock, err := lockEdgeMTLSPathInternal(context.Background(), assetsDir, ".ca.lock")
+ require.NoError(t, err)
+ defer unlock()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ _, err = lockEdgeMTLSPathInternal(ctx, assetsDir, ".ca.lock")
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "cancelled waiting for edge mTLS CA lock")
+}
+
+func TestCAKey_EmptyEncryptionPayloadReturnsError(t *testing.T) {
+ originalEncrypt := caKeyEncryptInternal
+ t.Cleanup(func() {
+ caKeyEncryptInternal = originalEncrypt
+ })
+
+ caKeyPath := filepath.Join(t.TempDir(), "ca.key")
+ caKeyEncryptInternal = func(string) (string, error) {
+ return "", nil
+ }
+
+ err := writeCAKeyFileInternal(caKeyPath, []byte{1, 2, 3})
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "encrypted payload is empty")
+ require.NoFileExists(t, caKeyPath)
+}
+
+func TestBuildGeneratedClientSANsInternal(t *testing.T) {
+ uri, dns := buildGeneratedClientSANsInternal("Lab Server", "env-123", "https://manager.example.com")
+ require.NotNil(t, uri)
+ require.Equal(t, "spiffe", uri.Scheme)
+ require.Equal(t, "manager.example.com", uri.Host)
+ require.Equal(t, "/edge/env-123", uri.Path)
+ require.Contains(t, dns, "arcane-agent")
+ require.Contains(t, dns, "Lab-Server.agent.manager.example.com")
+
+ uriEmpty, dnsEmpty := buildGeneratedClientSANsInternal("", "", "https://manager.example.com")
+ require.Nil(t, uriEmpty)
+ require.Nil(t, dnsEmpty)
+}
+
+func TestShouldAutoGenerateManagerCAInternal(t *testing.T) {
+ cfg := &Config{
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ EdgeMTLSAssetsDir: t.TempDir(),
+ }
+
+ require.True(t, shouldAutoGenerateManagerCAInternal(cfg))
+
+ cfg.EdgeMTLSCAFile = filepath.Join(t.TempDir(), "ca.crt")
+ require.False(t, shouldAutoGenerateManagerCAInternal(cfg))
+}
+
+func TestShouldAutoEnrollAgentMTLSInternal(t *testing.T) {
+ cfg := &Config{
+ EdgeMTLSMode: EdgeMTLSModeRequired,
+ }
+
+ require.True(t, shouldAutoEnrollAgentMTLSInternal(cfg))
+
+ cfg.EdgeMTLSCertFile = filepath.Join(t.TempDir(), "agent.crt")
+ cfg.EdgeMTLSKeyFile = filepath.Join(t.TempDir(), "agent.key")
+ require.False(t, shouldAutoEnrollAgentMTLSInternal(cfg))
+}
diff --git a/backend/pkg/libarcane/edge/transport.go b/backend/pkg/libarcane/edge/transport.go
index 88b4bf9e1..b4103ff52 100644
--- a/backend/pkg/libarcane/edge/transport.go
+++ b/backend/pkg/libarcane/edge/transport.go
@@ -11,6 +11,13 @@ type Config struct {
EdgeAgent bool
EdgeTransport string
EdgeReconnectInterval int
+ EdgeMTLSMode string
+ EdgeMTLSCAFile string
+ EdgeMTLSCertFile string
+ EdgeMTLSKeyFile string
+ EdgeMTLSServerName string
+ EdgeMTLSAssetsDir string
+ AppURL string
ManagerApiUrl string
AgentToken string
Port string
@@ -62,6 +69,11 @@ type TunnelRuntimeState struct {
Transport string
ConnectedAt *time.Time
LastHeartbeat *time.Time
+ SessionID string
+ AgentInstance string
+ SecurityMode string
+ Capabilities []string
+ State string
}
const (
@@ -75,6 +87,13 @@ const (
// EdgeTransportAuto preserves the legacy managed tunnel behavior: try gRPC
// first and fall back to websocket when available.
EdgeTransportAuto = "auto"
+
+ // EdgeMTLSModeDisabled disables edge tunnel mTLS.
+ EdgeMTLSModeDisabled = "disabled"
+ // EdgeMTLSModeOptional enables edge tunnel mTLS when certificates are configured.
+ EdgeMTLSModeOptional = "optional"
+ // EdgeMTLSModeRequired requires a verified client certificate on edge tunnel endpoints.
+ EdgeMTLSModeRequired = "required"
)
// NormalizeEdgeTransport normalizes transport config and defaults to the legacy
@@ -94,6 +113,18 @@ func NormalizeEdgeTransport(value string) string {
}
}
+// NormalizeEdgeMTLSMode normalizes edge mTLS config and defaults to disabled.
+func NormalizeEdgeMTLSMode(value string) string {
+ switch strings.ToLower(strings.TrimSpace(value)) {
+ case EdgeMTLSModeOptional:
+ return EdgeMTLSModeOptional
+ case EdgeMTLSModeRequired:
+ return EdgeMTLSModeRequired
+ default:
+ return EdgeMTLSModeDisabled
+ }
+}
+
// UseGRPCEdgeTransport reports whether gRPC managed tunnel mode should be attempted.
func UseGRPCEdgeTransport(cfg *Config) bool {
if cfg == nil {
@@ -156,6 +187,11 @@ func GetTunnelRuntimeState(envID string) (*TunnelRuntimeState, bool) {
state.ConnectedAt = new(tunnel.ConnectedAt)
state.LastHeartbeat = new(tunnel.GetLastHeartbeat())
+ state.SessionID = tunnel.SessionID
+ state.AgentInstance = tunnel.AgentInstance
+ state.SecurityMode = tunnel.SecurityMode
+ state.Capabilities = append([]string(nil), tunnel.Capabilities...)
+ state.State = tunnel.State
return state, true
}
diff --git a/backend/pkg/libarcane/edge/transport_test.go b/backend/pkg/libarcane/edge/transport_test.go
index 74c4f0263..3e4b2e663 100644
--- a/backend/pkg/libarcane/edge/transport_test.go
+++ b/backend/pkg/libarcane/edge/transport_test.go
@@ -18,6 +18,13 @@ func TestNormalizeEdgeTransport(t *testing.T) {
assert.Equal(t, EdgeTransportAuto, NormalizeEdgeTransport("auto"))
}
+func TestNormalizeEdgeMTLSMode(t *testing.T) {
+ assert.Equal(t, EdgeMTLSModeDisabled, NormalizeEdgeMTLSMode(""))
+ assert.Equal(t, EdgeMTLSModeOptional, NormalizeEdgeMTLSMode("optional"))
+ assert.Equal(t, EdgeMTLSModeRequired, NormalizeEdgeMTLSMode("REQUIRED"))
+ assert.Equal(t, EdgeMTLSModeDisabled, NormalizeEdgeMTLSMode("invalid"))
+}
+
func TestUseGRPCEdgeTransport(t *testing.T) {
assert.False(t, UseGRPCEdgeTransport(nil))
assert.True(t, UseGRPCEdgeTransport(&Config{EdgeTransport: "grpc"}))
@@ -72,7 +79,7 @@ func TestGetActiveTunnelTransport(t *testing.T) {
conn := createTestConn(t)
defer func() { _ = conn.Close() }()
- tunnel := NewAgentTunnel(envID, conn)
+ tunnel := newWebSocketAgentTunnel(envID, conn)
GetRegistry().Register(envID, tunnel)
transport, ok := GetActiveTunnelTransport(envID)
@@ -121,6 +128,10 @@ func TestGetTunnelRuntimeState(t *testing.T) {
defer GetRegistry().Unregister(envID)
tunnel := NewAgentTunnelWithConn(envID, NewGRPCManagerTunnelConn(nil))
+ tunnel.SessionID = "session-1"
+ tunnel.AgentInstance = "agent-1"
+ tunnel.SecurityMode = "mtls"
+ tunnel.Capabilities = []string{"container.list"}
GetRegistry().Register(envID, tunnel)
state, ok := GetTunnelRuntimeState(envID)
@@ -129,6 +140,10 @@ func TestGetTunnelRuntimeState(t *testing.T) {
assert.Equal(t, EdgeTransportGRPC, state.Transport)
assert.NotNil(t, state.ConnectedAt)
assert.NotNil(t, state.LastHeartbeat)
+ assert.Equal(t, "session-1", state.SessionID)
+ assert.Equal(t, "agent-1", state.AgentInstance)
+ assert.Equal(t, "mtls", state.SecurityMode)
+ assert.Equal(t, []string{"container.list"}, state.Capabilities)
}
})
diff --git a/backend/pkg/libarcane/edge/tunnel.go b/backend/pkg/libarcane/edge/tunnel.go
index 913a65c2d..f96aa9add 100644
--- a/backend/pkg/libarcane/edge/tunnel.go
+++ b/backend/pkg/libarcane/edge/tunnel.go
@@ -42,6 +42,22 @@ const (
MessageTypeRegisterResponse TunnelMessageType = "register_response"
// MessageTypeEvent carries an event emitted by an agent to the manager.
MessageTypeEvent TunnelMessageType = "event"
+ // MessageTypeCommandRequest sends a typed edge command from manager to agent.
+ MessageTypeCommandRequest TunnelMessageType = "command_request"
+ // MessageTypeCommandAck acknowledges a command was accepted by the agent.
+ MessageTypeCommandAck TunnelMessageType = "command_ack"
+ // MessageTypeCommandOutput carries chunked command output from agent to manager.
+ MessageTypeCommandOutput TunnelMessageType = "command_output"
+ // MessageTypeCommandComplete indicates final command completion.
+ MessageTypeCommandComplete TunnelMessageType = "command_complete"
+ // MessageTypeFileChunk carries chunked request or response payload data.
+ MessageTypeFileChunk TunnelMessageType = "file_chunk"
+ // MessageTypeStreamOpen opens a command-backed stream.
+ MessageTypeStreamOpen TunnelMessageType = "stream_open"
+ // MessageTypeStreamClose closes a command-backed stream.
+ MessageTypeStreamClose TunnelMessageType = "stream_close"
+ // MessageTypeCancelRequest requests cancellation of an in-flight command.
+ MessageTypeCancelRequest TunnelMessageType = "cancel_request"
)
// TunnelMessage represents a transport-agnostic edge tunnel message.
@@ -60,6 +76,18 @@ type TunnelMessage struct {
EnvironmentID string `json:"environment_id,omitempty"` // Manager-resolved environment ID
Error string `json:"error,omitempty"` // Error field for register response
Event *TunnelEvent `json:"event,omitempty"` // Agent event payload
+ Command string `json:"command,omitempty"` // Typed command name
+ SessionID string `json:"session_id,omitempty"` // Manager-issued session identifier
+ ResumeSession string `json:"resume_session,omitempty"` // Previous session being resumed
+ AgentInstance string `json:"agent_instance,omitempty"` // Stable agent runtime identity
+ Capabilities []string `json:"capabilities,omitempty"` // Agent advertised capabilities
+ SecurityMode string `json:"security_mode,omitempty"` // token, mtls, etc.
+ DrainPrevious bool `json:"drain_previous,omitempty"` // Replace previous session
+ TimeoutMillis int64 `json:"timeout_millis,omitempty"` // Command timeout
+ Sequence int64 `json:"sequence,omitempty"` // Chunk sequence number
+ Streaming bool `json:"streaming,omitempty"` // Response used chunked output
+ Metadata map[string]string `json:"metadata,omitempty"` // Correlation and audit metadata
+ EOF bool `json:"eof,omitempty"` // Final chunk indicator
}
// TunnelEvent is an event payload sent from an agent to the manager.
diff --git a/backend/pkg/libarcane/edge/tunnel_proto_adapter.go b/backend/pkg/libarcane/edge/tunnel_proto_adapter.go
index a04c1df73..55a668b68 100644
--- a/backend/pkg/libarcane/edge/tunnel_proto_adapter.go
+++ b/backend/pkg/libarcane/edge/tunnel_proto_adapter.go
@@ -42,6 +42,16 @@ func tunnelMessageToManagerProto(msg *TunnelMessage) (*tunnelpb.ManagerMessage,
Data: msg.Body,
MessageType: messageType,
}}}, nil
+ case MessageTypeStreamData:
+ messageType, err := intToInt32(msg.WSMessageType, "ws_message_type")
+ if err != nil {
+ return nil, err
+ }
+ return &tunnelpb.ManagerMessage{Payload: &tunnelpb.ManagerMessage_WsData{WsData: &tunnelpb.WebSocketData{
+ StreamId: msg.ID,
+ Data: msg.Body,
+ MessageType: messageType,
+ }}}, nil
case MessageTypeWebSocketClose:
return &tunnelpb.ManagerMessage{Payload: &tunnelpb.ManagerMessage_WsClose{WsClose: &tunnelpb.WebSocketClose{StreamId: msg.ID}}}, nil
case MessageTypeRegisterResponse:
@@ -49,8 +59,58 @@ func tunnelMessageToManagerProto(msg *TunnelMessage) (*tunnelpb.ManagerMessage,
Accepted: msg.Accepted,
EnvironmentId: msg.EnvironmentID,
Error: msg.Error,
+ SessionId: msg.SessionID,
+ SecurityMode: msg.SecurityMode,
+ Capabilities: append([]string(nil), msg.Capabilities...),
+ DrainPrevious: msg.DrainPrevious,
+ }}}, nil
+ case MessageTypeCommandRequest:
+ return &tunnelpb.ManagerMessage{Payload: &tunnelpb.ManagerMessage_CommandRequest{CommandRequest: &tunnelpb.CommandRequest{
+ CommandId: msg.ID,
+ CommandName: msg.Command,
+ Method: msg.Method,
+ Path: msg.Path,
+ Query: msg.Query,
+ Headers: cloneHeaderMap(msg.Headers),
+ Body: msg.Body,
+ TimeoutMillis: msg.TimeoutMillis,
+ SessionId: msg.SessionID,
+ AgentInstanceId: msg.AgentInstance,
+ Metadata: cloneHeaderMap(msg.Metadata),
+ }}}, nil
+ case MessageTypeStreamOpen:
+ return &tunnelpb.ManagerMessage{Payload: &tunnelpb.ManagerMessage_StreamOpen{StreamOpen: &tunnelpb.StreamOpen{
+ StreamId: msg.ID,
+ CommandName: msg.Command,
+ Path: msg.Path,
+ Query: msg.Query,
+ Headers: cloneHeaderMap(msg.Headers),
+ SessionId: msg.SessionID,
+ }}}, nil
+ case MessageTypeStreamClose:
+ return &tunnelpb.ManagerMessage{Payload: &tunnelpb.ManagerMessage_StreamClose{StreamClose: &tunnelpb.StreamClose{
+ StreamId: msg.ID,
+ Error: msg.Error,
}}}, nil
- case MessageTypeResponse, MessageTypeHeartbeat, MessageTypeStreamData, MessageTypeStreamEnd, MessageTypeRegister, MessageTypeEvent:
+ case MessageTypeCancelRequest:
+ return &tunnelpb.ManagerMessage{Payload: &tunnelpb.ManagerMessage_CancelRequest{CancelRequest: &tunnelpb.CancelRequest{
+ CommandId: msg.ID,
+ }}}, nil
+ case MessageTypeFileChunk:
+ return &tunnelpb.ManagerMessage{Payload: &tunnelpb.ManagerMessage_FileChunk{FileChunk: &tunnelpb.FileChunk{
+ TransferId: msg.ID,
+ Data: msg.Body,
+ Sequence: msg.Sequence,
+ Eof: msg.EOF,
+ }}}, nil
+ case MessageTypeResponse,
+ MessageTypeHeartbeat,
+ MessageTypeStreamEnd,
+ MessageTypeRegister,
+ MessageTypeEvent,
+ MessageTypeCommandAck,
+ MessageTypeCommandOutput,
+ MessageTypeCommandComplete:
return nil, fmt.Errorf("unsupported manager message type: %s", msg.Type)
default:
return nil, fmt.Errorf("unsupported manager message type: %s", msg.Type)
@@ -98,6 +158,54 @@ func managerProtoToTunnelMessage(msg *tunnelpb.ManagerMessage) (*TunnelMessage,
Accepted: payload.RegisterResponse.GetAccepted(),
EnvironmentID: payload.RegisterResponse.GetEnvironmentId(),
Error: payload.RegisterResponse.GetError(),
+ SessionID: payload.RegisterResponse.GetSessionId(),
+ SecurityMode: payload.RegisterResponse.GetSecurityMode(),
+ Capabilities: append([]string(nil), payload.RegisterResponse.GetCapabilities()...),
+ DrainPrevious: payload.RegisterResponse.GetDrainPrevious(),
+ }, nil
+ case *tunnelpb.ManagerMessage_CommandRequest:
+ return &TunnelMessage{
+ ID: payload.CommandRequest.GetCommandId(),
+ Type: MessageTypeCommandRequest,
+ Command: payload.CommandRequest.GetCommandName(),
+ Method: payload.CommandRequest.GetMethod(),
+ Path: payload.CommandRequest.GetPath(),
+ Query: payload.CommandRequest.GetQuery(),
+ Headers: cloneHeaderMap(payload.CommandRequest.GetHeaders()),
+ Body: payload.CommandRequest.GetBody(),
+ TimeoutMillis: payload.CommandRequest.GetTimeoutMillis(),
+ SessionID: payload.CommandRequest.GetSessionId(),
+ AgentInstance: payload.CommandRequest.GetAgentInstanceId(),
+ Metadata: cloneHeaderMap(payload.CommandRequest.GetMetadata()),
+ }, nil
+ case *tunnelpb.ManagerMessage_StreamOpen:
+ return &TunnelMessage{
+ ID: payload.StreamOpen.GetStreamId(),
+ Type: MessageTypeStreamOpen,
+ Command: payload.StreamOpen.GetCommandName(),
+ Path: payload.StreamOpen.GetPath(),
+ Query: payload.StreamOpen.GetQuery(),
+ Headers: cloneHeaderMap(payload.StreamOpen.GetHeaders()),
+ SessionID: payload.StreamOpen.GetSessionId(),
+ }, nil
+ case *tunnelpb.ManagerMessage_StreamClose:
+ return &TunnelMessage{
+ ID: payload.StreamClose.GetStreamId(),
+ Type: MessageTypeStreamClose,
+ Error: payload.StreamClose.GetError(),
+ }, nil
+ case *tunnelpb.ManagerMessage_CancelRequest:
+ return &TunnelMessage{
+ ID: payload.CancelRequest.GetCommandId(),
+ Type: MessageTypeCancelRequest,
+ }, nil
+ case *tunnelpb.ManagerMessage_FileChunk:
+ return &TunnelMessage{
+ ID: payload.FileChunk.GetTransferId(),
+ Type: MessageTypeFileChunk,
+ Body: payload.FileChunk.GetData(),
+ Sequence: payload.FileChunk.GetSequence(),
+ EOF: payload.FileChunk.GetEof(),
}, nil
default:
return nil, fmt.Errorf("unsupported manager payload type %T", payload)
@@ -136,11 +244,24 @@ func tunnelMessageToAgentProto(msg *TunnelMessage) (*tunnelpb.AgentMessage, erro
case MessageTypeWebSocketClose:
return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_WsClose{WsClose: &tunnelpb.WebSocketClose{StreamId: msg.ID}}}, nil
case MessageTypeStreamData:
- return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_StreamData{StreamData: &tunnelpb.StreamData{RequestId: msg.ID, Data: msg.Body}}}, nil
+ messageType, err := intToInt32(msg.WSMessageType, "ws_message_type")
+ if err != nil {
+ return nil, err
+ }
+ return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_StreamData{StreamData: &tunnelpb.StreamData{
+ RequestId: msg.ID,
+ Data: msg.Body,
+ MessageType: messageType,
+ }}}, nil
case MessageTypeStreamEnd:
return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_StreamEnd{StreamEnd: &tunnelpb.StreamEnd{RequestId: msg.ID}}}, nil
case MessageTypeRegister:
- return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_Register{Register: &tunnelpb.RegisterRequest{AgentToken: msg.AgentToken}}}, nil
+ return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_Register{Register: &tunnelpb.RegisterRequest{
+ AgentToken: msg.AgentToken,
+ AgentInstanceId: msg.AgentInstance,
+ Capabilities: append([]string(nil), msg.Capabilities...),
+ ResumeSessionId: msg.ResumeSession,
+ }}}, nil
case MessageTypeEvent:
if msg.Event == nil {
return nil, fmt.Errorf("event payload is required for message type: %s", msg.Type)
@@ -157,7 +278,48 @@ func tunnelMessageToAgentProto(msg *TunnelMessage) (*tunnelpb.AgentMessage, erro
Username: msg.Event.Username,
MetadataJson: append([]byte(nil), msg.Event.MetadataJSON...),
}}}, nil
- case MessageTypeRequest, MessageTypeHeartbeatAck, MessageTypeWebSocketStart, MessageTypeRegisterResponse:
+ case MessageTypeCommandAck:
+ return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
+ CommandId: msg.ID,
+ }}}, nil
+ case MessageTypeCommandOutput:
+ return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandOutput{CommandOutput: &tunnelpb.CommandOutput{
+ CommandId: msg.ID,
+ Data: msg.Body,
+ Sequence: msg.Sequence,
+ }}}, nil
+ case MessageTypeCommandComplete:
+ status, err := intToInt32(msg.Status, "status")
+ if err != nil {
+ return nil, err
+ }
+ return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandComplete{CommandComplete: &tunnelpb.CommandComplete{
+ CommandId: msg.ID,
+ Status: status,
+ Headers: cloneHeaderMap(msg.Headers),
+ Body: msg.Body,
+ Error: msg.Error,
+ Streaming: msg.Streaming,
+ }}}, nil
+ case MessageTypeFileChunk:
+ return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_FileChunk{FileChunk: &tunnelpb.FileChunk{
+ TransferId: msg.ID,
+ Data: msg.Body,
+ Sequence: msg.Sequence,
+ Eof: msg.EOF,
+ }}}, nil
+ case MessageTypeStreamClose:
+ return &tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_StreamClose{StreamClose: &tunnelpb.StreamClose{
+ StreamId: msg.ID,
+ Error: msg.Error,
+ }}}, nil
+ case MessageTypeRequest,
+ MessageTypeHeartbeatAck,
+ MessageTypeWebSocketStart,
+ MessageTypeRegisterResponse,
+ MessageTypeCommandRequest,
+ MessageTypeStreamOpen,
+ MessageTypeCancelRequest:
return nil, fmt.Errorf("unsupported agent message type: %s", msg.Type)
default:
return nil, fmt.Errorf("unsupported agent message type: %s", msg.Type)
@@ -190,11 +352,22 @@ func agentProtoToTunnelMessage(msg *tunnelpb.AgentMessage) (*TunnelMessage, erro
case *tunnelpb.AgentMessage_WsClose:
return &TunnelMessage{ID: payload.WsClose.GetStreamId(), Type: MessageTypeWebSocketClose}, nil
case *tunnelpb.AgentMessage_StreamData:
- return &TunnelMessage{ID: payload.StreamData.GetRequestId(), Type: MessageTypeStreamData, Body: payload.StreamData.GetData()}, nil
+ return &TunnelMessage{
+ ID: payload.StreamData.GetRequestId(),
+ Type: MessageTypeStreamData,
+ Body: payload.StreamData.GetData(),
+ WSMessageType: int(payload.StreamData.GetMessageType()),
+ }, nil
case *tunnelpb.AgentMessage_StreamEnd:
return &TunnelMessage{ID: payload.StreamEnd.GetRequestId(), Type: MessageTypeStreamEnd}, nil
case *tunnelpb.AgentMessage_Register:
- return &TunnelMessage{Type: MessageTypeRegister, AgentToken: payload.Register.GetAgentToken()}, nil
+ return &TunnelMessage{
+ Type: MessageTypeRegister,
+ AgentToken: payload.Register.GetAgentToken(),
+ AgentInstance: payload.Register.GetAgentInstanceId(),
+ Capabilities: append([]string(nil), payload.Register.GetCapabilities()...),
+ ResumeSession: payload.Register.GetResumeSessionId(),
+ }, nil
case *tunnelpb.AgentMessage_Event:
return &TunnelMessage{
Type: MessageTypeEvent,
@@ -211,6 +384,39 @@ func agentProtoToTunnelMessage(msg *tunnelpb.AgentMessage) (*TunnelMessage, erro
MetadataJSON: append([]byte(nil), payload.Event.GetMetadataJson()...),
},
}, nil
+ case *tunnelpb.AgentMessage_CommandAck:
+ return &TunnelMessage{ID: payload.CommandAck.GetCommandId(), Type: MessageTypeCommandAck}, nil
+ case *tunnelpb.AgentMessage_CommandOutput:
+ return &TunnelMessage{
+ ID: payload.CommandOutput.GetCommandId(),
+ Type: MessageTypeCommandOutput,
+ Body: payload.CommandOutput.GetData(),
+ Sequence: payload.CommandOutput.GetSequence(),
+ }, nil
+ case *tunnelpb.AgentMessage_CommandComplete:
+ return &TunnelMessage{
+ ID: payload.CommandComplete.GetCommandId(),
+ Type: MessageTypeCommandComplete,
+ Status: int(payload.CommandComplete.GetStatus()),
+ Headers: cloneHeaderMap(payload.CommandComplete.GetHeaders()),
+ Body: payload.CommandComplete.GetBody(),
+ Error: payload.CommandComplete.GetError(),
+ Streaming: payload.CommandComplete.GetStreaming(),
+ }, nil
+ case *tunnelpb.AgentMessage_FileChunk:
+ return &TunnelMessage{
+ ID: payload.FileChunk.GetTransferId(),
+ Type: MessageTypeFileChunk,
+ Body: payload.FileChunk.GetData(),
+ Sequence: payload.FileChunk.GetSequence(),
+ EOF: payload.FileChunk.GetEof(),
+ }, nil
+ case *tunnelpb.AgentMessage_StreamClose:
+ return &TunnelMessage{
+ ID: payload.StreamClose.GetStreamId(),
+ Type: MessageTypeStreamClose,
+ Error: payload.StreamClose.GetError(),
+ }, nil
default:
return nil, fmt.Errorf("unsupported agent payload type %T", payload)
}
diff --git a/backend/pkg/libarcane/edge/tunnel_proto_adapter_test.go b/backend/pkg/libarcane/edge/tunnel_proto_adapter_test.go
index c822220ba..656368ac7 100644
--- a/backend/pkg/libarcane/edge/tunnel_proto_adapter_test.go
+++ b/backend/pkg/libarcane/edge/tunnel_proto_adapter_test.go
@@ -3,6 +3,7 @@ package edge
import (
"testing"
+ "github.com/gorilla/websocket"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -33,6 +34,24 @@ func TestTunnelMessageToManagerProto_RoundTripRequest(t *testing.T) {
assert.Equal(t, original.Body, decoded.Body)
}
+func TestTunnelMessageToManagerProto_StreamDataUsesWebSocketPayload(t *testing.T) {
+ original := &TunnelMessage{
+ ID: "stream-1",
+ Type: MessageTypeStreamData,
+ Body: []byte("hello"),
+ WSMessageType: websocket.TextMessage,
+ }
+
+ protoMsg, err := tunnelMessageToManagerProto(original)
+ require.NoError(t, err)
+
+ wsData := protoMsg.GetWsData()
+ require.NotNil(t, wsData)
+ assert.Equal(t, original.ID, wsData.GetStreamId())
+ assert.Equal(t, original.Body, wsData.GetData())
+ assert.Equal(t, int32(original.WSMessageType), wsData.GetMessageType())
+}
+
func TestTunnelMessageToAgentProto_RoundTripResponse(t *testing.T) {
original := &TunnelMessage{
ID: "req-1",
@@ -110,3 +129,23 @@ func TestTunnelMessageToManagerProto_UnsupportedType(t *testing.T) {
_, err := tunnelMessageToManagerProto(&TunnelMessage{Type: MessageTypeResponse})
require.Error(t, err)
}
+
+func TestTunnelMessageToAgentProto_RoundTripStreamDataPreservesWebSocketType(t *testing.T) {
+ original := &TunnelMessage{
+ ID: "stream-1",
+ Type: MessageTypeStreamData,
+ Body: []byte(`{"cpu":10}`),
+ WSMessageType: websocket.TextMessage,
+ }
+
+ protoMsg, err := tunnelMessageToAgentProto(original)
+ require.NoError(t, err)
+
+ decoded, err := agentProtoToTunnelMessage(protoMsg)
+ require.NoError(t, err)
+
+ assert.Equal(t, original.ID, decoded.ID)
+ assert.Equal(t, original.Type, decoded.Type)
+ assert.Equal(t, original.Body, decoded.Body)
+ assert.Equal(t, original.WSMessageType, decoded.WSMessageType)
+}
diff --git a/backend/pkg/libarcane/edge/tunnel_test.go b/backend/pkg/libarcane/edge/tunnel_test.go
index 6c3ee78b8..1a94b7309 100644
--- a/backend/pkg/libarcane/edge/tunnel_test.go
+++ b/backend/pkg/libarcane/edge/tunnel_test.go
@@ -16,6 +16,10 @@ import (
"github.com/stretchr/testify/require"
)
+func newWebSocketAgentTunnel(envID string, conn *websocket.Conn) *AgentTunnel {
+ return NewAgentTunnelWithConn(envID, NewTunnelConn(conn))
+}
+
func TestTunnelMessage_MarshalJSON(t *testing.T) {
msg := &TunnelMessage{
ID: "test-id",
diff --git a/backend/pkg/libarcane/edge/ws_proxy.go b/backend/pkg/libarcane/edge/ws_proxy.go
index 7df3892a7..1c6af8c98 100644
--- a/backend/pkg/libarcane/edge/ws_proxy.go
+++ b/backend/pkg/libarcane/edge/ws_proxy.go
@@ -45,7 +45,13 @@ func ProxyWebSocketRequest(c *gin.Context, tunnel *AgentTunnel, targetPath strin
defer tunnel.Pending.Delete(streamID)
headers := buildWebSocketHeaders(c.Request)
- if err := sendWebSocketStart(tunnel, streamID, targetPath, c.Request.URL.RawQuery, headers); err != nil {
+ if err := DefaultCommandClient.OpenStream(streamCtx, tunnel, &CommandRequest{
+ ID: streamID,
+ Method: http.MethodGet,
+ Path: targetPath,
+ Query: c.Request.URL.RawQuery,
+ Headers: headers,
+ }); err != nil {
slog.ErrorContext(ctx, "Failed to send WebSocket start to agent", "error", err)
return
}
@@ -72,17 +78,6 @@ func buildWebSocketHeaders(req *http.Request) map[string]string {
return headers
}
-func sendWebSocketStart(tunnel *AgentTunnel, streamID, targetPath, query string, headers map[string]string) error {
- startMsg := &TunnelMessage{
- ID: streamID,
- Type: MessageTypeWebSocketStart,
- Path: targetPath,
- Query: query,
- Headers: headers,
- }
- return tunnel.Conn.Send(startMsg)
-}
-
func forwardClientToAgent(ctx context.Context, streamCtx context.Context, clientWS *websocket.Conn, tunnel *AgentTunnel, streamID string, doneCh chan<- struct{}) {
defer close(doneCh)
for {
@@ -136,12 +131,26 @@ func forwardAgentToClient(ctx context.Context, streamCtx context.Context, client
func handleAgentMessage(ctx context.Context, clientWS *websocket.Conn, msg *TunnelMessage, streamID string) (bool, error) {
switch msg.Type {
- case MessageTypeWebSocketData:
+ case MessageTypeWebSocketData, MessageTypeStreamData:
return false, writeWebSocketData(clientWS, msg)
- case MessageTypeWebSocketClose, MessageTypeStreamEnd:
+ case MessageTypeWebSocketClose, MessageTypeStreamClose, MessageTypeStreamEnd:
slog.DebugContext(ctx, "Agent closed WebSocket stream", "stream_id", streamID)
return true, nil
- case MessageTypeRequest, MessageTypeResponse, MessageTypeHeartbeat, MessageTypeHeartbeatAck, MessageTypeStreamData, MessageTypeWebSocketStart, MessageTypeRegister, MessageTypeRegisterResponse, MessageTypeEvent:
+ case MessageTypeRequest,
+ MessageTypeResponse,
+ MessageTypeHeartbeat,
+ MessageTypeHeartbeatAck,
+ MessageTypeWebSocketStart,
+ MessageTypeRegister,
+ MessageTypeRegisterResponse,
+ MessageTypeEvent,
+ MessageTypeCommandRequest,
+ MessageTypeCommandAck,
+ MessageTypeCommandOutput,
+ MessageTypeCommandComplete,
+ MessageTypeFileChunk,
+ MessageTypeStreamOpen,
+ MessageTypeCancelRequest:
slog.DebugContext(ctx, "Ignoring tunnel message", "type", msg.Type, "stream_id", streamID)
return false, nil
default:
@@ -159,10 +168,10 @@ func writeWebSocketData(clientWS *websocket.Conn, msg *TunnelMessage) error {
return clientWS.WriteMessage(msgType, msg.Body)
}
-func sendWebSocketData(tunnel *AgentTunnel, streamID string, msgType int, data []byte) error {
+func sendStreamDataInternal(tunnel *AgentTunnel, streamID string, msgType int, data []byte) error {
wsDataMsg := &TunnelMessage{
ID: streamID,
- Type: MessageTypeWebSocketData,
+ Type: MessageTypeStreamData,
Body: data,
WSMessageType: msgType,
}
@@ -172,11 +181,15 @@ func sendWebSocketData(tunnel *AgentTunnel, streamID string, msgType int, data [
func sendWebSocketClose(tunnel *AgentTunnel, streamID string) {
closeMsg := &TunnelMessage{
ID: streamID,
- Type: MessageTypeWebSocketClose,
+ Type: MessageTypeStreamClose,
}
_ = tunnel.Conn.Send(closeMsg)
}
+func sendWebSocketData(tunnel *AgentTunnel, streamID string, msgType int, data []byte) error {
+ return sendStreamDataInternal(tunnel, streamID, msgType, data)
+}
+
func isForwardableWSMessage(msgType int) bool {
return msgType == websocket.TextMessage || msgType == websocket.BinaryMessage
}
diff --git a/backend/pkg/libarcane/edge/ws_proxy_test.go b/backend/pkg/libarcane/edge/ws_proxy_test.go
index fd1246b5b..9fb091ad8 100644
--- a/backend/pkg/libarcane/edge/ws_proxy_test.go
+++ b/backend/pkg/libarcane/edge/ws_proxy_test.go
@@ -32,11 +32,11 @@ func TestProxyWebSocketRequest(t *testing.T) {
var msg TunnelMessage
_ = json.Unmarshal(data, &msg)
- if msg.Type == MessageTypeWebSocketStart {
+ if msg.Type == MessageTypeStreamOpen {
// 1. Send Data
resp := &TunnelMessage{
ID: msg.ID,
- Type: MessageTypeWebSocketData,
+ Type: MessageTypeStreamData,
Body: []byte("hello"),
WSMessageType: websocket.TextMessage,
}
@@ -54,7 +54,7 @@ func TestProxyWebSocketRequest(t *testing.T) {
// 3. Send Close
closeMsg := &TunnelMessage{
ID: msg.ID,
- Type: MessageTypeWebSocketClose,
+ Type: MessageTypeStreamClose,
}
closeData, _ := json.Marshal(closeMsg)
_ = conn.WriteMessage(websocket.TextMessage, closeData)
@@ -71,7 +71,7 @@ func TestProxyWebSocketRequest(t *testing.T) {
defer func() { _ = resp.Body.Close() }()
}
- tunnel := NewAgentTunnel("env-ws-proxy", agentConn)
+ tunnel := newWebSocketAgentTunnel("env-ws-proxy", agentConn)
defer func() { _ = tunnel.Close() }()
// Start receiving on tunnel
@@ -95,7 +95,7 @@ func TestProxyWebSocketRequest(t *testing.T) {
// Setup Manager
ginRouter := gin.New()
ginRouter.GET("/proxy-ws", func(c *gin.Context) {
- ProxyWebSocketRequest(c, tunnel, "/target/ws")
+ ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats")
})
proxyServer := httptest.NewServer(ginRouter)
@@ -151,7 +151,7 @@ func TestProxyWebSocketRequest_ClientClose(t *testing.T) {
defer func() { _ = resp.Body.Close() }()
}
- tunnel := NewAgentTunnel("env-ws-close", agentConn)
+ tunnel := newWebSocketAgentTunnel("env-ws-close", agentConn)
defer func() { _ = tunnel.Close() }()
go func() {
@@ -164,7 +164,7 @@ func TestProxyWebSocketRequest_ClientClose(t *testing.T) {
ginRouter := gin.New()
ginRouter.GET("/proxy-ws", func(c *gin.Context) {
- ProxyWebSocketRequest(c, tunnel, "/target/ws")
+ ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats")
})
proxyServer := httptest.NewServer(ginRouter)
defer proxyServer.Close()
@@ -207,7 +207,7 @@ func TestSendWebSocketData(t *testing.T) {
var msg TunnelMessage
_ = json.Unmarshal(data, &msg)
- assert.Equal(t, MessageTypeWebSocketData, msg.Type)
+ assert.Equal(t, MessageTypeStreamData, msg.Type)
assert.Equal(t, "test-stream", msg.ID)
assert.Equal(t, websocket.TextMessage, msg.WSMessageType)
assert.Equal(t, "payload", string(msg.Body))
@@ -222,7 +222,7 @@ func TestSendWebSocketData(t *testing.T) {
}
defer func() { _ = conn.Close() }()
- tunnel := NewAgentTunnel("env-helper", conn)
+ tunnel := newWebSocketAgentTunnel("env-helper", conn)
defer func() { _ = tunnel.Close() }()
err = sendWebSocketData(tunnel, "test-stream", websocket.TextMessage, []byte("payload"))
@@ -245,7 +245,7 @@ func TestSendWebSocketClose(t *testing.T) {
var msg TunnelMessage
_ = json.Unmarshal(data, &msg)
- assert.Equal(t, MessageTypeWebSocketClose, msg.Type)
+ assert.Equal(t, MessageTypeStreamClose, msg.Type)
assert.Equal(t, "test-stream", msg.ID)
}))
defer server.Close()
@@ -257,8 +257,46 @@ func TestSendWebSocketClose(t *testing.T) {
defer func() { _ = resp.Body.Close() }()
}
- tunnel := NewAgentTunnel("env-helper-close", conn)
+ tunnel := newWebSocketAgentTunnel("env-helper-close", conn)
defer func() { _ = tunnel.Close() }()
sendWebSocketClose(tunnel, "test-stream")
}
+
+func TestHandleAgentMessage_StreamDataPreservesTextFrame(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ serverConnCh := make(chan *websocket.Conn, 1)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ upgrader := websocket.Upgrader{}
+ conn, err := upgrader.Upgrade(w, r, nil)
+ require.NoError(t, err)
+ serverConnCh <- conn
+ }))
+ defer server.Close()
+
+ clientURL := "ws" + strings.TrimPrefix(server.URL, "http")
+ clientConn, resp, err := websocket.DefaultDialer.Dial(clientURL, nil)
+ require.NoError(t, err)
+ if resp != nil {
+ defer func() { _ = resp.Body.Close() }()
+ }
+ defer func() { _ = clientConn.Close() }()
+
+ serverConn := <-serverConnCh
+ defer func() { _ = serverConn.Close() }()
+
+ stop, err := handleAgentMessage(t.Context(), serverConn, &TunnelMessage{
+ ID: "stats-stream",
+ Type: MessageTypeStreamData,
+ Body: []byte(`{"cpuPercent":12.5}`),
+ WSMessageType: websocket.TextMessage,
+ }, "stats-stream")
+ require.NoError(t, err)
+ assert.False(t, stop)
+
+ msgType, payload, err := clientConn.ReadMessage()
+ require.NoError(t, err)
+ assert.Equal(t, websocket.TextMessage, msgType)
+ assert.Equal(t, `{"cpuPercent":12.5}`, string(payload))
+}
diff --git a/backend/pkg/utils/cookie/cookie_util.go b/backend/pkg/utils/cookie/cookie_util.go
index 9347eda4d..0778b045f 100644
--- a/backend/pkg/utils/cookie/cookie_util.go
+++ b/backend/pkg/utils/cookie/cookie_util.go
@@ -43,7 +43,7 @@ func BuildTokenCookieString(maxAgeInSeconds int, token string) string {
if maxAgeInSeconds < 0 {
maxAgeInSeconds = 0
}
- cookie := &http.Cookie{ // #nosec G124
+ cookie := &http.Cookie{ // #nosec G124: Huma handlers intentionally use the HTTP-compatible fallback token cookie here.
Name: InsecureTokenCookieName,
Value: token,
Path: "/",
@@ -56,7 +56,7 @@ func BuildTokenCookieString(maxAgeInSeconds int, token string) string {
// BuildClearTokenCookieString builds a Set-Cookie header string to clear the token cookie.
func BuildClearTokenCookieString() string {
- cookie := &http.Cookie{ // #nosec G124
+ cookie := &http.Cookie{ // #nosec G124: clearing must target the same HTTP-compatible fallback token cookie.
Name: InsecureTokenCookieName,
Value: "",
Path: "/",
@@ -72,7 +72,7 @@ func BuildOidcStateCookieString(value string, maxAgeInSeconds int, secure bool)
if maxAgeInSeconds < 0 {
maxAgeInSeconds = 0
}
- cookie := &http.Cookie{ // #nosec G124
+ cookie := &http.Cookie{ // #nosec G124: secure is provided by the caller based on request context.
Name: OidcStateCookieName,
Value: value,
Path: "/",
@@ -86,7 +86,7 @@ func BuildOidcStateCookieString(value string, maxAgeInSeconds int, secure bool)
// BuildClearOidcStateCookieString builds a Set-Cookie header string to clear the OIDC state cookie.
func BuildClearOidcStateCookieString(secure bool) string {
- cookie := &http.Cookie{ // #nosec G124
+ cookie := &http.Cookie{ // #nosec G124: secure is provided by the caller based on request context.
Name: OidcStateCookieName,
Value: "",
Path: "/",
diff --git a/cli/pkg/generate/certs.go b/cli/pkg/generate/certs.go
new file mode 100644
index 000000000..4c2d5b3a3
--- /dev/null
+++ b/cli/pkg/generate/certs.go
@@ -0,0 +1,425 @@
+package generate
+
+import (
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ crand "crypto/rand"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/pem"
+ "fmt"
+ "math/big"
+ "net"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/spf13/cobra"
+)
+
+const (
+ certValidity = 5 * 365 * 24 * time.Hour
+)
+
+var (
+ mtlsOutDir string
+ mtlsEnvID string
+ mtlsAppURL string
+ tlsOutDir string
+ tlsCommonName string
+ tlsHosts []string
+ tlsCertName string
+ tlsKeyName string
+)
+
+var mtlsCmd = &cobra.Command{
+ Use: "mtls",
+ Short: "Generate Arcane edge mTLS assets",
+ Long: `Generate an Arcane-managed edge mTLS CA and agent client certificate bundle using ECDSA P-384.`,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return generateMTLSOutputInternal()
+ },
+}
+
+var tlsCmd = &cobra.Command{
+ Use: "tls",
+ Short: "Generate Arcane HTTPS TLS assets",
+ Long: `Generate a self-signed Arcane HTTPS server certificate bundle using ECDSA P-384.`,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ return generateTLSOutputInternal()
+ },
+}
+
+func init() {
+ GenerateCmd.AddCommand(mtlsCmd)
+ GenerateCmd.AddCommand(tlsCmd)
+
+ mtlsCmd.Flags().StringVar(&mtlsOutDir, "out-dir", "./edge-mtls", "directory to write generated edge mTLS assets")
+ mtlsCmd.Flags().StringVar(&mtlsEnvID, "env-id", "local-edge", "environment identifier to embed in the generated edge agent certificate")
+ mtlsCmd.Flags().StringVar(&mtlsAppURL, "app-url", "http://localhost:3552", "Arcane manager app URL to embed as the edge mTLS SPIFFE trust domain")
+
+ tlsCmd.Flags().StringVar(&tlsOutDir, "out-dir", "./arcane-tls", "directory to write generated Arcane TLS assets")
+ tlsCmd.Flags().StringVar(&tlsCommonName, "common-name", "localhost", "certificate common name")
+ tlsCmd.Flags().StringSliceVar(&tlsHosts, "host", []string{"localhost", "127.0.0.1"}, "DNS name or IP SAN to include; repeat flag to add more")
+ tlsCmd.Flags().StringVar(&tlsCertName, "cert-name", "server.crt", "certificate file name to write under out-dir")
+ tlsCmd.Flags().StringVar(&tlsKeyName, "key-name", "server.key", "private key file name to write under out-dir")
+}
+
+func generateMTLSOutputInternal() error {
+ outDir, err := filepath.Abs(strings.TrimSpace(mtlsOutDir))
+ if err != nil {
+ return fmt.Errorf("failed to resolve output directory: %w", err)
+ }
+
+ paths, err := generateEdgeMTLSBundleInternal(outDir, strings.TrimSpace(mtlsEnvID), strings.TrimSpace(mtlsAppURL))
+ if err != nil {
+ return err
+ }
+
+ fmt.Println("Generated Arcane edge mTLS assets (ECDSA P-384)")
+ fmt.Printf("CA cert: %s\n", paths.CACertPath)
+ fmt.Printf("CA key: %s\n", paths.CAKeyPath)
+ fmt.Printf("Agent cert: %s\n", paths.ClientCertPath)
+ fmt.Printf("Agent key: %s\n", paths.ClientKeyPath)
+ fmt.Println()
+ fmt.Println("Manager env")
+ fmt.Printf("EDGE_MTLS_MODE=required\nEDGE_MTLS_CA_FILE=%s\n", paths.CACertPath)
+ fmt.Println()
+ fmt.Println("Agent env")
+ fmt.Printf("EDGE_MTLS_MODE=required\nEDGE_MTLS_CA_FILE=%s\nEDGE_MTLS_CERT_FILE=%s\nEDGE_MTLS_KEY_FILE=%s\n", paths.CACertPath, paths.ClientCertPath, paths.ClientKeyPath)
+ return nil
+}
+
+func generateTLSOutputInternal() error {
+ outDir, err := filepath.Abs(strings.TrimSpace(tlsOutDir))
+ if err != nil {
+ return fmt.Errorf("failed to resolve output directory: %w", err)
+ }
+
+ paths, err := generateServerTLSBundleInternal(outDir, strings.TrimSpace(tlsCommonName), tlsHosts, strings.TrimSpace(tlsCertName), strings.TrimSpace(tlsKeyName))
+ if err != nil {
+ return err
+ }
+
+ fmt.Println("Generated Arcane TLS assets (ECDSA P-384)")
+ fmt.Printf("Server cert: %s\n", paths.CertPath)
+ fmt.Printf("Server key: %s\n", paths.KeyPath)
+ fmt.Println()
+ fmt.Println("Manager env")
+ fmt.Printf("TLS_ENABLED=true\nTLS_CERT_FILE=%s\nTLS_KEY_FILE=%s\n", paths.CertPath, paths.KeyPath)
+ return nil
+}
+
+type edgeMTLSPaths struct {
+ CACertPath string
+ CAKeyPath string
+ ClientCertPath string
+ ClientKeyPath string
+}
+
+type serverTLSPaths struct {
+ CertPath string
+ KeyPath string
+}
+
+func generateEdgeMTLSBundleInternal(outDir, envID string, appURL string) (*edgeMTLSPaths, error) {
+ if envID == "" {
+ return nil, fmt.Errorf("env ID is required")
+ }
+ if err := os.MkdirAll(outDir, 0o755); err != nil {
+ return nil, fmt.Errorf("failed to create output directory: %w", err)
+ }
+
+ caKey, err := GenerateP384PrivateKey()
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate CA private key: %w", err)
+ }
+ caTemplate, err := NewEdgeMTLSCATemplate()
+ if err != nil {
+ return nil, err
+ }
+
+ caDER, err := x509.CreateCertificate(crand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create CA certificate: %w", err)
+ }
+
+ clientKey, err := GenerateP384PrivateKey()
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate client private key: %w", err)
+ }
+ trustDomain := EdgeMTLSTrustDomain(appURL)
+ dnsSANs := []string{"arcane-agent"}
+ if trustDomain != "" {
+ dnsSANs = append(dnsSANs, "arcane-agent."+trustDomain)
+ }
+ clientTemplate, err := NewEdgeMTLSClientTemplate(fmt.Sprintf("arcane-edge-%s", envID), BuildEdgeMTLSURISAN(appURL, envID), dnsSANs)
+ if err != nil {
+ return nil, err
+ }
+
+ caCert, err := x509.ParseCertificate(caDER)
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse generated CA certificate: %w", err)
+ }
+ clientDER, err := x509.CreateCertificate(crand.Reader, clientTemplate, caCert, &clientKey.PublicKey, caKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create client certificate: %w", err)
+ }
+
+ paths := &edgeMTLSPaths{
+ CACertPath: filepath.Join(outDir, "ca.crt"),
+ CAKeyPath: filepath.Join(outDir, "ca.key"),
+ ClientCertPath: filepath.Join(outDir, "agent.crt"),
+ ClientKeyPath: filepath.Join(outDir, "agent.key"),
+ }
+ if err := writeCertificateBundleInternal(paths.CACertPath, paths.CAKeyPath, caDER, caKey); err != nil {
+ return nil, err
+ }
+ if err := writeCertificateBundleInternal(paths.ClientCertPath, paths.ClientKeyPath, clientDER, clientKey); err != nil {
+ return nil, err
+ }
+
+ return paths, nil
+}
+
+func generateServerTLSBundleInternal(outDir, commonName string, hosts []string, certName string, keyName string) (*serverTLSPaths, error) {
+ if commonName == "" {
+ return nil, fmt.Errorf("common name is required")
+ }
+ certName = filepath.Base(strings.TrimSpace(certName))
+ if certName == "." || certName == "" {
+ return nil, fmt.Errorf("certificate file name is required")
+ }
+ keyName = filepath.Base(strings.TrimSpace(keyName))
+ if keyName == "." || keyName == "" {
+ return nil, fmt.Errorf("key file name is required")
+ }
+ if err := os.MkdirAll(outDir, 0o755); err != nil {
+ return nil, fmt.Errorf("failed to create output directory: %w", err)
+ }
+
+ privateKey, err := GenerateP384PrivateKey()
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate server private key: %w", err)
+ }
+
+ template, err := NewServerTLSTemplate(commonName, hosts)
+ if err != nil {
+ return nil, err
+ }
+
+ certDER, err := x509.CreateCertificate(crand.Reader, template, template, &privateKey.PublicKey, privateKey)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create server certificate: %w", err)
+ }
+
+ paths := &serverTLSPaths{
+ CertPath: filepath.Join(outDir, certName),
+ KeyPath: filepath.Join(outDir, keyName),
+ }
+ if err := writeCertificateBundleInternal(paths.CertPath, paths.KeyPath, certDER, privateKey); err != nil {
+ return nil, err
+ }
+ return paths, nil
+}
+
+// GenerateP384PrivateKey generates an ECDSA P-384 private key.
+func GenerateP384PrivateKey() (*ecdsa.PrivateKey, error) {
+ return ecdsa.GenerateKey(elliptic.P384(), crand.Reader)
+}
+
+// NewEdgeMTLSCATemplate builds Arcane's edge mTLS CA certificate template.
+func NewEdgeMTLSCATemplate() (*x509.Certificate, error) {
+ template, err := newCertificateTemplateInternal("Arcane Edge mTLS CA")
+ if err != nil {
+ return nil, err
+ }
+ template.Subject = pkix.Name{CommonName: "Arcane Edge mTLS CA", Organization: []string{"Arcane"}}
+ template.IsCA = true
+ template.BasicConstraintsValid = true
+ template.MaxPathLen = 1
+ template.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature
+ return template, nil
+}
+
+// NewEdgeMTLSClientTemplate builds an edge-agent client certificate template.
+func NewEdgeMTLSClientTemplate(commonName string, uriSAN *url.URL, dnsSANs []string) (*x509.Certificate, error) {
+ commonName = strings.TrimSpace(commonName)
+ if commonName == "" {
+ return nil, fmt.Errorf("common name is required")
+ }
+ template, err := newCertificateTemplateInternal(commonName)
+ if err != nil {
+ return nil, err
+ }
+ template.NotBefore = time.Now().UTC().Add(-24 * time.Hour)
+ template.Subject = pkix.Name{
+ CommonName: commonName,
+ Organization: []string{"Arcane Edge Agents"},
+ }
+ template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
+ template.KeyUsage = x509.KeyUsageDigitalSignature
+ if uriSAN != nil {
+ template.URIs = []*url.URL{uriSAN}
+ }
+ for _, dnsSAN := range dnsSANs {
+ dnsSAN = strings.TrimSpace(dnsSAN)
+ if dnsSAN != "" {
+ template.DNSNames = append(template.DNSNames, dnsSAN)
+ }
+ }
+ return template, nil
+}
+
+// NewServerTLSTemplate builds a self-signed Arcane HTTPS server certificate template.
+func NewServerTLSTemplate(commonName string, hosts []string) (*x509.Certificate, error) {
+ commonName = strings.TrimSpace(commonName)
+ if commonName == "" {
+ return nil, fmt.Errorf("common name is required")
+ }
+ template, err := newCertificateTemplateInternal(commonName)
+ if err != nil {
+ return nil, err
+ }
+ template.Subject = pkix.Name{CommonName: commonName, Organization: []string{"Arcane"}}
+ template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
+ template.KeyUsage = x509.KeyUsageDigitalSignature
+
+ for _, host := range hosts {
+ host = strings.TrimSpace(host)
+ if host == "" {
+ continue
+ }
+ if ip := net.ParseIP(host); ip != nil {
+ template.IPAddresses = append(template.IPAddresses, ip)
+ continue
+ }
+ template.DNSNames = append(template.DNSNames, host)
+ }
+ if len(template.DNSNames) == 0 && len(template.IPAddresses) == 0 {
+ template.DNSNames = []string{commonName}
+ }
+ return template, nil
+}
+
+// EdgeMTLSTrustDomain returns the SPIFFE trust domain derived from an Arcane app URL.
+func EdgeMTLSTrustDomain(appURL string) string {
+ appURL = strings.TrimSpace(appURL)
+ if appURL == "" {
+ return ""
+ }
+ parseURL := appURL
+ if !strings.Contains(parseURL, "://") {
+ parseURL = "https://" + parseURL
+ }
+ parsed, err := url.Parse(parseURL)
+ if err == nil {
+ if host := strings.TrimSpace(parsed.Hostname()); host != "" {
+ return strings.ToLower(strings.TrimSuffix(host, "."))
+ }
+ }
+ return strings.ToLower(strings.TrimSuffix(appURL, "."))
+}
+
+// BuildEdgeMTLSURISAN returns the SPIFFE URI SAN for an edge environment ID.
+func BuildEdgeMTLSURISAN(appURL string, envID string) *url.URL {
+ trustDomain := EdgeMTLSTrustDomain(appURL)
+ envID = strings.TrimSpace(envID)
+ if trustDomain == "" || envID == "" {
+ return nil
+ }
+ return &url.URL{Scheme: "spiffe", Host: trustDomain, Path: "/edge/" + envID}
+}
+
+func newCertificateTemplateInternal(commonName string) (*x509.Certificate, error) {
+ serial, err := randomSerialInternal()
+ if err != nil {
+ return nil, err
+ }
+
+ now := time.Now().UTC()
+ return &x509.Certificate{
+ SerialNumber: serial,
+ Subject: pkix.Name{CommonName: commonName},
+ NotBefore: now.Add(-time.Hour),
+ NotAfter: now.Add(certValidity),
+ }, nil
+}
+
+func randomSerialInternal() (*big.Int, error) {
+ limit := new(big.Int).Lsh(big.NewInt(1), 128)
+ serial, err := crand.Int(crand.Reader, limit)
+ if err != nil {
+ return nil, fmt.Errorf("failed to generate certificate serial: %w", err)
+ }
+ return serial, nil
+}
+
+func writeCertificateBundleInternal(certPath, keyPath string, certDER []byte, privateKey *ecdsa.PrivateKey) error {
+ keyDER, err := x509.MarshalECPrivateKey(privateKey)
+ if err != nil {
+ return fmt.Errorf("failed to marshal EC private key: %w", err)
+ }
+ if err := writePEMFileInternal(certPath, "CERTIFICATE", certDER, 0o644); err != nil {
+ return err
+ }
+ if err := writePEMFileInternal(keyPath, "EC PRIVATE KEY", keyDER, 0o600); err != nil {
+ return err
+ }
+ return nil
+}
+
+func writePEMFileInternal(path, blockType string, bytes []byte, perm os.FileMode) error {
+ pemBytes := pem.EncodeToMemory(&pem.Block{Type: blockType, Bytes: bytes})
+ if pemBytes == nil {
+ return fmt.Errorf("failed to encode PEM file %s", path)
+ }
+ return writeFileAtomicInternal(path, pemBytes, perm)
+}
+
+func writeFileAtomicInternal(path string, data []byte, perm os.FileMode) error {
+ dir := filepath.Dir(path)
+ tmp, err := os.CreateTemp(dir, filepath.Base(path)+".tmp-*")
+ if err != nil {
+ return fmt.Errorf("failed to create temp file for %s: %w", path, err)
+ }
+ tmpName := tmp.Name()
+ cleanup := func() { _ = os.Remove(tmpName) }
+
+ if _, err := tmp.Write(data); err != nil {
+ _ = tmp.Close()
+ cleanup()
+ return fmt.Errorf("failed to write temp file %s: %w", tmpName, err)
+ }
+ if err := tmp.Chmod(perm); err != nil {
+ _ = tmp.Close()
+ cleanup()
+ return fmt.Errorf("failed to chmod temp file %s: %w", tmpName, err)
+ }
+ if err := tmp.Sync(); err != nil {
+ _ = tmp.Close()
+ cleanup()
+ return fmt.Errorf("failed to sync temp file %s: %w", tmpName, err)
+ }
+ if err := tmp.Close(); err != nil {
+ cleanup()
+ return fmt.Errorf("failed to close temp file %s: %w", tmpName, err)
+ }
+ if err := os.Rename(tmpName, path); err != nil {
+ cleanup()
+ return fmt.Errorf("failed to rename %s to %s: %w", tmpName, path, err)
+ }
+
+ dirFile, err := os.Open(dir)
+ if err != nil {
+ return fmt.Errorf("failed to open directory %s for sync: %w", dir, err)
+ }
+ defer func() { _ = dirFile.Close() }()
+ if err := dirFile.Sync(); err != nil {
+ return fmt.Errorf("failed to sync directory %s: %w", dir, err)
+ }
+ return nil
+}
diff --git a/cli/pkg/generate/certs_test.go b/cli/pkg/generate/certs_test.go
new file mode 100644
index 000000000..4d5d6ed1c
--- /dev/null
+++ b/cli/pkg/generate/certs_test.go
@@ -0,0 +1,160 @@
+package generate_test
+
+import (
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/x509"
+ "encoding/pem"
+ "net"
+ "os"
+ "path/filepath"
+ "testing"
+
+ gen "github.com/getarcaneapp/arcane/cli/pkg/generate"
+)
+
+func TestGenerateMTLSCommandWritesECDSAP384Assets(t *testing.T) {
+ outDir := t.TempDir()
+
+ cmd := gen.GenerateCmd
+ cmd.SetArgs([]string{"mtls", "--out-dir", outDir, "--env-id", "env-123", "--app-url", "https://manager.example.com"})
+
+ _, err := captureOutput(func() error {
+ _, err := cmd.ExecuteC()
+ return err
+ })
+ if err != nil {
+ t.Fatalf("command failed: %v", err)
+ }
+
+ assertECDSAP384PrivateKey(t, filepath.Join(outDir, "ca.key"))
+ assertECDSAP384PrivateKey(t, filepath.Join(outDir, "agent.key"))
+ assertECDSAP384Certificate(t, filepath.Join(outDir, "ca.crt"))
+ cert := assertECDSAP384Certificate(t, filepath.Join(outDir, "agent.crt"))
+ if len(cert.URIs) == 0 || cert.URIs[0].String() != "spiffe://manager.example.com/edge/env-123" {
+ t.Fatalf("expected edge SPIFFE URI SAN, got %v", cert.URIs)
+ }
+}
+
+func TestGenerateTLSCommandWritesECDSAP384ServerCert(t *testing.T) {
+ outDir := t.TempDir()
+
+ cmd := gen.GenerateCmd
+ cmd.SetArgs([]string{"tls", "--out-dir", outDir, "--common-name", "localhost", "--host", "localhost", "--host", "127.0.0.1", "--cert-name", "local-manager.crt", "--key-name", "local-manager.key"})
+
+ _, err := captureOutput(func() error {
+ _, err := cmd.ExecuteC()
+ return err
+ })
+ if err != nil {
+ t.Fatalf("command failed: %v", err)
+ }
+
+ assertECDSAP384PrivateKey(t, filepath.Join(outDir, "local-manager.key"))
+ cert := assertECDSAP384Certificate(t, filepath.Join(outDir, "local-manager.crt"))
+
+ if len(cert.DNSNames) == 0 || cert.DNSNames[0] != "localhost" {
+ t.Fatalf("expected localhost DNS SAN, got %v", cert.DNSNames)
+ }
+ if len(cert.IPAddresses) == 0 || !cert.IPAddresses[0].Equal(net.ParseIP("127.0.0.1")) {
+ t.Fatalf("expected 127.0.0.1 IP SAN, got %v", cert.IPAddresses)
+ }
+}
+
+func TestGenerateTLSCommandOverwritesCertificateAtomically(t *testing.T) {
+ outDir := t.TempDir()
+
+ cmd := gen.GenerateCmd
+ cmd.SetArgs([]string{"tls", "--out-dir", outDir, "--common-name", "localhost", "--host", "localhost", "--cert-name", "server.crt", "--key-name", "server.key"})
+ _, err := captureOutput(func() error {
+ _, err := cmd.ExecuteC()
+ return err
+ })
+ if err != nil {
+ t.Fatalf("command failed: %v", err)
+ }
+
+ certPath := filepath.Join(outDir, "server.crt")
+ keyPath := filepath.Join(outDir, "server.key")
+ firstCert, err := os.ReadFile(certPath)
+ if err != nil {
+ t.Fatalf("failed to read first cert: %v", err)
+ }
+
+ cmd.SetArgs([]string{"tls", "--out-dir", outDir, "--common-name", "localhost", "--host", "localhost", "--cert-name", "server.crt", "--key-name", "server.key"})
+ _, err = captureOutput(func() error {
+ _, err := cmd.ExecuteC()
+ return err
+ })
+ if err != nil {
+ t.Fatalf("command failed: %v", err)
+ }
+
+ secondCert, err := os.ReadFile(certPath)
+ if err != nil {
+ t.Fatalf("failed to read second cert: %v", err)
+ }
+ if string(firstCert) == string(secondCert) {
+ t.Fatalf("expected certificate to be replaced on second generation")
+ }
+ assertECDSAP384Certificate(t, certPath)
+ assertECDSAP384PrivateKey(t, keyPath)
+
+ tmpFiles, err := filepath.Glob(filepath.Join(outDir, "*.tmp-*"))
+ if err != nil {
+ t.Fatalf("failed to glob temp files: %v", err)
+ }
+ if len(tmpFiles) != 0 {
+ t.Fatalf("expected atomic write temp files to be cleaned up, got %v", tmpFiles)
+ }
+}
+
+func assertECDSAP384PrivateKey(t *testing.T, path string) {
+ t.Helper()
+
+ pemBytes, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("failed to read key %s: %v", path, err)
+ }
+ block, _ := pem.Decode(pemBytes)
+ if block == nil {
+ t.Fatalf("failed to decode key PEM %s", path)
+ }
+ if block.Type != "EC PRIVATE KEY" {
+ t.Fatalf("expected EC PRIVATE KEY for %s, got %s", path, block.Type)
+ }
+
+ key, err := x509.ParseECPrivateKey(block.Bytes)
+ if err != nil {
+ t.Fatalf("failed to parse EC private key %s: %v", path, err)
+ }
+ if key.Curve != elliptic.P384() {
+ t.Fatalf("expected P-384 private key for %s", path)
+ }
+}
+
+func assertECDSAP384Certificate(t *testing.T, path string) *x509.Certificate {
+ t.Helper()
+
+ pemBytes, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("failed to read certificate %s: %v", path, err)
+ }
+ block, _ := pem.Decode(pemBytes)
+ if block == nil {
+ t.Fatalf("failed to decode certificate PEM %s", path)
+ }
+
+ cert, err := x509.ParseCertificate(block.Bytes)
+ if err != nil {
+ t.Fatalf("failed to parse certificate %s: %v", path, err)
+ }
+ publicKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
+ if !ok {
+ t.Fatalf("expected ECDSA public key for %s", path)
+ }
+ if publicKey.Curve != elliptic.P384() {
+ t.Fatalf("expected P-384 certificate for %s", path)
+ }
+ return cert
+}
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 3d2f9a74f..aa4cd9969 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -1245,8 +1245,8 @@
"environments_current_environment": "Current Environment",
"environments_switched_to": "Switched to {name}",
"environments_cannot_switch_disabled": "Cannot switch to a disabled environment",
- "environments_agent_config_title": "Agent Configuration",
- "environments_agent_config_description": "Regenerate API key and deployment configuration for this agent",
+ "environments_agent_mtls_section_title": "mTLS Certificates",
+ "environments_agent_mtls_download_bundle": "Download mTLS Bundle",
"environments_new_api_key": "New API Key",
"environments_api_key_save_warning": "Save this API key - it won't be shown again. Update your agent with the new key.",
"environments_regenerate_warning_title": "Warning",
@@ -1256,6 +1256,17 @@
"environments_regenerate_dialog_message": "This will create a new API key for this environment. The current API key will be invalidated immediately, and the agent will lose connection until you update it with the new key.",
"environments_regenerate_key_success": "API key regenerated successfully",
"environments_regenerate_key_failed": "Failed to regenerate API key",
+ "environments_agent_mtls_connected": "This edge agent is connected with mTLS.",
+ "environments_agent_mtls_description": "Use the generated client certificate and key when you redeploy or rotate this edge agent.",
+ "environments_agent_mtls_loading_assets": "Loading mTLS assets…",
+ "environments_agent_mtls_download_certificate": "Download certificate",
+ "environments_agent_mtls_download_key": "Download key",
+ "environments_agent_mtls_assets_unavailable": "mTLS assets are not available for this environment.",
+ "environments_new_agent_mtls_enabled": "Manager mTLS is enabled for this edge agent.",
+ "environments_new_agent_mtls_auto_enroll": "The agent will enroll and persist its certificate automatically on first start. Downloads are only for manual provisioning or recovery.",
+ "environments_new_agent_mtls_assets_unavailable": "Manager mTLS assets are not available. Showing the standard edge agent config instead.",
+ "environments_download_edge_ca": "Download Edge CA",
+ "environments_download_edge_ca_failed": "Failed to download Edge CA",
"environments_edge_polling_label": "Polling",
"environments_edge_control_plane_label": "Control Plane",
"environments_edge_polling_active": "Polling Active",
@@ -1271,6 +1282,13 @@
"environments_edge_tunnel_disconnected": "Disconnected",
"environments_edge_connected_since_label": "Connected Since",
"environments_edge_last_heartbeat_label": "Last Heartbeat",
+ "environments_edge_mtls_certificate_status_label": "mTLS Certificate",
+ "environments_edge_mtls_certificate_expires_label": "mTLS Cert Expires",
+ "environments_edge_mtls_certificate_common_name_label": "mTLS Common Name",
+ "environments_edge_mtls_certificate_status_valid": "Valid",
+ "environments_edge_mtls_certificate_status_expiring_soon": "Expiring Soon",
+ "environments_edge_mtls_certificate_status_expired": "Expired",
+ "environments_edge_mtls_certificate_days_remaining": "{count} days remaining",
"environments_version_unavailable": "Version information unavailable",
"_comment_users": "=== USERS ===",
"users_title": "Users",
diff --git a/frontend/src/lib/components/action-button-group/action-button-group.svelte b/frontend/src/lib/components/action-button-group/action-button-group.svelte
index 7fa3073f7..21ba6c24a 100644
--- a/frontend/src/lib/components/action-button-group/action-button-group.svelte
+++ b/frontend/src/lib/components/action-button-group/action-button-group.svelte
@@ -1,10 +1,12 @@
<script lang="ts">
+ import * as ButtonGroup from '$lib/components/ui/button-group/index.js';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
import type { ArcaneButtonSize } from '$lib/components/arcane-button/index.js';
import { EllipsisIcon } from '$lib/icons';
import { cn } from '$lib/utils';
- import type { ActionButton } from './types.js';
+ import { ArrowDownIcon } from '$lib/icons';
+ import type { ActionButton, ActionButtonMenuItem } from './types.js';
interface Props {
buttons?: ActionButton[];
@@ -19,7 +21,6 @@
let containerWidth = $state(0);
let buttonWidths = $state<number[]>([]);
- let measurementNode: HTMLElement | null = null;
const visibleCount = $derived.by(() => {
const total = buttons.length;
@@ -46,34 +47,51 @@
const visibleButtons = $derived(buttons.slice(0, visibleCount));
const overflowButtons = $derived(buttons.slice(visibleCount));
- function measureButtons(node: HTMLElement) {
- measurementNode = node;
- return {
- destroy: () => {
- measurementNode = null;
- }
- };
+ function handleOverflowAction(button: ActionButton) {
+ if (button.disabled || button.loading) return;
+ if (button.href) {
+ window.location.assign(button.href);
+ return;
+ }
+ button.onclick?.();
}
- $effect(() => {
- const actionButtons = buttons;
- if (!measurementNode || actionButtons.length === 0) return;
+ function handleMenuItemAction(item: ActionButtonMenuItem) {
+ if (item.disabled) return;
+ if (item.href) {
+ window.location.assign(item.href);
+ return;
+ }
+ item.onclick?.();
+ }
- const timeoutId = setTimeout(() => {
- requestAnimationFrame(() => {
- if (!measurementNode) return;
- const widths: number[] = [];
- for (const child of measurementNode.children) {
- widths.push((child as HTMLElement).offsetWidth);
- }
- if (widths.length > 0 && widths.length === actionButtons.length) {
- buttonWidths = widths;
- }
- });
- }, 0);
+ function measureButtons(actionButtons: ActionButton[], currentSize: ArcaneButtonSize) {
+ void currentSize;
+ return (node: HTMLElement) => {
+ if (actionButtons.length === 0) {
+ buttonWidths = [];
+ return;
+ }
- return () => clearTimeout(timeoutId);
- });
+ let rafId: number | null = null;
+ const timeoutId = setTimeout(() => {
+ rafId = requestAnimationFrame(() => {
+ const widths: number[] = [];
+ for (const child of node.children) {
+ widths.push((child as HTMLElement).offsetWidth);
+ }
+ if (widths.length > 0 && widths.length === actionButtons.length) {
+ buttonWidths = widths;
+ }
+ });
+ }, 0);
+
+ return () => {
+ clearTimeout(timeoutId);
+ if (rafId) cancelAnimationFrame(rafId);
+ };
+ };
+ }
function observeWidth(node: HTMLElement) {
let rafId: number | null = null;
@@ -87,56 +105,115 @@
});
});
ro.observe(node);
- return {
- destroy: () => {
- if (rafId) cancelAnimationFrame(rafId);
- ro.disconnect();
- }
+ return () => {
+ if (rafId) cancelAnimationFrame(rafId);
+ ro.disconnect();
};
}
</script>
+{#snippet buttonContent(button: ActionButton)}
+ {#if button.badge !== undefined}
+ <span class="text-muted-foreground rounded-full border px-1 py-0.5 text-[10px]">
+ {button.badge}
+ </span>
+ {/if}
+{/snippet}
+
+{#snippet splitButton(button: ActionButton, inert: boolean)}
+ <ButtonGroup.Root>
+ <ArcaneButton
+ action={button.action}
+ customLabel={button.label}
+ loadingLabel={button.loadingLabel}
+ loading={button.loading}
+ disabled={button.disabled}
+ onclick={inert ? () => {} : button.onclick}
+ href={button.href}
+ rel={button.rel}
+ {size}
+ icon={button.icon}
+ >
+ {@render buttonContent(button)}
+ </ArcaneButton>
+
+ {#if inert}
+ <ArcaneButton action="base" tone="outline" size="icon" onclick={() => {}} class={cn(size === 'sm' ? 'size-8' : 'size-9')}>
+ <ArrowDownIcon class="size-4" />
+ </ArcaneButton>
+ {:else}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger
+ class={cn(
+ 'border-input bg-background hover:bg-accent hover:text-accent-foreground inline-flex items-center justify-center rounded-md border transition-colors outline-none',
+ size === 'sm' ? 'size-8' : 'size-9'
+ )}
+ aria-label="Open menu"
+ >
+ <ArrowDownIcon class="size-4" />
+ </DropdownMenu.Trigger>
+
+ <DropdownMenu.Content align="end" class="min-w-[180px]">
+ {#each button.menuItems ?? [] as item (item.id)}
+ <DropdownMenu.Item onclick={() => handleMenuItemAction(item)} disabled={item.disabled}>
+ {item.label}
+ </DropdownMenu.Item>
+ {/each}
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ {/if}
+ </ButtonGroup.Root>
+{/snippet}
+
{#if buttons.length > 0}
- <div class={cn('flex min-w-0 flex-1 items-center justify-end gap-2', className)} use:observeWidth>
- <div use:measureButtons class="pointer-events-none invisible fixed -left-[9999px] flex items-center gap-2" aria-hidden="true">
+ <div class={cn('flex min-w-0 flex-1 items-center justify-end gap-2', className)} {@attach observeWidth}>
+ <div
+ {@attach measureButtons(buttons, size)}
+ class="pointer-events-none invisible fixed -left-[9999px] flex items-center gap-2"
+ aria-hidden="true"
+ >
{#each buttons as button (button.id)}
- <ArcaneButton
- action={button.action}
- customLabel={button.label}
- loadingLabel={button.loadingLabel}
- loading={button.loading}
- disabled={button.disabled}
- onclick={() => {}}
- {size}
- icon={button.icon}
- >
- {#if button.badge !== undefined}
- <span class="text-muted-foreground rounded-full border px-1 py-0.5 text-[10px]">
- {button.badge}
- </span>
- {/if}
- </ArcaneButton>
+ {#if button.menuItems && button.menuItems.length > 0}
+ {@render splitButton(button, true)}
+ {:else}
+ <ArcaneButton
+ action={button.action}
+ customLabel={button.label}
+ loadingLabel={button.loadingLabel}
+ loading={button.loading}
+ disabled={button.disabled}
+ onclick={() => {}}
+ href={button.href}
+ rel={button.rel}
+ {size}
+ icon={button.icon}
+ >
+ {@render buttonContent(button)}
+ </ArcaneButton>
+ {/if}
{/each}
</div>
<div class="hidden items-center gap-2 lg:flex">
{#each visibleButtons as button (button.id)}
- <ArcaneButton
- action={button.action}
- customLabel={button.label}
- loadingLabel={button.loadingLabel}
- loading={button.loading}
- disabled={button.disabled}
- onclick={button.onclick}
- {size}
- icon={button.icon}
- >
- {#if button.badge !== undefined}
- <span class="text-muted-foreground rounded-full border px-1 py-0.5 text-[10px]">
- {button.badge}
- </span>
- {/if}
- </ArcaneButton>
+ {#if button.menuItems && button.menuItems.length > 0}
+ {@render splitButton(button, false)}
+ {:else}
+ <ArcaneButton
+ action={button.action}
+ customLabel={button.label}
+ loadingLabel={button.loadingLabel}
+ loading={button.loading}
+ disabled={button.disabled}
+ onclick={button.onclick}
+ href={button.href}
+ rel={button.rel}
+ {size}
+ icon={button.icon}
+ >
+ {@render buttonContent(button)}
+ </ArcaneButton>
+ {/if}
{/each}
{#if overflowButtons.length > 0}
@@ -159,14 +236,41 @@
<DropdownMenu.Content align="end" class="min-w-[160px]">
<DropdownMenu.Group>
{#each overflowButtons as button (button.id)}
- <DropdownMenu.Item onclick={button.onclick} disabled={button.disabled || button.loading}>
- <div class="flex w-full items-center justify-between gap-2">
- <span>{button.loading ? button.loadingLabel || button.label : button.label}</span>
- {#if button.badge !== undefined}
- <span class="text-muted-foreground text-[10px]">({button.badge})</span>
- {/if}
- </div>
- </DropdownMenu.Item>
+ {#if button.menuItems && button.menuItems.length > 0}
+ <DropdownMenu.Sub>
+ <DropdownMenu.SubTrigger disabled={button.disabled || button.loading}>
+ <div class="flex w-full items-center justify-between gap-2">
+ <span>{button.loading ? button.loadingLabel || button.label : button.label}</span>
+ {#if button.badge !== undefined}
+ <span class="text-muted-foreground text-[10px]">({button.badge})</span>
+ {/if}
+ </div>
+ </DropdownMenu.SubTrigger>
+ <DropdownMenu.SubContent class="min-w-[180px]">
+ <DropdownMenu.Item
+ onclick={() => handleOverflowAction(button)}
+ disabled={button.disabled || button.loading}
+ >
+ {button.label}
+ </DropdownMenu.Item>
+ <DropdownMenu.Separator />
+ {#each button.menuItems as item (item.id)}
+ <DropdownMenu.Item onclick={() => handleMenuItemAction(item)} disabled={item.disabled}>
+ {item.label}
+ </DropdownMenu.Item>
+ {/each}
+ </DropdownMenu.SubContent>
+ </DropdownMenu.Sub>
+ {:else}
+ <DropdownMenu.Item onclick={() => handleOverflowAction(button)} disabled={button.disabled || button.loading}>
+ <div class="flex w-full items-center justify-between gap-2">
+ <span>{button.loading ? button.loadingLabel || button.label : button.label}</span>
+ {#if button.badge !== undefined}
+ <span class="text-muted-foreground text-[10px]">({button.badge})</span>
+ {/if}
+ </div>
+ </DropdownMenu.Item>
+ {/if}
{/each}
</DropdownMenu.Group>
</DropdownMenu.Content>
@@ -194,14 +298,38 @@
<DropdownMenu.Content align="end" class="min-w-[160px]">
<DropdownMenu.Group>
{#each buttons as button (button.id)}
- <DropdownMenu.Item onclick={button.onclick} disabled={button.disabled || button.loading}>
- <div class="flex w-full items-center justify-between gap-2">
- <span>{button.loading ? button.loadingLabel || button.label : button.label}</span>
- {#if button.badge !== undefined}
- <span class="text-muted-foreground text-[10px]">({button.badge})</span>
- {/if}
- </div>
- </DropdownMenu.Item>
+ {#if button.menuItems && button.menuItems.length > 0}
+ <DropdownMenu.Sub>
+ <DropdownMenu.SubTrigger disabled={button.disabled || button.loading}>
+ <div class="flex w-full items-center justify-between gap-2">
+ <span>{button.loading ? button.loadingLabel || button.label : button.label}</span>
+ {#if button.badge !== undefined}
+ <span class="text-muted-foreground text-[10px]">({button.badge})</span>
+ {/if}
+ </div>
+ </DropdownMenu.SubTrigger>
+ <DropdownMenu.SubContent class="min-w-[180px]">
+ <DropdownMenu.Item onclick={() => handleOverflowAction(button)} disabled={button.disabled || button.loading}>
+ {button.label}
+ </DropdownMenu.Item>
+ <DropdownMenu.Separator />
+ {#each button.menuItems as item (item.id)}
+ <DropdownMenu.Item onclick={() => handleMenuItemAction(item)} disabled={item.disabled}>
+ {item.label}
+ </DropdownMenu.Item>
+ {/each}
+ </DropdownMenu.SubContent>
+ </DropdownMenu.Sub>
+ {:else}
+ <DropdownMenu.Item onclick={() => handleOverflowAction(button)} disabled={button.disabled || button.loading}>
+ <div class="flex w-full items-center justify-between gap-2">
+ <span>{button.loading ? button.loadingLabel || button.label : button.label}</span>
+ {#if button.badge !== undefined}
+ <span class="text-muted-foreground text-[10px]">({button.badge})</span>
+ {/if}
+ </div>
+ </DropdownMenu.Item>
+ {/if}
{/each}
</DropdownMenu.Group>
</DropdownMenu.Content>
diff --git a/frontend/src/lib/components/action-button-group/index.ts b/frontend/src/lib/components/action-button-group/index.ts
index a6d4e5ad3..d4295c83f 100644
--- a/frontend/src/lib/components/action-button-group/index.ts
+++ b/frontend/src/lib/components/action-button-group/index.ts
@@ -1,2 +1,2 @@
export { default as ActionButtonGroup } from './action-button-group.svelte';
-export type { ActionButton } from './types.js';
+export type { ActionButton, ActionButtonMenuItem } from './types.js';
diff --git a/frontend/src/lib/components/action-button-group/types.ts b/frontend/src/lib/components/action-button-group/types.ts
index 1eaef1bd1..116b32010 100644
--- a/frontend/src/lib/components/action-button-group/types.ts
+++ b/frontend/src/lib/components/action-button-group/types.ts
@@ -1,6 +1,14 @@
import type { Action } from '$lib/components/arcane-button/index.js';
import type { IconType } from '$lib/icons';
+export interface ActionButtonMenuItem {
+ id: string;
+ label: string;
+ disabled?: boolean;
+ onclick?: () => void;
+ href?: string;
+}
+
export interface ActionButton {
id: string;
action: Action;
@@ -8,8 +16,11 @@ export interface ActionButton {
loadingLabel?: string;
loading?: boolean;
disabled?: boolean;
- onclick: () => void;
+ onclick?: () => void;
+ href?: string;
+ rel?: string;
showOnMobile?: boolean;
badge?: string | number;
icon?: IconType | null;
+ menuItems?: ActionButtonMenuItem[];
}
diff --git a/frontend/src/lib/components/sheets/new-environment-sheet.svelte b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
index 2b020d148..1cbdf3901 100644
--- a/frontend/src/lib/components/sheets/new-environment-sheet.svelte
+++ b/frontend/src/lib/components/sheets/new-environment-sheet.svelte
@@ -4,17 +4,19 @@
import * as Tabs from '$lib/components/ui/tabs/index.js';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import FormInput from '$lib/components/form/form-input.svelte';
+ import LabeledSwitch from '$lib/components/form/labeled-switch.svelte';
import UrlInput from '$lib/components/form/url-input.svelte';
import { Spinner } from '$lib/components/ui/spinner/index.js';
import { CopyButton } from '$lib/components/ui/copy-button';
- import type { CreateEnvironmentDTO } from '$lib/types/environment.type';
+ import type { CreateEnvironmentDTO, DeploymentSnippetFile } from '$lib/types/environment.type';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/form.utils';
import { m } from '$lib/paraglide/messages';
import { environmentManagementService } from '$lib/services/env-mgmt-service';
import { queryKeys } from '$lib/query/query-keys';
- import { RemoteEnvironmentIcon, EdgeConnectionIcon } from '$lib/icons';
+ import { RemoteEnvironmentIcon, EdgeConnectionIcon, DownloadIcon } from '$lib/icons';
import { createMutation, useQueryClient } from '@tanstack/svelte-query';
+ import { downloadTextFile } from '$lib/utils/download-text-file';
type NewEnvironmentSheetProps = {
open: boolean;
@@ -33,14 +35,16 @@
name: string;
apiUrl: string;
isEdge: boolean;
+ mtlsEnabled: boolean;
+ mtlsFiles?: DeploymentSnippetFile[];
dockerRun?: string;
dockerCompose?: string;
} | null>(null);
let isLoadingSnippets = $state(false);
const createEnvironmentMutation = createMutation(() => ({
- mutationFn: ({ dto }: { dto: CreateEnvironmentDTO; apiUrl: string; isEdge: boolean }) =>
- environmentManagementService.create(dto),
+ mutationFn: (variables: { dto: CreateEnvironmentDTO; apiUrl: string; isEdge: boolean; useMTLS: boolean }) =>
+ environmentManagementService.create(variables.dto),
onSuccess: async (created, variables) => {
await queryClient.invalidateQueries({ queryKey: queryKeys.environments.all });
@@ -50,7 +54,8 @@
apiKey: created.apiKey,
name: created.name,
apiUrl: variables.apiUrl,
- isEdge: variables.isEdge
+ isEdge: variables.isEdge,
+ mtlsEnabled: false
};
isLoadingSnippets = true;
@@ -60,8 +65,15 @@
queryFn: () => environmentManagementService.getDeploymentSnippets(created.id),
staleTime: 0
});
- createdEnvironment.dockerRun = snippets.dockerRun;
- createdEnvironment.dockerCompose = snippets.dockerCompose;
+ const useGeneratedMTLS = variables.useMTLS && !!snippets.mtls;
+ if (variables.useMTLS && !snippets.mtls) {
+ toast.warning(m.environments_new_agent_mtls_assets_unavailable());
+ }
+
+ createdEnvironment.dockerRun = useGeneratedMTLS ? snippets.mtls!.dockerRun : snippets.dockerRun;
+ createdEnvironment.dockerCompose = useGeneratedMTLS ? snippets.mtls!.dockerCompose : snippets.dockerCompose;
+ createdEnvironment.mtlsEnabled = useGeneratedMTLS;
+ createdEnvironment.mtlsFiles = useGeneratedMTLS ? snippets.mtls!.files : [];
} catch (err) {
console.error('Failed to fetch deployment snippets:', err);
} finally {
@@ -82,6 +94,7 @@
let newAgentUrlProtocol = $state<'https' | 'http'>('http');
let newAgentUrlHost = $state('');
+ let edgeMTLSEnabled = $state(false);
// Direct mode form schema requires URL
const directFormSchema = z.object({
@@ -110,6 +123,7 @@
connectionMode = 'direct';
newAgentUrlProtocol = 'http';
newAgentUrlHost = '';
+ edgeMTLSEnabled = false;
$directInputs.name.value = '';
$directInputs.apiUrl.value = '';
$edgeInputs.name.value = '';
@@ -134,7 +148,7 @@
isEdge: false
};
- createEnvironmentMutation.mutate({ dto, apiUrl: fullUrl, isEdge: false });
+ createEnvironmentMutation.mutate({ dto, apiUrl: fullUrl, isEdge: false, useMTLS: false });
}
function handleEdgeSubmit() {
@@ -155,13 +169,48 @@
isEdge: true
};
- createEnvironmentMutation.mutate({ dto, apiUrl: '', isEdge: true });
+ createEnvironmentMutation.mutate({ dto, apiUrl: '', isEdge: true, useMTLS: edgeMTLSEnabled });
}
function handleDone() {
onEnvironmentCreated?.();
open = false;
}
+
+ function findCreatedMTLSFile(fileName: string): DeploymentSnippetFile | undefined {
+ return createdEnvironment?.mtlsFiles?.find((file) => file.name === fileName);
+ }
+
+ async function downloadCreatedMTLSFile(fileName: string) {
+ const file = findCreatedMTLSFile(fileName);
+ if (!file) return;
+ if (file.content) {
+ downloadTextFile(file.name, file.content);
+ return;
+ }
+ if (!file.downloadUrl) {
+ toast.error('Unable to download file.');
+ return;
+ }
+ try {
+ const response = await fetch(file.downloadUrl, { credentials: 'include' });
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`);
+ }
+ const blob = await response.blob();
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = file.name;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ } catch (err) {
+ console.error('Failed to download mTLS asset:', err);
+ toast.error('Unable to download file.');
+ }
+ }
</script>
<ResponsiveDialog.Root
@@ -195,6 +244,37 @@
<p class="text-muted-foreground text-xs">{m.environments_api_key_warning()}</p>
</div>
+ {#if createdEnvironment.mtlsEnabled}
+ <div class="space-y-3 rounded-lg border border-sky-500/25 bg-sky-500/8 p-4">
+ <div class="space-y-1">
+ <p class="text-sm font-medium">{m.environments_new_agent_mtls_enabled()}</p>
+ <p class="text-muted-foreground text-xs">
+ {m.environments_new_agent_mtls_auto_enroll()}
+ </p>
+ </div>
+ <div class="flex flex-col gap-2 sm:flex-row">
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ class="flex-1"
+ icon={DownloadIcon}
+ customLabel={m.environments_agent_mtls_download_certificate()}
+ onclick={() => downloadCreatedMTLSFile('agent.crt')}
+ disabled={!findCreatedMTLSFile('agent.crt')}
+ />
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ class="flex-1"
+ icon={DownloadIcon}
+ customLabel={m.environments_agent_mtls_download_key()}
+ onclick={() => downloadCreatedMTLSFile('agent.key')}
+ disabled={!findCreatedMTLSFile('agent.key')}
+ />
+ </div>
+ </div>
+ {/if}
+
{#if isLoadingSnippets}
<div class="flex items-center justify-center py-8">
<Spinner class="size-6" />
@@ -277,6 +357,15 @@
<form onsubmit={preventDefault(handleEdgeSubmit)} class="space-y-4">
<FormInput label={m.common_name()} placeholder="Remote Docker Host" bind:input={$edgeInputs.name} />
+ <LabeledSwitch
+ id="new-edge-agent-mtls"
+ label="Enable manager mTLS"
+ description="Use Arcane-generated edge mTLS assets when they are available on the manager."
+ checked={edgeMTLSEnabled}
+ onCheckedChange={(checked) => (edgeMTLSEnabled = checked)}
+ disabled={isSubmittingNewAgent}
+ />
+
<ArcaneButton
action="confirm"
type="submit"
diff --git a/frontend/src/lib/services/env-mgmt-service.ts b/frontend/src/lib/services/env-mgmt-service.ts
index 701e38d0d..fa108f10b 100644
--- a/frontend/src/lib/services/env-mgmt-service.ts
+++ b/frontend/src/lib/services/env-mgmt-service.ts
@@ -1,6 +1,5 @@
import BaseAPIService from './api-service';
-import type { DeploymentSnippets, Environment } from '$lib/types/environment.type';
-import type { CreateEnvironmentDTO, UpdateEnvironmentDTO } from '$lib/types/environment.type';
+import type { CreateEnvironmentDTO, DeploymentSnippets, Environment, UpdateEnvironmentDTO } from '$lib/types/environment.type';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
import type { AppVersionInformation } from '$lib/types/application-configuration';
import { transformPaginationParams } from '$lib/utils/params.util';
diff --git a/frontend/src/lib/types/environment.type.ts b/frontend/src/lib/types/environment.type.ts
index 61987e807..5ce75b2c4 100644
--- a/frontend/src/lib/types/environment.type.ts
+++ b/frontend/src/lib/types/environment.type.ts
@@ -1,5 +1,13 @@
export type EnvironmentStatus = 'online' | 'standby' | 'offline' | 'error' | 'pending';
+export type EdgeMTLSCertificate = {
+ commonName?: string;
+ expiresAt?: string;
+ daysRemaining?: number;
+ expired: boolean;
+ expiringSoon: boolean;
+};
+
export type Environment = {
id: string;
name: string;
@@ -8,11 +16,13 @@ export type Environment = {
enabled: boolean;
isEdge: boolean;
edgeTransport?: 'grpc' | 'websocket';
+ edgeSecurityMode?: 'token' | 'mtls';
connected?: boolean;
connectedAt?: string;
lastHeartbeat?: string;
lastPollAt?: string;
lastSeen?: string;
+ edgeMTLSCertificate?: EdgeMTLSCertificate;
apiKey?: string;
};
@@ -33,7 +43,24 @@ export interface UpdateEnvironmentDTO {
regenerateApiKey?: boolean;
}
+export interface DeploymentSnippetFile {
+ name: string;
+ content?: string;
+ downloadUrl?: string;
+ sensitive?: boolean;
+ containerPath: string;
+ permissions: string;
+}
+
+export interface DeploymentSnippetMTLS {
+ dockerRun: string;
+ dockerCompose: string;
+ files: DeploymentSnippetFile[];
+ hostDirHint: string;
+}
+
export interface DeploymentSnippets {
dockerRun: string;
dockerCompose: string;
+ mtls?: DeploymentSnippetMTLS;
}
diff --git a/frontend/src/lib/types/settings.type.ts b/frontend/src/lib/types/settings.type.ts
index 8f03d803f..2c111ff89 100644
--- a/frontend/src/lib/types/settings.type.ts
+++ b/frontend/src/lib/types/settings.type.ts
@@ -51,6 +51,7 @@ export type Settings = {
oledMode: boolean;
autoInjectEnv: boolean;
backupVolumeName?: string;
+ edgeMTLSManagerCAAvailable?: boolean;
authLocalEnabled: boolean;
authSessionTimeout: number;
diff --git a/frontend/src/lib/utils/download-text-file.ts b/frontend/src/lib/utils/download-text-file.ts
new file mode 100644
index 000000000..50e030a43
--- /dev/null
+++ b/frontend/src/lib/utils/download-text-file.ts
@@ -0,0 +1,11 @@
+export function downloadTextFile(filename: string, content: string, mimeType = 'application/x-pem-file'): void {
+ const blob = new Blob([content], { type: `${mimeType};charset=utf-8` });
+ const url = window.URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.setAttribute('download', filename);
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ window.URL.revokeObjectURL(url);
+}
diff --git a/frontend/src/lib/utils/settings.util.ts b/frontend/src/lib/utils/settings.util.ts
index 5796de3ae..e5aec036f 100644
--- a/frontend/src/lib/utils/settings.util.ts
+++ b/frontend/src/lib/utils/settings.util.ts
@@ -8,6 +8,7 @@ export type LocalSettings = {
mobileNavigationShowLabels: boolean;
sidebarHoverExpansion: boolean;
keyboardShortcutsEnabled: boolean;
+ edgeMTLSManagerCAAvailable?: boolean;
};
const LOCAL_SETTING_KEYS = new Set([
@@ -33,7 +34,8 @@ const LOCAL_SETTING_KEYS = new Set([
'oidcAdminClaim',
'oidcAdminValue',
'oidcProviderName',
- 'oidcProviderLogoUrl'
+ 'oidcProviderLogoUrl',
+ 'edgeMTLSManagerCAAvailable'
]);
export function isLocalSetting(key: string): boolean {
diff --git a/frontend/src/routes/(app)/environments/+page.svelte b/frontend/src/routes/(app)/environments/+page.svelte
index a02fb723b..5f9fa5e76 100644
--- a/frontend/src/routes/(app)/environments/+page.svelte
+++ b/frontend/src/routes/(app)/environments/+page.svelte
@@ -11,6 +11,7 @@
import { ResourcePageLayout, type ActionButton } from '$lib/layouts/index.js';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { simpleRefresh } from '$lib/utils/refresh.util';
+ import { DownloadIcon } from '$lib/icons';
let { data } = $props();
@@ -103,6 +104,18 @@
}
]
: []),
+ ...(currentUserIsAdmin && data.settings?.edgeMTLSManagerCAAvailable
+ ? [
+ {
+ id: 'download-edge-ca',
+ action: 'save' as const,
+ label: m.environments_download_edge_ca(),
+ href: '/api/edge-mtls/ca',
+ rel: 'external',
+ icon: DownloadIcon
+ }
+ ]
+ : []),
{
id: 'refresh',
action: 'restart' as const,
diff --git a/frontend/src/routes/(app)/environments/[id]/+page.svelte b/frontend/src/routes/(app)/environments/[id]/+page.svelte
index 315ea477c..5bc173605 100644
--- a/frontend/src/routes/(app)/environments/[id]/+page.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/+page.svelte
@@ -3,8 +3,10 @@
import { z } from 'zod/v4';
import * as Tabs from '$lib/components/ui/tabs/index.js';
import { TabBar, type TabItem } from '$lib/components/tab-bar';
+ import { ActionButtonGroup, type ActionButton } from '$lib/components/action-button-group/index.js';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import * as AlertDialog from '$lib/components/ui/alert-dialog';
+ import { CopyButton } from '$lib/components/ui/copy-button';
import { goto, invalidateAll } from '$app/navigation';
import { page } from '$app/state';
import { toast } from 'svelte-sonner';
@@ -21,19 +23,19 @@
import GeneralTab from './components/GeneralTab.svelte';
import DockerTab from './components/DockerTab.svelte';
import JobsTab from './components/JobsTab.svelte';
- import AgentTab from './components/AgentTab.svelte';
import TrivySecuritySettings from '$lib/components/settings/trivy-security-settings.svelte';
import {
ArrowLeftIcon,
EnvironmentsIcon,
AlertIcon,
+ DownloadIcon,
RefreshIcon,
- ApiKeyIcon,
DockerBrandIcon,
SecurityIcon,
SettingsIcon,
GitBranchIcon,
- JobsIcon
+ JobsIcon,
+ ResetIcon
} from '$lib/icons';
let { data } = $props();
@@ -48,41 +50,126 @@
let activeTab = $state('details');
+ let isRefreshing = $state(false);
+ let isTestingConnection = $state(false);
+ let isSyncing = $state(false);
+ let isRegeneratingKey = $state(false);
+ let showRegenerateDialog = $state(false);
+ let regeneratedApiKey = $state<string | null>(null);
+
+ // Version state
+ let remoteVersion = $state<AppVersionInformation | null>(null);
+ let isLoadingVersion = $state(false);
+
+ // Only non-edge custom URL tests should temporarily override the displayed status.
+ let statusOverride = $state<EnvironmentStatus | null>(null);
+ let currentStatus = $derived(resolveEnvironmentStatus(runtimeEnvironment, statusOverride));
+ let isCurrentlyOnline = $derived(isEnvironmentOnline(runtimeEnvironment, statusOverride));
+ let isCurrentlyStandby = $derived(currentStatus === 'standby');
+ let showSettingsTabs = $derived(runtimeEnvironment.enabled && isCurrentlyOnline && settings !== null);
+ let hasMTLSAssets = $derived(Boolean(runtimeEnvironment.edgeMTLSCertificate));
+ let showMTLSDownloads = $derived(
+ runtimeEnvironment.id !== '0' &&
+ runtimeEnvironment.isEdge &&
+ (runtimeEnvironment.edgeSecurityMode === 'mtls' || hasMTLSAssets)
+ );
+ let mtlsBundleDownloadHref = $derived(`/api/environments/${runtimeEnvironment.id}/deployment/mtls/bundle`);
+ let mtlsCertificateDownloadHref = $derived(`/api/environments/${runtimeEnvironment.id}/deployment/mtls/agent.crt`);
+ let mtlsKeyDownloadHref = $derived(`/api/environments/${runtimeEnvironment.id}/deployment/mtls/agent.key`);
+ let headerActions = $derived.by((): ActionButton[] => {
+ const actions: ActionButton[] = [];
+
+ if (environment.id !== '0') {
+ actions.push({
+ id: 'sync',
+ action: 'base',
+ label: m.sync_environment(),
+ onclick: syncEnvironment,
+ disabled: isSyncing,
+ loading: isSyncing,
+ icon: RefreshIcon
+ });
+
+ if (showMTLSDownloads) {
+ actions.push({
+ id: 'mtls-downloads',
+ action: 'base',
+ label: m.environments_agent_mtls_download_bundle(),
+ href: mtlsBundleDownloadHref,
+ rel: 'external',
+ icon: DownloadIcon,
+ menuItems: [
+ {
+ id: 'mtls-certificate',
+ label: m.environments_agent_mtls_download_certificate(),
+ href: mtlsCertificateDownloadHref
+ },
+ {
+ id: 'mtls-key',
+ label: m.environments_agent_mtls_download_key(),
+ href: mtlsKeyDownloadHref
+ }
+ ]
+ });
+ }
+
+ actions.push({
+ id: 'regenerate-api-key',
+ action: 'base',
+ label: m.environments_regenerate_api_key(),
+ onclick: () => {
+ showRegenerateDialog = true;
+ },
+ disabled: isRegeneratingKey,
+ loading: isRegeneratingKey,
+ icon: ResetIcon
+ });
+ }
+
+ actions.push({
+ id: 'refresh',
+ action: 'refresh',
+ label: m.common_refresh(),
+ onclick: refreshEnvironment,
+ disabled: isRefreshing,
+ loading: isRefreshing
+ });
+
+ return actions;
+ });
+
const tabItems = $derived.by((): TabItem[] => {
const items: TabItem[] = [
{
value: 'details',
label: m.environments_overview_title(),
icon: EnvironmentsIcon
- },
- {
- value: 'general',
- label: m.general_title(),
- icon: SettingsIcon
- },
- {
- value: 'docker',
- label: m.environments_docker_settings_title(),
- icon: DockerBrandIcon
- },
- {
- value: 'security',
- label: m.security_title(),
- icon: SecurityIcon
- },
- {
- value: 'jobs',
- label: m.jobs_title(),
- icon: JobsIcon
}
];
- if (environment.id !== '0') {
- items.push({
- value: 'agent',
- label: m.environments_agent_config_title(),
- icon: ApiKeyIcon
- });
+ if (showSettingsTabs) {
+ items.push(
+ {
+ value: 'general',
+ label: m.general_title(),
+ icon: SettingsIcon
+ },
+ {
+ value: 'docker',
+ label: m.environments_docker_settings_title(),
+ icon: DockerBrandIcon
+ },
+ {
+ value: 'security',
+ label: m.security_title(),
+ icon: SecurityIcon
+ },
+ {
+ value: 'jobs',
+ label: m.jobs_title(),
+ icon: JobsIcon
+ }
+ );
}
items.push({
@@ -122,23 +209,6 @@
activeTab = value;
}
- let isRefreshing = $state(false);
- let isTestingConnection = $state(false);
- let isSyncing = $state(false);
- let isRegeneratingKey = $state(false);
- let showRegenerateDialog = $state(false);
- let regeneratedApiKey = $state<string | null>(null);
-
- // Version state
- let remoteVersion = $state<AppVersionInformation | null>(null);
- let isLoadingVersion = $state(false);
-
- // Only non-edge custom URL tests should temporarily override the displayed status.
- let statusOverride = $state<EnvironmentStatus | null>(null);
- let currentStatus = $derived(resolveEnvironmentStatus(runtimeEnvironment, statusOverride));
- let isCurrentlyOnline = $derived(isEnvironmentOnline(runtimeEnvironment, statusOverride));
- let isCurrentlyStandby = $derived(currentStatus === 'standby');
-
// Form schema combining environment info and settings
const formSchema = z.object({
// Environment basic info
@@ -474,8 +544,8 @@
<p class="text-muted-foreground mt-1.5 text-sm wrap-break-word sm:text-base">{m.environments_page_subtitle()}</p>
</div>
- <div class="flex flex-wrap items-center gap-2">
- <div class="hidden items-center gap-2 sm:flex">
+ <div class="flex min-w-0 flex-1 flex-col items-start gap-3 sm:items-end">
+ <div class="hidden flex-wrap items-center gap-2 self-start sm:flex sm:self-end">
{#if settingsForm.hasChanges}
<span class="text-xs text-orange-600 dark:text-orange-400">{m.environments_unsaved_changes()}</span>
{:else}
@@ -501,29 +571,11 @@
loadingLabel={m.common_saving()}
/>
</div>
-
- {#if environment.id !== '0'}
- <ArcaneButton
- action="base"
- tone="outline"
- onclick={syncEnvironment}
- disabled={isSyncing}
- loading={isSyncing}
- icon={RefreshIcon}
- customLabel={m.sync_environment()}
- />
- {/if}
-
- <ArcaneButton
- action="refresh"
- tone="outline"
- onclick={refreshEnvironment}
- disabled={isRefreshing}
- loading={isRefreshing}
- />
</div>
</div>
+ <ActionButtonGroup buttons={headerActions} class="justify-end" />
+
{#if environment.enabled && settings && isCurrentlyStandby}
<div
class="flex items-start gap-3 rounded-lg border border-blue-500/30 bg-blue-500/10 p-4 text-blue-900 dark:text-blue-200"
@@ -557,6 +609,31 @@
{/if}
</div>
+ {#if regeneratedApiKey}
+ <div class="rounded-lg border border-emerald-500/30 bg-emerald-500/10 p-4 text-emerald-950 dark:text-emerald-100">
+ <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
+ <div class="space-y-2">
+ <p class="text-sm font-medium">{m.environments_new_api_key()}</p>
+ <div class="flex items-center gap-2">
+ <code class="bg-background/70 flex-1 rounded-md px-3 py-2 font-mono text-sm break-all">
+ {regeneratedApiKey}
+ </code>
+ <CopyButton text={regeneratedApiKey} size="icon" class="size-8 shrink-0" />
+ </div>
+ <p class="text-sm">{m.environments_api_key_save_warning()}</p>
+ </div>
+
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ onclick={() => (regeneratedApiKey = null)}
+ customLabel={m.common_dismiss()}
+ class="shrink-0"
+ />
+ </div>
+ </div>
+ {/if}
+
<Tabs.Root bind:value={activeTab} class="w-full">
<div class="my-4">
<TabBar items={tabItems} value={activeTab} onValueChange={handleTabChange} class="w-full" />
@@ -575,7 +652,7 @@
/>
</Tabs.Content>
- {#if settings}
+ {#if showSettingsTabs}
<Tabs.Content value="general">
<GeneralTab {formInputs} />
</Tabs.Content>
@@ -593,12 +670,6 @@
</Tabs.Content>
{/if}
- {#if environment.id !== '0'}
- <Tabs.Content value="agent">
- <AgentTab bind:regeneratedApiKey {isRegeneratingKey} bind:showRegenerateDialog />
- </Tabs.Content>
- {/if}
-
<Tabs.Content value="gitops" />
</Tabs.Root>
diff --git a/frontend/src/routes/(app)/environments/[id]/components/AgentTab.svelte b/frontend/src/routes/(app)/environments/[id]/components/AgentTab.svelte
deleted file mode 100644
index 18098adb6..000000000
--- a/frontend/src/routes/(app)/environments/[id]/components/AgentTab.svelte
+++ /dev/null
@@ -1,59 +0,0 @@
-<script lang="ts">
- import * as Card from '$lib/components/ui/card/index.js';
- import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { CopyButton } from '$lib/components/ui/copy-button';
- import { m } from '$lib/paraglide/messages';
- import { ApiKeyIcon, ResetIcon } from '$lib/icons';
-
- let { regeneratedApiKey = $bindable(), isRegeneratingKey, showRegenerateDialog = $bindable() } = $props();
-</script>
-
-<Card.Root class="flex flex-col">
- <Card.Header icon={ApiKeyIcon}>
- <div class="flex flex-col space-y-1.5">
- <Card.Title>
- <h2>{m.environments_agent_config_title()}</h2>
- </Card.Title>
- <Card.Description>{m.environments_agent_config_description()}</Card.Description>
- </div>
- </Card.Header>
- <Card.Content class="space-y-4 p-4">
- {#if regeneratedApiKey}
- <div class="space-y-4">
- <div class="space-y-2">
- <div class="text-sm font-medium">{m.environments_new_api_key()}</div>
- <div class="flex items-center gap-2">
- <code class="bg-muted flex-1 rounded-md px-3 py-2 font-mono text-sm break-all">
- {regeneratedApiKey}
- </code>
- <CopyButton text={regeneratedApiKey} size="icon" class="size-7" />
- </div>
- <p class="text-muted-foreground text-xs">{m.environments_api_key_save_warning()}</p>
- </div>
- <ArcaneButton
- action="base"
- tone="outline"
- onclick={() => (regeneratedApiKey = null)}
- customLabel={m.common_dismiss()}
- class="w-full"
- />
- </div>
- {:else}
- <div class="rounded-lg border border-amber-500/30 bg-amber-500/10 p-4 text-sm text-amber-900 dark:text-amber-200">
- <p class="font-medium">{m.environments_regenerate_warning_title()}</p>
- <p class="mt-1">{m.environments_regenerate_warning_message()}</p>
- </div>
- <ArcaneButton
- action="remove"
- onclick={() => {
- showRegenerateDialog = true;
- }}
- disabled={isRegeneratingKey}
- loading={isRegeneratingKey}
- icon={ResetIcon}
- customLabel={m.environments_regenerate_api_key()}
- class="w-full"
- />
- {/if}
- </Card.Content>
-</Card.Root>
diff --git a/frontend/src/routes/(app)/environments/[id]/components/DetailsTab.svelte b/frontend/src/routes/(app)/environments/[id]/components/DetailsTab.svelte
index 8e4b90aca..3a959dcde 100644
--- a/frontend/src/routes/(app)/environments/[id]/components/DetailsTab.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/components/DetailsTab.svelte
@@ -82,6 +82,18 @@
}
});
+ let mtlsCertificateBadge = $derived.by((): { text: string; variant: 'green' | 'amber' | 'red' } | null => {
+ const cert = environment.edgeMTLSCertificate;
+ if (!cert) return null;
+ if (cert.expired) {
+ return { text: m.environments_edge_mtls_certificate_status_expired(), variant: 'red' };
+ }
+ if (cert.expiringSoon) {
+ return { text: m.environments_edge_mtls_certificate_status_expiring_soon(), variant: 'amber' };
+ }
+ return { text: m.environments_edge_mtls_certificate_status_valid(), variant: 'green' };
+ });
+
let tunnelBadge = $derived.by((): { text: string; variant: 'green' | 'blue' | 'gray' | 'amber' | 'red' } => {
if (!environment.isEdge) {
return statusBadge;
@@ -304,5 +316,50 @@
</div>
</div>
</div>
+
+ {#if mtlsCertificateBadge && environment.edgeMTLSCertificate}
+ <div class="space-y-3 rounded-lg border p-4">
+ <div class="space-y-1">
+ <h3 class="text-sm font-medium">{m.environments_agent_mtls_section_title()}</h3>
+ <p class="text-muted-foreground text-xs">{m.environments_agent_mtls_description()}</p>
+ </div>
+
+ <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
+ <div>
+ <Label class="text-muted-foreground text-xs font-medium">
+ {m.environments_edge_mtls_certificate_status_label()}
+ </Label>
+ <div class="mt-1">
+ <StatusBadge text={mtlsCertificateBadge.text} variant={mtlsCertificateBadge.variant} />
+ </div>
+ </div>
+ <div>
+ <Label class="text-muted-foreground text-xs font-medium">
+ {m.environments_edge_mtls_certificate_expires_label()}
+ </Label>
+ <div class="mt-1 space-y-1">
+ <div class="font-mono text-sm">
+ {environment.edgeMTLSCertificate.expiresAt ? formatDateTime(environment.edgeMTLSCertificate.expiresAt) : '—'}
+ </div>
+ {#if environment.edgeMTLSCertificate.daysRemaining !== undefined}
+ <div class="text-muted-foreground text-xs">
+ {m.environments_edge_mtls_certificate_days_remaining({
+ count: environment.edgeMTLSCertificate.daysRemaining
+ })}
+ </div>
+ {/if}
+ </div>
+ </div>
+ {#if environment.edgeMTLSCertificate.commonName}
+ <div class="sm:col-span-2">
+ <Label class="text-muted-foreground text-xs font-medium">
+ {m.environments_edge_mtls_certificate_common_name_label()}
+ </Label>
+ <div class="mt-1 font-mono text-sm">{environment.edgeMTLSCertificate.commonName}</div>
+ </div>
+ {/if}
+ </div>
+ </div>
+ {/if}
</Card.Content>
</Card.Root>
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index 3a1436639..ffde22c60 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -5,6 +5,37 @@ import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import Icons from 'unplugin-icons/vite';
+const devBackendURL = process.env['DEV_BACKEND_URL'] || 'https://localhost:3552';
+const parsedDevBackendURL = new URL(devBackendURL);
+
+function parseBooleanEnv(value: string | undefined): boolean | undefined {
+ if (value == null || value === '') {
+ return undefined;
+ }
+
+ switch (value.trim().toLowerCase()) {
+ case '1':
+ case 'true':
+ case 'yes':
+ case 'on':
+ return true;
+ case '0':
+ case 'false':
+ case 'no':
+ case 'off':
+ return false;
+ default:
+ return undefined;
+ }
+}
+
+const explicitInsecureTLS = parseBooleanEnv(process.env['DEV_BACKEND_INSECURE_TLS']);
+// Allow local self-signed HTTPS while developing edge mTLS against the manager.
+const useInsecureLocalTLS =
+ explicitInsecureTLS ??
+ (parsedDevBackendURL.protocol === 'https:' &&
+ (parsedDevBackendURL.hostname === 'localhost' || parsedDevBackendURL.hostname === '127.0.0.1'));
+
export default defineConfig({
plugins: [
tailwindcss(),
@@ -29,9 +60,10 @@ export default defineConfig({
host: process.env['HOST'],
proxy: {
'/api': {
- target: process.env['DEV_BACKEND_URL'] || 'http://localhost:3552',
+ target: devBackendURL,
changeOrigin: true,
- ws: true
+ ws: true,
+ secure: !useInsecureLocalTLS
}
}
}
diff --git a/types/environment/environment.go b/types/environment/environment.go
index 47a80189c..033c61928 100644
--- a/types/environment/environment.go
+++ b/types/environment/environment.go
@@ -91,6 +91,33 @@ type TestConnectionRequest struct {
ApiUrl *string `json:"apiUrl,omitempty"`
}
+type EdgeMTLSCertificate struct {
+ // CommonName is the certificate subject common name.
+ //
+ // Required: false
+ CommonName *string `json:"commonName,omitempty"`
+
+ // ExpiresAt is when the generated mTLS client certificate expires.
+ //
+ // Required: false
+ ExpiresAt *time.Time `json:"expiresAt,omitempty"`
+
+ // DaysRemaining is the rounded number of days until certificate expiry.
+ //
+ // Required: false
+ DaysRemaining *int `json:"daysRemaining,omitempty"`
+
+ // Expired indicates whether the certificate is already expired.
+ //
+ // Required: false
+ Expired bool `json:"expired"`
+
+ // ExpiringSoon indicates whether the certificate is within the warning window.
+ //
+ // Required: false
+ ExpiringSoon bool `json:"expiringSoon"`
+}
+
// Environment represents an environment in API responses.
type Environment struct {
// ID of the environment.
@@ -134,6 +161,27 @@ type Environment struct {
// Required: false
EdgeTransport *string `json:"edgeTransport,omitempty"`
+ // EdgeSecurityMode indicates how the current edge tunnel authenticated.
+ // Values include "token" and "mtls".
+ //
+ // Required: false
+ EdgeSecurityMode *string `json:"edgeSecurityMode,omitempty"`
+
+ // EdgeSessionID is the manager-issued ID for the current live edge session.
+ //
+ // Required: false
+ EdgeSessionID *string `json:"edgeSessionId,omitempty"`
+
+ // EdgeAgentInstance identifies the currently connected agent runtime instance.
+ //
+ // Required: false
+ EdgeAgentInstance *string `json:"edgeAgentInstance,omitempty"`
+
+ // EdgeCapabilities lists the commands advertised by the connected edge agent.
+ //
+ // Required: false
+ EdgeCapabilities []string `json:"edgeCapabilities,omitempty"`
+
// Connected reports whether an edge environment currently has a live tunnel.
//
// Required: false
@@ -156,6 +204,11 @@ type Environment struct {
// Required: false
LastPollAt *time.Time `json:"lastPollAt,omitempty"`
+ // EdgeMTLSCertificate describes the generated edge client certificate when available.
+ //
+ // Required: false
+ EdgeMTLSCertificate *EdgeMTLSCertificate `json:"edgeMTLSCertificate,omitempty"`
+
// ApiKey is returned only when creating or regenerating
//
// Required: false