-
Notifications
You must be signed in to change notification settings - Fork 110
/
config.go
1106 lines (982 loc) · 37.4 KB
/
config.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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package config defines the structures to configure a robot and its connected parts.
package config
import (
"crypto/tls"
"encoding/json"
"fmt"
"net"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"time"
"github.com/pkg/errors"
"go.viam.com/utils/jwks"
"go.viam.com/utils/pexec"
"go.viam.com/utils/rpc"
"golang.org/x/exp/slices"
"go.viam.com/rdk/logging"
"go.viam.com/rdk/referenceframe"
"go.viam.com/rdk/resource"
rutils "go.viam.com/rdk/utils"
)
// A Config describes the configuration of a robot.
type Config struct {
Cloud *Cloud
Modules []Module
Remotes []Remote
Components []resource.Config
Processes []pexec.ProcessConfig
Services []resource.Config
Packages []PackageConfig
Network NetworkConfig
Auth AuthConfig
Debug bool
GlobalLogConfig []GlobalLogConfig
ConfigFilePath string
// AllowInsecureCreds is used to have all connections allow insecure
// downgrades and send credentials over plaintext. This is an option
// a user must pass via command line arguments.
AllowInsecureCreds bool
// UntrustedEnv is used to disable Processes and shell for untrusted environments
// where a process cannot be trusted. This is an option a user must pass via
// command line arguments.
UntrustedEnv bool
// FromCommand indicates if this config was parsed via the web server command.
// If false, it's for creating a robot via the RDK library. This is helpful for
// error messages that can indicate flags/config fields to use.
FromCommand bool
// DisablePartialStart ensures that a robot will only start when all the components,
// services, and remotes pass config validation. This value is false by default
DisablePartialStart bool
// PackagePath sets the directory used to store packages locally. Defaults to ~/.viam/packages
PackagePath string
}
// NOTE: This data must be maintained with what is in Config.
type configData struct {
Cloud *Cloud `json:"cloud,omitempty"`
Modules []Module `json:"modules,omitempty"`
Remotes []Remote `json:"remotes,omitempty"`
Components []resource.Config `json:"components,omitempty"`
Processes []pexec.ProcessConfig `json:"processes,omitempty"`
Services []resource.Config `json:"services,omitempty"`
Packages []PackageConfig `json:"packages,omitempty"`
Network NetworkConfig `json:"network"`
Auth AuthConfig `json:"auth"`
Debug bool `json:"debug,omitempty"`
DisablePartialStart bool `json:"disable_partial_start"`
GlobalLogConfig []GlobalLogConfig `json:"global_log_configuration"`
}
// AppValidationStatus refers to the.
type AppValidationStatus struct {
Error string `json:"error"`
}
func (c *Config) validateUniqueResource(logger logging.Logger, seenResources map[string]bool, name string) error {
if _, exists := seenResources[name]; exists {
errString := errors.Errorf("duplicate resource %s in robot config", name)
if c.DisablePartialStart {
return errString
}
logger.Error(errString)
}
seenResources[name] = true
return nil
}
// Ensure ensures all parts of the config are valid, which may include updating it. Only returns an error
// if c.DisablePartialStart is true (default: false).
func (c *Config) Ensure(fromCloud bool, logger logging.Logger) error {
seenResources := make(map[string]bool)
if c.Cloud != nil {
// Adds default for RefreshInterval if not set.
if err := c.Cloud.Validate("cloud", fromCloud); err != nil {
return err
}
}
// Adds default BindAddress and HeartbeatWindow if not set.
if err := c.Network.Validate("network"); err != nil {
return err
}
// Updates ValidatedKeySet once validated.
if err := c.Auth.Validate("auth"); err != nil {
return err
}
for idx := 0; idx < len(c.Modules); idx++ {
if err := c.Modules[idx].Validate(fmt.Sprintf("%s.%d", "modules", idx)); err != nil {
if c.DisablePartialStart {
return err
}
logger.Errorw("module config error; starting robot without module", "name", c.Modules[idx].Name, "error", err)
}
if err := c.validateUniqueResource(logger, seenResources, c.Modules[idx].Name); err != nil {
return err
}
}
for idx := 0; idx < len(c.Remotes); idx++ {
if _, err := c.Remotes[idx].Validate(fmt.Sprintf("%s.%d", "remotes", idx)); err != nil {
if c.DisablePartialStart {
return err
}
logger.Errorw("remote config error; starting robot without remote", "name", c.Remotes[idx].Name, "error", err)
}
// we need to figure out how to make it so that the remote is tied to the API
resourceRemoteName := resource.NewName(resource.APINamespaceRDK.WithType("remote").WithSubtype(""), c.Remotes[idx].Name)
if err := c.validateUniqueResource(logger, seenResources, resourceRemoteName.String()); err != nil {
return err
}
}
for idx := 0; idx < len(c.Components); idx++ {
component := &c.Components[idx]
// dependsOn will only be populated if attributes have been converted, which does not happen in this function.
// Attributes can be converted from an untyped, JSON-like object to a typed Go struct based on whether a converter/the typed struct
// was registered during resource model registration. If no converter but a typed struct was registered, the RDK provides a
// default converter. For modular resources, since lookup will fail as no converter or a typed struct is registered, implicit
// dependencies are gathered during robot reconfiguration itself.
dependsOn, err := component.Validate(fmt.Sprintf("%s.%d", "components", idx), resource.APITypeComponentName)
if err != nil {
fullErr := errors.Wrapf(err, "error validating component %s: %s", component.Name, err)
if c.DisablePartialStart {
return fullErr
}
resLogger := logger.Sublogger(component.ResourceName().String())
resLogger.Errorw("component config error; starting robot without component", "name", component.Name, "error", err)
} else {
component.ImplicitDependsOn = dependsOn
}
if err := c.validateUniqueResource(logger, seenResources, component.ResourceName().String()); err != nil {
return err
}
}
for idx := 0; idx < len(c.Processes); idx++ {
if err := c.Processes[idx].Validate(fmt.Sprintf("%s.%d", "processes", idx)); err != nil {
if c.DisablePartialStart {
return err
}
logger.Errorw("process config error; starting robot without process", "name", c.Processes[idx].Name, "error", err)
}
if err := c.validateUniqueResource(logger, seenResources, c.Processes[idx].ID); err != nil {
return err
}
}
for idx := 0; idx < len(c.Services); idx++ {
service := &c.Services[idx]
// dependsOn will only be populated if attributes have been converted, which does not happen in this function.
// Attributes can be converted from an untyped, JSON-like object to a typed Go struct based on whether a converter/the typed struct
// was registered during resource model registration. If no converter but a typed struct was registered, the RDK provides a
// default converter. For modular resources, since lookup will fail as no converter or a typed struct is registered, implicit
// dependencies are gathered during robot reconfiguration itself.
dependsOn, err := service.Validate(fmt.Sprintf("%s.%d", "services", idx), resource.APITypeServiceName)
if err != nil {
if c.DisablePartialStart {
return err
}
resLogger := logger.Sublogger(service.ResourceName().String())
resLogger.Errorw("service config error; starting robot without service", "name", service.Name, "error", err)
} else {
service.ImplicitDependsOn = dependsOn
}
if err := c.validateUniqueResource(logger, seenResources, service.ResourceName().String()); err != nil {
return err
}
}
for idx := 0; idx < len(c.Packages); idx++ {
if err := c.Packages[idx].Validate(fmt.Sprintf("%s.%d", "packages", idx)); err != nil {
fullErr := errors.Errorf("error validating package config %s", err)
if c.DisablePartialStart {
return fullErr
}
logger.Errorw("package config error; starting robot without package", "name", c.Packages[idx].Name, "error", err)
}
if err := c.validateUniqueResource(logger, seenResources, c.Packages[idx].Package); err != nil {
return err
}
}
for idx, globalLogConfig := range c.GlobalLogConfig {
if err := globalLogConfig.Validate(fmt.Sprintf("global_log_configuration.%d", idx)); err != nil {
logger.Errorw("log configuration error", "err", err)
}
}
return nil
}
// FindComponent finds a particular component by name.
func (c Config) FindComponent(name string) *resource.Config {
for _, cmp := range c.Components {
if cmp.Name == name {
return &cmp
}
}
return nil
}
// UnmarshalJSON unmarshals JSON into the config and adjusts some
// names if they are not fully filled in.
func (c *Config) UnmarshalJSON(data []byte) error {
var conf configData
if err := json.Unmarshal(data, &conf); err != nil {
return err
}
for idx := range conf.Components {
conf.Components[idx].AdjustPartialNames(resource.APITypeComponentName)
}
for idx := range conf.Services {
conf.Services[idx].AdjustPartialNames(resource.APITypeServiceName)
}
for idx := range conf.Remotes {
conf.Remotes[idx].adjustPartialNames()
}
c.Cloud = conf.Cloud
c.Modules = conf.Modules
c.Remotes = conf.Remotes
c.Components = conf.Components
c.Processes = conf.Processes
c.Services = conf.Services
c.Packages = conf.Packages
c.Network = conf.Network
c.Auth = conf.Auth
c.Debug = conf.Debug
c.DisablePartialStart = conf.DisablePartialStart
c.GlobalLogConfig = conf.GlobalLogConfig
return nil
}
// MarshalJSON marshals JSON from the config.
func (c Config) MarshalJSON() ([]byte, error) {
for idx := range c.Components {
c.Components[idx].AdjustPartialNames(resource.APITypeComponentName)
}
for idx := range c.Services {
c.Services[idx].AdjustPartialNames(resource.APITypeServiceName)
}
for idx := range c.Remotes {
c.Remotes[idx].adjustPartialNames()
}
return json.Marshal(configData{
Cloud: c.Cloud,
Modules: c.Modules,
Remotes: c.Remotes,
Components: c.Components,
Processes: c.Processes,
Services: c.Services,
Packages: c.Packages,
Network: c.Network,
Auth: c.Auth,
Debug: c.Debug,
DisablePartialStart: c.DisablePartialStart,
GlobalLogConfig: c.GlobalLogConfig,
})
}
// CopyOnlyPublicFields returns a deep-copy of the current config only preserving JSON exported fields.
func (c *Config) CopyOnlyPublicFields() (*Config, error) {
// We're using JSON as an intermediary to ensure only the json exported fields are
// copied.
tmpJSON, err := json.Marshal(c)
if err != nil {
return nil, errors.Wrap(err, "error marshaling config")
}
var cfg Config
err = json.Unmarshal(tmpJSON, &cfg)
if err != nil {
return nil, errors.Wrap(err, "error unmarshaling config")
}
return &cfg, nil
}
// A Remote describes a remote robot that should be integrated.
// The Frame field defines how the "world" node of the remote robot should be reconciled with the "world" node of
// the current robot. All components of the remote robot who have Parent as "world" will be attached to the parent defined
// in Frame, and with the given offset as well.
type Remote struct {
Name string
Address string
Frame *referenceframe.LinkConfig
Auth RemoteAuth
ManagedBy string
Insecure bool
ConnectionCheckInterval time.Duration
ReconnectInterval time.Duration
AssociatedResourceConfigs []resource.AssociatedResourceConfig
// Secret is a helper for a robot location secret.
Secret string
alreadyValidated bool
cachedErr error
}
// Note: keep this in sync with Remote.
type remoteData struct {
Name string `json:"name"`
Address string `json:"address"`
Frame *referenceframe.LinkConfig `json:"frame,omitempty"`
Auth RemoteAuth `json:"auth"`
ManagedBy string `json:"managed_by"`
Insecure bool `json:"insecure"`
ConnectionCheckInterval string `json:"connection_check_interval,omitempty"`
ReconnectInterval string `json:"reconnect_interval,omitempty"`
AssociatedResourceConfigs []resource.AssociatedResourceConfig `json:"service_configs"`
// Secret is a helper for a robot location secret.
Secret string `json:"secret"`
}
// Equals checks if the two configs are deeply equal to each other.
func (conf Remote) Equals(other Remote) bool {
conf.alreadyValidated = false
conf.cachedErr = nil
other.alreadyValidated = false
other.cachedErr = nil
//nolint:govet
return reflect.DeepEqual(conf, other)
}
// UnmarshalJSON unmarshals JSON data into this config.
func (conf *Remote) UnmarshalJSON(data []byte) error {
var temp remoteData
if err := json.Unmarshal(data, &temp); err != nil {
return err
}
*conf = Remote{
Name: temp.Name,
Address: temp.Address,
Frame: temp.Frame,
Auth: temp.Auth,
ManagedBy: temp.ManagedBy,
Insecure: temp.Insecure,
AssociatedResourceConfigs: temp.AssociatedResourceConfigs,
Secret: temp.Secret,
}
if temp.ConnectionCheckInterval != "" {
dur, err := time.ParseDuration(temp.ConnectionCheckInterval)
if err != nil {
return err
}
conf.ConnectionCheckInterval = dur
}
if temp.ReconnectInterval != "" {
dur, err := time.ParseDuration(temp.ReconnectInterval)
if err != nil {
return err
}
conf.ReconnectInterval = dur
}
return nil
}
// MarshalJSON marshals out this config.
func (conf Remote) MarshalJSON() ([]byte, error) {
temp := remoteData{
Name: conf.Name,
Address: conf.Address,
Frame: conf.Frame,
Auth: conf.Auth,
ManagedBy: conf.ManagedBy,
Insecure: conf.Insecure,
AssociatedResourceConfigs: conf.AssociatedResourceConfigs,
Secret: conf.Secret,
}
if conf.ConnectionCheckInterval != 0 {
temp.ConnectionCheckInterval = conf.ConnectionCheckInterval.String()
}
if conf.ReconnectInterval != 0 {
temp.ReconnectInterval = conf.ReconnectInterval.String()
}
return json.Marshal(temp)
}
// RemoteAuth specifies how to authenticate against a remote. If no credentials are
// specified, authentication does not happen. If an entity is specified, the
// authentication request will specify it.
type RemoteAuth struct {
Credentials *rpc.Credentials `json:"credentials"`
Entity string `json:"entity"`
// only used internally right now
ExternalAuthAddress string `json:"-"`
ExternalAuthInsecure bool `json:"-"`
ExternalAuthToEntity string `json:"-"`
Managed bool `json:"-"`
SignalingServerAddress string `json:"-"`
SignalingAuthEntity string `json:"-"`
SignalingCreds *rpc.Credentials `json:"-"`
}
// Validate ensures all parts of the config are valid.
func (conf *Remote) Validate(path string) ([]string, error) {
if conf.alreadyValidated {
return nil, conf.cachedErr
}
conf.cachedErr = conf.validate(path)
conf.alreadyValidated = true
return nil, conf.cachedErr
}
// adjustPartialNames assumes this config comes from a place where the associated
// config type names are partially stored (JSON/Proto/Database) and will
// fix them up to the builtin values they are intended for.
func (conf *Remote) adjustPartialNames() {
for idx := range conf.AssociatedResourceConfigs {
conf.AssociatedResourceConfigs[idx].RemoteName = conf.Name
}
}
func (conf *Remote) validate(path string) error {
conf.adjustPartialNames()
if conf.Name == "" {
return resource.NewConfigValidationFieldRequiredError(path, "name")
}
if !rutils.ValidNameRegex.MatchString(conf.Name) {
return resource.NewConfigValidationError(path, rutils.ErrInvalidName(conf.Name))
}
if conf.Address == "" {
return resource.NewConfigValidationFieldRequiredError(path, "address")
}
if conf.Frame != nil {
if conf.Frame.Parent == "" {
return resource.NewConfigValidationFieldRequiredError(path, "frame.parent")
}
}
if conf.Secret != "" {
conf.Auth = RemoteAuth{
Credentials: &rpc.Credentials{
Type: rutils.CredentialsTypeRobotLocationSecret,
Payload: conf.Secret,
},
}
}
return nil
}
// A Cloud describes how to configure a robot controlled by the
// cloud.
// The cloud source could be anything that supports http.
// URL is constructed as $Path?id=ID and secret is put in a http header.
type Cloud struct {
ID string
Secret string
LocationSecret string // Deprecated: Use LocationSecrets
LocationSecrets []LocationSecret
LocationID string
PrimaryOrgID string
ManagedBy string
FQDN string
LocalFQDN string
SignalingAddress string
SignalingInsecure bool
Path string
LogPath string
AppAddress string
RefreshInterval time.Duration
// cached by us and fetched from a non-config endpoint.
TLSCertificate string
TLSPrivateKey string
}
// Note: keep this in sync with Cloud.
type cloudData struct {
// these three fields are only set within the config passed to the robot as an argumenet.
ID string `json:"id"`
Secret string `json:"secret,omitempty"`
AppAddress string `json:"app_address,omitempty"`
LocationSecret string `json:"location_secret"`
LocationSecrets []LocationSecret `json:"location_secrets"`
LocationID string `json:"location_id"`
PrimaryOrgID string `json:"primary_org_id"`
ManagedBy string `json:"managed_by"`
FQDN string `json:"fqdn"`
LocalFQDN string `json:"local_fqdn"`
SignalingAddress string `json:"signaling_address"`
SignalingInsecure bool `json:"signaling_insecure,omitempty"`
Path string `json:"path,omitempty"`
LogPath string `json:"log_path,omitempty"`
RefreshInterval string `json:"refresh_interval,omitempty"`
// cached by us and fetched from a non-config endpoint.
TLSCertificate string `json:"tls_certificate"`
TLSPrivateKey string `json:"tls_private_key"`
}
// UnmarshalJSON unmarshals JSON data into this config.
func (config *Cloud) UnmarshalJSON(data []byte) error {
var temp cloudData
if err := json.Unmarshal(data, &temp); err != nil {
return err
}
*config = Cloud{
ID: temp.ID,
Secret: temp.Secret,
LocationSecret: temp.LocationSecret,
LocationSecrets: temp.LocationSecrets,
LocationID: temp.LocationID,
PrimaryOrgID: temp.PrimaryOrgID,
ManagedBy: temp.ManagedBy,
FQDN: temp.FQDN,
LocalFQDN: temp.LocalFQDN,
SignalingAddress: temp.SignalingAddress,
SignalingInsecure: temp.SignalingInsecure,
Path: temp.Path,
LogPath: temp.LogPath,
AppAddress: temp.AppAddress,
TLSCertificate: temp.TLSCertificate,
TLSPrivateKey: temp.TLSPrivateKey,
}
if temp.RefreshInterval != "" {
dur, err := time.ParseDuration(temp.RefreshInterval)
if err != nil {
return err
}
config.RefreshInterval = dur
}
return nil
}
// MarshalJSON marshals out this config.
func (config Cloud) MarshalJSON() ([]byte, error) {
temp := cloudData{
ID: config.ID,
Secret: config.Secret,
LocationSecret: config.LocationSecret,
LocationSecrets: config.LocationSecrets,
LocationID: config.LocationID,
PrimaryOrgID: config.PrimaryOrgID,
ManagedBy: config.ManagedBy,
FQDN: config.FQDN,
LocalFQDN: config.LocalFQDN,
SignalingAddress: config.SignalingAddress,
SignalingInsecure: config.SignalingInsecure,
Path: config.Path,
LogPath: config.LogPath,
AppAddress: config.AppAddress,
TLSCertificate: config.TLSCertificate,
TLSPrivateKey: config.TLSPrivateKey,
}
if config.RefreshInterval != 0 {
temp.RefreshInterval = config.RefreshInterval.String()
}
return json.Marshal(temp)
}
// Validate ensures all parts of the config are valid. Adds default for RefreshInterval if not set.
func (config *Cloud) Validate(path string, fromCloud bool) error {
if config.ID == "" {
return resource.NewConfigValidationFieldRequiredError(path, "id")
}
if fromCloud {
if config.FQDN == "" {
return resource.NewConfigValidationFieldRequiredError(path, "fqdn")
}
if config.LocalFQDN == "" {
return resource.NewConfigValidationFieldRequiredError(path, "local_fqdn")
}
if config.PrimaryOrgID == "" {
return resource.NewConfigValidationFieldRequiredError(path, "primary_org_id")
}
if config.LocationID == "" {
return resource.NewConfigValidationFieldRequiredError(path, "location_id")
}
} else if config.Secret == "" {
return resource.NewConfigValidationFieldRequiredError(path, "secret")
}
if config.RefreshInterval == 0 {
config.RefreshInterval = 10 * time.Second
}
return nil
}
// ValidateTLS ensures TLS fields are valid.
func (config *Cloud) ValidateTLS(path string) error {
if config.TLSCertificate == "" {
return resource.NewConfigValidationFieldRequiredError(path, "tls_certificate")
}
if config.TLSPrivateKey == "" {
return resource.NewConfigValidationFieldRequiredError(path, "tls_private_key")
}
return nil
}
// LocationSecret describes a location secret that can be used to authenticate to the rdk.
type LocationSecret struct {
ID string `json:"id"`
// Payload of the secret
Secret string `json:"secret"`
}
// NetworkConfig describes networking settings for the web server.
type NetworkConfig struct {
NetworkConfigData
}
// NetworkConfigData is the network config data that gets marshaled/unmarshaled.
type NetworkConfigData struct {
// FQDN is the unique name of this server.
FQDN string `json:"fqdn,omitempty"`
// Listener is the listener that the web server will use. This is mutually
// exclusive with BindAddress.
Listener net.Listener `json:"-"`
// BindAddress is the address that the web server will bind to.
// The default behavior is to bind to localhost:8080. This is mutually
// exclusive with Listener.
BindAddress string `json:"bind_address,omitempty"`
BindAddressDefaultSet bool `json:"-"`
// TLSCertFile is used to enable secure communications on the hosted HTTP server.
// This is mutually exclusive with TLSCertPEM and TLSKeyPEM.
TLSCertFile string `json:"tls_cert_file,omitempty"`
// TLSKeyFile is used to enable secure communications on the hosted HTTP server.
// This is mutually exclusive with TLSCertPEM and TLSKeyPEM.
TLSKeyFile string `json:"tls_key_file,omitempty"`
// TLSConfig is used to enable secure communications on the hosted HTTP server.
// This is mutually exclusive with TLSCertFile and TLSKeyFile.
TLSConfig *tls.Config `json:"-"`
// Sessions configures session management.
Sessions SessionsConfig `json:"sessions"`
}
// MarshalJSON marshals out this config.
func (nc NetworkConfig) MarshalJSON() ([]byte, error) {
if nc.BindAddressDefaultSet {
nc.BindAddress = ""
}
return json.Marshal(nc.NetworkConfigData)
}
// DefaultBindAddress is the default address that will be listened on. This default may
// not be used in managed cases when no bind address is explicitly set. In those cases
// the server will bind to all interfaces.
const DefaultBindAddress = "localhost:8080"
// Validate ensures all parts of the config are valid. Adds default BindAddress and HeartbeatWindow if not set.
func (nc *NetworkConfig) Validate(path string) error {
if nc.BindAddress != "" && nc.Listener != nil {
return resource.NewConfigValidationError(path, errors.New("may only set one of bind_address or listener"))
}
if nc.BindAddress == "" {
nc.BindAddress = DefaultBindAddress
nc.BindAddressDefaultSet = true
}
if _, _, err := net.SplitHostPort(nc.BindAddress); err != nil {
return resource.NewConfigValidationError(path, errors.Wrap(err, "error validating bind_address"))
}
if (nc.TLSCertFile == "") != (nc.TLSKeyFile == "") {
return resource.NewConfigValidationError(path, errors.New("must provide both tls_cert_file and tls_key_file"))
}
return nc.Sessions.Validate(path + ".sessions")
}
// SessionsConfig configures various parameters used in session management.
type SessionsConfig struct {
// HeartbeatWindow is the window within which clients must send at least one
// heartbeat in order to keep a session alive.
HeartbeatWindow time.Duration
}
// Note: keep this in sync with SessionsConfig.
type sessionsConfigData struct {
HeartbeatWindow string `json:"heartbeat_window,omitempty"`
}
// UnmarshalJSON unmarshals JSON data into this config.
func (sc *SessionsConfig) UnmarshalJSON(data []byte) error {
var temp sessionsConfigData
if err := json.Unmarshal(data, &temp); err != nil {
return err
}
if temp.HeartbeatWindow != "" {
dur, err := time.ParseDuration(temp.HeartbeatWindow)
if err != nil {
return err
}
sc.HeartbeatWindow = dur
}
return nil
}
// MarshalJSON marshals out this config.
func (sc SessionsConfig) MarshalJSON() ([]byte, error) {
var temp sessionsConfigData
if sc.HeartbeatWindow != 0 {
temp.HeartbeatWindow = sc.HeartbeatWindow.String()
}
return json.Marshal(temp)
}
// DefaultSessionHeartbeatWindow is the default session heartbeat window to use when not specified.
// It can be set with network.sessions.heartbeat_window.
const DefaultSessionHeartbeatWindow = 2 * time.Second
// Validate ensures all parts of the config are valid. Sets default HeartbeatWindow if not set.
func (sc *SessionsConfig) Validate(path string) error {
if sc.HeartbeatWindow == 0 {
sc.HeartbeatWindow = DefaultSessionHeartbeatWindow
} else if sc.HeartbeatWindow < 30*time.Millisecond ||
sc.HeartbeatWindow > time.Minute {
return resource.NewConfigValidationError(path, errors.New("heartbeat_window must be between [30ms, 1m]"))
}
return nil
}
// AuthConfig describes authentication and authorization settings for the web server.
type AuthConfig struct {
Handlers []AuthHandlerConfig `json:"handlers,omitempty"`
TLSAuthEntities []string `json:"tls_auth_entities,omitempty"`
ExternalAuthConfig *ExternalAuthConfig `json:"external_auth_config,omitempty"`
}
// ExternalAuthConfig contains information needed to verify externally authenticated tokens.
type ExternalAuthConfig struct {
// contains the raw jwks json.
JSONKeySet rutils.AttributeMap `json:"jwks"`
// on validation the JSONKeySet is validated and parsed into this field and can be used.
ValidatedKeySet jwks.KeySet `json:"-"`
}
var (
allowedKeyTypesForExternalAuth = map[string]bool{
"RSA": true,
}
allowedAlgsForExternalAuth = map[string]bool{
"RS256": true,
"RS384": true,
"RS512": true,
}
)
// Validate returns true if the config is valid. Ensures each key is valid and meets the required constraints.
// Updates ValidatedKeySet once validated. A sample ExternalAuthConfig in JSON form is shown below, where "keys"
// contains a list of JSON Web Keys as defined in https://datatracker.ietf.org/doc/html/rfc7517.
//
// "external_auth_config": {
// "jwks": {
// "keys": [
// {
// "alg": "XXXX",
// "e": "XXXX",
// "kid": "XXXX",
// "kty": "XXXX",
// "n": "XXXX"
// }
// ]
// }
// }
func (c *ExternalAuthConfig) Validate(path string) error {
jwksPath := fmt.Sprintf("%s.jwks", path)
jsonJWKs, err := json.Marshal(c.JSONKeySet)
if err != nil {
return resource.NewConfigValidationError(jwksPath, errors.Wrap(err, "failed to marshal jwks"))
}
keyset, err := jwks.ParseKeySet(string(jsonJWKs))
if err != nil {
return resource.NewConfigValidationError(jwksPath, errors.Wrap(err, "failed to parse jwks"))
}
if keyset.Len() == 0 {
return resource.NewConfigValidationError(jwksPath, errors.New("must contain at least 1 key"))
}
for i := 0; i < keyset.Len(); i++ {
// validate keys
key, ok := keyset.Get(i)
if !ok {
return resource.NewConfigValidationError(fmt.Sprintf("%s.%d", jwksPath, i), errors.New("failed to parse jwks, missing index"))
}
if _, ok := allowedKeyTypesForExternalAuth[key.KeyType().String()]; !ok {
return resource.NewConfigValidationError(fmt.Sprintf("%s.%d", jwksPath, i),
errors.Errorf("failed to parse jwks, invalid key type (%s) only (RSA) supported", key.KeyType().String()))
}
if _, ok := allowedAlgsForExternalAuth[key.Algorithm()]; !ok {
return resource.NewConfigValidationError(fmt.Sprintf("%s.%d", jwksPath, i),
errors.Errorf("failed to parse jwks, invalid alg (%s) type only (RS256, RS384, RS512) supported", key.Algorithm()))
}
}
c.ValidatedKeySet = keyset
return nil
}
// AuthHandlerConfig describes the configuration for a particular auth handler.
type AuthHandlerConfig struct {
Type rpc.CredentialsType `json:"type"`
Config rutils.AttributeMap `json:"config"`
}
// Validate ensures all parts of the config are valid. If it exists, updates ExternalAuthConfig's ValidatedKeySet once validated.
// A sample AuthConfig in JSON form is shown below, where "handlers" contains a list of auth handlers. The only accepted credential
// type for the RDK in the config is "api-key" currently. An auth handler for utils.CredentialsTypeRobotLocationSecret may be added
// later by the RDK during processing.
//
// "auth": {
// "handlers": [
// {
// "type": "api-key",
// "config": {
// "API_KEY_ID": "API_KEY",
// "API_KEY_ID_2": "API_KEY_2",
// "keys": ["API_KEY_ID", "API_KEY_ID_2"]
// }
// }
// ],
// "external_auth_config": {}
// }
func (config *AuthConfig) Validate(path string) error {
seenTypes := make(map[string]struct{}, len(config.Handlers))
for idx, handler := range config.Handlers {
handlerPath := fmt.Sprintf("%s.%s.%d", path, "handlers", idx)
if _, ok := seenTypes[string(handler.Type)]; ok {
return resource.NewConfigValidationError(handlerPath, errors.Errorf("duplicate handler type %q", handler.Type))
}
seenTypes[string(handler.Type)] = struct{}{}
if err := handler.Validate(handlerPath); err != nil {
return err
}
}
if config.ExternalAuthConfig != nil {
if err := config.ExternalAuthConfig.Validate(fmt.Sprintf("%s.%s", path, "external_auth_config")); err != nil {
return err
}
}
return nil
}
// Validate ensures all parts of the config are valid.
func (config *AuthHandlerConfig) Validate(path string) error {
if config.Type == "" {
return resource.NewConfigValidationError(path, errors.New("handler must have type"))
}
switch config.Type {
case rpc.CredentialsTypeAPIKey:
if config.Config.String("key") == "" && len(config.Config.StringSlice("keys")) == 0 {
return resource.NewConfigValidationError(fmt.Sprintf("%s.config", path), errors.New("key or keys is required"))
}
case rpc.CredentialsTypeExternal:
return errors.New("robot cannot issue external auth tokens")
default:
return resource.NewConfigValidationError(path, errors.Errorf("do not know how to handle auth for %q", config.Type))
}
return nil
}
// TLSConfig stores the TLS config for the robot.
type TLSConfig struct {
*tls.Config
certMu sync.Mutex
tlsCert *tls.Certificate
}
// NewTLSConfig creates a new tls config.
func NewTLSConfig(cfg *Config) *TLSConfig {
tlsCfg := &TLSConfig{}
var tlsConfig *tls.Config
if cfg.Cloud != nil && cfg.Cloud.TLSCertificate != "" {
tlsConfig = &tls.Config{
MinVersion: tls.VersionTLS12,
GetCertificate: func(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
// always return same cert
tlsCfg.certMu.Lock()
defer tlsCfg.certMu.Unlock()
return tlsCfg.tlsCert, nil
},
GetClientCertificate: func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) {
// always return same cert
tlsCfg.certMu.Lock()
defer tlsCfg.certMu.Unlock()
return tlsCfg.tlsCert, nil
},
}
}
tlsCfg.Config = tlsConfig
return tlsCfg
}
// UpdateCert updates the TLS certificate to be returned.
func (t *TLSConfig) UpdateCert(cfg *Config) error {
cert, err := tls.X509KeyPair([]byte(cfg.Cloud.TLSCertificate), []byte(cfg.Cloud.TLSPrivateKey))
if err != nil {
return err
}
t.certMu.Lock()
t.tlsCert = &cert
t.certMu.Unlock()
return nil
}
// ProcessConfig processes robot configs.
func ProcessConfig(in *Config, tlsCfg *TLSConfig) (*Config, error) {
out := *in
var selfCreds *rpc.Credentials
if in.Cloud != nil {
if in.Cloud.TLSCertificate != "" {
if err := tlsCfg.UpdateCert(in); err != nil {
return nil, err
}
}
selfCreds = &rpc.Credentials{rutils.CredentialsTypeRobotSecret, in.Cloud.Secret}
out.Network.TLSConfig = tlsCfg.Config // override
}
out.Remotes = make([]Remote, len(in.Remotes))
copy(out.Remotes, in.Remotes)
for idx, remote := range out.Remotes {
remoteCopy := remote
if in.Cloud == nil {
remoteCopy.Auth.SignalingCreds = remoteCopy.Auth.Credentials
} else {
if remote.ManagedBy != in.Cloud.ManagedBy {
continue
}
remoteCopy.Auth.Managed = true
remoteCopy.Auth.SignalingServerAddress = in.Cloud.SignalingAddress
remoteCopy.Auth.SignalingAuthEntity = in.Cloud.ID
remoteCopy.Auth.SignalingCreds = selfCreds
}
out.Remotes[idx] = remoteCopy
}
return &out, nil
}
// DefaultPackageVersionValue default value of the package version used when empty.
const DefaultPackageVersionValue = "latest"
// PackageType indicates the type of the package
// This is used to replace placeholder strings in the config.
type PackageType string
const (
// PackageTypeMlModel represents an ML model.
PackageTypeMlModel PackageType = "ml_model"
// PackageTypeModule represents a module type.
PackageTypeModule PackageType = "module"
// PackageTypeSlamMap represents a slam internal state.
PackageTypeSlamMap PackageType = "slam_map"