-
Notifications
You must be signed in to change notification settings - Fork 24
/
registry_ui.go
945 lines (874 loc) · 32.9 KB
/
registry_ui.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
/***************************************************************
*
* Copyright (C) 2024, Pelican Project, Morgridge Institute for Research
*
* 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 registry
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"github.com/jellydator/ttlcache/v3"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/lestrrat-go/jwx/v2/jwt"
log "github.com/sirupsen/logrus"
"github.com/pelicanplatform/pelican/config"
"github.com/pelicanplatform/pelican/param"
"github.com/pelicanplatform/pelican/server_structs"
"github.com/pelicanplatform/pelican/token_scopes"
"github.com/pelicanplatform/pelican/utils"
"github.com/pelicanplatform/pelican/web_ui"
)
type (
registrationFieldType string
registrationFieldOption struct {
Name string `mapstructure:"name" json:"name" yaml:"name"`
ID string `mapstructure:"id" json:"id" yaml:"id"`
}
registrationField struct {
Name string `json:"name"`
DisplayedName string `json:"displayed_name"`
Type registrationFieldType `json:"type"`
Required bool `json:"required"`
Options []registrationFieldOption `json:"options"`
Description string `json:"description"`
OptionsUrl string `json:"-"` // Internal field to keep track of Urls
}
listNamespaceRequest struct {
ServerType string `form:"server_type"`
Status string `form:"status"`
}
listNamespacesForUserRequest struct {
Status string `form:"status"`
}
)
var registrationFields []registrationField // A list of available registration fields
const (
String registrationFieldType = "string"
Int registrationFieldType = "int"
Boolean registrationFieldType = "bool"
Enum registrationFieldType = "enum"
DateTime registrationFieldType = "datetime"
)
func init() {
registrationFields = make([]registrationField, 0)
registrationFields = append(registrationFields, populateRegistrationFields("", server_structs.Namespace{})...)
}
// Populate registrationFields array to provide available namespace registration fields
// for UI to render registration form
func populateRegistrationFields(prefix string, data interface{}) []registrationField {
var fields []registrationField
val := reflect.ValueOf(data)
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
field := typ.Field(i)
// Check for the "post" tag, it can be "exlude" or "required"
if tag := field.Tag.Get("post"); tag == "exclude" {
continue
}
name := ""
if prefix != "" {
name += prefix + "."
}
// If the field has a json tag. Use the name from json tag
tempName := field.Name
jsonTag := field.Tag.Get("json")
if jsonTag != "" {
splitJson := strings.Split(jsonTag, ",")[0]
if splitJson != "-" {
tempName = splitJson
} else {
// `json:"-"` means this field should be removed from any marshaling
continue
}
}
description := ""
descTag := field.Tag.Get("description")
if descTag != "" {
description = descTag
}
regField := registrationField{
Name: name + tempName,
DisplayedName: utils.SnakeCaseToHumanReadable(tempName),
Required: strings.Contains(field.Tag.Get("validate"), "required"),
Description: description,
}
switch field.Type.Kind() {
case reflect.Int:
regField.Type = Int
fields = append(fields, regField)
case reflect.String:
regField.Type = String
// Institution is a special case
if regField.Name == "admin_metadata.institution" {
regField.Type = Enum
}
fields = append(fields, regField)
case reflect.Struct:
// Check if the struct is of type time.Time
if field.Type == reflect.TypeOf(time.Time{}) {
regField.Type = DateTime
fields = append(fields, regField)
break
}
// If it's AdminMetadata, add prefix and recursively call to parse fields
if field.Type == reflect.TypeOf(server_structs.AdminMetadata{}) {
existing_prefix := ""
if prefix != "" {
existing_prefix = prefix + "."
}
fields = append(fields, populateRegistrationFields(existing_prefix+"admin_metadata", server_structs.AdminMetadata{})...)
}
}
if field.Type == reflect.TypeOf(server_structs.RegistrationStatus("")) {
regField.Type = Enum
options := make([]registrationFieldOption, 3)
options[0] = registrationFieldOption{Name: server_structs.RegPending.String(), ID: server_structs.RegPending.LowerString()}
options[1] = registrationFieldOption{Name: server_structs.RegApproved.String(), ID: server_structs.RegApproved.LowerString()}
options[2] = registrationFieldOption{Name: server_structs.RegDenied.String(), ID: server_structs.RegDenied.LowerString()}
regField.Options = options
fields = append(fields, regField)
} else {
// Skip the field if it's not in the types listed above
continue
}
}
return fields
}
// List all namespaces in the registry.
// For authenticated users, it returns all namespaces.
// For non-authenticated users, it returns namespaces with AdminMetadata.Status = Approved
//
// Query against server_type, status
//
// GET /namespaces
func listNamespaces(ctx *gin.Context) {
// Directly call GetUser as we want this endpoint to also be able to serve unauthed users
user, _, err := web_ui.GetUserGroups(ctx)
if err != nil {
log.Error("Failed to check user login status: ", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Failed to check user login status"})
return
}
ctx.Set("User", user)
isAuthed := user != ""
queryParams := listNamespaceRequest{}
if err := ctx.ShouldBindQuery(&queryParams); err != nil {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Invalid query parameters"})
return
}
// For unauthed user with non-empty Status query != Approved, return 403
if !isAuthed && queryParams.Status != "" && queryParams.Status != server_structs.RegApproved.String() {
ctx.JSON(http.StatusForbidden, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "You don't have permission to filter non-approved namespace registrations"})
return
}
// Filter ns by server type
if queryParams.ServerType != "" && queryParams.ServerType != string(OriginType) && queryParams.ServerType != string(CacheType) {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Invalid server type: %s", queryParams.ServerType)})
return
}
filterNs := server_structs.Namespace{}
// For authenticated users, it returns all namespaces.
// For unauthenticated users, it returns namespaces with AdminMetadata.Status = Approved
if isAuthed {
if queryParams.Status != "" {
if server_structs.IsValidRegStatus(queryParams.Status) {
filterNs.AdminMetadata.Status = server_structs.RegistrationStatus(queryParams.Status)
} else {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Invalid query parameters %s: status must be one of 'Pending', 'Approved', 'Denied', 'Unknown'", queryParams.Status)})
}
}
} else {
filterNs.AdminMetadata.Status = server_structs.RegApproved
}
namespaces, err := getNamespacesByFilter(filterNs, ServerType(queryParams.ServerType))
if err != nil {
log.Error("Failed to get namespaces by server type: ", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Server encountered an error trying to list namespaces"})
return
}
nssWOPubkey := excludePubKey(namespaces)
ctx.JSON(http.StatusOK, nssWOPubkey)
}
// List namespaces for the currently authenticated user
//
// # Query against status
//
// GET /namespaces/user
func listNamespacesForUser(ctx *gin.Context) {
user := ctx.GetString("User")
if user == "" {
ctx.JSON(http.StatusUnauthorized, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "You need to login to perform this action"})
return
}
queryParams := listNamespacesForUserRequest{}
if err := ctx.ShouldBindQuery(&queryParams); err != nil {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Invalid query parameters: %v", err)})
return
}
filterNs := server_structs.Namespace{AdminMetadata: server_structs.AdminMetadata{UserID: user}}
if queryParams.Status != "" {
if server_structs.IsValidRegStatus(queryParams.Status) {
filterNs.AdminMetadata.Status = server_structs.RegistrationStatus(queryParams.Status)
} else {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Invalid query parameters %s: status must be one of 'Pending', 'Approved', 'Denied', 'Unknown'", queryParams.Status)})
}
}
namespaces, err := getNamespacesByFilter(filterNs, "")
if err != nil {
log.Error("Error getting namespaces for user ", user)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Error getting namespaces by user ID"})
return
}
ctx.JSON(http.StatusOK, namespaces)
}
func getNamespaceRegFields(ctx *gin.Context) {
for idx, field := range registrationFields {
if field.OptionsUrl != "" {
options, err := getCachedOptions(field.OptionsUrl, ttlcache.DefaultTTL)
if err != nil {
log.Errorf("failed to get options from optionsUrl %s for key %s", field.OptionsUrl, field.Name)
ctx.JSON(http.StatusInternalServerError,
server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("failed to get options from optionsUrl %s for key %s", field.OptionsUrl, field.Name),
})
}
registrationFields[idx].Options = options
}
}
ctx.JSON(http.StatusOK, registrationFields)
}
// Create a new namespace registration or update existing namespace registration.
//
// For update, only admin-user can update an existing registration if it's been approved already.
//
// One caveat in updating is that if the namespace to update was a legacy registration, i.e. It doesn't have
// AdminMetaData populated, an update __will__ populate the AdminMetaData field and update
// AdminMetaData based on user input. However, internal fields are still preserved.
//
// POST /namespaces
// PUT /namespaces/:id
func createUpdateNamespace(ctx *gin.Context, isUpdate bool) {
user := ctx.GetString("User")
accessToken := ctx.Query("access_token")
isAdmin, _ := web_ui.CheckAdmin(user)
id := 0 // namespace ID when doing update, will be populated later
if user == "" {
ctx.JSON(http.StatusUnauthorized, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "You need to login to perform this action"})
return
}
if isUpdate {
idStr := ctx.Param("id")
var err error
id, err = strconv.Atoi(idStr)
if err != nil || id <= 0 {
// Handle the error if id is not a valid integer
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Invalid ID format. ID must a positive integer"})
return
}
}
ns := server_structs.Namespace{}
if ctx.ShouldBindJSON(&ns) != nil {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Invalid create or update namespace request"})
return
}
if !isUpdate { // create
ns.AdminMetadata.UserID = user
}
// Assign ID from path param because the request data doesn't have ID set
ns.ID = id
// Check that Prefix is a valid prefix
updated_prefix, err := validatePrefix(ns.Prefix)
if err != nil {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Validation for Prefix failed: %v", err)})
return
}
ns.Prefix = updated_prefix
if !isUpdate {
// Check if prefix exists before doing anything else. Skip check if it's update operation
exists, err := namespaceExistsByPrefix(ns.Prefix)
if err != nil {
log.Errorf("Failed to check if namespace already exists: %v", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Server encountered an error checking if namespace already exists"})
return
}
if exists {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("The prefix %s is already registered", ns.Prefix)})
return
}
}
// Check if pubKey is a valid JWK
pubkey, err := validateJwks(ns.Pubkey)
if err != nil {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Validation for Pubkey failed: %v", err)})
return
}
// Check if the parent or child path along the prefix has been registered
inTopo, topoNss, valErr, sysErr := validateKeyChaining(ns.Prefix, pubkey)
if valErr != nil {
log.Errorln("Bad prefix when validating key chaining", valErr)
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: valErr.Error()})
return
}
if sysErr != nil {
log.Errorln("Validation for key chaining failed", sysErr)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: sysErr.Error()})
return
}
validInst, err := validateInstitution(ns.AdminMetadata.Institution)
if !validInst {
if err != nil {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Validation for Institution failed: %v", err)})
return
}
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Institution \"%s\" is not in the list of available institutions to register.", ns.AdminMetadata.Institution)})
return
}
formatCustomFields(ns.CustomFields)
if validCF, err := validateCustomFields(ns.CustomFields); !validCF {
if !validCF && err != nil {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Validation failed: %v", err)})
return
} else if !validCF {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Invalid custom fields without a validation error returned"})
return
}
}
if !isUpdate { // Create
// Overwrite status to Pending to filter malicious request
ns.AdminMetadata.Status = server_structs.RegPending
if inTopo {
ns.AdminMetadata.Description = fmt.Sprintf("[ Attention: A superspace or subspace of this prefix exists in OSDF topology: %s ] ", GetTopoPrefixString(topoNss))
}
// Basic validation (type, required, etc)
errs := config.GetValidate().Struct(ns)
if errs != nil {
validationErrs := errs.(validator.ValidationErrors)
errMsg := "Validation failed: "
for _, err := range validationErrs {
errMsg += err.Translate(config.GetEnTranslator()) + "\n"
}
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: errMsg,
})
return
}
if err := AddNamespace(&ns); err != nil {
log.Errorf("Failed to insert namespace with id %d. %v", ns.ID, err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Fail to insert namespace"})
return
}
if inTopo {
ctx.JSON(http.StatusOK,
server_structs.SimpleApiResp{
Status: server_structs.RespOK,
Msg: fmt.Sprintf("Prefix %s successfully registered. Note that there is an existing superspace or subspace of the namespace in the OSDF topology: %s. The registry admin will review your request and approve your namespace if this is expected.", ns.Prefix, GetTopoPrefixString(topoNss)),
})
} else {
ctx.JSON(http.StatusOK,
server_structs.SimpleApiResp{
Status: server_structs.RespOK,
Msg: fmt.Sprintf("Prefix %s successfully registered", ns.Prefix),
})
}
} else { // Update
// First check if the namespace exists
exists, err := namespaceExistsById(ns.ID)
if err != nil {
log.Error("Failed to get namespace by ID:", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Fail to find if namespace exists"})
return
}
if !exists { // Return 404 is the namespace does not exists
ctx.JSON(http.StatusNotFound, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Can't update namespace: namespace not found"})
return
}
// Then check if the user has previlege to update
belongsTo := false
if !isAdmin { // Not admin, need to check if the namespace belongs to the user
belongsTo, err = namespaceBelongsToUserId(ns.ID, user)
if err != nil {
log.Error("Error checking if namespace belongs to the user: ", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Error checking if namespace belongs to the user"})
return
}
if !belongsTo {
// If the user doen's own the namespace, they can't edit it
// but if they have an access token generated by the private key
// that corresponds to the public key of the namespace they are trying to access,
// we allow them to do it so that admin can fill out the rest of the registration if the user_id is empty
if accessToken == "" {
log.Errorf("Access denied from user %s for namespace with id=%d", user, id)
ctx.JSON(http.StatusForbidden, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "You do not have permissions to access this namespace registration. Check the id or if you own the namespace"})
return
}
}
existingStatus, err := getNamespaceStatusById(ns.ID)
if err != nil {
log.Error("Error checking namespace status: ", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Error checking namespace status"})
return
}
if existingStatus == server_structs.RegApproved {
log.Errorf("User '%s' is trying to modify approved namespace registration with id=%d", user, ns.ID)
ctx.JSON(http.StatusForbidden, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "You don't have permission to modify an approved registration. Please contact your federation administrator"})
return
}
// If non-admin user accesses a namespace with user_id != user but with access_token
if !isAdmin && !belongsTo && accessToken != "" {
jwks, err := jwk.Parse([]byte(ns.Pubkey))
if err != nil {
log.Errorf("Error parsing the public key of the namespace %s with ID %d: %v", ns.Prefix, ns.ID, err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Error parsing the public key of the namespace %s with ID %d: %v", ns.Prefix, ns.ID, err),
})
return
}
accessJWT, err := jwt.Parse(
[]byte(accessToken),
jwt.WithKeySet(jwks),
jwt.WithVerify(true),
)
if err != nil {
ctx.JSON(http.StatusForbidden,
server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprint("Invalid access token: ", err),
})
return
}
scopeValidator := token_scopes.CreateScopeValidator([]token_scopes.TokenScope{token_scopes.Registry_EditRegistration}, false)
if err = jwt.Validate(accessJWT, jwt.WithValidator(scopeValidator)); err != nil {
log.Errorf("Failed to verify the scope of the token: %v", err)
ctx.JSON(http.StatusForbidden,
server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Failed to verify the scope of the token. Require %s", token_scopes.Registry_EditRegistration.String()),
})
}
if ns.AdminMetadata.UserID == "" {
ns.AdminMetadata.UserID = user
}
}
}
// Basic validation (type, required, etc)
errs := config.GetValidate().Struct(ns)
if errs != nil {
validationErrs := errs.(validator.ValidationErrors)
errMsg := "Validation failed: "
totalErr := 0
for _, err := range validationErrs {
// Skip UserID check for the admin otherwise they won't be
// able to update a namespace without userID
if err.Field() == "UserID" && err.Tag() == "required" && isAdmin {
continue
}
errMsg += err.Translate(config.GetEnTranslator()) + "\n"
totalErr += 1
}
if totalErr > 0 {
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: errMsg,
})
return
}
}
// If the user has previlege to udpate, go ahead
if err := updateNamespace(&ns); err != nil {
log.Errorf("Failed to update namespace with id %d. %v", ns.ID, err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Fail to update namespace"})
return
}
}
}
// Get one namespace by id.
// Admin can see any namespace detail while non-admin can only see his/her namespace
//
// GET /namesapces/:id
func getNamespace(ctx *gin.Context) {
user := ctx.GetString("User")
idStr := ctx.Param("id")
accessToken := ctx.Query("access_token")
id, err := strconv.Atoi(idStr)
if err != nil || id <= 0 {
// Handle the error if id is not a valid integer
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Invalid ID format. ID must a non-zero integer"})
return
}
exists, err := namespaceExistsById(id)
if err != nil {
log.Error("Error checking if namespace exists: ", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Error checking if namespace exists"})
return
}
if !exists {
log.Errorf("Namespace not found for id: %d", id)
ctx.JSON(http.StatusNotFound, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Namespace not found"})
return
}
isAdmin, _ := web_ui.CheckAdmin(user)
belongsTo := false
if !isAdmin { // Not admin, need to check if the namespace belongs to the user
belongsTo, err = namespaceBelongsToUserId(id, user)
if err != nil {
log.Error("Error checking if namespace belongs to the user: ", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Error checking if namespace belongs to the user"})
return
}
if !belongsTo {
// If the user doen's own the namespace, they can't view it
// but if they have an access token generated by the private key
// that corresponds to the public key of the namespace they are trying to access,
// we allow them to do it so that admin can fill out the rest of the registration if the user_id is empty
if accessToken == "" {
log.Errorf("Access denied from user %s for namespace with id=%d", user, id)
ctx.JSON(http.StatusForbidden, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "You do not have permissions to access this namespace registration. Check the id or if you own the namespace"})
return
}
}
}
ns, err := getNamespaceById(id)
if err != nil {
log.Error("Error getting namespace: ", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Error getting namespace"})
return
}
// If non-admin user accesses a namespace with user_id != user but with access_token
if !isAdmin && !belongsTo && accessToken != "" {
jwks, err := jwk.Parse([]byte(ns.Pubkey))
if err != nil {
log.Errorf("Error parsing the public key of the namespace %s with ID %d: %v", ns.Prefix, ns.ID, err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Error parsing the public key of the namespace %s with ID %d: %v", ns.Prefix, ns.ID, err),
})
return
}
accessJWT, err := jwt.Parse(
[]byte(accessToken),
jwt.WithKeySet(jwks),
jwt.WithVerify(true),
)
if err != nil {
ctx.JSON(http.StatusForbidden,
server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprint("Invalid access token: ", err),
})
return
}
scopeValidator := token_scopes.CreateScopeValidator([]token_scopes.TokenScope{token_scopes.Registry_EditRegistration}, false)
if err = jwt.Validate(accessJWT, jwt.WithValidator(scopeValidator)); err != nil {
log.Errorf("Failed to verify the scope of the token: %v", err)
ctx.JSON(http.StatusForbidden,
server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprintf("Failed to verify the scope of the token. Require %s", token_scopes.Registry_EditRegistration.String()),
})
}
}
ctx.JSON(http.StatusOK, ns)
}
func updateNamespaceStatus(ctx *gin.Context, status server_structs.RegistrationStatus) {
user := ctx.GetString("User")
idStr := ctx.Param("id")
id, err := strconv.Atoi(idStr)
if err != nil || id <= 0 {
// Handle the error if id is not a valid integer
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Invalid ID format. ID must a non-zero integer"})
return
}
exists, err := namespaceExistsById(id)
if err != nil {
log.Error("Error checking if namespace exists: ", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Error checking if namespace exists"})
return
}
if !exists {
log.Errorf("Namespace not found for id: %d", id)
ctx.JSON(http.StatusNotFound, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Namespace not found"})
return
}
if err = updateNamespaceStatusById(id, status, user); err != nil {
log.Error("Error updating namespace status by ID:", id, " to status:", status)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Failed to update namespace"})
return
}
ctx.JSON(http.StatusOK,
server_structs.SimpleApiResp{
Status: server_structs.RespOK,
Msg: "success",
})
}
func getNamespaceJWKS(ctx *gin.Context) {
idStr := ctx.Param("id")
id, err := strconv.Atoi(idStr)
if err != nil || id <= 0 {
// Handle the error if id is not a valid integer
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Invalid ID format. ID must a non-zero integer"})
return
}
found, err := namespaceExistsById(id)
if err != nil {
log.Errorf("Failed to check if namespace exists with id %d. %v", id, err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprint("Error checking id:", err)})
return
}
if !found {
ctx.JSON(http.StatusNotFound, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Namespace not found"})
return
}
jwks, err := getNamespaceJwksById(id)
if err != nil {
log.Errorf("Failed to get namespace jwks by id %d. %v", id, err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: fmt.Sprint("Error getting jwks by id:", err)})
return
}
jsonData, err := json.MarshalIndent(jwks, "", " ")
if err != nil {
log.Errorf("Failed to marshall jwks. %v", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Failed to marshal JWKS"})
return
}
// Append a new line to the JSON data
jsonData = append(jsonData, '\n')
ctx.Header("Content-Disposition", fmt.Sprintf("attachment; filename=public-key-server-%v.jwks", id))
ctx.Data(200, "application/json", jsonData)
}
func deleteNamespace(ctx *gin.Context) {
idStr := ctx.Param("id")
id, err := strconv.Atoi(idStr)
if err != nil || id <= 0 {
// Handle the error if id is not a valid integer
ctx.JSON(http.StatusBadRequest, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Invalid ID format. ID must a non-zero integer"})
return
}
exists, err := namespaceExistsById(id)
if err != nil {
log.Error("Error checking if namespace exists: ", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Error checking if namespace exists"})
return
}
if !exists {
log.Errorf("Namespace not found for id: %d", id)
ctx.JSON(http.StatusNotFound, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Namespace not found"})
return
}
err = deleteNamespaceByID(id)
if err != nil {
log.Errorf("Error deleting the namespace: %v", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Error deleting the namespace"})
}
ctx.JSON(http.StatusOK,
server_structs.SimpleApiResp{
Status: server_structs.RespOK,
Msg: "success",
})
}
func listInstitutions(ctx *gin.Context) {
institutions := []registrationFieldOption{}
if err := param.Registry_Institutions.Unmarshal(&institutions); err != nil {
log.Error("Fail to read server configuration of institutions", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Fail to read server configuration of institutions"})
return
}
if len(institutions) != 0 {
ctx.JSON(http.StatusOK, institutions)
return
}
instUrl := param.Registry_InstitutionsUrl.GetString()
instUrlTTL := param.Registry_InstitutionsUrlReloadMinutes.GetDuration()
if instUrl != "" {
institutions, err := getCachedOptions(instUrl, instUrlTTL)
if err != nil {
log.Error(err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: err.Error(),
})
return
}
ctx.JSON(http.StatusOK, institutions)
} else {
log.Error("Server didn't configure Registry.Institutions and Registry.InstitutionsUrl")
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Server didn't configure Registry.Institutions and Registry.InstitutionsUrl",
})
}
}
func listTopologyNamespaces(ctx *gin.Context) {
nss, err := getTopologyNamespaces()
if err != nil {
log.Errorf("failed to get all namespaces from the topology: %v", err)
ctx.JSON(http.StatusInternalServerError, server_structs.SimpleApiResp{
Status: server_structs.RespFailed,
Msg: "Failed to get namespaces from topology"})
return
}
ctx.JSON(http.StatusOK, nss)
}
// Define Gin APIs for registry Web UI. All endpoints are user-facing
func RegisterRegistryWebAPI(router *gin.RouterGroup) error {
registryWebAPI := router.Group("/api/v1.0/registry_ui")
csrfHandler, err := config.GetCSRFHandler()
if err != nil {
return err
}
// Add CSRF middleware to all the routes below. CSRF middleware will look for
// any update methods (post/delete/patch, etc) and automatically check if a
// X-CSRF-Token header is present and the token matches
registryWebAPI.Use(csrfHandler)
// Follow RESTful schema
{
registryWebAPI.GET("/namespaces", listNamespaces)
registryWebAPI.OPTIONS("/namespaces", web_ui.AuthHandler, getNamespaceRegFields)
registryWebAPI.POST("/namespaces", web_ui.AuthHandler, func(ctx *gin.Context) {
createUpdateNamespace(ctx, false)
})
registryWebAPI.GET("/namespaces/user", web_ui.AuthHandler, listNamespacesForUser)
registryWebAPI.GET("/namespaces/:id", web_ui.AuthHandler, getNamespace)
registryWebAPI.PUT("/namespaces/:id", web_ui.AuthHandler, func(ctx *gin.Context) {
createUpdateNamespace(ctx, true)
})
registryWebAPI.DELETE("/namespaces/:id", web_ui.AuthHandler, web_ui.AdminAuthHandler, deleteNamespace)
registryWebAPI.GET("/namespaces/:id/pubkey", getNamespaceJWKS)
registryWebAPI.PATCH("/namespaces/:id/approve", web_ui.AuthHandler, web_ui.AdminAuthHandler, func(ctx *gin.Context) {
updateNamespaceStatus(ctx, server_structs.RegApproved)
})
registryWebAPI.PATCH("/namespaces/:id/deny", web_ui.AuthHandler, web_ui.AdminAuthHandler, func(ctx *gin.Context) {
updateNamespaceStatus(ctx, server_structs.RegDenied)
})
}
{
registryWebAPI.GET("/topology", listTopologyNamespaces)
}
{
registryWebAPI.GET("/institutions", web_ui.AuthHandler, listInstitutions)
}
return nil
}