-
Notifications
You must be signed in to change notification settings - Fork 301
/
gateway_registry.go
467 lines (429 loc) · 15.9 KB
/
gateway_registry.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// Copyright © 2019 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package identityserver
import (
"context"
"github.com/gogo/protobuf/types"
"github.com/jinzhu/gorm"
"go.thethings.network/lorawan-stack/v3/pkg/auth/rights"
"go.thethings.network/lorawan-stack/v3/pkg/errors"
"go.thethings.network/lorawan-stack/v3/pkg/events"
"go.thethings.network/lorawan-stack/v3/pkg/identityserver/blacklist"
"go.thethings.network/lorawan-stack/v3/pkg/identityserver/store"
"go.thethings.network/lorawan-stack/v3/pkg/log"
"go.thethings.network/lorawan-stack/v3/pkg/ttnpb"
)
var (
evtCreateGateway = events.Define(
"gateway.create", "create gateway",
events.WithVisibility(ttnpb.RIGHT_GATEWAY_INFO),
events.WithAuthFromContext(),
events.WithClientInfoFromContext(),
)
evtUpdateGateway = events.Define(
"gateway.update", "update gateway",
events.WithVisibility(ttnpb.RIGHT_GATEWAY_INFO),
events.WithUpdatedFieldsDataType(),
events.WithAuthFromContext(),
events.WithClientInfoFromContext(),
)
evtDeleteGateway = events.Define(
"gateway.delete", "delete gateway",
events.WithVisibility(ttnpb.RIGHT_GATEWAY_INFO),
events.WithAuthFromContext(),
events.WithClientInfoFromContext(),
)
evtPurgeGateway = events.Define(
"gateway.purge", "purge gateway",
events.WithVisibility(ttnpb.RIGHT_GATEWAY_INFO),
events.WithAuthFromContext(),
events.WithClientInfoFromContext(),
)
)
var (
errAdminsCreateGateways = errors.DefinePermissionDenied("admins_create_gateways", "gateways may only be created by admins, or in organizations")
errGatewayEUITaken = errors.DefineAlreadyExists("gateway_eui_taken", "a gateway with EUI `{gateway_eui}` is already registered as `{gateway_id}`")
errGatewaySecretEncryptionKey = errors.DefineNotFound("gateway_secret_encryption_key_not_found", "a gateway secret encryption key with id `{id}` not found")
errAdminsPurgeGateways = errors.DefinePermissionDenied("admins_purge_gateways", "gateways may only be purged by admins")
)
func (is *IdentityServer) createGateway(ctx context.Context, req *ttnpb.CreateGatewayRequest) (gtw *ttnpb.Gateway, err error) {
if err = blacklist.Check(ctx, req.GatewayID); err != nil {
return nil, err
}
if usrIDs := req.Collaborator.GetUserIDs(); usrIDs != nil {
if !is.IsAdmin(ctx) && !is.configFromContext(ctx).UserRights.CreateGateways {
return nil, errAdminsCreateGateways
}
if err = rights.RequireUser(ctx, *usrIDs, ttnpb.RIGHT_USER_GATEWAYS_CREATE); err != nil {
return nil, err
}
} else if orgIDs := req.Collaborator.GetOrganizationIDs(); orgIDs != nil {
if err = rights.RequireOrganization(ctx, *orgIDs, ttnpb.RIGHT_ORGANIZATION_GATEWAYS_CREATE); err != nil {
return nil, err
}
}
if err := validateContactInfo(req.Gateway.ContactInfo); err != nil {
return nil, err
}
if len(req.FrequencyPlanIDs) == 0 && req.FrequencyPlanID != "" {
req.FrequencyPlanIDs = []string{req.FrequencyPlanID}
}
if req.LBSLNSSecret != nil {
value := req.LBSLNSSecret.Value
if is.config.Gateways.EncryptionKeyID != "" {
value, err = is.KeyVault.Encrypt(ctx, req.LBSLNSSecret.Value, is.config.Gateways.EncryptionKeyID)
if err != nil {
return nil, err
}
} else {
log.FromContext(ctx).Warn("No encryption key defined, storing as plaintext")
}
req.LBSLNSSecret.Value = value
req.LBSLNSSecret.KeyID = is.config.Gateways.EncryptionKeyID
}
err = is.withDatabase(ctx, func(db *gorm.DB) (err error) {
gtw, err = store.GetGatewayStore(db).CreateGateway(ctx, &req.Gateway)
if err != nil {
return err
}
if err = is.getMembershipStore(ctx, db).SetMember(
ctx,
&req.Collaborator,
gtw.GatewayIdentifiers,
ttnpb.RightsFrom(ttnpb.RIGHT_ALL),
); err != nil {
return err
}
if len(req.ContactInfo) > 0 {
cleanContactInfo(req.ContactInfo)
gtw.ContactInfo, err = store.GetContactInfoStore(db).SetContactInfo(ctx, gtw.GatewayIdentifiers, req.ContactInfo)
if err != nil {
return err
}
}
return nil
})
if err != nil {
if errors.IsAlreadyExists(err) && errors.Resemble(err, store.ErrEUITaken) {
if ids, err := is.getGatewayIdentifiersForEUI(ctx, &ttnpb.GetGatewayIdentifiersForEUIRequest{
EUI: *req.EUI,
}); err == nil {
return nil, errGatewayEUITaken.WithAttributes(
"gateway_eui", req.EUI.String(),
"gateway_id", ids.GetGatewayID(),
)
}
}
return nil, err
}
events.Publish(evtCreateGateway.NewWithIdentifiersAndData(ctx, req.GatewayIdentifiers, nil))
return gtw, nil
}
func (is *IdentityServer) getGateway(ctx context.Context, req *ttnpb.GetGatewayRequest) (gtw *ttnpb.Gateway, err error) {
if err = is.RequireAuthenticated(ctx); err != nil {
return nil, err
}
// Backwards compatibility for frequency_plan_id field.
if ttnpb.HasAnyField(req.FieldMask.Paths, "frequency_plan_id") {
if !ttnpb.HasAnyField(req.FieldMask.Paths, "frequency_plan_ids") {
req.FieldMask.Paths = append(req.FieldMask.Paths, "frequency_plan_ids")
}
}
req.FieldMask.Paths = cleanFieldMaskPaths(ttnpb.GatewayFieldPathsNested, req.FieldMask.Paths, getPaths, []string{"frequency_plan_id"})
if err = rights.RequireGateway(ctx, req.GatewayIdentifiers, ttnpb.RIGHT_GATEWAY_INFO); err != nil {
if ttnpb.HasOnlyAllowedFields(req.FieldMask.Paths, ttnpb.PublicGatewayFields...) {
defer func() { gtw = gtw.PublicSafe() }()
} else {
return nil, err
}
}
if ttnpb.HasAnyField(req.FieldMask.Paths, "lbs_lns_secret") {
if err = rights.RequireGateway(ctx, req.GatewayIdentifiers, ttnpb.RIGHT_GATEWAY_READ_SECRETS); err != nil {
return nil, err
}
}
err = is.withDatabase(ctx, func(db *gorm.DB) (err error) {
gtw, err = store.GetGatewayStore(db).GetGateway(ctx, &req.GatewayIdentifiers, &req.FieldMask)
if err != nil {
return err
}
if ttnpb.HasAnyField(req.FieldMask.Paths, "contact_info") {
gtw.ContactInfo, err = store.GetContactInfoStore(db).GetContactInfo(ctx, gtw.GatewayIdentifiers)
if err != nil {
return err
}
}
return err
})
if err != nil {
return nil, err
}
if gtw.LBSLNSSecret != nil {
value := gtw.LBSLNSSecret.Value
if gtw.LBSLNSSecret.KeyID != "" {
value, err = is.KeyVault.Decrypt(ctx, gtw.LBSLNSSecret.Value, gtw.LBSLNSSecret.KeyID)
if err != nil {
return nil, err
}
} else {
log.FromContext(ctx).Warn("No encryption key defined, returning stored value")
}
gtw.LBSLNSSecret.Value = value
gtw.LBSLNSSecret.KeyID = is.config.Gateways.EncryptionKeyID
}
// Backwards compatibility for frequency_plan_id field.
if len(gtw.FrequencyPlanIDs) > 0 {
gtw.FrequencyPlanID = gtw.FrequencyPlanIDs[0]
}
return gtw, nil
}
func (is *IdentityServer) getGatewayIdentifiersForEUI(ctx context.Context, req *ttnpb.GetGatewayIdentifiersForEUIRequest) (ids *ttnpb.GatewayIdentifiers, err error) {
if err = is.RequireAuthenticated(ctx); err != nil {
return nil, err
}
err = is.withDatabase(ctx, func(db *gorm.DB) (err error) {
gtw, err := store.GetGatewayStore(db).GetGateway(ctx, &ttnpb.GatewayIdentifiers{
EUI: &req.EUI,
}, &types.FieldMask{Paths: []string{"ids.gateway_id", "ids.eui"}})
if err != nil {
return err
}
ids = >w.GatewayIdentifiers
return nil
})
if err != nil {
return nil, err
}
return ids, nil
}
func (is *IdentityServer) listGateways(ctx context.Context, req *ttnpb.ListGatewaysRequest) (gtws *ttnpb.Gateways, err error) {
// Backwards compatibility for frequency_plan_id field.
if ttnpb.HasAnyField(req.FieldMask.Paths, "frequency_plan_id") {
if !ttnpb.HasAnyField(req.FieldMask.Paths, "frequency_plan_ids") {
req.FieldMask.Paths = append(req.FieldMask.Paths, "frequency_plan_ids")
}
}
req.FieldMask.Paths = cleanFieldMaskPaths(ttnpb.GatewayFieldPathsNested, req.FieldMask.Paths, getPaths, []string{"frequency_plan_id"})
var includeIndirect bool
if req.Collaborator == nil {
authInfo, err := is.authInfo(ctx)
if err != nil {
return nil, err
}
collaborator := authInfo.GetOrganizationOrUserIdentifiers()
if collaborator == nil {
return &ttnpb.Gateways{}, nil
}
req.Collaborator = collaborator
includeIndirect = true
}
if usrIDs := req.Collaborator.GetUserIDs(); usrIDs != nil {
if err = rights.RequireUser(ctx, *usrIDs, ttnpb.RIGHT_USER_GATEWAYS_LIST); err != nil {
return nil, err
}
} else if orgIDs := req.Collaborator.GetOrganizationIDs(); orgIDs != nil {
if err = rights.RequireOrganization(ctx, *orgIDs, ttnpb.RIGHT_ORGANIZATION_GATEWAYS_LIST); err != nil {
return nil, err
}
}
ctx = store.WithOrder(ctx, req.Order)
var total uint64
paginateCtx := store.WithPagination(ctx, req.Limit, req.Page, &total)
defer func() {
if err == nil {
setTotalHeader(ctx, total)
}
}()
gtws = &ttnpb.Gateways{}
err = is.withDatabase(ctx, func(db *gorm.DB) error {
ids, err := is.getMembershipStore(ctx, db).FindMemberships(paginateCtx, req.Collaborator, "gateway", includeIndirect)
if err != nil {
return err
}
if len(ids) == 0 {
return nil
}
gtwIDs := make([]*ttnpb.GatewayIdentifiers, 0, len(ids))
for _, id := range ids {
if gtwID := id.EntityIdentifiers().GetGatewayIDs(); gtwID != nil {
gtwIDs = append(gtwIDs, gtwID)
}
}
gtws.Gateways, err = store.GetGatewayStore(db).FindGateways(ctx, gtwIDs, &req.FieldMask)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
for i, gtw := range gtws.Gateways {
// Backwards compatibility for frequency_plan_id field.
if len(gtw.FrequencyPlanIDs) > 0 {
gtw.FrequencyPlanID = gtw.FrequencyPlanIDs[0]
}
if rights.RequireGateway(ctx, gtw.GatewayIdentifiers, ttnpb.RIGHT_GATEWAY_INFO) != nil {
gtws.Gateways[i] = gtw.PublicSafe()
}
if ttnpb.HasAnyField(req.FieldMask.Paths, "lbs_lns_secret") {
if rights.RequireGateway(ctx, gtw.GatewayIdentifiers, ttnpb.RIGHT_GATEWAY_READ_SECRETS) != nil {
gtws.Gateways[i].LBSLNSSecret = nil
} else if gtws.Gateways[i].LBSLNSSecret != nil {
value := gtws.Gateways[i].LBSLNSSecret.Value
if gtws.Gateways[i].LBSLNSSecret.KeyID != "" {
value, err = is.KeyVault.Decrypt(ctx, gtws.Gateways[i].LBSLNSSecret.Value, gtws.Gateways[i].LBSLNSSecret.KeyID)
if err != nil {
return nil, err
}
} else {
logger := log.FromContext(ctx)
logger.Warn("No encryption key defined, returning stored value")
}
gtws.Gateways[i].LBSLNSSecret.Value = value
gtws.Gateways[i].LBSLNSSecret.KeyID = is.config.Gateways.EncryptionKeyID
}
}
}
return gtws, nil
}
func (is *IdentityServer) updateGateway(ctx context.Context, req *ttnpb.UpdateGatewayRequest) (gtw *ttnpb.Gateway, err error) {
if err = rights.RequireGateway(ctx, req.GatewayIdentifiers, ttnpb.RIGHT_GATEWAY_SETTINGS_BASIC); err != nil {
// Allow setting only the location field with the RIGHT_GATEWAY_LINK right.
isLink := rights.RequireGateway(ctx, req.GatewayIdentifiers, ttnpb.RIGHT_GATEWAY_LINK) == nil
if topLevel := ttnpb.TopLevelFields(req.FieldMask.Paths); !isLink || len(topLevel) != 1 || topLevel[0] != "antennas" {
return nil, err
}
}
// Backwards compatibility for frequency_plan_id field.
if ttnpb.HasAnyField(req.FieldMask.Paths, "frequency_plan_id") {
if !ttnpb.HasAnyField(req.FieldMask.Paths, "frequency_plan_ids") {
req.FieldMask.Paths = append(req.FieldMask.Paths, "frequency_plan_ids")
}
}
if len(req.FrequencyPlanIDs) == 0 && req.FrequencyPlanID != "" {
req.FrequencyPlanIDs = []string{req.FrequencyPlanID}
}
req.FieldMask.Paths = cleanFieldMaskPaths(ttnpb.GatewayFieldPathsNested, req.FieldMask.Paths, nil, append(getPaths, "frequency_plan_id"))
if len(req.FieldMask.Paths) == 0 {
req.FieldMask.Paths = updatePaths
}
if ttnpb.HasAnyField(req.FieldMask.Paths, "contact_info") {
if err := validateContactInfo(req.Gateway.ContactInfo); err != nil {
return nil, err
}
}
if ttnpb.HasAnyField(req.FieldMask.Paths, "lbs_lns_secret") {
if err := rights.RequireGateway(ctx, req.GatewayIdentifiers, ttnpb.RIGHT_GATEWAY_WRITE_SECRETS); err != nil {
return nil, err
} else if req.LBSLNSSecret != nil {
value := req.LBSLNSSecret.Value
if is.config.Gateways.EncryptionKeyID != "" {
value, err = is.KeyVault.Encrypt(ctx, req.LBSLNSSecret.Value, is.config.Gateways.EncryptionKeyID)
if err != nil {
return nil, err
}
} else {
logger := log.FromContext(ctx)
logger.Warn("No encryption key defined, storing as plaintext")
}
req.LBSLNSSecret.Value = value
req.LBSLNSSecret.KeyID = is.config.Gateways.EncryptionKeyID
}
}
err = is.withDatabase(ctx, func(db *gorm.DB) (err error) {
gtw, err = store.GetGatewayStore(db).UpdateGateway(ctx, &req.Gateway, &req.FieldMask)
if err != nil {
return err
}
if ttnpb.HasAnyField(req.FieldMask.Paths, "contact_info") {
cleanContactInfo(req.ContactInfo)
gtw.ContactInfo, err = store.GetContactInfoStore(db).SetContactInfo(ctx, gtw.GatewayIdentifiers, req.ContactInfo)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, err
}
events.Publish(evtUpdateGateway.NewWithIdentifiersAndData(ctx, req.GatewayIdentifiers, req.FieldMask.Paths))
return gtw, nil
}
func (is *IdentityServer) deleteGateway(ctx context.Context, ids *ttnpb.GatewayIdentifiers) (*types.Empty, error) {
if err := rights.RequireGateway(ctx, *ids, ttnpb.RIGHT_GATEWAY_DELETE); err != nil {
return nil, err
}
err := is.withDatabase(ctx, func(db *gorm.DB) error {
return store.GetGatewayStore(db).DeleteGateway(ctx, ids)
})
if err != nil {
return nil, err
}
events.Publish(evtDeleteGateway.NewWithIdentifiersAndData(ctx, ids, nil))
return ttnpb.Empty, nil
}
func (is *IdentityServer) purgeGateway(ctx context.Context, ids *ttnpb.GatewayIdentifiers) (*types.Empty, error) {
if !is.IsAdmin(ctx) {
return nil, errAdminsPurgeGateways
}
err := is.withDatabase(ctx, func(db *gorm.DB) error {
// delete related API keys before purging the gateway
err := store.GetAPIKeyStore(db).DeleteEntityAPIKeys(ctx, ids)
if err != nil {
return err
}
// delete related memberships before purging the gateway
err = store.GetMembershipStore(db).DeleteEntityMembers(ctx, ids)
if err != nil {
return err
}
// delete related contact info before purging the gateway
err = store.GetContactInfoStore(db).DeleteEntityContactInfo(ctx, ids)
if err != nil {
return err
}
return store.GetGatewayStore(db).PurgeGateway(ctx, ids)
})
if err != nil {
return nil, err
}
events.Publish(evtPurgeGateway.NewWithIdentifiersAndData(ctx, ids, nil))
return ttnpb.Empty, nil
}
type gatewayRegistry struct {
*IdentityServer
}
func (gr *gatewayRegistry) Create(ctx context.Context, req *ttnpb.CreateGatewayRequest) (*ttnpb.Gateway, error) {
return gr.createGateway(ctx, req)
}
func (gr *gatewayRegistry) Get(ctx context.Context, req *ttnpb.GetGatewayRequest) (*ttnpb.Gateway, error) {
return gr.getGateway(ctx, req)
}
func (gr *gatewayRegistry) GetIdentifiersForEUI(ctx context.Context, req *ttnpb.GetGatewayIdentifiersForEUIRequest) (*ttnpb.GatewayIdentifiers, error) {
return gr.getGatewayIdentifiersForEUI(ctx, req)
}
func (gr *gatewayRegistry) List(ctx context.Context, req *ttnpb.ListGatewaysRequest) (*ttnpb.Gateways, error) {
return gr.listGateways(ctx, req)
}
func (gr *gatewayRegistry) Update(ctx context.Context, req *ttnpb.UpdateGatewayRequest) (*ttnpb.Gateway, error) {
return gr.updateGateway(ctx, req)
}
func (gr *gatewayRegistry) Delete(ctx context.Context, req *ttnpb.GatewayIdentifiers) (*types.Empty, error) {
return gr.deleteGateway(ctx, req)
}
func (gr *gatewayRegistry) Purge(ctx context.Context, req *ttnpb.GatewayIdentifiers) (*types.Empty, error) {
return gr.purgeGateway(ctx, req)
}