Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: harden gRPC tunnel reliability and request lifecycle (#3325)
Kyle Mendelld6fcfd36bce0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 93ac83aea..6d3fedf8b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -74,6 +74,10 @@ jobs:CGO_ENABLED: ${{ matrix.module.cgo_enabled }}run: just test ${{ matrix.module.name }}+ - name: Lint protobuf definitions+ if: matrix.module.name == 'backend'+ run: just lint proto+- name: Upload coverage artifactif: always()uses: actions/upload-artifact@v7diff --git a/Justfile b/Justfileindex 5c126f9ee..2abb9558e 100644--- a/Justfile+++ b/Justfile@@ -331,6 +331,11 @@ _lint-cli:_lint-types:cd types && golangci-lint run -c ../.github/.golangci.yml ./...+# Lint edge tunnel protobuf definitions.+[group('quality')]+_lint-proto:+ cd {{ edge_proto_dir }} && go run github.com/bufbuild/buf/cmd/buf@latest lint+# Lint all Go code[group('quality')]_lint-go: _lint-backend _lint-cli _lint-types@@ -339,8 +344,9 @@ _lint-go: _lint-backend _lint-cli _lint-types_lint-all:@just _lint-js@just _lint-go+ @just _lint-proto-# Lint targets. Valid: "backend", "frontend", "tests", "email-templates", "js", "cli", "types", "go", "all".+# Lint targets. Valid: "backend", "frontend", "tests", "email-templates", "js", "cli", "types", "go", "proto", "all".[group('quality')]lint target="all":@just "_lint-{{ target }}"@@ -507,6 +513,7 @@ gomod action="tidy" target="all":# Generate edge tunnel protobuf/gRPC code.[group('codegen')]_generate-proto:+ cd {{ edge_proto_dir }} && go run github.com/bufbuild/buf/cmd/buf@latest lintcd {{ edge_proto_dir }} && go run github.com/bufbuild/buf/cmd/buf@latest generate# Generate targets. Valid: "proto".diff --git a/backend/api/handlers/environments.go b/backend/api/handlers/environments.goindex d63f0ee0e..d4f74c83e 100644--- a/backend/api/handlers/environments.go+++ b/backend/api/handlers/environments.go@@ -823,6 +823,8 @@ func (h *EnvironmentHandler) triggerEnvironmentResourceSyncInternal(ctx context.detachedCtx := context.WithoutCancel(ctx)go func(syncCtx context.Context, envID string, envName string, syncReason string) {+ syncCtx, cancel := context.WithTimeout(syncCtx, edge.DefaultProxyTimeout)+ defer cancel()if err := h.environmentService.SyncRegistriesToEnvironment(syncCtx, envID); err != nil {slog.WarnContext(syncCtx, "Failed to sync registries to environment","environmentID", envID,@@ -833,6 +835,8 @@ func (h *EnvironmentHandler) triggerEnvironmentResourceSyncInternal(ctx context.}(detachedCtx, environmentID, environmentName, reason)go func(syncCtx context.Context, envID string, envName string, syncReason string) {+ syncCtx, cancel := context.WithTimeout(syncCtx, edge.DefaultProxyTimeout)+ defer cancel()if err := h.environmentService.SyncRepositoriesToEnvironment(syncCtx, envID); err != nil {slog.WarnContext(syncCtx, "Failed to sync git repositories to environment","environmentID", envID,diff --git a/backend/internal/bootstrap/server_bootstrap.go b/backend/internal/bootstrap/server_bootstrap.goindex ad9152da5..b7c3b5527 100644--- a/backend/internal/bootstrap/server_bootstrap.go+++ b/backend/internal/bootstrap/server_bootstrap.go@@ -150,7 +150,8 @@ func configureTunnelServerInternal(appCtx context.Context, cfg *config.Config, rvar grpcServer *grpc.Serverif !cfg.AgentMode && tunnelServer != nil {- grpcServer = grpc.NewServer(tunnelServer.GRPCServerOptions(appCtx)...)+ //nolint:contextcheck // Stream interceptors receive request-scoped context from grpc.ServerStream.+ grpcServer = grpc.NewServer(tunnelServer.GRPCServerOptions()...)tunnelpb.RegisterTunnelServiceServer(grpcServer, tunnelServer)httpHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/backend/pkg/libarcane/edge/client.go b/backend/pkg/libarcane/edge/client.goindex 698ac5174..9e2b8dec7 100644--- a/backend/pkg/libarcane/edge/client.go+++ b/backend/pkg/libarcane/edge/client.go@@ -10,8 +10,6 @@ import ("net""net/http""strings"- "sync"- "sync/atomic""time""github.com/google/uuid"@@ -36,49 +34,15 @@ const (defaultCommandChunkSize = 256 * 1024)-// activeWSStream tracks an active WebSocket stream on the agent side.-type activeWSStream struct {- ws *websocket.Conn- conn TunnelConnection // tunnel connection the stream was opened on- cancel context.CancelFunc- dataCh chan wsPayload- mu sync.Mutex- closed bool-}--type wsPayload struct {- messageType int- data []byte-}--// TunnelClient represents the agent-side tunnel client-type TunnelClient struct {- cfg *Config- handler http.Handler- reconnectInterval time.Duration- heartbeatInterval time.Duration- grpcRegistrationTimeout time.Duration- websocketPreferenceTTL time.Duration- managerURL string- managerGRPCAddr string- localPort string // Port the agent is running on locally- httpClient *http.Client- conn atomic.Pointer[connBox]- stopCh chan struct{}- requestTimeout time.Duration- activeStreams sync.Map // map[string]*activeWSStream- transportPreferenceMu sync.RWMutex- preferWebSocketUntil time.Time- agentInstanceID string- sessionID string-}--// connBox wraps the active TunnelConnection so it can be swapped atomically on-// reconnect. The wrapper is required because the gRPC and WebSocket connections-// are different concrete types; a bare atomic.Value would panic on the type-// change, whereas an atomic.Pointer to a fixed box type does not.-type connBox struct {- conn TunnelConnection+func (t *commandRequestTransfer) stopInternal() {+ if t == nil {+ return+ }+ t.timerMu.Lock()+ defer t.timerMu.Unlock()+ if t.timer != nil {+ t.timer.Stop()+ }}// setConn stores the active tunnel connection. The connection is reassigned on@@ -272,11 +236,6 @@ func (c *TunnelClient) shouldAttemptWebSocketTunnelInternal() bool {return transports.websocket}-type managedTunnelTransportsInternal struct {- grpc bool- websocket bool-}-func (c *TunnelClient) managedTunnelTransportsInternal() managedTunnelTransportsInternal {if c == nil || c.cfg == nil {return managedTunnelTransportsInternal{}@@ -334,6 +293,13 @@ func (c *TunnelClient) grpcRegistrationTimeoutInternal() time.Duration {return c.grpcRegistrationTimeout}+func (c *TunnelClient) requestTimeoutInternal() time.Duration {+ if c == nil || c.requestTimeout <= 0 {+ return DefaultRequestTimeout+ }+ return c.requestTimeout+}+func (c *TunnelClient) websocketPreferenceTTLInternal() time.Duration {if c == nil || c.websocketPreferenceTTL <= 0 {return DefaultWebSocketPreferenceTTL@@ -375,11 +341,13 @@ func (c *TunnelClient) markTransportConnectedInternal(transport string) {}func (c *TunnelClient) registerMessageInternal() *TunnelMessage {+ capabilities := AdvertisedEdgeCommands()+ capabilities = append(capabilities, tunnelCapabilityChunkedRequest)return &TunnelMessage{Type: MessageTypeRegister,AgentToken: c.cfg.AgentToken,AgentInstance: c.agentInstanceID,- Capabilities: AdvertisedEdgeCommands(),+ Capabilities: capabilities,ResumeSession: c.sessionID,}}@@ -473,6 +441,7 @@ func (c *TunnelClient) messageLoop(ctx context.Context) error {defer c.closeAllStreams()conn := c.getConn()+ defer c.clearCommandRequestTransfersInternal(conn)for {select {case <-ctx.Done():@@ -487,7 +456,13 @@ func (c *TunnelClient) messageLoop(ctx context.Context) error {case MessageTypeRequest:go c.handleRequest(ctx, conn, msg)case MessageTypeCommandRequest:- go c.handleCommandRequest(ctx, conn, msg)+ if transferID := strings.TrimSpace(msg.Metadata[bodyTransferMetadataKey]); transferID != "" {+ c.beginCommandRequestTransferInternal(ctx, conn, transferID, msg)+ } else {+ go c.handleCommandRequest(ctx, conn, msg)+ }+ case MessageTypeFileChunk:+ c.handleCommandRequestChunkInternal(ctx, msg)case MessageTypeWebSocketStart:c.handleWebSocketStart(ctx, conn, msg)case MessageTypeStreamOpen:@@ -502,7 +477,7 @@ func (c *TunnelClient) messageLoop(ctx context.Context) error {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:+ case MessageTypeResponse, MessageTypeHeartbeat, MessageTypeStreamEnd, MessageTypeEvent, MessageTypeCommandAck, MessageTypeCommandOutput, MessageTypeCommandComplete:slog.DebugContext(ctx, "Ignoring message type on agent", "type", msg.Type)case MessageTypeHeartbeatAck:slog.DebugContext(ctx, "Received heartbeat ack")@@ -523,9 +498,91 @@ func (c *TunnelClient) messageLoop(ctx context.Context) error {}}+func (c *TunnelClient) beginCommandRequestTransferInternal(ctx context.Context, conn TunnelConnection, transferID string, msg *TunnelMessage) {+ if c == nil || conn == nil || msg == nil {+ return+ }++ timeout := c.requestTimeoutInternal()+ transfer := &commandRequestTransfer{request: msg, conn: conn}+ transfer.timerMu.Lock()+ previous, loaded := c.requestTransfers.Swap(transferID, transfer)+ transfer.timer = time.AfterFunc(timeout, func() {+ if c.requestTransfers.CompareAndDelete(transferID, transfer) {+ slog.WarnContext(ctx, "Command body transfer expired", "transfer_id", transferID, "command_id", msg.ID)+ c.sendCommandCompleteInternal(conn, msg.ID, http.StatusRequestTimeout, "command body transfer timed out")+ }+ })+ transfer.timerMu.Unlock()+ if loaded {+ if previous, ok := previous.(*commandRequestTransfer); ok {+ previous.stopInternal()+ c.sendCommandCompleteInternal(previous.conn, previous.request.ID, http.StatusBadRequest, "duplicate command body transfer ID")+ }+ }+}++func (c *TunnelClient) handleCommandRequestChunkInternal(ctx context.Context, msg *TunnelMessage) {+ if c == nil || msg == nil {+ return+ }++ value, ok := c.requestTransfers.Load(msg.ID)+ if !ok {+ slog.WarnContext(ctx, "Received command body chunk for unknown transfer", "transfer_id", msg.ID)+ return+ }+ transfer, ok := value.(*commandRequestTransfer)+ if !ok {+ c.requestTransfers.Delete(msg.ID)+ slog.WarnContext(ctx, "Discarded invalid command body transfer state", "transfer_id", msg.ID)+ return+ }+ if msg.Sequence != transfer.nextSequence {+ if c.requestTransfers.CompareAndDelete(msg.ID, transfer) {+ transfer.stopInternal()+ c.sendCommandCompleteInternal(transfer.conn, transfer.request.ID, http.StatusBadRequest, "command body chunks arrived out of order")+ }+ return+ }++ _, _ = transfer.body.Write(msg.Body)+ transfer.nextSequence+++ if !msg.EOF {+ return+ }++ if c.requestTransfers.CompareAndDelete(msg.ID, transfer) {+ transfer.stopInternal()+ transfer.request.Body = append([]byte(nil), transfer.body.Bytes()...)+ go c.handleCommandRequest(ctx, transfer.conn, transfer.request)+ }+}++func (c *TunnelClient) clearCommandRequestTransfersInternal(conn TunnelConnection) {+ if c == nil {+ return+ }++ c.requestTransfers.Range(func(transferID, value any) bool {+ transfer, ok := value.(*commandRequestTransfer)+ if !ok {+ c.requestTransfers.Delete(transferID)+ return true+ }+ if transfer.conn != conn {+ return true+ }+ if c.requestTransfers.CompareAndDelete(transferID, transfer) {+ transfer.stopInternal()+ }+ return true+ })+}+func (c *TunnelClient) handleCommandRequest(ctx context.Context, conn TunnelConnection, msg *TunnelMessage) {if !ValidateEdgeCommand(msg.Command, msg.Method, msg.Path, false) {- c.sendCommandComplete(conn, msg.ID, http.StatusBadRequest, nil, nil, "unsupported edge command", false)+ c.sendCommandCompleteInternal(conn, msg.ID, http.StatusBadRequest, "unsupported edge command")return}if conn == nil {@@ -536,12 +593,12 @@ func (c *TunnelClient) handleCommandRequest(ctx context.Context, conn TunnelConnreturn}- reqCtx, cancel := context.WithTimeout(ctx, c.requestTimeout)+ reqCtx, cancel := context.WithTimeout(ctx, c.requestTimeoutInternal())defer cancel()req, err := c.buildLocalHTTPRequest(reqCtx, msg)if err != nil {- c.sendCommandComplete(conn, msg.ID, http.StatusInternalServerError, nil, nil, fmt.Sprintf("failed to create request: %v", err), false)+ c.sendCommandCompleteInternal(conn, msg.ID, http.StatusInternalServerError, fmt.Sprintf("failed to create request: %v", err))return}@@ -1058,42 +1115,18 @@ func (c *TunnelClient) sendErrorResponse(conn TunnelConnection, requestID string_ = conn.Send(resp)}-func (c *TunnelClient) sendCommandComplete(conn TunnelConnection, commandID string, status int, headers map[string]string, body []byte, message string, streaming bool) {+func (c *TunnelClient) sendCommandCompleteInternal(conn TunnelConnection, commandID string, status int, message string) {if conn == nil {return}_ = conn.Send(&TunnelMessage{- ID: commandID,- Type: MessageTypeCommandComplete,- Status: status,- Headers: headers,- Body: body,- Error: message,- Streaming: streaming,+ ID: commandID,+ Type: MessageTypeCommandComplete,+ Status: status,+ Error: message,})}-// responseRecorder captures HTTP responses-type responseRecorder struct {- headers http.Header- body bytes.Buffer- statusCode int-}--type commandResponseRecorder struct {- conn TunnelConnection- headers http.Header- commandID string- commandName string- buffer bytes.Buffer- statusCode int- sequence int64- mu sync.Mutex- wroteHeader bool- streaming bool- closed bool-}-func newCommandResponseRecorderInternal(commandID, commandName string, conn TunnelConnection) *commandResponseRecorder {return &commandResponseRecorder{commandID: commandID,@@ -1246,16 +1279,6 @@ func (r *responseRecorder) WriteHeader(statusCode int) {r.statusCode = statusCode}-type streamingResponseRecorder struct {- requestID string- conn TunnelConnection- headers http.Header- statusCode int- wroteHeader bool- closed bool- mu sync.Mutex-}-func newStreamingResponseRecorder(requestID string, conn TunnelConnection) *streamingResponseRecorder {return &streamingResponseRecorder{requestID: requestID,@@ -1283,14 +1306,22 @@ func (r *streamingResponseRecorder) Write(b []byte) (int, error) {return 0, nil}- if err := r.conn.Send(&TunnelMessage{- ID: r.requestID,- Type: MessageTypeStreamData,- Body: append([]byte(nil), b...),- }); err != nil {- return 0, err+ originalLen := len(b)+ for len(b) > 0 {+ chunk := b+ if len(chunk) > defaultCommandChunkSize {+ chunk = chunk[:defaultCommandChunkSize]+ }+ if err := r.conn.Send(&TunnelMessage{+ ID: r.requestID,+ Type: MessageTypeStreamData,+ Body: append([]byte(nil), chunk...),+ }); err != nil {+ return 0, err+ }+ b = b[len(chunk):]}- return len(b), nil+ return originalLen, nil}func (r *streamingResponseRecorder) WriteHeader(statusCode int) {diff --git a/backend/pkg/libarcane/edge/client_test.go b/backend/pkg/libarcane/edge/client_test.goindex d2cef3cae..03dfd260c 100644--- a/backend/pkg/libarcane/edge/client_test.go+++ b/backend/pkg/libarcane/edge/client_test.go@@ -1,6 +1,7 @@package edgeimport (+ "bytes""context""encoding/json""errors"@@ -722,10 +723,6 @@ func (f *fakeTunnelConnForTransportCheck) IsClosed() bool {return false}-func (f *fakeTunnelConnForTransportCheck) SendRequest(context.Context, *TunnelMessage, *sync.Map) (*TunnelMessage, error) {- return nil, nil-}-type capturingTunnelConnForHandleRequest struct {sent []*TunnelMessage}@@ -759,10 +756,6 @@ func (c *capturingTunnelConnForHandleRequest) IsClosed() bool {return false}-func (c *capturingTunnelConnForHandleRequest) SendRequest(context.Context, *TunnelMessage, *sync.Map) (*TunnelMessage, error) {- return nil, nil-}-type failingHeartbeatConn struct {closeCalled bool}@@ -788,10 +781,6 @@ func (f *failingHeartbeatConn) IsClosed() bool {return false}-func (f *failingHeartbeatConn) SendRequest(context.Context, *TunnelMessage, *sync.Map) (*TunnelMessage, error) {- return nil, errors.New("not implemented")-}-type stallingTunnelService struct {tunnelpb.UnimplementedTunnelServiceServerconnectCount atomic.Int32@@ -839,10 +828,6 @@ func (c *blockingRegistrationConn) IsClosed() bool {}}-func (c *blockingRegistrationConn) SendRequest(context.Context, *TunnelMessage, *sync.Map) (*TunnelMessage, error) {- return nil, errors.New("not implemented")-}-func (s *stallingTunnelService) Connect(stream grpc.BidiStreamingServer[tunnelpb.AgentMessage, tunnelpb.ManagerMessage]) error {s.connectCount.Add(1)if _, err := stream.Recv(); err != nil {@@ -923,6 +908,61 @@ func TestTunnelClient_GRPC_EndToEnd(t *testing.T) {}}+func TestTunnelClient_GRPC_ChunkedRequestBodyEndToEnd(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)++ envID := "env-e2e-grpc-chunked-body"+ GetRegistry().Unregister(envID)+ defer GetRegistry().Unregister(envID)++ tunnelServer := NewTunnelServer(func(_ context.Context, token string) (string, error) {+ if token != "valid-token" {+ return "", errors.New("invalid token")+ }+ return envID, nil+ }, nil)+ go tunnelServer.StartCleanupLoop(ctx)+ defer func() {+ cancel()+ tunnelServer.WaitForCleanupDone()+ }()++ managerURL, stopManager := startTestGRPCTunnelServerOnAPIPathInternal(t, ctx, tunnelServer)+ defer stopManager()++ wantBody := bytes.Repeat([]byte("arcane-edge-chunk"), 320*1024)+ localHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, err := io.ReadAll(r.Body)+ if err != nil || r.URL.Path != "/api/environments/0/images/upload" || !bytes.Equal(body, wantBody) {+ http.Error(w, "unexpected request", http.StatusBadRequest)+ return+ }+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte("uploaded"))+ })++ client := NewTunnelClient(&Config{+ EdgeTransport: EdgeTransportGRPC,+ ManagerApiUrl: managerURL,+ AgentToken: "valid-token",+ EdgeReconnectInterval: 1,+ }, localHandler)+ go client.StartWithErrorChan(ctx, nil)++ var tunnel *AgentTunnel+ require.Eventually(t, func() bool {+ var ok bool+ tunnel, ok = GetRegistry().Get(envID).Get()+ return ok && tunnel != nil && !tunnel.Conn.IsClosed()+ }, 5*time.Second, 20*time.Millisecond)+ require.Contains(t, tunnel.Capabilities, tunnelCapabilityChunkedRequest)++ status, _, body, err := ProxyRequest(ctx, tunnel, http.MethodPost, "/api/environments/0/images/upload", "", nil, wantBody)+ require.NoError(t, err)+ assert.Equal(t, http.StatusOK, status)+ assert.Equal(t, "uploaded", string(body))+}+func TestTunnelClient_useTLSForManagerGRPC(t *testing.T) {tests := []struct {name string@@ -1043,7 +1083,7 @@ func TestTunnelClient_connectAndServeGRPC_RegistrationRejected(t *testing.T) {err := client.connectAndServeGRPC(ctx)require.Error(t, err)- assert.Contains(t, err.Error(), "manager rejected tunnel registration")+ assert.Contains(t, err.Error(), "failed to receive tunnel registration response")assert.Contains(t, err.Error(), "invalid agent token")}@@ -1605,7 +1645,11 @@ func startTestGRPCTunnelServerOnAPIPathInternal(t *testing.T, ctx context.Contexfunc startTestTunnelServiceOnAPIPathInternal(t *testing.T, ctx context.Context, service tunnelpb.TunnelServiceServer) (string, func()) {t.Helper()- grpcServer := grpc.NewServer()+ serverOptions := []grpc.ServerOption{}+ if tunnelServer, ok := service.(*TunnelServer); ok {+ serverOptions = tunnelServer.GRPCServerOptions()+ }+ grpcServer := grpc.NewServer(serverOptions...)tunnelpb.RegisterTunnelServiceServer(grpcServer, service)var lc net.ListenConfig@@ -1970,7 +2014,11 @@ func TestTunnelClient_syncPollManagedSessionInternal_IdleUsesBoundedStopTimeout(func startTestPollAndGRPCManagerInternal(t *testing.T, ctx context.Context, service tunnelpb.TunnelServiceServer, pollResp TunnelPollResponse) (string, func()) {t.Helper()- grpcServer := grpc.NewServer()+ serverOptions := []grpc.ServerOption{}+ if tunnelServer, ok := service.(*TunnelServer); ok {+ serverOptions = tunnelServer.GRPCServerOptions()+ }+ grpcServer := grpc.NewServer(serverOptions...)tunnelpb.RegisterTunnelServiceServer(grpcServer, service)var lc net.ListenConfig@@ -2153,10 +2201,6 @@ func (f *fakeTunnelConn) IsClosed() bool {return f.closed}-func (f *fakeTunnelConn) SendRequest(_ context.Context, _ *TunnelMessage, _ *sync.Map) (*TunnelMessage, error) {- return nil, errors.New("not implemented")-}-func TestStreamingResponseRecorder_Sequence(t *testing.T) {conn := &fakeTunnelConn{}r := newStreamingResponseRecorder("req-1", conn)diff --git a/backend/pkg/libarcane/edge/client_transport_grpc.go b/backend/pkg/libarcane/edge/client_transport_grpc.goindex 5ff3d0946..93ef791aa 100644--- a/backend/pkg/libarcane/edge/client_transport_grpc.go+++ b/backend/pkg/libarcane/edge/client_transport_grpc.go@@ -27,6 +27,7 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {}dialOpts := []grpc.DialOption{+ grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxGRPCTunnelMessageSize)),grpc.WithConnectParams(grpc.ConnectParams{Backoff: backoff.Config{BaseDelay: 1 * time.Second,@@ -36,6 +37,9 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {},MinConnectTimeout: 10 * time.Second,}),+ // The manager currently serves gRPC through grpc.Server.ServeHTTP, so+ // net/http owns HTTP/2 ping handling. A future native grpc.Serve listener+ // must add an enforcement policy whose MinTime permits this interval.grpc.WithKeepaliveParams(keepalive.ClientParameters{Time: 30 * time.Second,Timeout: 10 * time.Second,diff --git a/backend/pkg/libarcane/edge/client_transport_grpc_test.go b/backend/pkg/libarcane/edge/client_transport_grpc_test.goindex a2591eb08..0b7deef7d 100644--- a/backend/pkg/libarcane/edge/client_transport_grpc_test.go+++ b/backend/pkg/libarcane/edge/client_transport_grpc_test.go@@ -49,7 +49,7 @@ func TestGRPCTunnel_RequestResponse(t *testing.T) {defer func() { _ = conn.Close() }()client := tunnelpb.NewTunnelServiceClient(conn)- stream, err := client.Connect(ctx)+ stream, err := client.Connect(testGRPCOutgoingContextInternal(ctx, "valid-token"))require.NoError(t, err)err = stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_Register{Register: &tunnelpb.RegisterRequest{AgentToken: "valid-token"}}})@@ -137,7 +137,7 @@ func TestGRPCTunnel_RequestResponseStreamingChunks(t *testing.T) {defer func() { _ = conn.Close() }()client := tunnelpb.NewTunnelServiceClient(conn)- stream, err := client.Connect(ctx)+ stream, err := client.Connect(testGRPCOutgoingContextInternal(ctx, "valid-token"))require.NoError(t, err)err = stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_Register{Register: &tunnelpb.RegisterRequest{AgentToken: "valid-token"}}})@@ -337,18 +337,12 @@ func TestGRPCTunnel_InvalidTokenRejected(t *testing.T) {defer func() { _ = conn.Close() }()client := tunnelpb.NewTunnelServiceClient(conn)- stream, err := client.Connect(ctx)+ stream, err := client.Connect(testGRPCOutgoingContextInternal(ctx, "invalid-token"))require.NoError(t, err)err = stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_Register{Register: &tunnelpb.RegisterRequest{AgentToken: "invalid-token"}}})require.NoError(t, err)- registerResp, err := stream.Recv()- require.NoError(t, err)- require.NotNil(t, registerResp.GetRegisterResponse())- assert.False(t, registerResp.GetRegisterResponse().GetAccepted())- assert.Equal(t, "invalid agent token", registerResp.GetRegisterResponse().GetError())-_, err = stream.Recv()require.Error(t, err)st, ok := status.FromError(err)@@ -387,7 +381,7 @@ func TestGRPCTunnel_FirstMessageMustBeRegister(t *testing.T) {defer func() { _ = conn.Close() }()client := tunnelpb.NewTunnelServiceClient(conn)- stream, err := client.Connect(ctx)+ stream, err := client.Connect(testGRPCOutgoingContextInternal(ctx, "valid-token"))require.NoError(t, err)err = stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_HeartbeatPing{HeartbeatPing: &tunnelpb.HeartbeatPing{}}})@@ -431,7 +425,7 @@ func TestGRPCTunnel_RegisterMessageRequiredOnEOF(t *testing.T) {defer func() { _ = conn.Close() }()client := tunnelpb.NewTunnelServiceClient(conn)- stream, err := client.Connect(ctx)+ stream, err := client.Connect(testGRPCOutgoingContextInternal(ctx, "valid-token"))require.NoError(t, err)require.NoError(t, stream.CloseSend())@@ -446,7 +440,6 @@ func TestGRPCTunnel_RegisterMessageRequiredOnEOF(t *testing.T) {func startTestGRPCTunnelServer(ctx context.Context, envID string) (*bufconn.Listener, *grpc.Server, *TunnelServer) {lis := bufconn.Listen(1024 * 1024)- grpcServer := grpc.NewServer()tunnelServer := NewTunnelServer(func(ctx context.Context, token string) (string, error) {if token != "valid-token" {@@ -456,7 +449,12 @@ func startTestGRPCTunnelServer(ctx context.Context, envID string) (*bufconn.List},nil,)+ grpcServer := grpc.NewServer(tunnelServer.GRPCServerOptions()...)go tunnelServer.StartCleanupLoop(ctx)tunnelpb.RegisterTunnelServiceServer(grpcServer, tunnelServer)return lis, grpcServer, tunnelServer}++func testGRPCOutgoingContextInternal(ctx context.Context, token string) context.Context {+ return metadata.NewOutgoingContext(ctx, metadata.Pairs(strings.ToLower(HeaderAgentToken), token))+}diff --git a/backend/pkg/libarcane/edge/client_transport_poll.go b/backend/pkg/libarcane/edge/client_transport_poll.goindex 730d909da..150508322 100644--- a/backend/pkg/libarcane/edge/client_transport_poll.go+++ b/backend/pkg/libarcane/edge/client_transport_poll.go@@ -17,11 +17,6 @@ const defaultTunnelPollRequestTimeout = 15 * time.Secondvar defaultPollManagedSessionStopTimeout = 5 * time.Second-type pollManagedTunnelSession struct {- cancel context.CancelFunc- done chan error-}-func (c *TunnelClient) connectAndServePoll(ctx context.Context) error {managerBaseURL := strings.TrimRight(strings.TrimSpace(c.cfg.GetManagerBaseURL()), "/")if managerBaseURL == "" {diff --git a/backend/pkg/libarcane/edge/command_client.go b/backend/pkg/libarcane/edge/command_client.goindex a21a720cb..f0abe9754 100644--- a/backend/pkg/libarcane/edge/command_client.go+++ b/backend/pkg/libarcane/edge/command_client.go@@ -5,29 +5,16 @@ import ("errors""fmt""net/http"+ "slices""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{}+const (+ tunnelCapabilityChunkedRequest = "chunked-request"+ bodyTransferMetadataKey = "body_transfer_id"+)func NewCommandClient() *CommandClient {return &CommandClient{}@@ -77,17 +64,40 @@ func (c *CommandClient) Execute(ctx context.Context, tunnel *AgentTunnel, req *CAgentInstance: tunnel.AgentInstance,}- respCh, err := registerPendingRequestInternal(tunnel, requestID)+ pending, err := registerPendingRequestInternal(tunnel, requestID)if err != nil {return nil, err}defer tunnel.Pending.Delete(requestID)+ chunkRequestBody := len(req.Body) > defaultCommandChunkSize && slices.Contains(tunnel.Capabilities, tunnelCapabilityChunkedRequest)+ if chunkRequestBody {+ transferID := uuid.NewString()+ msg.Body = nil+ msg.Metadata = map[string]string{bodyTransferMetadataKey: transferID}+ }+if err := tunnel.Conn.Send(msg); err != nil {return nil, fmt.Errorf("tunnel request failed: %w", err)}+ if chunkRequestBody {+ transferID := msg.Metadata[bodyTransferMetadataKey]+ for sequence, offset := int64(0), 0; offset < len(req.Body); sequence++ {+ end := min(offset+defaultCommandChunkSize, len(req.Body))+ if err := tunnel.Conn.Send(&TunnelMessage{+ ID: transferID,+ Type: MessageTypeFileChunk,+ Body: req.Body[offset:end],+ Sequence: sequence,+ EOF: end == len(req.Body),+ }); err != nil {+ return nil, fmt.Errorf("tunnel request body transfer failed: %w", err)+ }+ offset = end+ }+ }- status, headers, body, err := collectCommandResponseInternal(ctx, respCh, req.Method)+ status, headers, body, err := collectCommandResponseInternal(ctx, tunnel, pending, req.Method)if err != nil {return nil, err}diff --git a/backend/pkg/libarcane/edge/commands.go b/backend/pkg/libarcane/edge/commands.goindex e2c36a9a6..ae3fb7ead 100644--- a/backend/pkg/libarcane/edge/commands.go+++ b/backend/pkg/libarcane/edge/commands.go@@ -7,14 +7,6 @@ import ("strings")-type commandRoute struct {- Method string- PathPattern string- CommandName string- Stream bool- LocalOnly bool-}-var commandRoutes = []commandRoute{{Method: http.MethodGet, PathPattern: "/api/health", CommandName: "system.health"},{Method: http.MethodHead, PathPattern: "/api/health", CommandName: "system.health"},@@ -234,21 +226,6 @@ var commandRoutes = []commandRoute{{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) mo.Option[string] {diff --git a/backend/pkg/libarcane/edge/commands_test.go b/backend/pkg/libarcane/edge/commands_test.goindex aee67ea31..3bc6c7506 100644--- a/backend/pkg/libarcane/edge/commands_test.go+++ b/backend/pkg/libarcane/edge/commands_test.go@@ -67,12 +67,17 @@ func TestBuildCommandRouteIndexInternalPanicsOnDuplicateRoute(t *testing.T) {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")}+ tunnel := NewAgentTunnelWithConn("env-1", &fakeServerTunnelConn{})+ pending := &PendingRequest{+ ResponseCh: make(chan *TunnelMessage, 4),+ failureCh: make(chan error, 1),+ }+ pending.ResponseCh <- &TunnelMessage{ID: "cmd-1", Type: MessageTypeCommandAck}+ pending.ResponseCh <- &TunnelMessage{ID: "cmd-1", Type: MessageTypeCommandOutput, Body: []byte("hello ")}+ pending.ResponseCh <- &TunnelMessage{ID: "cmd-1", Type: MessageTypeCommandComplete, Status: 200, Headers: map[string]string{"Content-Type": "text/plain"}, Body: []byte("world")}+ require.NoError(t, tunnel.Close())- status, headers, body, err := collectCommandResponseInternal(context.Background(), respCh, "")+ status, headers, body, err := collectCommandResponseInternal(context.Background(), tunnel, pending, "")require.NoError(t, err)require.Equal(t, 200, status)require.Equal(t, "text/plain", headers["Content-Type"])diff --git a/backend/pkg/libarcane/edge/event_sync_test.go b/backend/pkg/libarcane/edge/event_sync_test.goindex 00c62a167..c571690d3 100644--- a/backend/pkg/libarcane/edge/event_sync_test.go+++ b/backend/pkg/libarcane/edge/event_sync_test.go@@ -1,7 +1,6 @@package edgeimport (- "context""errors""sync""testing"@@ -39,10 +38,6 @@ func (f *fakeEventTunnelConn) Close() error { f.closed = true; return nil }func (f *fakeEventTunnelConn) IsClosed() bool { return f.closed }-func (f *fakeEventTunnelConn) SendRequest(ctx context.Context, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error) {- return nil, errors.New("not implemented")-}-func TestPublishEventToManager_NoActiveTunnel(t *testing.T) {clearActiveAgentTunnelConn(getActiveAgentTunnelConn())diff --git a/backend/pkg/libarcane/edge/poll_control.go b/backend/pkg/libarcane/edge/poll_control.goindex 34eda3524..45e97bd8d 100644--- a/backend/pkg/libarcane/edge/poll_control.go+++ b/backend/pkg/libarcane/edge/poll_control.go@@ -9,7 +9,6 @@ import ("log/slog""net/http""strings"- "sync""time""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"@@ -34,39 +33,6 @@ const (TunnelStatusActive = "ACTIVE")-// TunnelPollRequest is a forward-compatible control-plane check-in request.-type TunnelPollRequest struct {- Transport string `json:"transport,omitempty"`- Connected bool `json:"connected,omitempty"`-}--// TunnelPollResponse is a forward-compatible control-plane response.-type TunnelPollResponse struct {- Status string `json:"status"`- PollIntervalSeconds int `json:"pollIntervalSeconds"`- ActiveTransport string `json:"activeTransport,omitempty"`- Connected bool `json:"connected,omitempty"`-}--// PollRuntimeState describes the most recent poll-based control-plane activity-// observed for an edge environment.-type PollRuntimeState struct {- LastPollAt *time.Time- PollIntervalSeconds int-}--// TunnelDemandRegistry tracks short-lived tunnel demand on the manager side.-type TunnelDemandRegistry struct {- demands map[string]time.Time- mu sync.RWMutex-}--// PollRuntimeRegistry tracks recent poll check-ins from edge agents.-type PollRuntimeRegistry struct {- states map[string]PollRuntimeState- mu sync.RWMutex-}-func pollRuntimeTTLInternal(state PollRuntimeState) time.Duration {ttl := DefaultPollRuntimeTTLif state.PollIntervalSeconds > 0 {diff --git a/backend/pkg/libarcane/edge/proto/buf.yaml b/backend/pkg/libarcane/edge/proto/buf.yamlindex aed963ea9..f04c52f44 100644--- a/backend/pkg/libarcane/edge/proto/buf.yaml+++ b/backend/pkg/libarcane/edge/proto/buf.yaml@@ -6,6 +6,11 @@ modules:lint:use:- STANDARD+ # Connect is a bidirectional transport envelope, so directional names are+ # clearer than unary-style ConnectRequest and ConnectResponse names.+ except:+ - RPC_REQUEST_STANDARD_NAME+ - RPC_RESPONSE_STANDARD_NAMEbreaking:use:diff --git a/backend/pkg/libarcane/edge/proxy.go b/backend/pkg/libarcane/edge/proxy.goindex c4726c694..b488c9c01 100644--- a/backend/pkg/libarcane/edge/proxy.go+++ b/backend/pkg/libarcane/edge/proxy.go@@ -46,71 +46,96 @@ func ProxyRequest(ctx context.Context, tunnel *AgentTunnel, method, path, queryreturn result.Status, result.Headers, result.Body, nil}-func registerPendingRequestInternal(tunnel *AgentTunnel, requestID string) (<-chan *TunnelMessage, error) {+func registerPendingRequestInternal(tunnel *AgentTunnel, requestID string) (*PendingRequest, error) {if requestID == "" {return nil, errors.New("request ID is required")}- respCh := make(chan *TunnelMessage, 256)- tunnel.Pending.Store(requestID, &PendingRequest{- ResponseCh: respCh,- CreatedAt: time.Now(),- })- return respCh, nil+ pending := &PendingRequest{+ ResponseCh: make(chan *TunnelMessage, 256),+ failureCh: make(chan error, 1),+ }+ tunnel.Pending.Store(requestID, pending)+ return pending, nil}-func collectCommandResponseInternal(ctx context.Context, respCh <-chan *TunnelMessage, method string) (int, map[string]string, []byte, error) {+func collectCommandResponseInternal(ctx context.Context, tunnel *AgentTunnel, pending *PendingRequest, method string) (int, map[string]string, []byte, error) {state := &grpcResponseState{}for {select {case <-ctx.Done():return 0, nil, nil, ctx.Err()- case incoming := <-respCh:- if incoming == nil {- continue+ case <-tunnel.done:+ if done, status, headers, body, err := state.drainTerminalResponseInternal(pending.ResponseCh, method); done {+ return status, headers, body, err}-- switch incoming.Type {- case MessageTypeResponse:- if done, status, headers, body := state.handleResponse(method, incoming); done {- return status, headers, body, nil- }- case MessageTypeCommandAck:- continue- case MessageTypeCommandOutput, MessageTypeStreamData, MessageTypeFileChunk:- state.handleStreamData(incoming)- case MessageTypeCommandComplete:- status, headers, body, err := state.handleCommandComplete(incoming)+ return 0, nil, nil, errors.New("edge tunnel closed while waiting for response")+ case err := <-pending.failureCh:+ if done, status, headers, body, err := state.drainTerminalResponseInternal(pending.ResponseCh, method); done {+ return status, headers, body, err+ }+ return 0, nil, nil, err+ case incoming, ok := <-pending.ResponseCh:+ if !ok {+ return 0, nil, nil, errors.New("edge tunnel response channel closed before a response was received")+ }+ if done, status, headers, body, err := state.handleTunnelMessageInternal(method, 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:- continue}}}}-type grpcResponseState struct {- status int- respHeaders map[string]string- respBody bytes.Buffer- gotResponse bool+func (s *grpcResponseState) handleTunnelMessageInternal(method string, incoming *TunnelMessage) (bool, int, map[string]string, []byte, error) {+ if incoming == nil {+ return false, 0, nil, nil, nil+ }++ switch incoming.Type {+ case MessageTypeResponse:+ done, status, headers, body := s.handleResponse(method, incoming)+ return done, status, headers, body, nil+ case MessageTypeCommandOutput, MessageTypeStreamData, MessageTypeFileChunk:+ s.handleStreamData(incoming)+ case MessageTypeCommandComplete:+ status, headers, body, err := s.handleCommandComplete(incoming)+ return true, status, headers, body, err+ case MessageTypeStreamEnd:+ done, status, headers, body := s.handleStreamEnd()+ return done, status, headers, body, nil+ case MessageTypeRequest,+ MessageTypeHeartbeat,+ MessageTypeHeartbeatAck,+ MessageTypeWebSocketStart,+ MessageTypeWebSocketData,+ MessageTypeWebSocketClose,+ MessageTypeRegister,+ MessageTypeRegisterResponse,+ MessageTypeEvent,+ MessageTypeCommandRequest,+ MessageTypeCommandAck,+ MessageTypeStreamOpen,+ MessageTypeStreamClose,+ MessageTypeCancelRequest:+ }+ return false, 0, nil, nil, nil+}++func (s *grpcResponseState) drainTerminalResponseInternal(respCh <-chan *TunnelMessage, method string) (bool, int, map[string]string, []byte, error) {+ for {+ select {+ case incoming, ok := <-respCh:+ if !ok {+ return true, 0, nil, nil, errors.New("edge tunnel response channel closed before a response was received")+ }+ if done, status, headers, body, err := s.handleTunnelMessageInternal(method, incoming); done {+ return true, status, headers, body, err+ }+ default:+ return false, 0, nil, nil, nil+ }+ }}func (s *grpcResponseState) handleResponse(method string, incoming *TunnelMessage) (bool, int, map[string]string, []byte) {@@ -327,6 +352,15 @@ func RequestTunnelAndWait(ctx context.Context, envID string, demandTTL, timeout// This is for service-level calls that need to route through the tunnel.// Returns (statusCode, responseBody, error)func DoRequest(ctx context.Context, envID, method, path string, body []byte) (int, []byte, error) {+ if ctx == nil {+ return 0, nil, errors.New("context is required")+ }+ if _, hasDeadline := ctx.Deadline(); !hasDeadline {+ var cancel context.CancelFunc+ ctx, cancel = context.WithTimeout(ctx, DefaultProxyTimeout)+ defer cancel()+ }+tunnel, ok := GetRegistry().Get(envID).Get()if !ok {return 0, nil, fmt.Errorf("no active tunnel for environment %s", envID)diff --git a/backend/pkg/libarcane/edge/proxy_test.go b/backend/pkg/libarcane/edge/proxy_test.goindex a5c42f37b..bfc0958e2 100644--- a/backend/pkg/libarcane/edge/proxy_test.go+++ b/backend/pkg/libarcane/edge/proxy_test.go@@ -153,7 +153,7 @@ func TestProxyHTTPRequest_GRPCTunnel(t *testing.T) {defer func() { _ = conn.Close() }()client := tunnelpb.NewTunnelServiceClient(conn)- stream, err := client.Connect(ctx)+ stream, err := client.Connect(testGRPCOutgoingContextInternal(ctx, "valid-token"))require.NoError(t, err)err = stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_Register{Register: &tunnelpb.RegisterRequest{AgentToken: "valid-token"}}})@@ -272,6 +272,36 @@ func TestDoRequest_NoTunnel(t *testing.T) {assert.Contains(t, err.Error(), "no active tunnel")}+func TestCommandRequestFailsWhenTunnelCloses(t *testing.T) {+ tunnel := NewAgentTunnelWithConn("env-closing", &fakeTunnelConn{})+ errCh := make(chan error, 1)++ go func() {+ _, err := DefaultCommandClient.Execute(context.Background(), tunnel, &CommandRequest{+ Method: http.MethodGet,+ Path: "/api/health",+ })+ errCh <- err+ }()++ require.Eventually(t, func() bool {+ found := false+ tunnel.Pending.Range(func(_, _ any) bool {+ found = true+ return false+ })+ return found+ }, time.Second, 10*time.Millisecond)++ require.NoError(t, tunnel.CloseWithReason("test disconnect"))+ select {+ case err := <-errCh:+ require.ErrorContains(t, err, "edge tunnel closed while waiting for response")+ case <-time.After(time.Second):+ t.Fatal("pending command did not fail after tunnel close")+ }+}+func TestHasActiveTunnel(t *testing.T) {conn := createTestConn(t)defer func() { _ = conn.Close() }()diff --git a/backend/pkg/libarcane/edge/registry.go b/backend/pkg/libarcane/edge/registry.goindex 16c8d28eb..0c9f36f05 100644--- a/backend/pkg/libarcane/edge/registry.go+++ b/backend/pkg/libarcane/edge/registry.go@@ -8,23 +8,6 @@ import ("time")-// AgentTunnel represents an active tunnel connection from an edge agent-type AgentTunnel struct {- EnvironmentID string- Conn TunnelConnection- 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-}-// NewAgentTunnelWithConn creates a new agent tunnel from a transport-agnostic connection.func NewAgentTunnelWithConn(envID string, conn TunnelConnection) *AgentTunnel {now := time.Now()@@ -34,6 +17,7 @@ func NewAgentTunnelWithConn(envID string, conn TunnelConnection) *AgentTunnel {ConnectedAt: now,LastHeartbeat: now,State: "connected",+ done: make(chan struct{}),}}@@ -58,21 +42,26 @@ func (t *AgentTunnel) Close() error {// CloseWithReason closes the tunnel connection and records the disconnect reason.func (t *AgentTunnel) CloseWithReason(reason string) error {+ if t == nil {+ return nil+ }t.mu.Lock()t.State = "closed"if reason != "" {t.DisconnectErr = reason}t.mu.Unlock()+ t.closeOnce.Do(func() {+ if t.done != nil {+ close(t.done)+ }+ })+ if t.Conn == nil {+ return nil+ }return t.Conn.Close()}-// TunnelRegistry manages active edge agent tunnel connections-type TunnelRegistry struct {- tunnels map[string]*AgentTunnel // environmentID -> tunnel- mu sync.RWMutex-}-// NewTunnelRegistry creates a new tunnel registryfunc NewTunnelRegistry() *TunnelRegistry {return &TunnelRegistry{@@ -165,7 +154,7 @@ func (r *TunnelRegistry) UnregisterCurrent(envID string, current *AgentTunnel) (existing, ok := r.tunnels[envID]if !ok || existing != current {- if ok && existing != nil && !existing.Conn.IsClosed() {+ if ok && existing != nil && existing.Conn != nil && !existing.Conn.IsClosed() {return false, true}return false, false@@ -177,20 +166,20 @@ func (r *TunnelRegistry) UnregisterCurrent(envID string, current *AgentTunnel) (return true, false}-// CleanupStale removes tunnels that haven't had a heartbeat within the given duration-func (r *TunnelRegistry) CleanupStale(maxAge time.Duration) int {+// CleanupStale removes tunnels that haven't had a heartbeat within the given duration.+func (r *TunnelRegistry) CleanupStale(maxAge time.Duration) []*AgentTunnel {r.mu.Lock()defer r.mu.Unlock()now := time.Now()- removed := 0+ removed := make([]*AgentTunnel, 0)for envID, tunnel := range r.tunnels {if now.Sub(tunnel.GetLastHeartbeat()) > maxAge {slog.Warn("Removing stale edge tunnel", "last_heartbeat", tunnel.GetLastHeartbeat())- _ = tunnel.Close()+ _ = tunnel.CloseWithReason("edge tunnel heartbeat expired")delete(r.tunnels, envID)- removed+++ removed = append(removed, tunnel)}}diff --git a/backend/pkg/libarcane/edge/registry_test.go b/backend/pkg/libarcane/edge/registry_test.goindex ca55cb39f..77073b8fc 100644--- a/backend/pkg/libarcane/edge/registry_test.go+++ b/backend/pkg/libarcane/edge/registry_test.go@@ -159,7 +159,8 @@ func TestTunnelRegistry_CleanupStale(t *testing.T) {// Cleanupremoved := r.CleanupStale(5 * time.Minute)- assert.Equal(t, 1, removed)+ require.Len(t, removed, 1)+ assert.Same(t, tunnel, removed[0])_, ok := r.Get(envID).Get()assert.False(t, ok)diff --git a/backend/pkg/libarcane/edge/remenv_test.go b/backend/pkg/libarcane/edge/remenv_test.goindex 40e4b8d54..1b9868031 100644--- a/backend/pkg/libarcane/edge/remenv_test.go+++ b/backend/pkg/libarcane/edge/remenv_test.go@@ -376,7 +376,7 @@ func TestRemenvClient_EdgeWithGRPCTunnel(t *testing.T) {defer func() { _ = conn.Close() }()clientAPI := tunnelpb.NewTunnelServiceClient(conn)- stream, err := clientAPI.Connect(ctx)+ stream, err := clientAPI.Connect(testGRPCOutgoingContextInternal(ctx, "valid-token"))require.NoError(t, err)err = stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_Register{Register: &tunnelpb.RegisterRequest{AgentToken: "valid-token"}}})diff --git a/backend/pkg/libarcane/edge/request_context.go b/backend/pkg/libarcane/edge/request_context.goindex c2e0dfdfb..384a65073 100644--- a/backend/pkg/libarcane/edge/request_context.go+++ b/backend/pkg/libarcane/edge/request_context.go@@ -2,8 +2,6 @@ package edgeimport "context"-type internalTunnelRequestContextKey struct{}-// IsInternalTunnelRequest reports whether a request is being dispatched by the// in-process edge tunnel client instead of a real network listener.func IsInternalTunnelRequest(ctx context.Context) bool {diff --git a/backend/pkg/libarcane/edge/server.go b/backend/pkg/libarcane/edge/server.goindex a09d8cf21..533ef66c1 100644--- a/backend/pkg/libarcane/edge/server.go+++ b/backend/pkg/libarcane/edge/server.go@@ -4,6 +4,7 @@ import ("context""crypto/tls""errors"+ "fmt""io""log/slog""net/http"@@ -60,18 +61,6 @@ type EventCallback func(ctx context.Context, environmentID string, event *Tunnel// 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- nameResolver EnvironmentNameResolver- statusCallback StatusUpdateCallback- eventCallback EventCallback- enrollmentCallback EnrollmentCallback- cleanupDone chan struct{}- cfg *Config-}-// NewTunnelServer creates a new tunnel server.func NewTunnelServer(resolver EnvironmentResolver, statusCallback StatusUpdateCallback) *TunnelServer {return NewTunnelServerWithRegistry(GetRegistry(), resolver, statusCallback)@@ -99,16 +88,17 @@ func (s *TunnelServer) SetEnvironmentNameResolver(resolver EnvironmentNameResolvs.nameResolver = resolver}-type resolvedEnvironmentIDKey struct{}--// GRPCServerOptions returns the stream interceptor chain used by the tunnel service.-func (s *TunnelServer) GRPCServerOptions(ctx context.Context) []grpc.ServerOption {- _ = ctx+// GRPCServerOptions returns the receive guardrail and stream interceptor chain+// used by the tunnel service. Arcane serves this server through ServeHTTP, so+// transport-level server keepalive and MaxConcurrentStreams options would be+// inert here; those belong on net/http unless the server moves to grpc.Serve.+func (s *TunnelServer) GRPCServerOptions() []grpc.ServerOption {return []grpc.ServerOption{+ grpc.MaxRecvMsgSize(maxGRPCTunnelMessageSize),grpc.ChainStreamInterceptor(- s.recoveryStreamInterceptorInternal(ctx),- s.loggingStreamInterceptorInternal(ctx),- s.authStreamInterceptorInternal(ctx),+ s.recoveryStreamInterceptorInternal(),+ s.loggingStreamInterceptorInternal(),+ s.authStreamInterceptorInternal(),),}}@@ -293,21 +283,7 @@ func (s *TunnelServer) Connect(stream grpc.BidiStreamingServer[tunnelpb.AgentMesenvID, ok := resolvedEnvironmentIDFromContextInternal(ctx).Get()if !ok || envID == "" {- token := strings.TrimSpace(register.GetAgentToken())- if token == "" {- token = tokenFromMetadataInternal(ctx)- }-- var resolveErr error- envID, resolveErr = s.resolveEnvironment(ctx, token)- if resolveErr != nil {- slog.WarnContext(ctx, "Failed to resolve gRPC agent token", "error", resolveErr)- _ = stream.Send(&tunnelpb.ManagerMessage{Payload: &tunnelpb.ManagerMessage_RegisterResponse{RegisterResponse: &tunnelpb.RegisterResponse{- Accepted: false,- Error: "invalid agent token",- }}})- return status.Error(codes.Unauthenticated, "invalid agent token")- }+ return status.Error(codes.Unauthenticated, "authenticated environment is missing from stream context")}if err := s.requireCertificateIdentityFromContextInternal(ctx, envID); err != nil {return status.Error(codes.Unauthenticated, err.Error())@@ -441,13 +417,14 @@ func (s *TunnelServer) manageConnectedTunnel(ctx context.Context, callbackCtx co}); err != nil {slog.WarnContext(ctx, "Failed to send register response", "environment_id", tunnel.EnvironmentID, "error", err)_ = tunnel.Close()- _, _ = s.registry.UnregisterCurrent(tunnel.EnvironmentID, tunnel)+ removed, active := s.registry.UnregisterCurrent(tunnel.EnvironmentID, tunnel)+ if removed && !active {+ s.updateConnectionStatusInternal(callbackCtx, tunnel, false)+ }return}- if s.statusCallback != nil {- s.statusCallback(callbackCtx, tunnel.EnvironmentID, true)- }+ s.updateConnectionStatusInternal(callbackCtx, tunnel, true)defer func() {removed, active := s.registry.UnregisterCurrent(tunnel.EnvironmentID, tunnel)@@ -455,8 +432,8 @@ func (s *TunnelServer) manageConnectedTunnel(ctx context.Context, callbackCtx coreturn}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)+ if !active {+ s.updateConnectionStatusInternal(callbackCtx, tunnel, false)}}()@@ -524,7 +501,10 @@ func (s *TunnelServer) deliverResponse(ctx context.Context, tunnel *AgentTunnel,select {case pending.ResponseCh <- msg:default:- slog.WarnContext(ctx, "Response channel full, dropping response", "id", msg.ID)+ err := fmt.Errorf("response delivery failed because pending request %s is not consuming messages", msg.ID)+ tunnel.Pending.Delete(msg.ID)+ pending.failureCh <- err+ slog.WarnContext(ctx, "Failed pending request with full response channel", "id", msg.ID)}return}@@ -542,13 +522,21 @@ func (s *TunnelServer) deliverStream(ctx context.Context, tunnel *AgentTunnel, mcase <-ctx.Done():returncase <-time.After(streamDeliveryTimeout):- slog.WarnContext(ctx, "Timed out delivering stream message to pending consumer",+ err := fmt.Errorf("stream delivery timed out for pending request %s", msg.ID)+ tunnel.Pending.Delete(msg.ID)+ pending.failureCh <- err+ slog.WarnContext(ctx, "Failed slow pending stream consumer","id", msg.ID,"type", msg.Type,"timeout", streamDeliveryTimeout,)+ if sendErr := tunnel.Conn.Send(&TunnelMessage{ID: msg.ID, Type: MessageTypeStreamClose, Error: err.Error()}); sendErr != nil {+ slog.DebugContext(ctx, "Failed to close slow edge stream", "id", msg.ID, "error", sendErr)+ }}+ return}+ slog.DebugContext(ctx, "Received stream message for unknown request", "id", msg.ID, "type", msg.Type)}func (s *TunnelServer) handleEvent(ctx context.Context, tunnel *AgentTunnel, msg *TunnelMessage) {@@ -581,24 +569,40 @@ func (s *TunnelServer) StartCleanupLoop(ctx context.Context) {case <-ctx.Done():returncase <-ticker.C:- count := s.registry.CleanupStale(TunnelStaleTimeout)- if count > 0 {- slog.InfoContext(ctx, "Cleaned up stale tunnels", "count", count)+ removed := s.registry.CleanupStale(TunnelStaleTimeout)+ for _, tunnel := range removed {+ s.updateConnectionStatusInternal(context.WithoutCancel(ctx), tunnel, false)+ }+ if len(removed) > 0 {+ slog.InfoContext(ctx, "Cleaned up stale tunnels", "count", len(removed))}}}}+func (s *TunnelServer) updateConnectionStatusInternal(ctx context.Context, tunnel *AgentTunnel, connected bool) {+ if s == nil || s.statusCallback == nil || tunnel == nil {+ return+ }++ s.statusMu.Lock()+ defer s.statusMu.Unlock()+ if !connected {+ if active, ok := s.registry.Get(tunnel.EnvironmentID).Get(); ok && active != tunnel && active.Conn != nil && !active.Conn.IsClosed() {+ return+ }+ }+ s.statusCallback(ctx, tunnel.EnvironmentID, connected)+}+// WaitForCleanupDone blocks until the cleanup loop has stopped.func (s *TunnelServer) WaitForCleanupDone() {<-s.cleanupDone}-func (s *TunnelServer) authStreamInterceptorInternal(ctx context.Context) grpc.StreamServerInterceptor {- _ = ctx+func (s *TunnelServer) authStreamInterceptorInternal() grpc.StreamServerInterceptor {// 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)@@ -618,8 +622,7 @@ func (s *TunnelServer) authStreamInterceptorInternal(ctx context.Context) grpc.S}}-func (s *TunnelServer) loggingStreamInterceptorInternal(ctx context.Context) grpc.StreamServerInterceptor {- _ = ctx+func (s *TunnelServer) loggingStreamInterceptorInternal() grpc.StreamServerInterceptor {return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {start := time.Now()err := handler(srv, ss)@@ -639,8 +642,7 @@ func (s *TunnelServer) loggingStreamInterceptorInternal(ctx context.Context) grp}}-func (s *TunnelServer) recoveryStreamInterceptorInternal(ctx context.Context) grpc.StreamServerInterceptor {- _ = ctx+func (s *TunnelServer) recoveryStreamInterceptorInternal() grpc.StreamServerInterceptor {return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {defer func() {if recovered := recover(); recovered != nil {@@ -657,12 +659,6 @@ func (s *TunnelServer) recoveryStreamInterceptorInternal(ctx context.Context) gr}}-type contextualServerStream struct {- grpc.ServerStream-- ctx context.Context-}-func (s *contextualServerStream) Context() context.Context {return s.ctx}@@ -688,7 +684,13 @@ func (s *TunnelServer) requireCertificateIdentityInternal(state *tls.ConnectionS}func (s *TunnelServer) requireRequestCertificateIdentityInternal(req *http.Request, envID string) error {- if req == nil || req.TLS == nil || !hasVerifiedPeerCertificateInternal(req.TLS) {+ if req == nil || req.TLS == nil {+ return nil+ }+ if !hasVerifiedPeerCertificateInternal(req.TLS) {+ if NormalizeEdgeMTLSMode(s.edgeMTLSModeInternal()) == EdgeMTLSModeRequired {+ return errors.New("verified edge mTLS client certificate is required")+ }return nil}return s.requireCertificateIdentityInternal(req.TLS, envID)@@ -706,6 +708,12 @@ func (s *TunnelServer) requireCertificateIdentityFromContextInternal(ctx contextif !ok {return nil}+ if !hasVerifiedPeerCertificateInternal(&tlsInfo.State) {+ if NormalizeEdgeMTLSMode(s.edgeMTLSModeInternal()) == EdgeMTLSModeRequired {+ return errors.New("verified edge mTLS client certificate is required")+ }+ return nil+ }return verifiedPeerCertificateEnvironmentIDMatchesInternal(&tlsInfo.State, envID, edgeMTLSTrustDomainInternal(s.cfg))}diff --git a/backend/pkg/libarcane/edge/server_test.go b/backend/pkg/libarcane/edge/server_test.goindex 2053c2417..5e00a3fb2 100644--- a/backend/pkg/libarcane/edge/server_test.go+++ b/backend/pkg/libarcane/edge/server_test.go@@ -11,7 +11,6 @@ import ("net/http/httptest""os""strings"- "sync""testing""time"@@ -602,10 +601,6 @@ func (f *fakeServerTunnelConn) Close() error { return nil }func (f *fakeServerTunnelConn) IsClosed() bool { return false }-func (f *fakeServerTunnelConn) SendRequest(ctx context.Context, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error) {- return nil, errors.New("not implemented")-}-type registerResponseOrderConn struct {sendHook func(*TunnelMessage) errorrecvErr error@@ -631,10 +626,6 @@ func (f *registerResponseOrderConn) Close() error { return nil }func (f *registerResponseOrderConn) IsClosed() bool { return false }-func (f *registerResponseOrderConn) SendRequest(ctx context.Context, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error) {- return nil, errors.New("not implemented")-}-func TestTunnelServer_ManageConnectedTunnel_RegistersBeforeSendingGRPCRegisterResponse(t *testing.T) {server := NewTunnelServer(nil, nil)envID := "env-grpc-register-order"diff --git a/backend/pkg/libarcane/edge/tls.go b/backend/pkg/libarcane/edge/tls.goindex 8f842992f..ed5554ef4 100644--- a/backend/pkg/libarcane/edge/tls.go+++ b/backend/pkg/libarcane/edge/tls.go@@ -55,27 +55,6 @@ 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) {@@ -1154,11 +1133,6 @@ func removeStaleEdgeMTLSLockInternal(lockPath string) bool {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 {diff --git a/backend/pkg/libarcane/edge/tls_test.go b/backend/pkg/libarcane/edge/tls_test.goindex d8e7bc162..eca73ff2a 100644--- a/backend/pkg/libarcane/edge/tls_test.go+++ b/backend/pkg/libarcane/edge/tls_test.go@@ -330,6 +330,18 @@ func TestTunnelServerRequiredMTLS_AllowsHTTPRequestsWithoutVisibleTLSState(t *terequire.NoError(t, server.requireRequestCertificateIdentityInternal(req, "env-a"))}+func TestTunnelServerRequiredMTLS_RejectsDirectTLSWithoutVerifiedClientCertificate(t *testing.T) {+ server := NewTunnelServer(nil, nil)+ server.SetConfig(&Config{EdgeMTLSMode: EdgeMTLSModeRequired})++ req := httptest.NewRequest(http.MethodGet, "https://manager.example.com/api/tunnel/connect", nil)+ req.TLS = &tls.ConnectionState{}+ require.ErrorContains(t, server.requireRequestCertificateIdentityInternal(req, "env-a"), "verified edge mTLS client certificate is required")++ server.SetConfig(&Config{EdgeMTLSMode: EdgeMTLSModeOptional})+ require.NoError(t, server.requireRequestCertificateIdentityInternal(req, "env-a"))+}+func TestTunnelServerRequiredMTLS_DetectsOnlyDirectTLSForRequestSecurityMode(t *testing.T) {server := NewTunnelServer(nil, nil)server.SetConfig(&Config{@@ -387,6 +399,11 @@ func TestTunnelServerRequiredMTLS_AllowsGRPCContextsWithoutVisibleTLSState(t *terequire.NoError(t, server.requireCertificateIdentityFromContextInternal(ctx, "env-a"))})+ t.Run("direct tls without verified client certificate", func(t *testing.T) {+ ctx := peer.NewContext(context.Background(), &peer.Peer{AuthInfo: credentials.TLSInfo{}})+ require.ErrorContains(t, server.requireCertificateIdentityFromContextInternal(ctx, "env-a"), "verified edge mTLS client certificate is required")+ })+t.Run("verified tls peer checks identity", func(t *testing.T) {uriSAN, err := url.Parse("spiffe://manager.example.com/edge/env-a")require.NoError(t, err)diff --git a/backend/pkg/libarcane/edge/transport.go b/backend/pkg/libarcane/edge/transport.goindex adda5ed75..3dd57c80a 100644--- a/backend/pkg/libarcane/edge/transport.go+++ b/backend/pkg/libarcane/edge/transport.go@@ -5,27 +5,8 @@ import ("net/url""strings"- "time")-// Config contains the public edge-tunnel runtime settings needed by pkg/libarcane/edge.-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- Listen string-}-// GetManagerBaseURL returns the base URL of the manager application.// It strips any trailing slashes or /api suffix from MANAGER_API_URL.func (c *Config) GetManagerBaseURL() string {@@ -66,18 +47,6 @@ func (c *Config) GetManagerGRPCAddr() string {return host + ":" + port}-// TunnelRuntimeState describes the live, in-memory state of an active edge tunnel.-type TunnelRuntimeState struct {- Transport string- ConnectedAt *time.Time- LastHeartbeat *time.Time- SessionID string- AgentInstance string- SecurityMode string- Capabilities []string- State string-}-const (// EdgeTransportAuto prefers gRPC and falls back to WebSocket automatically.EdgeTransportAuto = "auto"diff --git a/backend/pkg/libarcane/edge/transport_test.go b/backend/pkg/libarcane/edge/transport_test.goindex f9c04ef2b..18978146c 100644--- a/backend/pkg/libarcane/edge/transport_test.go+++ b/backend/pkg/libarcane/edge/transport_test.go@@ -9,7 +9,6 @@ import ("net/http""net/http/httptest""strings"- "sync""testing""time"@@ -186,10 +185,6 @@ func (u *unknownTunnelConn) Close() error { return nil }func (u *unknownTunnelConn) IsClosed() bool { return false }-func (u *unknownTunnelConn) SendRequest(ctx context.Context, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error) {- return nil, nil-}-func BenchmarkEdgeTunnelProxyRequest(b *testing.B) {previousLogger := slog.Default()slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, nil)))@@ -265,7 +260,7 @@ func setupGRPCBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel, func}client := tunnelpb.NewTunnelServiceClient(conn)- stream, err := client.Connect(ctx)+ stream, err := client.Connect(testGRPCOutgoingContextInternal(ctx, "valid-token"))if err != nil {_ = conn.Close()cancel()diff --git a/backend/pkg/libarcane/edge/tunnel.go b/backend/pkg/libarcane/edge/tunnel.goindex ff60b891d..978a9ea99 100644--- a/backend/pkg/libarcane/edge/tunnel.go+++ b/backend/pkg/libarcane/edge/tunnel.go@@ -5,9 +5,6 @@ import (json "encoding/json/v2""errors""io"- "sync"- "sync/atomic"- "time"tunnelpb "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge/proto/tunnel/v1""github.com/gorilla/websocket"@@ -18,6 +15,8 @@ import (// TunnelMessageType represents the type of message sent over the tunnel.type TunnelMessageType string+const maxGRPCTunnelMessageSize = 16 * 1024 * 1024+const (// MessageTypeRequest is sent from manager to agent to initiate a request.MessageTypeRequest TunnelMessageType = "request"@@ -61,56 +60,6 @@ const (MessageTypeCancelRequest TunnelMessageType = "cancel_request")-// TunnelMessage represents a transport-agnostic edge tunnel message.-type TunnelMessage struct {- Headers map[string]string `json:"headers,omitempty"` // HTTP headers- Event *TunnelEvent `json:"event,omitempty"` // Agent event payload- Metadata map[string]string `json:"metadata,omitempty"` // Correlation and audit metadata- ID string `json:"id"` // Unique request/stream ID- Type TunnelMessageType `json:"type"` // Message type- Method string `json:"method,omitempty"` // HTTP method for requests- Path string `json:"path,omitempty"` // Request path- Query string `json:"query,omitempty"` // Query string- AgentToken string `json:"agent_token,omitempty"` // Register request token- EnvironmentID string `json:"environment_id,omitempty"` // Manager-resolved environment ID- Error string `json:"error,omitempty"` // Error field for register response- 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- SecurityMode string `json:"security_mode,omitempty"` // token, mtls, etc.- Body []byte `json:"body,omitempty"` // Request/response body- Capabilities []string `json:"capabilities,omitempty"` // Agent advertised capabilities- WSMessageType int `json:"ws_message_type,omitempty"` // WebSocket message type- Status int `json:"status,omitempty"` // HTTP status for responses- TimeoutMillis int64 `json:"timeout_millis,omitempty"` // Command timeout- Sequence int64 `json:"sequence,omitempty"` // Chunk sequence number- Accepted bool `json:"accepted,omitempty"` // Registration accepted- DrainPrevious bool `json:"drain_previous,omitempty"` // Replace previous session- Streaming bool `json:"streaming,omitempty"` // Response used chunked output- EOF bool `json:"eof,omitempty"` // Final chunk indicator-}--// TunnelEvent is an event payload sent from an agent to the manager.-type TunnelEvent struct {- Type string `json:"type"`- Severity string `json:"severity,omitempty"`- Title string `json:"title"`- Description string `json:"description,omitempty"`- ResourceType string `json:"resource_type,omitempty"`- ResourceID string `json:"resource_id,omitempty"`- ResourceName string `json:"resource_name,omitempty"`- UserID string `json:"user_id,omitempty"`- Username string `json:"username,omitempty"`- MetadataJSON []byte `json:"metadata_json,omitempty"`-}--// PendingRequest tracks an in-flight request waiting for response.-type PendingRequest struct {- ResponseCh chan *TunnelMessage- CreatedAt time.Time-}-// TunnelConnection is the transport contract shared by WebSocket and gRPC wrappers.type TunnelConnection interface {Send(msg *TunnelMessage) error@@ -118,16 +67,6 @@ type TunnelConnection interface {IsExpectedReceiveError(err error) boolClose() errorIsClosed() bool- SendRequest(ctx context.Context, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error)-}--const defaultSendRequestTimeout = 5 * time.Minute--// TunnelConn wraps a WebSocket connection with send/receive helpers.-type TunnelConn struct {- conn *websocket.Conn- mu sync.Mutex- closed atomic.Bool}// NewTunnelConn creates a new WebSocket tunnel connection wrapper.@@ -196,11 +135,6 @@ func (t *TunnelConn) IsClosed() bool {return t.closed.Load()}-// SendRequest sends a request and waits for response.-func (t *TunnelConn) SendRequest(ctx context.Context, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error) {- return sendRequestWithPending(ctx, t, msg, pending)-}-type grpcManagerStream interface {Send(msg *tunnelpb.ManagerMessage) errorRecv() (*tunnelpb.AgentMessage, error)@@ -214,14 +148,6 @@ type grpcAgentStream interface {CloseSend() error}-// GRPCManagerTunnelConn wraps the manager-side gRPC tunnel stream.-type GRPCManagerTunnelConn struct {- stream grpcManagerStream- cancel context.CancelFunc- mu sync.Mutex- closed atomic.Bool-}-// NewGRPCManagerTunnelConn creates a manager-side gRPC tunnel wrapper.func NewGRPCManagerTunnelConn(stream grpcManagerStream) *GRPCManagerTunnelConn {if stream == nil {@@ -295,23 +221,10 @@ func (t *GRPCManagerTunnelConn) IsClosed() bool {return t.closed.Load()}-// SendRequest sends a request and waits for response.-func (t *GRPCManagerTunnelConn) SendRequest(ctx context.Context, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error) {- return sendRequestWithPending(ctx, t, msg, pending)-}-func (t *GRPCManagerTunnelConn) markClosed() {t.closed.Store(true)}-// GRPCAgentTunnelConn wraps the agent-side gRPC tunnel stream.-type GRPCAgentTunnelConn struct {- stream grpcAgentStream- cancel context.CancelFunc- mu sync.Mutex- closed atomic.Bool-}-// NewGRPCAgentTunnelConn creates an agent-side gRPC tunnel wrapper.func NewGRPCAgentTunnelConn(stream grpcAgentStream, cancelFns ...context.CancelFunc) *GRPCAgentTunnelConn {var cancel context.CancelFunc@@ -382,45 +295,10 @@ func (t *GRPCAgentTunnelConn) IsClosed() bool {return t.closed.Load()}-// SendRequest sends a request and waits for response.-func (t *GRPCAgentTunnelConn) SendRequest(ctx context.Context, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error) {- return sendRequestWithPending(ctx, t, msg, pending)-}-func (t *GRPCAgentTunnelConn) markClosed() {t.closed.Store(true)}-func sendRequestWithPending(ctx context.Context, conn interface {- Send(msg *TunnelMessage) error-}, msg *TunnelMessage, pending *sync.Map) (*TunnelMessage, error) {- ctx, cancel := ensureSendRequestContextInternal(ctx)- defer cancel()-- respCh := make(chan *TunnelMessage, 1)- pending.Store(msg.ID, &PendingRequest{- ResponseCh: respCh,- CreatedAt: time.Now(),- })- defer pending.Delete(msg.ID)-- if err := conn.Send(msg); err != nil {- return nil, err- }-- select {- case <-ctx.Done():- return nil, ctx.Err()- case resp := <-respCh:- return resp, nil- }-}--type cancelableGRPCManagerStream struct {- stream grpcManagerStream- ctx context.Context-}-func (s *cancelableGRPCManagerStream) Send(msg *tunnelpb.ManagerMessage) error {return s.stream.Send(msg)}@@ -449,18 +327,6 @@ func (s *cancelableGRPCManagerStream) Context() context.Context {return s.ctx}-func ensureSendRequestContextInternal(ctx context.Context) (context.Context, context.CancelFunc) {- if ctx == nil {- return context.WithTimeout(context.Background(), defaultSendRequestTimeout)- }-- if _, hasDeadline := ctx.Deadline(); hasDeadline {- return ctx, func() {}- }-- return context.WithTimeout(ctx, defaultSendRequestTimeout)-}-func isExpectedGRPCReceiveErrorInternal(err error) bool {if err == nil {return falsediff --git a/backend/pkg/libarcane/edge/tunnel_test.go b/backend/pkg/libarcane/edge/tunnel_test.goindex 071f3379c..3a5019217 100644--- a/backend/pkg/libarcane/edge/tunnel_test.go+++ b/backend/pkg/libarcane/edge/tunnel_test.go@@ -6,7 +6,6 @@ import ("net/http""net/http/httptest""strings"- "sync""testing""time"@@ -100,79 +99,6 @@ func TestTunnelConn(t *testing.T) {assert.Equal(t, websocket.ErrCloseSent, err)}-func TestTunnelConn_SendRequest(t *testing.T) {- // Start a test server that responds to requests- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- upgrader := websocket.Upgrader{}- conn, err := upgrader.Upgrade(w, r, nil)- if err != nil {- return- }- defer func() { _ = conn.Close() }()-- for {- _, message, err := conn.ReadMessage()- if err != nil {- break- }-- var msg TunnelMessage- _ = json.Unmarshal(message, &msg)-- // Respond- resp := &TunnelMessage{- ID: msg.ID,- Type: MessageTypeResponse,- Body: []byte("response"),- }- data, _ := json.Marshal(resp)- _ = conn.WriteMessage(websocket.TextMessage, data)- }- }))- defer server.Close()-- // Connect- url := "ws" + strings.TrimPrefix(server.URL, "http")- conn, dialResp, err := websocket.DefaultDialer.Dial(url, nil)- require.NoError(t, err)- if dialResp != nil {- defer func() { _ = dialResp.Body.Close() }()- }-- tunnelConn := NewTunnelConn(conn)- defer func() { _ = tunnelConn.Close() }()-- // Setup background receiver- pending := &sync.Map{}- go func() {- for {- msg, err := tunnelConn.Receive()- if err != nil {- return- }- if req, ok := pending.Load(msg.ID); ok {- pendingReq := req.(*PendingRequest)- pendingReq.ResponseCh <- msg- }- }- }()-- // Test SendRequest- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)- defer cancel()-- req := &TunnelMessage{- ID: "req-1",- Type: MessageTypeRequest,- }-- resp, err := tunnelConn.SendRequest(ctx, req, pending)- require.NoError(t, err)- assert.Equal(t, "req-1", resp.ID)- assert.Equal(t, MessageTypeResponse, resp.Type)- assert.Equal(t, []byte("response"), resp.Body)-}-func TestGRPCManagerTunnelConn_CloseCancelsReceive(t *testing.T) {baseCtx := t.Context()diff --git a/backend/pkg/libarcane/edge/types.go b/backend/pkg/libarcane/edge/types.gonew file mode 100644index 000000000..5ce1a8fff--- /dev/null+++ b/backend/pkg/libarcane/edge/types.go@@ -0,0 +1,373 @@+package edge++import (+ "bytes"+ "context"+ "net/http"+ "sync"+ "sync/atomic"+ "time"++ "github.com/gorilla/websocket"+ "google.golang.org/grpc"+)++// activeWSStream tracks an active WebSocket stream on the agent side.+type activeWSStream struct {+ ws *websocket.Conn+ conn TunnelConnection // tunnel connection the stream was opened on+ cancel context.CancelFunc+ dataCh chan wsPayload+ mu sync.Mutex+ closed bool+}++type wsPayload struct {+ messageType int+ data []byte+}++type commandRequestTransfer struct {+ request *TunnelMessage+ conn TunnelConnection+ body bytes.Buffer+ nextSequence int64+ timerMu sync.Mutex+ timer *time.Timer+}++// TunnelClient represents the agent-side tunnel client+type TunnelClient struct {+ cfg *Config+ handler http.Handler+ reconnectInterval time.Duration+ heartbeatInterval time.Duration+ grpcRegistrationTimeout time.Duration+ websocketPreferenceTTL time.Duration+ managerURL string+ managerGRPCAddr string+ localPort string // Port the agent is running on locally+ httpClient *http.Client+ conn atomic.Pointer[connBox]+ stopCh chan struct{}+ requestTimeout time.Duration+ activeStreams sync.Map // map[string]*activeWSStream+ requestTransfers sync.Map // map[string]*commandRequestTransfer+ transportPreferenceMu sync.RWMutex+ preferWebSocketUntil time.Time+ agentInstanceID string+ sessionID string+}++// connBox wraps the active TunnelConnection so it can be swapped atomically on+// reconnect. The wrapper is required because the gRPC and WebSocket connections+// are different concrete types; a bare atomic.Value would panic on the type+// change, whereas an atomic.Pointer to a fixed box type does not.+type connBox struct {+ conn TunnelConnection+}++type managedTunnelTransportsInternal struct {+ grpc bool+ websocket bool+}++// responseRecorder captures HTTP responses+type responseRecorder struct {+ headers http.Header+ body bytes.Buffer+ statusCode int+}++type commandResponseRecorder struct {+ conn TunnelConnection+ headers http.Header+ commandID string+ commandName string+ buffer bytes.Buffer+ statusCode int+ sequence int64+ mu sync.Mutex+ wroteHeader bool+ streaming bool+ closed bool+}++type streamingResponseRecorder struct {+ requestID string+ conn TunnelConnection+ headers http.Header+ statusCode int+ wroteHeader bool+ closed bool+ mu sync.Mutex+}++type pollManagedTunnelSession struct {+ cancel context.CancelFunc+ done chan error+}++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{}++type commandRoute struct {+ Method string+ PathPattern string+ CommandName string+ Stream bool+ LocalOnly bool+}++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+}++// TunnelPollRequest is a forward-compatible control-plane check-in request.+type TunnelPollRequest struct {+ Transport string `json:"transport,omitempty"`+ Connected bool `json:"connected,omitempty"`+}++// TunnelPollResponse is a forward-compatible control-plane response.+type TunnelPollResponse struct {+ Status string `json:"status"`+ PollIntervalSeconds int `json:"pollIntervalSeconds"`+ ActiveTransport string `json:"activeTransport,omitempty"`+ Connected bool `json:"connected,omitempty"`+}++// PollRuntimeState describes the most recent poll-based control-plane activity+// observed for an edge environment.+type PollRuntimeState struct {+ LastPollAt *time.Time+ PollIntervalSeconds int+}++// TunnelDemandRegistry tracks short-lived tunnel demand on the manager side.+type TunnelDemandRegistry struct {+ demands map[string]time.Time+ mu sync.RWMutex+}++// PollRuntimeRegistry tracks recent poll check-ins from edge agents.+type PollRuntimeRegistry struct {+ states map[string]PollRuntimeState+ mu sync.RWMutex+}++type grpcResponseState struct {+ status int+ respHeaders map[string]string+ respBody bytes.Buffer+ gotResponse bool+}++// AgentTunnel represents an active tunnel connection from an edge agent+type AgentTunnel struct {+ EnvironmentID string+ Conn TunnelConnection+ 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+ done chan struct{}+ closeOnce sync.Once+}++// TunnelRegistry manages active edge agent tunnel connections+type TunnelRegistry struct {+ tunnels map[string]*AgentTunnel // environmentID -> tunnel+ mu sync.RWMutex+}++type internalTunnelRequestContextKey struct{}++// TunnelServer handles incoming edge agent connections on the manager side.+type TunnelServer struct {+ registry *TunnelRegistry+ resolver EnvironmentResolver+ nameResolver EnvironmentNameResolver+ statusCallback StatusUpdateCallback+ eventCallback EventCallback+ enrollmentCallback EnrollmentCallback+ cleanupDone chan struct{}+ cfg *Config+ statusMu sync.Mutex+}++type resolvedEnvironmentIDKey struct{}++type contextualServerStream struct {+ grpc.ServerStream++ ctx context.Context+}++// 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"`+}++type edgeMTLSLockInfo struct {+ pid int+ createdAt time.Time+}++// Config contains the public edge-tunnel runtime settings needed by pkg/libarcane/edge.+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+ Listen string+}++// TunnelRuntimeState describes the live, in-memory state of an active edge tunnel.+type TunnelRuntimeState struct {+ Transport string+ ConnectedAt *time.Time+ LastHeartbeat *time.Time+ SessionID string+ AgentInstance string+ SecurityMode string+ Capabilities []string+ State string+}++// TunnelMessage represents a transport-agnostic edge tunnel message.+type TunnelMessage struct {+ Headers map[string]string `json:"headers,omitempty"` // HTTP headers+ Event *TunnelEvent `json:"event,omitempty"` // Agent event payload+ Metadata map[string]string `json:"metadata,omitempty"` // Correlation and audit metadata+ ID string `json:"id"` // Unique request/stream ID+ Type TunnelMessageType `json:"type"` // Message type+ Method string `json:"method,omitempty"` // HTTP method for requests+ Path string `json:"path,omitempty"` // Request path+ Query string `json:"query,omitempty"` // Query string+ AgentToken string `json:"agent_token,omitempty"` // Register request token+ EnvironmentID string `json:"environment_id,omitempty"` // Manager-resolved environment ID+ Error string `json:"error,omitempty"` // Error field for register response+ 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+ SecurityMode string `json:"security_mode,omitempty"` // token, mtls, etc.+ Body []byte `json:"body,omitempty"` // Request/response body+ Capabilities []string `json:"capabilities,omitempty"` // Agent advertised capabilities+ WSMessageType int `json:"ws_message_type,omitempty"` // WebSocket message type+ Status int `json:"status,omitempty"` // HTTP status for responses+ TimeoutMillis int64 `json:"timeout_millis,omitempty"` // Command timeout+ Sequence int64 `json:"sequence,omitempty"` // Chunk sequence number+ Accepted bool `json:"accepted,omitempty"` // Registration accepted+ DrainPrevious bool `json:"drain_previous,omitempty"` // Replace previous session+ Streaming bool `json:"streaming,omitempty"` // Response used chunked output+ EOF bool `json:"eof,omitempty"` // Final chunk indicator+}++// TunnelEvent is an event payload sent from an agent to the manager.+type TunnelEvent struct {+ Type string `json:"type"`+ Severity string `json:"severity,omitempty"`+ Title string `json:"title"`+ Description string `json:"description,omitempty"`+ ResourceType string `json:"resource_type,omitempty"`+ ResourceID string `json:"resource_id,omitempty"`+ ResourceName string `json:"resource_name,omitempty"`+ UserID string `json:"user_id,omitempty"`+ Username string `json:"username,omitempty"`+ MetadataJSON []byte `json:"metadata_json,omitempty"`+}++// PendingRequest tracks an in-flight request waiting for response.+type PendingRequest struct {+ ResponseCh chan *TunnelMessage+ failureCh chan error+}++// TunnelConn wraps a WebSocket connection with send/receive helpers.+type TunnelConn struct {+ conn *websocket.Conn+ mu sync.Mutex+ closed atomic.Bool+}++// GRPCManagerTunnelConn wraps the manager-side gRPC tunnel stream.+type GRPCManagerTunnelConn struct {+ stream grpcManagerStream+ cancel context.CancelFunc+ mu sync.Mutex+ closed atomic.Bool+}++// GRPCAgentTunnelConn wraps the agent-side gRPC tunnel stream.+type GRPCAgentTunnelConn struct {+ stream grpcAgentStream+ cancel context.CancelFunc+ mu sync.Mutex+ closed atomic.Bool+}++type cancelableGRPCManagerStream struct {+ stream grpcManagerStream+ ctx context.Context+}diff --git a/backend/pkg/libarcane/edge/ws_proxy.go b/backend/pkg/libarcane/edge/ws_proxy.goindex c38e5af9b..4dfb76375 100644--- a/backend/pkg/libarcane/edge/ws_proxy.go+++ b/backend/pkg/libarcane/edge/ws_proxy.go@@ -55,12 +55,13 @@ func ProxyWebSocketRequest(c echo.Context, tunnel *AgentTunnel, targetPath strin// Register the stream before sending the start message so agent replies// are never dropped when the routing goroutine is faster than this goroutine.- agentDataCh := make(chan *TunnelMessage, 512)+ pending := &PendingRequest{+ ResponseCh: make(chan *TunnelMessage, 512),+ failureCh: make(chan error, 1),+ }clientDoneCh := make(chan struct{})- tunnel.Pending.Store(streamID, &PendingRequest{- ResponseCh: agentDataCh,- })+ tunnel.Pending.Store(streamID, pending)defer tunnel.Pending.Delete(streamID)headers := buildWebSocketHeaders(req)@@ -84,7 +85,7 @@ func ProxyWebSocketRequest(c echo.Context, tunnel *AgentTunnel, targetPath strin// Goroutine to read from client and send to agentgo forwardClientToAgent(ctx, streamCtx, clientWS, tunnel, streamID, clientDoneCh)- forwardAgentToClient(ctx, streamCtx, clientWS, tunnel, agentDataCh, streamID, clientDoneCh)+ forwardAgentToClient(ctx, streamCtx, clientWS, tunnel, pending, streamID, clientDoneCh)return nil}@@ -128,7 +129,7 @@ func forwardClientToAgent(ctx context.Context, streamCtx context.Context, client}}-func forwardAgentToClient(ctx context.Context, streamCtx context.Context, clientWS *websocket.Conn, tunnel *AgentTunnel, agentDataCh <-chan *TunnelMessage, streamID string, clientDoneCh <-chan struct{}) {+func forwardAgentToClient(ctx context.Context, streamCtx context.Context, clientWS *websocket.Conn, tunnel *AgentTunnel, pending *PendingRequest, streamID string, clientDoneCh <-chan struct{}) {pingTicker := time.NewTicker(tunnelWSPingPeriod)defer pingTicker.Stop()@@ -136,6 +137,10 @@ func forwardAgentToClient(ctx context.Context, streamCtx context.Context, clientselect {case <-streamCtx.Done():return+ case <-tunnel.done:+ return+ case <-pending.failureCh:+ returncase <-clientDoneCh:returncase <-pingTicker.C:@@ -145,7 +150,7 @@ func forwardAgentToClient(ctx context.Context, streamCtx context.Context, clientsendWebSocketClose(tunnel, streamID)return}- case msg, ok := <-agentDataCh:+ case msg, ok := <-pending.ResponseCh:if !ok {return}