-
Notifications
You must be signed in to change notification settings - Fork 51
/
serviceregistry.go
349 lines (299 loc) · 10.6 KB
/
serviceregistry.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package serviceregistry
import (
"crypto/x509"
"fmt"
"net"
"sync"
"go.aporeto.io/tg/tglib"
"go.aporeto.io/trireme-lib/controller/internal/enforcer/applicationproxy/common"
"go.aporeto.io/trireme-lib/controller/internal/enforcer/applicationproxy/servicecache"
"go.aporeto.io/trireme-lib/controller/pkg/auth"
"go.aporeto.io/trireme-lib/controller/pkg/pucontext"
"go.aporeto.io/trireme-lib/controller/pkg/secrets"
"go.aporeto.io/trireme-lib/controller/pkg/urisearch"
"go.aporeto.io/trireme-lib/policy"
)
// ServiceContext includes all the all the service related information
// for dependent services. It is indexed by the PU ID and a PU can
// easily retrieve all the state with a simple lookup. Note, that
// there is one ServiceContext for every PU.
type ServiceContext struct {
PU *policy.PUInfo
PUContext *pucontext.PUContext
RootCA [][]byte
// The dependent service cache is only accessible internally,
// so that all types are properly converted.
dependentServiceCache *servicecache.ServiceCache
}
// DependentServiceData are the data that are held for each service
// in the dependentServiceCache.
type DependentServiceData struct {
// Used for authorization
APICache *urisearch.APICache
// Used by the protomux to find the right service type.
ServiceType common.ListenerType
}
// PortContext includes all the needed associations to refer to a service by port.
// For incoming connections the only available information is the IP/port
// pair of the original request and we use this to map the connection and
// request to a port. For network services we have additional state data
// such as the authorizers. Note that there is one PortContext for every
// service of every PU.
type PortContext struct {
ID string
Type common.ListenerType
Service *policy.ApplicationService
Authorizer *auth.Processor
PUContext *pucontext.PUContext
TargetPort int
ClientTrustedRoots *x509.CertPool
}
// Registry is a service registry. It maintains all the state information
// and provides a simple API to retrieve the data. The registry always
// locks and allows multi-threading.
type Registry struct {
indexByName map[string]*ServiceContext
indexByPort *servicecache.ServiceCache
sync.Mutex
}
// NewServiceRegistry creates and initializes the registry.
func NewServiceRegistry() *Registry {
return &Registry{
indexByName: map[string]*ServiceContext{},
indexByPort: servicecache.NewTable(),
}
}
// Register registers a new service with the registry. If the service
// already exists it updates the service with the new information, otherwise
// it creates a new service.
func (r *Registry) Register(
puID string,
pu *policy.PUInfo,
puContext *pucontext.PUContext,
secrets secrets.Secrets,
) (*ServiceContext, error) {
r.Lock()
defer r.Unlock()
sctx := &ServiceContext{
PU: pu,
PUContext: puContext,
dependentServiceCache: servicecache.NewTable(),
RootCA: [][]byte{},
}
// Delete all old references first. Since the registry is locked
// nobody will be affected.
r.indexByPort.DeleteByID(puID, true)
r.indexByPort.DeleteByID(puID, false)
if err := r.updateDependentServices(sctx); err != nil {
return nil, err
}
if err := r.updateExposedServices(sctx, secrets); err != nil {
return nil, err
}
r.indexByName[puID] = sctx
return sctx, nil
}
// Unregister unregisters a pu from the registry.
func (r *Registry) Unregister(puID string) error {
r.Lock()
defer r.Unlock()
delete(r.indexByName, puID)
r.indexByPort.DeleteByID(puID, true)
r.indexByPort.DeleteByID(puID, false)
return nil
}
// RetrieveServiceByID retrieves a service by the PU ID. Returns error if not found.
func (r *Registry) RetrieveServiceByID(id string) (*ServiceContext, error) {
r.Lock()
defer r.Unlock()
svc, ok := r.indexByName[id]
if !ok {
return nil, fmt.Errorf("Service not found: %s", id)
}
return svc, nil
}
// RetrieveExposedServiceContext retrieves a service by the provided IP and or port. This
// is called by the network side of processing to find the context.
func (r *Registry) RetrieveExposedServiceContext(ip net.IP, port int, host string) (*PortContext, error) {
r.Lock()
defer r.Unlock()
data := r.indexByPort.Find(ip, port, host, true)
if data == nil {
return nil, fmt.Errorf("Service information not found: %s %d %s", ip.String(), port, host)
}
portContext, ok := data.(*PortContext)
if !ok {
return nil, fmt.Errorf("Internal server error")
}
return portContext, nil
}
// RetrieveServiceDataByIDAndNetwork will return the service data that match the given
// PU and the given IP/port information.
func (r *Registry) RetrieveServiceDataByIDAndNetwork(id string, ip net.IP, port int, host string) (*ServiceContext, *DependentServiceData, error) {
sctx, err := r.RetrieveServiceByID(id)
if err != nil {
return nil, nil, fmt.Errorf("Services for PU %s not found: %s", id, err)
}
data := sctx.dependentServiceCache.Find(ip, port, "", false)
if data == nil {
return nil, nil, fmt.Errorf("Service not found for this PU: %s", id)
}
serviceData, ok := data.(*DependentServiceData)
if !ok {
return nil, nil, fmt.Errorf("Internal server error - bad data types")
}
return sctx, serviceData, nil
}
// updateExposedPortAssociations will insert the association between a port
// and a service in the global exposed service cache. This is needed
// for all incoming connections, so that can determine both the type
// of proxy as well the correct policy for this connection. This
// association cannot have overlaps.
func (r *Registry) updateExposedPortAssociations(sctx *ServiceContext, service *policy.ApplicationService, secrets secrets.Secrets) error {
// Do All the basic validations first.
if service.PrivateNetworkInfo == nil {
return fmt.Errorf("Private network is required for exposed services")
}
port, err := service.PrivateNetworkInfo.Ports.SinglePort()
if err != nil {
return fmt.Errorf("Multi-port is not supported for exposed services: %s", err)
}
if service.PublicNetworkInfo != nil {
if _, err := service.PublicNetworkInfo.Ports.SinglePort(); err != nil {
return fmt.Errorf("Multi-port is not supported for public network services: %s", err)
}
}
// Find any existing state and get the authorizer. We do not want
// to re-initialize the authorizer for every policy update.
authProcessor, err := r.createOrUpdateAuthProcessor(sctx, service, secrets)
if err != nil {
return err
}
clientCAs := x509.NewCertPool()
if (service.UserAuthorizationType == policy.UserAuthorizationMutualTLS || service.UserAuthorizationType == policy.UserAuthorizationJWT) &&
len(service.MutualTLSTrustedRoots) > 0 {
if !clientCAs.AppendCertsFromPEM(service.MutualTLSTrustedRoots) {
return fmt.Errorf("Unable to process client CAs")
}
}
// Add the new references.
if err := r.indexByPort.Add(
service.PrivateNetworkInfo,
sctx.PU.ContextID,
&PortContext{
ID: sctx.PU.ContextID,
Service: service,
TargetPort: int(port),
Type: serviceTypeToNetworkListenerType(service.Type, false),
Authorizer: authProcessor,
ClientTrustedRoots: clientCAs,
PUContext: sctx.PUContext,
},
true,
); err != nil {
return fmt.Errorf("Possible port overlap: %s", err)
}
if service.Type == policy.ServiceHTTP && service.PublicNetworkInfo != nil {
if err := r.indexByPort.Add(
service.PublicNetworkInfo,
sctx.PU.ContextID,
&PortContext{
ID: sctx.PU.ContextID,
Service: service,
TargetPort: int(port),
Type: serviceTypeToNetworkListenerType(service.Type, service.PublicServiceNoTLS),
Authorizer: authProcessor,
ClientTrustedRoots: clientCAs,
PUContext: sctx.PUContext,
},
true,
); err != nil {
return fmt.Errorf("Possible port overlap with public services: %s", err)
}
}
return nil
}
// buildExposedServices builds the caches for the exposed services. It assumes that an authorization
func (r *Registry) updateExposedServices(sctx *ServiceContext, secrets secrets.Secrets) error {
for _, service := range sctx.PU.Policy.ExposedServices() {
if service.Type != policy.ServiceHTTP && service.Type != policy.ServiceTCP {
continue
}
if err := r.updateExposedPortAssociations(sctx, service, secrets); err != nil {
return err
}
}
return nil
}
// updateDependentServices will update all the information in the
// ServiceContext for the dependent services.
func (r *Registry) updateDependentServices(sctx *ServiceContext) error {
for _, service := range sctx.PU.Policy.DependentServices() {
if len(service.CACert) != 0 {
sctx.RootCA = append(sctx.RootCA, service.CACert)
}
serviceData := &DependentServiceData{
ServiceType: serviceTypeToApplicationListenerType(service.Type),
}
if service.Type == policy.ServiceHTTP {
serviceData.APICache = urisearch.NewAPICache(service.HTTPRules, service.ID, service.External)
}
if err := sctx.dependentServiceCache.Add(
service.NetworkInfo,
sctx.PU.ContextID,
serviceData,
false,
); err != nil {
return fmt.Errorf("Possible overlap in dependent services: %s", err)
}
}
return nil
}
func (r *Registry) createOrUpdateAuthProcessor(sctx *ServiceContext, service *policy.ApplicationService, secrets secrets.Secrets) (*auth.Processor, error) {
var cert *x509.Certificate
if len(service.FallbackJWTAuthorizationCert) > 0 {
var err error
cert, err = tglib.ParseCertificate([]byte(service.FallbackJWTAuthorizationCert))
if err != nil {
return nil, err
}
}
portContext, _ := r.indexByPort.FindListeningServicesForPU(sctx.PU.ContextID)
var authProcessor *auth.Processor
if portContext != nil {
existingPortCtx, ok := portContext.(*PortContext)
if !ok {
return nil, fmt.Errorf("Internal error - unusable data structure")
}
authProcessor = existingPortCtx.Authorizer
authProcessor.UpdateSecrets(secrets, cert)
} else {
authProcessor = auth.NewProcessor(secrets, cert)
}
authProcessor.AddOrUpdateService(
urisearch.NewAPICache(service.HTTPRules, service.ID, false),
service.UserAuthorizationType,
service.UserAuthorizationHandler,
service.UserTokenToHTTPMappings,
)
return authProcessor, nil
}
func serviceTypeToNetworkListenerType(serviceType policy.ServiceType, noTLS bool) common.ListenerType {
switch serviceType {
case policy.ServiceHTTP:
if noTLS {
return common.HTTPNetwork
}
return common.HTTPSNetwork
default:
return common.TCPNetwork
}
}
func serviceTypeToApplicationListenerType(serviceType policy.ServiceType) common.ListenerType {
switch serviceType {
case policy.ServiceHTTP:
return common.HTTPApplication
default:
return common.TCPApplication
}
}