• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pomerium / pomerium / 25170861833

30 Apr 2026 02:23PM UTC coverage: 45.419% (-0.006%) from 45.425%
25170861833

push

github

web-flow
ci: update dependencies (#6290)

This PR updates dependencies not managed by dependabot.

Co-authored-by: GitHub Actions <apparitor@users.noreply.github.com>

35624 of 78434 relevant lines covered (45.42%)

113.8 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.34
/pkg/ssh/manager.go
1
package ssh
2

3
import (
4
        "cmp"
5
        "context"
6
        "errors"
7
        "fmt"
8
        "slices"
9
        "strconv"
10
        "sync"
11
        "time"
12

13
        corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
14
        envoy_config_endpoint_v3 "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3"
15
        datav3 "github.com/envoyproxy/go-control-plane/envoy/data/core/v3"
16
        discoveryv3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
17
        endpointv3 "github.com/envoyproxy/go-control-plane/envoy/service/endpoint/v3"
18
        "github.com/envoyproxy/go-control-plane/pkg/cache/types"
19
        "github.com/envoyproxy/go-control-plane/pkg/cache/v3"
20
        "github.com/envoyproxy/go-control-plane/pkg/resource/v3"
21
        "github.com/envoyproxy/go-control-plane/pkg/server/delta/v3"
22
        "github.com/rs/zerolog"
23
        "golang.org/x/sync/errgroup"
24
        "google.golang.org/grpc/codes"
25
        "google.golang.org/grpc/status"
26
        "google.golang.org/protobuf/types/known/anypb"
27
        "google.golang.org/protobuf/types/known/emptypb"
28

29
        extensions_ssh "github.com/pomerium/envoy-custom/api/extensions/filters/network/ssh"
30
        "github.com/pomerium/pomerium/config"
31
        "github.com/pomerium/pomerium/internal/log"
32
        "github.com/pomerium/pomerium/pkg/grpc/databroker"
33
        "github.com/pomerium/pomerium/pkg/grpc/session"
34
        "github.com/pomerium/pomerium/pkg/ssh/cli"
35
        "github.com/pomerium/pomerium/pkg/ssh/portforward"
36
)
37

38
type streamClusterEndpointDiscovery struct {
39
        self     *StreamManager
40
        streamID uint64
41
}
42

43
type streamEndpointsUpdate struct {
44
        streamID uint64
45
        added    map[string]portforward.RoutePortForwardInfo
46
        removed  map[string]struct{}
47
}
48

49
// UpdateClusterEndpoints implements EndpointDiscoveryInterface.
50
func (ed *streamClusterEndpointDiscovery) UpdateClusterEndpoints(added map[string]portforward.RoutePortForwardInfo, removed map[string]struct{}) {
58✔
51
        // run this callback in a separate goroutine, since it can deadlock if called
58✔
52
        // synchronously during startup
58✔
53
        ed.self.endpointsUpdateQueue <- streamEndpointsUpdate{
58✔
54
                streamID: ed.streamID,
58✔
55
                added:    added,
58✔
56
                removed:  removed,
58✔
57
        }
58✔
58
}
58✔
59

60
// PortForwardManager implements EndpointDiscoveryInterface.
61
func (ed *streamClusterEndpointDiscovery) PortForwardManager() *portforward.Manager {
6✔
62
        return ed.self.getPortForwardManagerForStream(ed.streamID)
6✔
63
}
6✔
64

65
var _ EndpointDiscoveryInterface = (*streamClusterEndpointDiscovery)(nil)
66

67
var ErrReauthDone = errors.New("reauth loop done")
68

69
type activeStream struct {
70
        Handler            *StreamHandler
71
        PortForwardManager *portforward.Manager
72
        Session            *string
73
        SessionBindingID   *string
74
        Endpoints          map[string]struct{}
75
}
76

77
type StreamManager struct {
78
        endpointv3.UnimplementedEndpointDiscoveryServiceServer
79
        ready                            chan struct{}
80
        logger                           *zerolog.Logger
81
        auth                             AuthInterface
82
        reauthC                          chan struct{}
83
        initialSessionSyncDone           bool
84
        initialSessionBindingSyncDone    bool
85
        waitForInitialSessionSync        chan struct{}
86
        waitForInitialSessionBindingSync chan struct{}
87

88
        mu sync.Mutex
89

90
        cfg           *config.Config
91
        activeStreams map[uint64]*activeStream
92

93
        // Tracks stream IDs for active sessions
94
        sessionStreams map[string]map[uint64]struct{}
95

96
        // Tracks stream IDs per sessionBindingID for active sessions
97
        bindingStreams map[string]map[uint64]struct{}
98

99
        bindingSyncer *bindingSyncer
100
        // Tracks endpoint stream IDs for clusters
101
        clusterEndpoints     map[string]map[uint64]*extensions_ssh.EndpointMetadata
102
        endpointsUpdateQueue chan streamEndpointsUpdate
103
        edsCache             *cache.LinearCache
104
        edsServer            delta.Server
105
        indexer              PolicyIndexer
106
        cliCtrl              cli.InternalCLIController
107
}
108

109
// LogHealthCheckEvent implements grpc.HealthCheckEventSinkServer.
110
func (sm *StreamManager) LogHealthCheckEvent(ctx context.Context, event *datav3.HealthCheckEvent) (*emptypb.Empty, error) {
×
111
        sm.mu.Lock()
×
112
        defer sm.mu.Unlock()
×
113
        // metadata looks like this:
×
114
        /*
×
115
                {
×
116
                        "healthCheckerType": "TCP",
×
117
                        "host": {
×
118
                                "envoyInternalAddress": {
×
119
                                        "serverListenerName": "ssh:10447317534193689787"
×
120
                                }
×
121
                        },
×
122
                        "clusterName": "route-d5461d93f5ff6efd",
×
123
                        "ejectUnhealthyEvent": {
×
124
                                "failureType": "NETWORK_TIMEOUT"
×
125
                        },
×
126
                        "timestamp": "2025-12-03T22:22:52.742Z",
×
127
                        "metadata": {
×
128
                                "typedFilterMetadata": {
×
129
                                        "com.pomerium.ssh.endpoint": {
×
130
                                                "@type": "type.googleapis.com/pomerium.extensions.ssh.EndpointMetadata",
×
131
                                                "serverPort": {
×
132
                                                        "value": 56301,
×
133
                                                        "isDynamic": true
×
134
                                                },
×
135
                                                "matchedPermission": {
×
136
                                                        "requestedHost": "localhost"
×
137
                                                }
×
138
                                        }
×
139
                                }
×
140
                        },
×
141
                        "locality": {}
×
142
                }
×
143
        */
×
144

×
145
        for streamID := range sm.clusterEndpoints[event.ClusterName] {
×
146
                sm.activeStreams[streamID].Handler.OnClusterHealthUpdate(ctx, event)
×
147
        }
×
148

149
        return &emptypb.Empty{}, nil
×
150
}
151

152
func (sm *StreamManager) getPortForwardManagerForStream(streamID uint64) *portforward.Manager {
6✔
153
        sm.mu.Lock()
6✔
154
        defer sm.mu.Unlock()
6✔
155
        activeStream := sm.activeStreams[streamID]
6✔
156
        if activeStream == nil || activeStream.PortForwardManager == nil {
6✔
157
                return nil
×
158
        }
×
159
        return activeStream.PortForwardManager // may be nil
6✔
160
}
161

162
// OnDeltaStreamClosed implements delta.Callbacks.
163
func (sm *StreamManager) OnDeltaStreamClosed(int64, *corev3.Node) {
×
164
}
×
165

166
// OnDeltaStreamOpen implements delta.Callbacks.
167
func (sm *StreamManager) OnDeltaStreamOpen(context.Context, int64, string) error {
×
168
        return nil
×
169
}
×
170

171
// OnStreamDeltaRequest implements delta.Callbacks.
172
func (sm *StreamManager) OnStreamDeltaRequest(_ int64, req *discoveryv3.DeltaDiscoveryRequest) error {
×
173
        if len(req.ResourceNamesSubscribe) == 0 {
×
174
                return nil
×
175
        }
×
176
        sm.mu.Lock()
×
177
        defer sm.mu.Unlock()
×
178
        initialEmptyResources := make(map[string]types.Resource)
×
179
        for _, clusterID := range req.ResourceNamesSubscribe {
×
180
                if _, ok := sm.clusterEndpoints[clusterID]; !ok {
×
181
                        sm.clusterEndpoints[clusterID] = map[uint64]*extensions_ssh.EndpointMetadata{}
×
182
                        initialEmptyResources[clusterID] = &envoy_config_endpoint_v3.ClusterLoadAssignment{
×
183
                                ClusterName: clusterID,
×
184
                        }
×
185
                }
×
186
        }
187
        return sm.edsCache.UpdateResources(initialEmptyResources, nil)
×
188
}
189

190
// OnStreamDeltaResponse implements delta.Callbacks.
191
func (sm *StreamManager) OnStreamDeltaResponse(int64, *discoveryv3.DeltaDiscoveryRequest, *discoveryv3.DeltaDiscoveryResponse) {
×
192
}
×
193

194
// DeltaEndpoints implements endpointv3.EndpointDiscoveryServiceServer.
195
func (sm *StreamManager) DeltaEndpoints(stream endpointv3.EndpointDiscoveryService_DeltaEndpointsServer) error {
×
196
        select {
×
197
        case <-stream.Context().Done():
×
198
                return context.Cause(stream.Context())
×
199
        case <-sm.ready:
×
200
        }
201
        log.Ctx(stream.Context()).Debug().Msg("delta endpoint stream started")
×
202
        defer log.Ctx(stream.Context()).Debug().Msg("delta endpoint stream ended")
×
203
        return sm.edsServer.DeltaStreamHandler(stream, resource.EndpointType)
×
204
}
205

206
// ClearRecords implements databroker.SyncerHandler.
207
func (sm *StreamManager) ClearRecords(ctx context.Context) {
145✔
208
        sm.mu.Lock()
145✔
209
        defer sm.mu.Unlock()
145✔
210
        if !sm.initialSessionSyncDone {
290✔
211
                sm.initialSessionSyncDone = true
145✔
212
                close(sm.waitForInitialSessionSync)
145✔
213
                log.Ctx(ctx).Debug().
145✔
214
                        Msg("ssh stream manager: initial sync done")
145✔
215
                return
145✔
216
        }
145✔
217
        for sessionID, streamIDs := range sm.sessionStreams {
×
218
                for streamID := range streamIDs {
×
219
                        log.Ctx(ctx).Debug().
×
220
                                Str("session-id", sessionID).
×
221
                                Uint64("stream-id", streamID).
×
222
                                Msg("terminating stream: databroker sync reset")
×
223
                        sm.terminateStreamLocked(streamID)
×
224
                }
×
225
        }
226
        clear(sm.sessionStreams)
×
227
}
228

229
func (sm *StreamManager) clearRecordsBinding(ctx context.Context) {
44✔
230
        sm.mu.Lock()
44✔
231
        defer sm.mu.Unlock()
44✔
232
        if !sm.initialSessionBindingSyncDone {
87✔
233
                sm.initialSessionBindingSyncDone = true
43✔
234
                close(sm.waitForInitialSessionBindingSync)
43✔
235
                log.Ctx(ctx).Debug().
43✔
236
                        Msg("ssh stream manager: initial sync done")
43✔
237
                return
43✔
238
        }
43✔
239
        for sessionID, streamIDs := range sm.bindingStreams {
3✔
240
                for streamID := range streamIDs {
6✔
241
                        log.Ctx(ctx).Debug().
4✔
242
                                Str("session-binding-id", sessionID).
4✔
243
                                Uint64("stream-id", streamID).
4✔
244
                                Msg("terminating stream: databroker sync reset")
4✔
245
                        sm.terminateStreamLocked(streamID)
4✔
246
                }
4✔
247
        }
248
        clear(sm.sessionStreams)
1✔
249
}
250

251
// GetDataBrokerServiceClient implements databroker.SyncerHandler.
252
func (sm *StreamManager) GetDataBrokerServiceClient() databroker.DataBrokerServiceClient {
196✔
253
        return sm.auth.GetDataBrokerServiceClient()
196✔
254
}
196✔
255

256
// UpdateRecords implements databroker.SyncerHandler.
257
func (sm *StreamManager) UpdateRecords(ctx context.Context, _ uint64, records []*databroker.Record) {
91✔
258
        sm.mu.Lock()
91✔
259
        defer sm.mu.Unlock()
91✔
260
        for _, record := range records {
139✔
261
                if record.DeletedAt == nil {
93✔
262
                        // New session
45✔
263
                        var s session.Session
45✔
264
                        if err := record.Data.UnmarshalTo(&s); err != nil {
45✔
265
                                log.Ctx(ctx).Err(err).Msg("invalid session object, ignoring")
×
266
                                continue
×
267
                        }
268
                        s.Version = strconv.FormatUint(record.GetVersion(), 10)
45✔
269
                        sm.indexer.OnSessionCreated(&s)
45✔
270
                        continue
45✔
271
                }
272
                // Session was deleted; terminate all of its associated streams
273
                sm.indexer.OnSessionDeleted(record.Id)
3✔
274
                for streamID := range sm.sessionStreams[record.Id] {
6✔
275
                        log.Ctx(ctx).Debug().
3✔
276
                                Str("session-id", record.Id).
3✔
277
                                Uint64("stream-id", streamID).
3✔
278
                                Msg("terminating stream: session revoked")
3✔
279
                        sm.terminateStreamLocked(streamID)
3✔
280
                }
3✔
281
                delete(sm.sessionStreams, record.Id)
3✔
282
        }
283
}
284

285
func (sm *StreamManager) updateRecordsBinding(ctx context.Context, _ uint64, records []*databroker.Record) {
94✔
286
        sm.mu.Lock()
94✔
287
        defer sm.mu.Unlock()
94✔
288
        for _, record := range records {
144✔
289
                if record.DeletedAt == nil {
93✔
290
                        continue
43✔
291
                }
292
                // Session binding was deleted; terminate all of its associated streams
293
                for streamID := range sm.bindingStreams[record.Id] {
13✔
294
                        log.Ctx(ctx).Debug().
6✔
295
                                Str("session-id", record.Id).
6✔
296
                                Uint64("stream-id", streamID).
6✔
297
                                Msg("terminating stream: session binding revoked")
6✔
298
                        sm.terminateStreamLocked(streamID)
6✔
299
                }
6✔
300
                delete(sm.bindingStreams, record.Id)
7✔
301
        }
302
}
303

304
func (sm *StreamManager) OnStreamAuthenticated(ctx context.Context, streamID uint64, req AuthRequest) error {
48✔
305
        if err := sm.waitForInitialSync(ctx); err != nil {
48✔
306
                return err
×
307
        }
×
308
        sm.mu.Lock()
48✔
309
        defer sm.mu.Unlock()
48✔
310
        activeStream := sm.activeStreams[streamID]
48✔
311
        if activeStream.Session != nil || activeStream.SessionBindingID != nil {
48✔
312
                return status.Errorf(codes.Internal, "stream %d already has an associated session", streamID)
×
313
        }
×
314

315
        if sm.sessionStreams[req.SessionID] == nil {
95✔
316
                sm.sessionStreams[req.SessionID] = map[uint64]struct{}{}
47✔
317
        }
47✔
318
        if sm.bindingStreams[req.SessionBindingID] == nil {
93✔
319
                sm.bindingStreams[req.SessionBindingID] = map[uint64]struct{}{}
45✔
320
        }
45✔
321
        sm.sessionStreams[req.SessionID][streamID] = struct{}{}
48✔
322
        sm.bindingStreams[req.SessionBindingID][streamID] = struct{}{}
48✔
323

48✔
324
        activeStream.Session = new(string)
48✔
325
        *activeStream.Session = req.SessionID
48✔
326
        activeStream.SessionBindingID = new(string)
48✔
327
        *activeStream.SessionBindingID = req.SessionBindingID
48✔
328

48✔
329
        activeStream.PortForwardManager.AddUpdateListener(activeStream.Handler)
48✔
330

48✔
331
        sm.indexer.OnStreamAuthenticated(streamID, req)
48✔
332
        return nil
48✔
333
}
334

335
type bindingSyncer struct {
336
        clientHandler func() databroker.DataBrokerServiceClient
337
        clearHandler  func(context.Context)
338
        updateHandler func(context.Context, uint64, []*databroker.Record)
339
}
340

341
var _ databroker.SyncerHandler = (*bindingSyncer)(nil)
342

343
func (sbr *bindingSyncer) ClearRecords(ctx context.Context) {
44✔
344
        sbr.clearHandler(ctx)
44✔
345
}
44✔
346

347
// GetDataBrokerServiceClient implements databroker.SyncerHandler.
348
func (sbr *bindingSyncer) GetDataBrokerServiceClient() databroker.DataBrokerServiceClient {
101✔
349
        return sbr.clientHandler()
101✔
350
}
101✔
351

352
// UpdateRecords implements databroker.SyncerHandler.
353
func (sbr *bindingSyncer) UpdateRecords(ctx context.Context, serverVersion uint64, records []*databroker.Record) {
94✔
354
        sbr.updateHandler(ctx, serverVersion, records)
94✔
355
}
94✔
356

357
func NewStreamManager(ctx context.Context, auth AuthInterface, indexer PolicyIndexer, cliCtrl cli.InternalCLIController, cfg *config.Config) *StreamManager {
145✔
358
        sm := &StreamManager{
145✔
359
                logger:                           log.Ctx(ctx),
145✔
360
                auth:                             auth,
145✔
361
                ready:                            make(chan struct{}),
145✔
362
                waitForInitialSessionSync:        make(chan struct{}),
145✔
363
                waitForInitialSessionBindingSync: make(chan struct{}),
145✔
364
                reauthC:                          make(chan struct{}, 1),
145✔
365
                cfg:                              cfg,
145✔
366
                activeStreams:                    map[uint64]*activeStream{},
145✔
367
                sessionStreams:                   map[string]map[uint64]struct{}{},
145✔
368
                clusterEndpoints:                 map[string]map[uint64]*extensions_ssh.EndpointMetadata{},
145✔
369
                edsCache:                         cache.NewLinearCache(resource.EndpointType),
145✔
370
                endpointsUpdateQueue:             make(chan streamEndpointsUpdate, 128),
145✔
371
                bindingStreams:                   map[string]map[uint64]struct{}{},
145✔
372
                indexer:                          indexer,
145✔
373
                cliCtrl:                          cliCtrl,
145✔
374
        }
145✔
375

145✔
376
        bindingSyncer := &bindingSyncer{
145✔
377
                clientHandler: sm.GetDataBrokerServiceClient,
145✔
378
                clearHandler:  sm.clearRecordsBinding,
145✔
379
                updateHandler: sm.updateRecordsBinding,
145✔
380
        }
145✔
381

145✔
382
        sm.bindingSyncer = bindingSyncer
145✔
383

145✔
384
        sm.indexer.ProcessConfigUpdate(cfg)
145✔
385
        return sm
145✔
386
}
145✔
387

388
func (sm *StreamManager) waitForInitialSync(ctx context.Context) error {
51✔
389
        sm.mu.Lock()
51✔
390
        for !sm.initialSessionSyncDone || !sm.initialSessionBindingSyncDone {
913✔
391
                sm.mu.Unlock()
862✔
392
                select {
862✔
393
                case <-sm.waitForInitialSessionSync:
1✔
394
                case <-sm.waitForInitialSessionBindingSync:
861✔
395
                case <-time.After(10 * time.Second):
×
396
                        return errors.New("timed out waiting for initial sync")
×
397
                case <-ctx.Done():
×
398
                        return context.Cause(ctx)
×
399
                }
400
                sm.mu.Lock()
862✔
401
        }
402
        sm.mu.Unlock()
51✔
403
        return nil
51✔
404
}
405

406
func (sm *StreamManager) Run(ctx context.Context) error {
43✔
407
        sm.edsServer = delta.NewServer(ctx, sm.edsCache, sm)
43✔
408
        eg, eCtx := errgroup.WithContext(ctx)
43✔
409
        eg.Go(func() error {
86✔
410
                syncer := databroker.NewSyncer(
43✔
411
                        eCtx,
43✔
412
                        "ssh-auth-session-sync",
43✔
413
                        sm,
43✔
414
                        databroker.WithTypeURL("type.googleapis.com/session.Session"))
43✔
415
                return syncer.Run(eCtx)
43✔
416
        })
43✔
417

418
        eg.Go(func() error {
86✔
419
                syncer := databroker.NewSyncer(
43✔
420
                        eCtx,
43✔
421
                        "ssh-auth-session-binding-sync",
43✔
422
                        sm.bindingSyncer,
43✔
423
                        databroker.WithTypeURL("type.googleapis.com/session.SessionBinding"),
43✔
424
                )
43✔
425
                return syncer.Run(eCtx)
43✔
426
        })
43✔
427

428
        eg.Go(func() error {
86✔
429
                sm.reauthLoop(eCtx)
43✔
430
                return ErrReauthDone
43✔
431
        })
43✔
432
        eg.Go(func() error {
86✔
433
                sm.endpointsUpdateLoop(ctx)
43✔
434
                return nil
43✔
435
        })
43✔
436

437
        close(sm.ready)
43✔
438
        err := eg.Wait()
43✔
439
        if errors.Is(err, ErrReauthDone) {
65✔
440
                return nil
22✔
441
        }
22✔
442

443
        return err
21✔
444
}
445

446
func (sm *StreamManager) OnConfigChange(cfg *config.Config) {
145✔
447
        sm.indexer.ProcessConfigUpdate(cfg)
145✔
448

145✔
449
        // TODO: integrate the re-auth mechanism with the indexer
145✔
450
        select {
145✔
451
        case sm.reauthC <- struct{}{}:
126✔
452
        default:
19✔
453
        }
454
}
455

456
func (sm *StreamManager) LookupStream(streamID uint64) *StreamHandler {
24✔
457
        sm.mu.Lock()
24✔
458
        defer sm.mu.Unlock()
24✔
459
        if info, ok := sm.activeStreams[streamID]; ok {
46✔
460
                return info.Handler
22✔
461
        }
22✔
462
        return nil
2✔
463
}
464

465
func (sm *StreamManager) NewStreamHandler(
466
        downstream *extensions_ssh.DownstreamConnectEvent,
467
) *StreamHandler {
151✔
468
        sm.mu.Lock()
151✔
469
        defer sm.mu.Unlock()
151✔
470
        streamID := downstream.StreamId
151✔
471

151✔
472
        onClose := func() {
293✔
473
                sm.onStreamHandlerClosed(streamID)
142✔
474
        }
142✔
475
        discovery := &streamClusterEndpointDiscovery{
151✔
476
                self:     sm,
151✔
477
                streamID: streamID,
151✔
478
        }
151✔
479
        sh := NewStreamHandler(sm.auth, discovery, sm.cliCtrl, sm.cfg, downstream, onClose)
151✔
480
        portForwardMgr := portforward.NewManager()
151✔
481
        sm.activeStreams[streamID] = &activeStream{
151✔
482
                Handler:            sh,
151✔
483
                Endpoints:          map[string]struct{}{},
151✔
484
                PortForwardManager: portForwardMgr,
151✔
485
        }
151✔
486
        sm.indexer.AddStream(streamID, portForwardMgr)
151✔
487
        return sh
151✔
488
}
489

490
func (sm *StreamManager) onStreamHandlerClosed(streamID uint64) {
142✔
491
        sm.mu.Lock()
142✔
492
        defer sm.mu.Unlock()
142✔
493
        info := sm.activeStreams[streamID]
142✔
494
        delete(sm.activeStreams, streamID)
142✔
495

142✔
496
        info.PortForwardManager.RemoveUpdateListener(info.Handler)
142✔
497
        sm.indexer.RemoveStream(streamID)
142✔
498

142✔
499
        if info.Session != nil {
185✔
500
                session := *info.Session
43✔
501
                delete(sm.sessionStreams[session], streamID)
43✔
502
                if len(sm.sessionStreams[session]) == 0 {
86✔
503
                        delete(sm.sessionStreams, session)
43✔
504
                }
43✔
505
        }
506
        if info.SessionBindingID != nil {
185✔
507
                bindingID := *info.SessionBindingID
43✔
508
                delete(sm.bindingStreams[bindingID], streamID)
43✔
509
                if len(sm.bindingStreams[bindingID]) == 0 {
86✔
510
                        delete(sm.bindingStreams, bindingID)
43✔
511
                }
43✔
512
        }
513

514
        if len(info.Endpoints) > 0 {
144✔
515
                sm.logger.Debug().
2✔
516
                        Uint64("stream-id", streamID).
2✔
517
                        Any("endpoints", info.Endpoints).
2✔
518
                        Msg("clearing endpoints for closed stream")
2✔
519
                sm.endpointsUpdateQueue <- streamEndpointsUpdate{
2✔
520
                        streamID: streamID,
2✔
521
                        removed:  info.Endpoints,
2✔
522
                }
2✔
523
        }
2✔
524
}
525

526
func (sm *StreamManager) processStreamEndpointsUpdate(update streamEndpointsUpdate) {
60✔
527
        sm.mu.Lock()
60✔
528
        defer sm.mu.Unlock()
60✔
529
        streamID := update.streamID
60✔
530

60✔
531
        activeStream := sm.activeStreams[streamID] // can be nil
60✔
532

60✔
533
        toUpdate := map[string]types.Resource{} // *envoy_config_endpoint_v3.LbEndpoint
60✔
534
        var toDelete []string
60✔
535
        for clusterID, info := range update.added {
66✔
536
                if activeStream != nil {
12✔
537
                        activeStream.Endpoints[clusterID] = struct{}{}
6✔
538
                }
6✔
539
                if _, ok := sm.clusterEndpoints[clusterID]; !ok {
10✔
540
                        sm.clusterEndpoints[clusterID] = map[uint64]*extensions_ssh.EndpointMetadata{}
4✔
541
                }
4✔
542
                sm.clusterEndpoints[clusterID][streamID] = buildEndpointMetadata(info)
6✔
543
                toUpdate[clusterID] = buildClusterLoadAssignment(clusterID, sm.clusterEndpoints[clusterID])
6✔
544
        }
545
        for clusterID := range update.removed {
66✔
546
                if activeStream != nil {
10✔
547
                        delete(activeStream.Endpoints, clusterID)
4✔
548
                }
4✔
549
                delete(sm.clusterEndpoints[clusterID], streamID)
6✔
550
                if len(sm.clusterEndpoints[clusterID]) == 0 {
10✔
551
                        // No more endpoints for this cluster, so delete the resource. The cluster
4✔
552
                        // will handle this by clearing the endpoints.
4✔
553
                        toDelete = append(toDelete, clusterID)
4✔
554
                        delete(sm.clusterEndpoints, clusterID)
4✔
555
                } else {
6✔
556
                        // There are still endpoints
2✔
557
                        toUpdate[clusterID] = buildClusterLoadAssignment(clusterID, sm.clusterEndpoints[clusterID])
2✔
558
                }
2✔
559
        }
560

561
        if err := sm.edsCache.UpdateResources(toUpdate, toDelete); err != nil {
60✔
562
                sm.logger.Err(err).Msg("error updating EDS resources")
×
563
        }
×
564
}
565

566
func buildClusterLoadAssignment(clusterID string, clusterEndpoints map[uint64]*extensions_ssh.EndpointMetadata) types.Resource {
8✔
567
        endpoints := []*envoy_config_endpoint_v3.LbEndpoint{}
8✔
568
        for streamID, metadata := range clusterEndpoints {
18✔
569
                endpoints = append(endpoints, buildLbEndpoint(streamID, metadata))
10✔
570
        }
10✔
571
        slices.SortFunc(endpoints, compareEndpoints)
8✔
572
        return &envoy_config_endpoint_v3.ClusterLoadAssignment{
8✔
573
                ClusterName: clusterID,
8✔
574
                Endpoints:   []*envoy_config_endpoint_v3.LocalityLbEndpoints{{LbEndpoints: endpoints}},
8✔
575
        }
8✔
576
}
577

578
func compareEndpoints(a, b *envoy_config_endpoint_v3.LbEndpoint) int {
2✔
579
        return cmp.Compare(
2✔
580
                a.GetEndpoint().GetAddress().GetSocketAddress().GetAddress(),
2✔
581
                b.GetEndpoint().GetAddress().GetSocketAddress().GetAddress())
2✔
582
}
2✔
583

584
func buildEndpointMetadata(info portforward.RoutePortForwardInfo) *extensions_ssh.EndpointMetadata {
6✔
585
        serverPort := info.Permission.ServerPort()
6✔
586
        return &extensions_ssh.EndpointMetadata{
6✔
587
                ServerPort: &extensions_ssh.ServerPort{
6✔
588
                        Value:     serverPort.Value,
6✔
589
                        IsDynamic: serverPort.IsDynamic,
6✔
590
                },
6✔
591
                MatchedPermission: &extensions_ssh.PortForwardPermission{
6✔
592
                        RequestedHost: info.Permission.HostMatcher.InputPattern(),
6✔
593
                        RequestedPort: info.Permission.RequestedPort,
6✔
594
                },
6✔
595
                PomeriumRouteInfo: &extensions_ssh.EndpointMetadata_RouteInfo{
6✔
596
                        From:     info.From,
6✔
597
                        Hostname: info.Hostname,
6✔
598
                        Port:     info.Port,
6✔
599
                },
6✔
600
        }
6✔
601
}
6✔
602

603
func buildLbEndpoint(streamID uint64, metadata *extensions_ssh.EndpointMetadata) *envoy_config_endpoint_v3.LbEndpoint {
10✔
604
        endpointMdAny, _ := anypb.New(metadata)
10✔
605
        return &envoy_config_endpoint_v3.LbEndpoint{
10✔
606
                HostIdentifier: &envoy_config_endpoint_v3.LbEndpoint_Endpoint{
10✔
607
                        Endpoint: &envoy_config_endpoint_v3.Endpoint{
10✔
608
                                Address: &corev3.Address{
10✔
609
                                        Address: &corev3.Address_SocketAddress{
10✔
610
                                                SocketAddress: &corev3.SocketAddress{
10✔
611
                                                        Address: fmt.Sprintf("ssh:%d", streamID),
10✔
612
                                                        PortSpecifier: &corev3.SocketAddress_PortValue{
10✔
613
                                                                PortValue: metadata.ServerPort.Value,
10✔
614
                                                        },
10✔
615
                                                },
10✔
616
                                        },
10✔
617
                                },
10✔
618
                                HealthCheckConfig: &envoy_config_endpoint_v3.Endpoint_HealthCheckConfig{},
10✔
619
                        },
10✔
620
                },
10✔
621
                Metadata: &corev3.Metadata{
10✔
622
                        TypedFilterMetadata: map[string]*anypb.Any{
10✔
623
                                "com.pomerium.ssh.endpoint": endpointMdAny,
10✔
624
                        },
10✔
625
                },
10✔
626
                HealthStatus: corev3.HealthStatus_UNKNOWN,
10✔
627
        }
10✔
628
}
10✔
629

630
func (sm *StreamManager) reauthLoop(ctx context.Context) {
43✔
631
        for {
212✔
632
                select {
169✔
633
                case <-ctx.Done():
43✔
634
                        return
43✔
635
                case <-sm.reauthC:
126✔
636
                        sm.mu.Lock()
126✔
637
                        snapshot := make([]*activeStream, 0, len(sm.activeStreams))
126✔
638
                        for _, s := range sm.activeStreams {
214✔
639
                                snapshot = append(snapshot, s)
88✔
640
                        }
88✔
641
                        sm.mu.Unlock()
126✔
642

126✔
643
                        for _, s := range snapshot {
214✔
644
                                s.Handler.Reauth()
88✔
645
                        }
88✔
646
                }
647
        }
648
}
649

650
func (sm *StreamManager) endpointsUpdateLoop(ctx context.Context) {
43✔
651
        for {
146✔
652
                select {
103✔
653
                case <-ctx.Done():
43✔
654
                        return
43✔
655
                case update := <-sm.endpointsUpdateQueue:
60✔
656
                        sm.processStreamEndpointsUpdate(update)
60✔
657
                }
658
        }
659
}
660

661
func (sm *StreamManager) terminateStreamLocked(streamID uint64) {
13✔
662
        if sh, ok := sm.activeStreams[streamID]; ok {
26✔
663
                sh.Handler.Terminate(status.Errorf(codes.PermissionDenied, "no longer authorized"))
13✔
664
        }
13✔
665
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc