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

pomerium / pomerium / 20384304389

19 Dec 2025 10:34PM UTC coverage: 52.915% (-0.05%) from 52.963%
20384304389

push

github

web-flow
feat(ssh): custom sign in success hook (#6000)

## Summary

<!--  For example...
The existing implementation has poor numerical properties for
large arguments, so use the McGillicutty algorithm to improve
accuracy above 1e10.

The algorithm is described at
https://wikipedia.org/wiki/McGillicutty_Algorithm
-->

## Related issues

<!-- For example...
- #159
-->

## User Explanation

<!-- How would you explain this change to the user? If this
change doesn't create any user-facing changes, you can leave
this blank. If filled out, add the `docs` label -->

## Checklist

- [ ] reference any related issues
- [ ] updated unit tests
- [ ] add appropriate label (`enhancement`, `bug`, `breaking`,
`dependencies`, `ci`)
- [ ] ready for review

12 of 65 new or added lines in 4 files covered. (18.46%)

20 existing lines in 7 files now uncovered.

29524 of 55795 relevant lines covered (52.92%)

127.25 hits per line

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

86.97
/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
        discoveryv3 "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3"
16
        endpointv3 "github.com/envoyproxy/go-control-plane/envoy/service/endpoint/v3"
17
        "github.com/envoyproxy/go-control-plane/pkg/cache/types"
18
        "github.com/envoyproxy/go-control-plane/pkg/cache/v3"
19
        "github.com/envoyproxy/go-control-plane/pkg/resource/v3"
20
        "github.com/envoyproxy/go-control-plane/pkg/server/delta/v3"
21
        "github.com/rs/zerolog"
22
        "golang.org/x/sync/errgroup"
23
        "google.golang.org/grpc/codes"
24
        "google.golang.org/grpc/status"
25
        "google.golang.org/protobuf/types/known/anypb"
26

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

35
type streamClusterEndpointDiscovery struct {
36
        self     *StreamManager
37
        streamID uint64
38
}
39

40
type streamEndpointsUpdate struct {
41
        streamID uint64
42
        added    map[string]portforward.RoutePortForwardInfo
43
        removed  map[string]struct{}
44
}
45

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

57
// PortForwardManager implements EndpointDiscoveryInterface.
58
func (ed *streamClusterEndpointDiscovery) PortForwardManager() *portforward.Manager {
6✔
59
        return ed.self.getPortForwardManagerForStream(ed.streamID)
6✔
60
}
6✔
61

62
var _ EndpointDiscoveryInterface = (*streamClusterEndpointDiscovery)(nil)
63

64
var ErrReauthDone = errors.New("reauth loop done")
65

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

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

85
        mu sync.Mutex
86

87
        cfg           *config.Config
88
        activeStreams map[uint64]*activeStream
89

90
        // Tracks stream IDs for active sessions
91
        sessionStreams map[string]map[uint64]struct{}
92

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

96
        bindingSyncer *bindingSyncer
97
        // Tracks endpoint stream IDs for clusters
98
        clusterEndpoints     map[string]map[uint64]*extensions_ssh.EndpointMetadata
99
        endpointsUpdateQueue chan streamEndpointsUpdate
100
        edsCache             *cache.LinearCache
101
        edsServer            delta.Server
102
        indexer              PolicyIndexer
103
}
104

105
func (sm *StreamManager) getPortForwardManagerForStream(streamID uint64) *portforward.Manager {
6✔
106
        sm.mu.Lock()
6✔
107
        defer sm.mu.Unlock()
6✔
108
        activeStream := sm.activeStreams[streamID]
6✔
109
        if activeStream == nil || activeStream.PortForwardManager == nil {
6✔
110
                return nil
×
111
        }
×
112
        return activeStream.PortForwardManager // may be nil
6✔
113
}
114

115
// OnDeltaStreamClosed implements delta.Callbacks.
116
func (sm *StreamManager) OnDeltaStreamClosed(int64, *corev3.Node) {
×
117
}
×
118

119
// OnDeltaStreamOpen implements delta.Callbacks.
120
func (sm *StreamManager) OnDeltaStreamOpen(context.Context, int64, string) error {
×
121
        return nil
×
122
}
×
123

124
// OnStreamDeltaRequest implements delta.Callbacks.
125
func (sm *StreamManager) OnStreamDeltaRequest(_ int64, req *discoveryv3.DeltaDiscoveryRequest) error {
×
126
        if len(req.ResourceNamesSubscribe) == 0 {
×
127
                return nil
×
128
        }
×
129
        sm.mu.Lock()
×
130
        defer sm.mu.Unlock()
×
131
        initialEmptyResources := make(map[string]types.Resource)
×
132
        for _, clusterID := range req.ResourceNamesSubscribe {
×
133
                if _, ok := sm.clusterEndpoints[clusterID]; !ok {
×
134
                        sm.clusterEndpoints[clusterID] = map[uint64]*extensions_ssh.EndpointMetadata{}
×
135
                        initialEmptyResources[clusterID] = &envoy_config_endpoint_v3.ClusterLoadAssignment{
×
136
                                ClusterName: clusterID,
×
137
                        }
×
138
                }
×
139
        }
140
        return sm.edsCache.UpdateResources(initialEmptyResources, nil)
×
141
}
142

143
// OnStreamDeltaResponse implements delta.Callbacks.
144
func (sm *StreamManager) OnStreamDeltaResponse(int64, *discoveryv3.DeltaDiscoveryRequest, *discoveryv3.DeltaDiscoveryResponse) {
×
145
}
×
146

147
// DeltaEndpoints implements endpointv3.EndpointDiscoveryServiceServer.
148
func (sm *StreamManager) DeltaEndpoints(stream endpointv3.EndpointDiscoveryService_DeltaEndpointsServer) error {
×
149
        select {
×
150
        case <-stream.Context().Done():
×
151
                return context.Cause(stream.Context())
×
152
        case <-sm.ready:
×
153
        }
154
        log.Ctx(stream.Context()).Debug().Msg("delta endpoint stream started")
×
155
        defer log.Ctx(stream.Context()).Debug().Msg("delta endpoint stream ended")
×
156
        return sm.edsServer.DeltaStreamHandler(stream, resource.EndpointType)
×
157
}
158

159
// ClearRecords implements databroker.SyncerHandler.
160
func (sm *StreamManager) ClearRecords(ctx context.Context) {
146✔
161
        sm.mu.Lock()
146✔
162
        defer sm.mu.Unlock()
146✔
163
        if !sm.initialSessionSyncDone {
292✔
164
                sm.initialSessionSyncDone = true
146✔
165
                close(sm.waitForInitialSessionSync)
146✔
166
                log.Ctx(ctx).Debug().
146✔
167
                        Msg("ssh stream manager: initial sync done")
146✔
168
                return
146✔
169
        }
146✔
170
        for sessionID, streamIDs := range sm.sessionStreams {
×
171
                for streamID := range streamIDs {
×
172
                        log.Ctx(ctx).Debug().
×
173
                                Str("session-id", sessionID).
×
174
                                Uint64("stream-id", streamID).
×
175
                                Msg("terminating stream: databroker sync reset")
×
176
                        sm.terminateStreamLocked(streamID)
×
177
                }
×
178
        }
179
        clear(sm.sessionStreams)
×
180
}
181

182
func (sm *StreamManager) clearRecordsBinding(ctx context.Context) {
41✔
183
        sm.mu.Lock()
41✔
184
        defer sm.mu.Unlock()
41✔
185
        if !sm.initialSessionBindingSyncDone {
81✔
186
                sm.initialSessionBindingSyncDone = true
40✔
187
                close(sm.waitForInitialSessionBindingSync)
40✔
188
                log.Ctx(ctx).Debug().
40✔
189
                        Msg("ssh stream manager: initial sync done")
40✔
190
                return
40✔
191
        }
40✔
192
        for sessionID, streamIDs := range sm.bindingStreams {
3✔
193
                for streamID := range streamIDs {
6✔
194
                        log.Ctx(ctx).Debug().
4✔
195
                                Str("session-binding-id", sessionID).
4✔
196
                                Uint64("stream-id", streamID).
4✔
197
                                Msg("terminating stream: databroker sync reset")
4✔
198
                        sm.terminateStreamLocked(streamID)
4✔
199
                }
4✔
200
        }
201
        clear(sm.sessionStreams)
1✔
202
}
203

204
// GetDataBrokerServiceClient implements databroker.SyncerHandler.
205
func (sm *StreamManager) GetDataBrokerServiceClient() databroker.DataBrokerServiceClient {
190✔
206
        return sm.auth.GetDataBrokerServiceClient()
190✔
207
}
190✔
208

209
// UpdateRecords implements databroker.SyncerHandler.
210
func (sm *StreamManager) UpdateRecords(ctx context.Context, _ uint64, records []*databroker.Record) {
85✔
211
        sm.mu.Lock()
85✔
212
        defer sm.mu.Unlock()
85✔
213
        for _, record := range records {
130✔
214
                if record.DeletedAt == nil {
87✔
215
                        // New session
42✔
216
                        var s session.Session
42✔
217
                        if err := record.Data.UnmarshalTo(&s); err != nil {
42✔
218
                                log.Ctx(ctx).Err(err).Msg("invalid session object, ignoring")
×
219
                                continue
×
220
                        }
221
                        s.Version = strconv.FormatUint(record.GetVersion(), 10)
42✔
222
                        sm.indexer.OnSessionCreated(&s)
42✔
223
                        continue
42✔
224
                }
225
                // Session was deleted; terminate all of its associated streams
226
                sm.indexer.OnSessionDeleted(record.Id)
3✔
227
                for streamID := range sm.sessionStreams[record.Id] {
6✔
228
                        log.Ctx(ctx).Debug().
3✔
229
                                Str("session-id", record.Id).
3✔
230
                                Uint64("stream-id", streamID).
3✔
231
                                Msg("terminating stream: session revoked")
3✔
232
                        sm.terminateStreamLocked(streamID)
3✔
233
                }
3✔
234
                delete(sm.sessionStreams, record.Id)
3✔
235
        }
236
}
237

238
func (sm *StreamManager) updateRecordsBinding(ctx context.Context, _ uint64, records []*databroker.Record) {
87✔
239
        sm.mu.Lock()
87✔
240
        defer sm.mu.Unlock()
87✔
241
        for _, record := range records {
133✔
242
                if record.DeletedAt == nil {
86✔
243
                        continue
40✔
244
                }
245
                // Session binding was deleted; terminate all of its associated streams
246
                for streamID := range sm.bindingStreams[record.Id] {
12✔
247
                        log.Ctx(ctx).Debug().
6✔
248
                                Str("session-id", record.Id).
6✔
249
                                Uint64("stream-id", streamID).
6✔
250
                                Msg("terminating stream: session binding revoked")
6✔
251
                        sm.terminateStreamLocked(streamID)
6✔
252
                }
6✔
253
                delete(sm.bindingStreams, record.Id)
6✔
254
        }
255
}
256

257
func (sm *StreamManager) OnStreamAuthenticated(ctx context.Context, streamID uint64, req AuthRequest) error {
45✔
258
        if err := sm.waitForInitialSync(ctx); err != nil {
45✔
259
                return err
×
260
        }
×
261
        sm.mu.Lock()
45✔
262
        defer sm.mu.Unlock()
45✔
263
        activeStream := sm.activeStreams[streamID]
45✔
264
        if activeStream.Session != nil || activeStream.SessionBindingID != nil {
45✔
265
                return status.Errorf(codes.Internal, "stream %d already has an associated session", streamID)
×
266
        }
×
267

268
        if sm.sessionStreams[req.SessionID] == nil {
89✔
269
                sm.sessionStreams[req.SessionID] = map[uint64]struct{}{}
44✔
270
        }
44✔
271
        if sm.bindingStreams[req.SessionBindingID] == nil {
87✔
272
                sm.bindingStreams[req.SessionBindingID] = map[uint64]struct{}{}
42✔
273
        }
42✔
274
        sm.sessionStreams[req.SessionID][streamID] = struct{}{}
45✔
275
        sm.bindingStreams[req.SessionBindingID][streamID] = struct{}{}
45✔
276

45✔
277
        activeStream.Session = new(string)
45✔
278
        *activeStream.Session = req.SessionID
45✔
279
        activeStream.SessionBindingID = new(string)
45✔
280
        *activeStream.SessionBindingID = req.SessionBindingID
45✔
281

45✔
282
        activeStream.PortForwardManager.AddUpdateListener(activeStream.Handler)
45✔
283

45✔
284
        sm.indexer.OnStreamAuthenticated(streamID, req)
45✔
285
        return nil
45✔
286
}
287

288
type bindingSyncer struct {
289
        clientHandler func() databroker.DataBrokerServiceClient
290
        clearHandler  func(context.Context)
291
        updateHandler func(context.Context, uint64, []*databroker.Record)
292
}
293

294
var _ databroker.SyncerHandler = (*bindingSyncer)(nil)
295

296
func (sbr *bindingSyncer) ClearRecords(ctx context.Context) {
41✔
297
        sbr.clearHandler(ctx)
41✔
298
}
41✔
299

300
// GetDataBrokerServiceClient implements databroker.SyncerHandler.
301
func (sbr *bindingSyncer) GetDataBrokerServiceClient() databroker.DataBrokerServiceClient {
99✔
302
        return sbr.clientHandler()
99✔
303
}
99✔
304

305
// UpdateRecords implements databroker.SyncerHandler.
306
func (sbr *bindingSyncer) UpdateRecords(ctx context.Context, serverVersion uint64, records []*databroker.Record) {
87✔
307
        sbr.updateHandler(ctx, serverVersion, records)
87✔
308
}
87✔
309

310
func NewStreamManager(ctx context.Context, auth AuthInterface, indexer PolicyIndexer, cfg *config.Config) *StreamManager {
146✔
311
        sm := &StreamManager{
146✔
312
                logger:                           log.Ctx(ctx),
146✔
313
                auth:                             auth,
146✔
314
                ready:                            make(chan struct{}),
146✔
315
                waitForInitialSessionSync:        make(chan struct{}),
146✔
316
                waitForInitialSessionBindingSync: make(chan struct{}),
146✔
317
                reauthC:                          make(chan struct{}, 1),
146✔
318
                cfg:                              cfg,
146✔
319
                activeStreams:                    map[uint64]*activeStream{},
146✔
320
                sessionStreams:                   map[string]map[uint64]struct{}{},
146✔
321
                clusterEndpoints:                 map[string]map[uint64]*extensions_ssh.EndpointMetadata{},
146✔
322
                edsCache:                         cache.NewLinearCache(resource.EndpointType),
146✔
323
                endpointsUpdateQueue:             make(chan streamEndpointsUpdate, 128),
146✔
324
                bindingStreams:                   map[string]map[uint64]struct{}{},
146✔
325
                indexer:                          indexer,
146✔
326
        }
146✔
327

146✔
328
        bindingSyncer := &bindingSyncer{
146✔
329
                clientHandler: sm.GetDataBrokerServiceClient,
146✔
330
                clearHandler:  sm.clearRecordsBinding,
146✔
331
                updateHandler: sm.updateRecordsBinding,
146✔
332
        }
146✔
333

146✔
334
        sm.bindingSyncer = bindingSyncer
146✔
335

146✔
336
        sm.indexer.ProcessConfigUpdate(cfg)
146✔
337
        return sm
146✔
338
}
146✔
339

340
func (sm *StreamManager) waitForInitialSync(ctx context.Context) error {
48✔
341
        sm.mu.Lock()
48✔
342
        for !sm.initialSessionSyncDone || !sm.initialSessionBindingSyncDone {
193✔
343
                sm.mu.Unlock()
145✔
344
                select {
145✔
345
                case <-sm.waitForInitialSessionSync:
145✔
UNCOV
346
                case <-sm.waitForInitialSessionBindingSync:
×
347
                case <-time.After(10 * time.Second):
×
348
                        return errors.New("timed out waiting for initial sync")
×
349
                case <-ctx.Done():
×
350
                        return context.Cause(ctx)
×
351
                }
352
                sm.mu.Lock()
145✔
353
        }
354
        sm.mu.Unlock()
48✔
355
        return nil
48✔
356
}
357

358
func (sm *StreamManager) Run(ctx context.Context) error {
40✔
359
        sm.edsServer = delta.NewServer(ctx, sm.edsCache, sm)
40✔
360
        eg, eCtx := errgroup.WithContext(ctx)
40✔
361
        eg.Go(func() error {
80✔
362
                syncer := databroker.NewSyncer(
40✔
363
                        eCtx,
40✔
364
                        "ssh-auth-session-sync",
40✔
365
                        sm,
40✔
366
                        databroker.WithTypeURL("type.googleapis.com/session.Session"))
40✔
367
                return syncer.Run(eCtx)
40✔
368
        })
40✔
369

370
        eg.Go(func() error {
80✔
371
                syncer := databroker.NewSyncer(
40✔
372
                        eCtx,
40✔
373
                        "ssh-auth-session-binding-sync",
40✔
374
                        sm.bindingSyncer,
40✔
375
                        databroker.WithTypeURL("type.googleapis.com/session.SessionBinding"),
40✔
376
                )
40✔
377
                return syncer.Run(eCtx)
40✔
378
        })
40✔
379

380
        eg.Go(func() error {
80✔
381
                sm.reauthLoop(eCtx)
40✔
382
                return ErrReauthDone
40✔
383
        })
40✔
384
        eg.Go(func() error {
80✔
385
                sm.endpointsUpdateLoop(ctx)
40✔
386
                return nil
40✔
387
        })
40✔
388

389
        close(sm.ready)
40✔
390
        err := eg.Wait()
40✔
391
        if errors.Is(err, ErrReauthDone) {
64✔
392
                return nil
24✔
393
        }
24✔
394

395
        return err
16✔
396
}
397

398
func (sm *StreamManager) OnConfigChange(cfg *config.Config) {
45✔
399
        sm.indexer.ProcessConfigUpdate(cfg)
45✔
400

45✔
401
        // TODO: integrate the re-auth mechanism with the indexer
45✔
402
        select {
45✔
403
        case sm.reauthC <- struct{}{}:
45✔
404
        default:
×
405
        }
406
}
407

408
func (sm *StreamManager) LookupStream(streamID uint64) *StreamHandler {
21✔
409
        sm.mu.Lock()
21✔
410
        defer sm.mu.Unlock()
21✔
411
        if info, ok := sm.activeStreams[streamID]; ok {
40✔
412
                return info.Handler
19✔
413
        }
19✔
414
        return nil
2✔
415
}
416

417
func (sm *StreamManager) NewStreamHandler(
418
        _ context.Context,
419
        downstream *extensions_ssh.DownstreamConnectEvent,
420
) *StreamHandler {
152✔
421
        sm.mu.Lock()
152✔
422
        defer sm.mu.Unlock()
152✔
423
        streamID := downstream.StreamId
152✔
424

152✔
425
        onClose := func() {
291✔
426
                sm.onStreamHandlerClosed(streamID)
139✔
427
        }
139✔
428
        discovery := &streamClusterEndpointDiscovery{
152✔
429
                self:     sm,
152✔
430
                streamID: streamID,
152✔
431
        }
152✔
432
        sh := NewStreamHandler(sm.auth, discovery, sm.cfg, downstream, onClose)
152✔
433
        portForwardMgr := portforward.NewManager()
152✔
434
        sm.activeStreams[streamID] = &activeStream{
152✔
435
                Handler:            sh,
152✔
436
                Endpoints:          map[string]struct{}{},
152✔
437
                PortForwardManager: portForwardMgr,
152✔
438
        }
152✔
439
        sm.indexer.AddStream(streamID, portForwardMgr)
152✔
440
        return sh
152✔
441
}
442

443
func (sm *StreamManager) onStreamHandlerClosed(streamID uint64) {
139✔
444
        sm.mu.Lock()
139✔
445
        defer sm.mu.Unlock()
139✔
446
        info := sm.activeStreams[streamID]
139✔
447
        delete(sm.activeStreams, streamID)
139✔
448

139✔
449
        info.PortForwardManager.RemoveUpdateListener(info.Handler)
139✔
450
        sm.indexer.RemoveStream(streamID)
139✔
451

139✔
452
        if info.Session != nil {
179✔
453
                session := *info.Session
40✔
454
                delete(sm.sessionStreams[session], streamID)
40✔
455
                if len(sm.sessionStreams[session]) == 0 {
80✔
456
                        delete(sm.sessionStreams, session)
40✔
457
                }
40✔
458
        }
459
        if info.SessionBindingID != nil {
179✔
460
                bindingID := *info.SessionBindingID
40✔
461
                delete(sm.bindingStreams[bindingID], streamID)
40✔
462
                if len(sm.bindingStreams[bindingID]) == 0 {
80✔
463
                        delete(sm.bindingStreams, bindingID)
40✔
464
                }
40✔
465
        }
466

467
        if len(info.Endpoints) > 0 {
141✔
468
                sm.logger.Debug().
2✔
469
                        Uint64("stream-id", streamID).
2✔
470
                        Any("endpoints", info.Endpoints).
2✔
471
                        Msg("clearing endpoints for closed stream")
2✔
472
                sm.endpointsUpdateQueue <- streamEndpointsUpdate{
2✔
473
                        streamID: streamID,
2✔
474
                        removed:  info.Endpoints,
2✔
475
                }
2✔
476
        }
2✔
477
}
478

479
func (sm *StreamManager) processStreamEndpointsUpdate(update streamEndpointsUpdate) {
57✔
480
        sm.mu.Lock()
57✔
481
        defer sm.mu.Unlock()
57✔
482
        streamID := update.streamID
57✔
483

57✔
484
        activeStream := sm.activeStreams[streamID] // can be nil
57✔
485

57✔
486
        toUpdate := map[string]types.Resource{} // *envoy_config_endpoint_v3.LbEndpoint
57✔
487
        var toDelete []string
57✔
488
        for clusterID, info := range update.added {
63✔
489
                if activeStream != nil {
12✔
490
                        activeStream.Endpoints[clusterID] = struct{}{}
6✔
491
                }
6✔
492
                if _, ok := sm.clusterEndpoints[clusterID]; !ok {
10✔
493
                        sm.clusterEndpoints[clusterID] = map[uint64]*extensions_ssh.EndpointMetadata{}
4✔
494
                }
4✔
495
                sm.clusterEndpoints[clusterID][streamID] = buildEndpointMetadata(info)
6✔
496
                toUpdate[clusterID] = buildClusterLoadAssignment(clusterID, sm.clusterEndpoints[clusterID])
6✔
497
        }
498
        for clusterID := range update.removed {
63✔
499
                if activeStream != nil {
10✔
500
                        delete(activeStream.Endpoints, clusterID)
4✔
501
                }
4✔
502
                delete(sm.clusterEndpoints[clusterID], streamID)
6✔
503
                if len(sm.clusterEndpoints[clusterID]) == 0 {
10✔
504
                        // No more endpoints for this cluster, so delete the resource. The cluster
4✔
505
                        // will handle this by clearing the endpoints.
4✔
506
                        toDelete = append(toDelete, clusterID)
4✔
507
                        delete(sm.clusterEndpoints, clusterID)
4✔
508
                } else {
6✔
509
                        // There are still endpoints
2✔
510
                        toUpdate[clusterID] = buildClusterLoadAssignment(clusterID, sm.clusterEndpoints[clusterID])
2✔
511
                }
2✔
512
        }
513

514
        if err := sm.edsCache.UpdateResources(toUpdate, toDelete); err != nil {
57✔
515
                sm.logger.Err(err).Msg("error updating EDS resources")
×
516
        }
×
517
}
518

519
func buildClusterLoadAssignment(clusterID string, clusterEndpoints map[uint64]*extensions_ssh.EndpointMetadata) types.Resource {
8✔
520
        endpoints := []*envoy_config_endpoint_v3.LbEndpoint{}
8✔
521
        for streamID, metadata := range clusterEndpoints {
18✔
522
                endpoints = append(endpoints, buildLbEndpoint(streamID, metadata))
10✔
523
        }
10✔
524
        slices.SortFunc(endpoints, compareEndpoints)
8✔
525
        return &envoy_config_endpoint_v3.ClusterLoadAssignment{
8✔
526
                ClusterName: clusterID,
8✔
527
                Endpoints:   []*envoy_config_endpoint_v3.LocalityLbEndpoints{{LbEndpoints: endpoints}},
8✔
528
        }
8✔
529
}
530

531
func compareEndpoints(a, b *envoy_config_endpoint_v3.LbEndpoint) int {
2✔
532
        return cmp.Compare(
2✔
533
                a.GetEndpoint().GetAddress().GetSocketAddress().GetAddress(),
2✔
534
                b.GetEndpoint().GetAddress().GetSocketAddress().GetAddress())
2✔
535
}
2✔
536

537
func buildEndpointMetadata(info portforward.RoutePortForwardInfo) *extensions_ssh.EndpointMetadata {
6✔
538
        serverPort := info.Permission.ServerPort()
6✔
539
        return &extensions_ssh.EndpointMetadata{
6✔
540
                ServerPort: &extensions_ssh.ServerPort{
6✔
541
                        Value:     serverPort.Value,
6✔
542
                        IsDynamic: serverPort.IsDynamic,
6✔
543
                },
6✔
544
                MatchedPermission: &extensions_ssh.PortForwardPermission{
6✔
545
                        RequestedHost: info.Permission.HostMatcher.InputPattern(),
6✔
546
                        RequestedPort: info.Permission.RequestedPort,
6✔
547
                },
6✔
548
        }
6✔
549
}
6✔
550

551
func buildLbEndpoint(streamID uint64, metadata *extensions_ssh.EndpointMetadata) *envoy_config_endpoint_v3.LbEndpoint {
10✔
552
        endpointMdAny, _ := anypb.New(metadata)
10✔
553
        return &envoy_config_endpoint_v3.LbEndpoint{
10✔
554
                HostIdentifier: &envoy_config_endpoint_v3.LbEndpoint_Endpoint{
10✔
555
                        Endpoint: &envoy_config_endpoint_v3.Endpoint{
10✔
556
                                Address: &corev3.Address{
10✔
557
                                        Address: &corev3.Address_SocketAddress{
10✔
558
                                                SocketAddress: &corev3.SocketAddress{
10✔
559
                                                        Address: fmt.Sprintf("ssh:%d", streamID),
10✔
560
                                                        PortSpecifier: &corev3.SocketAddress_PortValue{
10✔
561
                                                                PortValue: metadata.ServerPort.Value,
10✔
562
                                                        },
10✔
563
                                                },
10✔
564
                                        },
10✔
565
                                },
10✔
566
                        },
10✔
567
                },
10✔
568
                Metadata: &corev3.Metadata{
10✔
569
                        TypedFilterMetadata: map[string]*anypb.Any{
10✔
570
                                "com.pomerium.ssh.endpoint": endpointMdAny,
10✔
571
                        },
10✔
572
                },
10✔
573
                HealthStatus: corev3.HealthStatus_HEALTHY,
10✔
574
        }
10✔
575
}
10✔
576

577
func (sm *StreamManager) reauthLoop(ctx context.Context) {
40✔
578
        for {
125✔
579
                select {
85✔
580
                case <-ctx.Done():
40✔
581
                        return
40✔
582
                case <-sm.reauthC:
45✔
583
                        sm.mu.Lock()
45✔
584
                        snapshot := make([]*activeStream, 0, len(sm.activeStreams))
45✔
585
                        for _, s := range sm.activeStreams {
55✔
586
                                snapshot = append(snapshot, s)
10✔
587
                        }
10✔
588
                        sm.mu.Unlock()
45✔
589

45✔
590
                        for _, s := range snapshot {
55✔
591
                                s.Handler.Reauth()
10✔
592
                        }
10✔
593
                }
594
        }
595
}
596

597
func (sm *StreamManager) endpointsUpdateLoop(ctx context.Context) {
40✔
598
        for {
137✔
599
                select {
97✔
600
                case <-ctx.Done():
40✔
601
                        return
40✔
602
                case update := <-sm.endpointsUpdateQueue:
57✔
603
                        sm.processStreamEndpointsUpdate(update)
57✔
604
                }
605
        }
606
}
607

608
func (sm *StreamManager) terminateStreamLocked(streamID uint64) {
13✔
609
        if sh, ok := sm.activeStreams[streamID]; ok {
26✔
610
                sh.Handler.Terminate(status.Errorf(codes.PermissionDenied, "no longer authorized"))
13✔
611
        }
13✔
612
}
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