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

pomerium / pomerium / 20144099951

11 Dec 2025 06:57PM UTC coverage: 52.95% (+0.09%) from 52.864%
20144099951

push

github

web-flow
authorize: fix two bugs in upstream policy (#5981)

Attempting to evaluate the upstream policy for a tunnel route without an
ssh_policy would result in an error. Handle this case gracefully (return
a result with both "allow: false" and "deny: false", to match the result
of regular policy evaluation).

Make sure to set the ReverseTunnel field to true for upstream policy
evaluation.

Add a unit test exercising both of these issues.

6 of 6 new or added lines in 2 files covered. (100.0%)

11 existing lines in 2 files now uncovered.

29450 of 55618 relevant lines covered (52.95%)

128.2 hits per line

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

87.2
/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{}) {
54✔
48
        // run this callback in a separate goroutine, since it can deadlock if called
54✔
49
        // synchronously during startup
54✔
50
        ed.self.endpointsUpdateQueue <- streamEndpointsUpdate{
54✔
51
                streamID: ed.streamID,
54✔
52
                added:    added,
54✔
53
                removed:  removed,
54✔
54
        }
54✔
55
}
54✔
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 {
291✔
164
                sm.initialSessionSyncDone = true
145✔
165
                close(sm.waitForInitialSessionSync)
145✔
166
                log.Ctx(ctx).Debug().
145✔
167
                        Msg("ssh stream manager: initial sync done")
145✔
168
                return
145✔
169
        }
145✔
170
        for sessionID, streamIDs := range sm.sessionStreams {
3✔
171
                for streamID := range streamIDs {
4✔
172
                        log.Ctx(ctx).Debug().
2✔
173
                                Str("session-id", sessionID).
2✔
174
                                Uint64("stream-id", streamID).
2✔
175
                                Msg("terminating stream: databroker sync reset")
2✔
176
                        sm.terminateStreamLocked(streamID)
2✔
177
                }
2✔
178
        }
179
        clear(sm.sessionStreams)
1✔
180
}
181

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

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

209
// UpdateRecords implements databroker.SyncerHandler.
210
func (sm *StreamManager) UpdateRecords(ctx context.Context, _ uint64, records []*databroker.Record) {
83✔
211
        sm.mu.Lock()
83✔
212
        defer sm.mu.Unlock()
83✔
213
        for _, record := range records {
126✔
214
                if record.DeletedAt == nil {
84✔
215
                        // New session
41✔
216
                        var s session.Session
41✔
217
                        if err := record.Data.UnmarshalTo(&s); err != nil {
41✔
218
                                log.Ctx(ctx).Err(err).Msg("invalid session object, ignoring")
×
219
                                continue
×
220
                        }
221
                        s.Version = strconv.FormatUint(record.GetVersion(), 10)
41✔
222
                        sm.indexer.OnSessionCreated(&s)
41✔
223
                        continue
41✔
224
                }
225
                // Session was deleted; terminate all of its associated streams
226
                sm.indexer.OnSessionDeleted(record.Id)
2✔
227
                for streamID := range sm.sessionStreams[record.Id] {
5✔
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)
2✔
235
        }
236
}
237

238
func (sm *StreamManager) updateRecordsBinding(ctx context.Context, _ uint64, records []*databroker.Record) {
84✔
239
        sm.mu.Lock()
84✔
240
        defer sm.mu.Unlock()
84✔
241
        for _, record := range records {
129✔
242
                if record.DeletedAt == nil {
84✔
243
                        continue
39✔
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 {
44✔
258
        if err := sm.waitForInitialSync(ctx); err != nil {
44✔
259
                return err
×
260
        }
×
261
        sm.mu.Lock()
44✔
262
        defer sm.mu.Unlock()
44✔
263
        activeStream := sm.activeStreams[streamID]
44✔
264
        if activeStream.Session != nil || activeStream.SessionBindingID != nil {
44✔
265
                return status.Errorf(codes.Internal, "stream %d already has an associated session", streamID)
×
266
        }
×
267

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

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

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

44✔
284
        sm.indexer.OnStreamAuthenticated(streamID, req)
44✔
285
        return nil
44✔
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) {
39✔
297
        sbr.clearHandler(ctx)
39✔
298
}
39✔
299

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

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

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

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

145✔
334
        sm.bindingSyncer = bindingSyncer
145✔
335

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

340
func (sm *StreamManager) waitForInitialSync(ctx context.Context) error {
47✔
341
        sm.mu.Lock()
47✔
342
        for !sm.initialSessionSyncDone || !sm.initialSessionBindingSyncDone {
2,061✔
343
                sm.mu.Unlock()
2,014✔
344
                select {
2,014✔
345
                case <-sm.waitForInitialSessionSync:
1,141✔
346
                case <-sm.waitForInitialSessionBindingSync:
873✔
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()
2,014✔
353
        }
354
        sm.mu.Unlock()
47✔
355
        return nil
47✔
356
}
357

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

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

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

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

395
        return err
18✔
396
}
397

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

44✔
401
        // TODO: integrate the re-auth mechanism with the indexer
44✔
402
        select {
44✔
403
        case sm.reauthC <- struct{}{}:
44✔
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 {
151✔
421
        sm.mu.Lock()
151✔
422
        defer sm.mu.Unlock()
151✔
423
        streamID := downstream.StreamId
151✔
424

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

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

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

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

467
        if len(info.Endpoints) > 0 {
140✔
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) {
56✔
480
        sm.mu.Lock()
56✔
481
        defer sm.mu.Unlock()
56✔
482
        streamID := update.streamID
56✔
483

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

56✔
486
        toUpdate := map[string]types.Resource{} // *envoy_config_endpoint_v3.LbEndpoint
56✔
487
        var toDelete []string
56✔
488
        for clusterID, info := range update.added {
62✔
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 {
62✔
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 {
56✔
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) {
39✔
578
        for {
122✔
579
                select {
83✔
580
                case <-ctx.Done():
39✔
581
                        return
39✔
582
                case <-sm.reauthC:
44✔
583
                        sm.mu.Lock()
44✔
584
                        snapshot := make([]*activeStream, 0, len(sm.activeStreams))
44✔
585
                        for _, s := range sm.activeStreams {
54✔
586
                                snapshot = append(snapshot, s)
10✔
587
                        }
10✔
588
                        sm.mu.Unlock()
44✔
589

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

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

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