forked from smartcontractkit/chainlink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shell.go
1026 lines (890 loc) · 33.2 KB
/
shell.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 cmd
import (
"bytes"
"context"
"crypto/tls"
"database/sql"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/Depado/ginprom"
"github.com/Masterminds/semver/v3"
"github.com/getsentry/sentry-go"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"github.com/urfave/cli"
"go.uber.org/multierr"
"go.uber.org/zap/zapcore"
"golang.org/x/sync/errgroup"
"github.com/jmoiron/sqlx"
"github.com/smartcontractkit/chainlink-common/pkg/loop"
"github.com/smartcontractkit/chainlink/v2/core/build"
"github.com/smartcontractkit/chainlink/v2/core/chains/legacyevm"
"github.com/smartcontractkit/chainlink/v2/core/config"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/logger/audit"
"github.com/smartcontractkit/chainlink/v2/core/services"
"github.com/smartcontractkit/chainlink/v2/core/services/chainlink"
"github.com/smartcontractkit/chainlink/v2/core/services/keystore"
"github.com/smartcontractkit/chainlink/v2/core/services/periodicbackup"
"github.com/smartcontractkit/chainlink/v2/core/services/pg"
"github.com/smartcontractkit/chainlink/v2/core/services/relay/evm/mercury/wsrpc"
"github.com/smartcontractkit/chainlink/v2/core/services/relay/evm/mercury/wsrpc/cache"
"github.com/smartcontractkit/chainlink/v2/core/services/versioning"
"github.com/smartcontractkit/chainlink/v2/core/services/webhook"
"github.com/smartcontractkit/chainlink/v2/core/sessions"
"github.com/smartcontractkit/chainlink/v2/core/static"
"github.com/smartcontractkit/chainlink/v2/core/store/migrate"
"github.com/smartcontractkit/chainlink/v2/core/utils"
clhttp "github.com/smartcontractkit/chainlink/v2/core/utils/http"
"github.com/smartcontractkit/chainlink/v2/core/web"
"github.com/smartcontractkit/chainlink/v2/plugins"
)
var (
initGlobalsOnce sync.Once
prometheus *ginprom.Prometheus
grpcOpts loop.GRPCOpts
)
func initGlobals(cfgProm config.Prometheus, cfgTracing config.Tracing, logger logger.Logger) error {
// Avoid double initializations, but does not prevent relay methods from being called multiple times.
var err error
initGlobalsOnce.Do(func() {
prometheus = ginprom.New(ginprom.Namespace("service"), ginprom.Token(cfgProm.AuthToken()))
grpcOpts = loop.NewGRPCOpts(nil) // default prometheus.Registerer
err = loop.SetupTracing(loop.TracingConfig{
Enabled: cfgTracing.Enabled(),
CollectorTarget: cfgTracing.CollectorTarget(),
NodeAttributes: cfgTracing.Attributes(),
SamplingRatio: cfgTracing.SamplingRatio(),
OnDialError: func(error) { logger.Errorw("Failed to dial", "err", err) },
})
})
return err
}
var (
// ErrorNoAPICredentialsAvailable is returned when not run from a terminal
// and no API credentials have been provided
ErrorNoAPICredentialsAvailable = errors.New("API credentials must be supplied")
)
// Shell for the node, local commands and remote commands.
type Shell struct {
Renderer
Config chainlink.GeneralConfig // initialized in Before
Logger logger.Logger // initialized in Before
CloseLogger func() error // called in After
AppFactory AppFactory
KeyStoreAuthenticator TerminalKeyStoreAuthenticator
FallbackAPIInitializer APIInitializer
Runner Runner
HTTP HTTPClient
CookieAuthenticator CookieAuthenticator
FileSessionRequestBuilder SessionRequestBuilder
PromptingSessionRequestBuilder SessionRequestBuilder
ChangePasswordPrompter ChangePasswordPrompter
PasswordPrompter PasswordPrompter
configFiles []string
configFilesIsSet bool
secretsFiles []string
secretsFileIsSet bool
}
func (s *Shell) errorOut(err error) cli.ExitCoder {
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
return nil
}
// exitOnConfigError is helper that executes as validation func and
// pretty-prints errors
func (s *Shell) configExitErr(validateFn func() error) cli.ExitCoder {
err := validateFn()
if err != nil {
fmt.Println("Invalid configuration:", err)
fmt.Println()
return s.errorOut(errors.New("invalid configuration"))
}
return nil
}
// AppFactory implements the NewApplication method.
type AppFactory interface {
NewApplication(ctx context.Context, cfg chainlink.GeneralConfig, appLggr logger.Logger, db *sqlx.DB) (chainlink.Application, error)
}
// ChainlinkAppFactory is used to create a new Application.
type ChainlinkAppFactory struct{}
// NewApplication returns a new instance of the node with the given config.
func (n ChainlinkAppFactory) NewApplication(ctx context.Context, cfg chainlink.GeneralConfig, appLggr logger.Logger, db *sqlx.DB) (app chainlink.Application, err error) {
err = initGlobals(cfg.Prometheus(), cfg.Tracing(), appLggr)
if err != nil {
appLggr.Errorf("Failed to initialize globals: %v", err)
}
err = migrate.SetMigrationENVVars(cfg)
if err != nil {
return nil, err
}
err = handleNodeVersioning(ctx, db, appLggr, cfg.RootDir(), cfg.Database(), cfg.WebServer().HTTPPort())
if err != nil {
return nil, err
}
keyStore := keystore.New(db, utils.GetScryptParams(cfg), appLggr, cfg.Database())
mailMon := utils.NewMailboxMonitor(cfg.AppID().String())
dbListener := cfg.Database().Listener()
eventBroadcaster := pg.NewEventBroadcaster(cfg.Database().URL(), dbListener.MinReconnectInterval(), dbListener.MaxReconnectDuration(), appLggr, cfg.AppID())
loopRegistry := plugins.NewLoopRegistry(appLggr, cfg.Tracing())
mercuryPool := wsrpc.NewPool(appLggr, cache.Config{
LatestReportTTL: cfg.Mercury().Cache().LatestReportTTL(),
MaxStaleAge: cfg.Mercury().Cache().MaxStaleAge(),
LatestReportDeadline: cfg.Mercury().Cache().LatestReportDeadline(),
})
// create the relayer-chain interoperators from application configuration
relayerFactory := chainlink.RelayerFactory{
Logger: appLggr,
LoopRegistry: loopRegistry,
GRPCOpts: grpcOpts,
MercuryPool: mercuryPool,
}
evmFactoryCfg := chainlink.EVMFactoryConfig{
CSAETHKeystore: keyStore,
ChainOpts: legacyevm.ChainOpts{AppConfig: cfg, EventBroadcaster: eventBroadcaster, MailMon: mailMon, DB: db},
}
// evm always enabled for backward compatibility
// TODO BCF-2510 this needs to change in order to clear the path for EVM extraction
initOps := []chainlink.CoreRelayerChainInitFunc{chainlink.InitEVM(ctx, relayerFactory, evmFactoryCfg)}
if cfg.CosmosEnabled() {
cosmosCfg := chainlink.CosmosFactoryConfig{
Keystore: keyStore.Cosmos(),
TOMLConfigs: cfg.CosmosConfigs(),
DB: db,
QConfig: cfg.Database(),
}
initOps = append(initOps, chainlink.InitCosmos(ctx, relayerFactory, cosmosCfg))
}
if cfg.SolanaEnabled() {
solanaCfg := chainlink.SolanaFactoryConfig{
Keystore: keyStore.Solana(),
TOMLConfigs: cfg.SolanaConfigs(),
}
initOps = append(initOps, chainlink.InitSolana(ctx, relayerFactory, solanaCfg))
}
if cfg.StarkNetEnabled() {
starkCfg := chainlink.StarkNetFactoryConfig{
Keystore: keyStore.StarkNet(),
TOMLConfigs: cfg.StarknetConfigs(),
}
initOps = append(initOps, chainlink.InitStarknet(ctx, relayerFactory, starkCfg))
}
relayChainInterops, err := chainlink.NewCoreRelayerChainInteroperators(initOps...)
if err != nil {
return nil, err
}
// Configure and optionally start the audit log forwarder service
auditLogger, err := audit.NewAuditLogger(appLggr, cfg.AuditLogger())
if err != nil {
return nil, err
}
restrictedClient := clhttp.NewRestrictedHTTPClient(cfg.Database(), appLggr)
unrestrictedClient := clhttp.NewUnrestrictedHTTPClient()
externalInitiatorManager := webhook.NewExternalInitiatorManager(db, unrestrictedClient, appLggr, cfg.Database())
return chainlink.NewApplication(chainlink.ApplicationOpts{
Config: cfg,
SqlxDB: db,
KeyStore: keyStore,
RelayerChainInteroperators: relayChainInterops,
EventBroadcaster: eventBroadcaster,
MailMon: mailMon,
Logger: appLggr,
AuditLogger: auditLogger,
ExternalInitiatorManager: externalInitiatorManager,
Version: static.Version,
RestrictedHTTPClient: restrictedClient,
UnrestrictedHTTPClient: unrestrictedClient,
SecretGenerator: chainlink.FilePersistedSecretGenerator{},
LoopRegistry: loopRegistry,
GRPCOpts: grpcOpts,
MercuryPool: mercuryPool,
})
}
// handleNodeVersioning is a setup-time helper to encapsulate version changes and db migration
func handleNodeVersioning(ctx context.Context, db *sqlx.DB, appLggr logger.Logger, rootDir string, cfg config.Database, healthReportPort uint16) error {
var err error
// Set up the versioning Configs
verORM := versioning.NewORM(db, appLggr, cfg.DefaultQueryTimeout())
if static.Version != static.Unset {
var appv, dbv *semver.Version
appv, dbv, err = versioning.CheckVersion(db, appLggr, static.Version)
if err != nil {
// Exit immediately and don't touch the database if the app version is too old
return fmt.Errorf("CheckVersion: %w", err)
}
// Take backup if app version is newer than DB version
// Need to do this BEFORE migration
backupCfg := cfg.Backup()
if backupCfg.Mode() != config.DatabaseBackupModeNone && backupCfg.OnVersionUpgrade() {
if err = takeBackupIfVersionUpgrade(cfg.URL(), rootDir, cfg.Backup(), appLggr, appv, dbv, healthReportPort); err != nil {
if errors.Is(err, sql.ErrNoRows) {
appLggr.Debugf("Failed to find any node version in the DB: %w", err)
} else if strings.Contains(err.Error(), "relation \"node_versions\" does not exist") {
appLggr.Debugf("Failed to find any node version in the DB, the node_versions table does not exist yet: %w", err)
} else {
return fmt.Errorf("initializeORM#FindLatestNodeVersion: %w", err)
}
}
}
}
// Migrate the database
if cfg.MigrateDatabase() {
if err = migrate.Migrate(ctx, db.DB, appLggr); err != nil {
return fmt.Errorf("initializeORM#Migrate: %w", err)
}
}
// Update to latest version
if static.Version != static.Unset {
version := versioning.NewNodeVersion(static.Version)
if err = verORM.UpsertNodeVersion(version); err != nil {
return fmt.Errorf("UpsertNodeVersion: %w", err)
}
}
return nil
}
func takeBackupIfVersionUpgrade(dbUrl url.URL, rootDir string, cfg periodicbackup.BackupConfig, lggr logger.Logger, appv, dbv *semver.Version, healthReportPort uint16) (err error) {
if appv == nil {
lggr.Debug("Application version is missing, skipping automatic DB backup.")
return nil
}
if dbv == nil {
lggr.Debug("Database version is missing, skipping automatic DB backup.")
return nil
}
if !appv.GreaterThan(dbv) {
lggr.Debugf("Application version %s is older or equal to database version %s, skipping automatic DB backup.", appv.String(), dbv.String())
return nil
}
lggr.Infof("Upgrade detected: application version %s is newer than database version %s, taking automatic DB backup. To skip automatic database backup before version upgrades, set Database.Backup.OnVersionUpgrade=false. To disable backups entirely set Database.Backup.Mode=none.", appv.String(), dbv.String())
databaseBackup, err := periodicbackup.NewDatabaseBackup(dbUrl, rootDir, cfg, lggr)
if err != nil {
return errors.Wrap(err, "takeBackupIfVersionUpgrade failed")
}
//Because backups can take a long time we must start a "fake" health report to prevent
//node shutdown because of healthcheck fail/timeout
ibhr := services.NewInBackupHealthReport(healthReportPort, lggr)
ibhr.Start()
defer ibhr.Stop()
err = databaseBackup.RunBackup(appv.String())
return err
}
// Runner implements the Run method.
type Runner interface {
Run(context.Context, chainlink.Application) error
}
// ChainlinkRunner is used to run the node application.
type ChainlinkRunner struct{}
// Run sets the log level based on config and starts the web router to listen
// for input and return data.
func (n ChainlinkRunner) Run(ctx context.Context, app chainlink.Application) error {
config := app.GetConfig()
mode := gin.ReleaseMode
if !build.IsProd() && config.Log().Level() < zapcore.InfoLevel {
mode = gin.DebugMode
}
gin.SetMode(mode)
gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {
app.GetLogger().Debugf("%-6s %-25s --> %s (%d handlers)", httpMethod, absolutePath, handlerName, nuHandlers)
}
if err := sentryInit(config.Sentry()); err != nil {
return errors.Wrap(err, "failed to initialize sentry")
}
ws := config.WebServer()
if ws.HTTPPort() == 0 && ws.TLS().HTTPSPort() == 0 {
return errors.New("You must specify at least one port to listen on")
}
handler, err := web.NewRouter(app, prometheus)
if err != nil {
return errors.Wrap(err, "failed to create web router")
}
server := server{handler: handler, lggr: app.GetLogger()}
g, gCtx := errgroup.WithContext(ctx)
serverStartTimeoutDuration := config.WebServer().StartTimeout()
if ws.HTTPPort() != 0 {
go tryRunServerUntilCancelled(gCtx, app.GetLogger(), serverStartTimeoutDuration, func() error {
return server.run(ws.ListenIP(), ws.HTTPPort(), config.WebServer().HTTPWriteTimeout())
})
}
tls := config.WebServer().TLS()
if tls.HTTPSPort() != 0 {
go tryRunServerUntilCancelled(gCtx, app.GetLogger(), serverStartTimeoutDuration, func() error {
return server.runTLS(
tls.ListenIP(),
tls.HTTPSPort(),
tls.CertFile(),
tls.KeyFile(),
config.WebServer().HTTPWriteTimeout())
})
}
g.Go(func() error {
<-gCtx.Done()
var err error
if server.httpServer != nil {
err = errors.WithStack(server.httpServer.Shutdown(context.Background()))
}
if server.tlsServer != nil {
err = multierr.Combine(err, errors.WithStack(server.tlsServer.Shutdown(context.Background())))
}
return err
})
return errors.WithStack(g.Wait())
}
func sentryInit(cfg config.Sentry) error {
sentrydsn := cfg.DSN()
if sentrydsn == "" {
// Do not initialize sentry at all if the DSN is missing
return nil
}
var sentryenv string
if env := cfg.Environment(); env != "" {
sentryenv = env
} else if !build.IsProd() {
sentryenv = "dev"
} else {
sentryenv = "prod"
}
var sentryrelease string
if release := cfg.Release(); release != "" {
sentryrelease = release
} else {
sentryrelease = static.Version
}
return sentry.Init(sentry.ClientOptions{
// AttachStacktrace is needed to send stacktrace alongside panics
AttachStacktrace: true,
Dsn: sentrydsn,
Environment: sentryenv,
Release: sentryrelease,
Debug: cfg.Debug(),
})
}
func tryRunServerUntilCancelled(ctx context.Context, lggr logger.Logger, timeout time.Duration, runServer func() error) {
for {
// try calling runServer() and log error if any
if err := runServer(); err != nil {
if !errors.Is(err, http.ErrServerClosed) {
lggr.Criticalf("Error starting server: %v", err)
}
}
// if ctx is cancelled, we must leave the loop
select {
case <-ctx.Done():
return
case <-time.After(timeout):
// pause between attempts, default 15s
}
}
}
type server struct {
httpServer *http.Server
tlsServer *http.Server
handler *gin.Engine
lggr logger.Logger
}
func (s *server) run(ip net.IP, port uint16, writeTimeout time.Duration) error {
addr := fmt.Sprintf("%s:%d", ip.String(), port)
s.lggr.Infow(fmt.Sprintf("Listening and serving HTTP on %s", addr), "ip", ip, "port", port)
s.httpServer = createServer(s.handler, addr, writeTimeout)
err := s.httpServer.ListenAndServe()
return errors.Wrap(err, "failed to run plaintext HTTP server")
}
func (s *server) runTLS(ip net.IP, port uint16, certFile, keyFile string, requestTimeout time.Duration) error {
addr := fmt.Sprintf("%s:%d", ip.String(), port)
s.lggr.Infow(fmt.Sprintf("Listening and serving HTTPS on %s", addr), "ip", ip, "port", port)
s.tlsServer = createServer(s.handler, addr, requestTimeout)
err := s.tlsServer.ListenAndServeTLS(certFile, keyFile)
return errors.Wrap(err, "failed to run TLS server (NOTE: you can disable TLS server completely and silence these errors by setting WebServer.TLS.HTTPSPort=0 in your config)")
}
func createServer(handler *gin.Engine, addr string, requestTimeout time.Duration) *http.Server {
s := &http.Server{
Addr: addr,
Handler: handler,
ReadTimeout: requestTimeout,
WriteTimeout: requestTimeout,
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 20,
}
return s
}
// HTTPClient encapsulates all methods used to interact with a chainlink node API.
type HTTPClient interface {
Get(string, ...map[string]string) (*http.Response, error)
Post(string, io.Reader) (*http.Response, error)
Put(string, io.Reader) (*http.Response, error)
Patch(string, io.Reader, ...map[string]string) (*http.Response, error)
Delete(string) (*http.Response, error)
}
type authenticatedHTTPClient struct {
client *http.Client
cookieAuth CookieAuthenticator
sessionRequest sessions.SessionRequest
remoteNodeURL url.URL
}
// NewAuthenticatedHTTPClient uses the CookieAuthenticator to generate a sessionID
// which is then used for all subsequent HTTP API requests.
func NewAuthenticatedHTTPClient(lggr logger.Logger, clientOpts ClientOpts, cookieAuth CookieAuthenticator, sessionRequest sessions.SessionRequest) HTTPClient {
return &authenticatedHTTPClient{
client: newHttpClient(lggr, clientOpts.InsecureSkipVerify),
cookieAuth: cookieAuth,
sessionRequest: sessionRequest,
remoteNodeURL: clientOpts.RemoteNodeURL,
}
}
func newHttpClient(lggr logger.Logger, insecureSkipVerify bool) *http.Client {
tr := &http.Transport{
// User enables this at their own risk!
// #nosec G402
TLSClientConfig: &tls.Config{InsecureSkipVerify: insecureSkipVerify},
}
if insecureSkipVerify {
lggr.Warn("InsecureSkipVerify is on, skipping SSL certificate verification.")
}
return &http.Client{Transport: tr}
}
// Get performs an HTTP Get using the authenticated HTTP client's cookie.
func (h *authenticatedHTTPClient) Get(path string, headers ...map[string]string) (*http.Response, error) {
return h.doRequest("GET", path, nil, headers...)
}
// Post performs an HTTP Post using the authenticated HTTP client's cookie.
func (h *authenticatedHTTPClient) Post(path string, body io.Reader) (*http.Response, error) {
return h.doRequest("POST", path, body)
}
// Put performs an HTTP Put using the authenticated HTTP client's cookie.
func (h *authenticatedHTTPClient) Put(path string, body io.Reader) (*http.Response, error) {
return h.doRequest("PUT", path, body)
}
// Patch performs an HTTP Patch using the authenticated HTTP client's cookie.
func (h *authenticatedHTTPClient) Patch(path string, body io.Reader, headers ...map[string]string) (*http.Response, error) {
return h.doRequest("PATCH", path, body, headers...)
}
// Delete performs an HTTP Delete using the authenticated HTTP client's cookie.
func (h *authenticatedHTTPClient) Delete(path string) (*http.Response, error) {
return h.doRequest("DELETE", path, nil)
}
func (h *authenticatedHTTPClient) doRequest(verb, path string, body io.Reader, headerArgs ...map[string]string) (*http.Response, error) {
var headers map[string]string
if len(headerArgs) > 0 {
headers = headerArgs[0]
} else {
headers = map[string]string{}
}
request, err := http.NewRequest(verb, h.remoteNodeURL.String()+path, body)
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
for key, value := range headers {
request.Header.Add(key, value)
}
cookie, err := h.cookieAuth.Cookie()
if err != nil {
return nil, err
} else if cookie != nil {
request.AddCookie(cookie)
}
response, err := h.client.Do(request)
if err != nil {
return response, err
}
if response.StatusCode == http.StatusUnauthorized && (h.sessionRequest.Email != "" || h.sessionRequest.Password != "") {
var cookieerr error
cookie, cookieerr = h.cookieAuth.Authenticate(h.sessionRequest)
if cookieerr != nil {
return response, err
}
request.Header.Set("Cookie", "")
request.AddCookie(cookie)
response, err = h.client.Do(request)
if err != nil {
return response, err
}
}
return response, nil
}
// CookieAuthenticator is the interface to generating a cookie to authenticate
// future HTTP requests.
type CookieAuthenticator interface {
Cookie() (*http.Cookie, error)
Authenticate(sessions.SessionRequest) (*http.Cookie, error)
Logout() error
}
type ClientOpts struct {
RemoteNodeURL url.URL
InsecureSkipVerify bool
}
// SessionCookieAuthenticator is a concrete implementation of CookieAuthenticator
// that retrieves a session id for the user with credentials from the session request.
type SessionCookieAuthenticator struct {
config ClientOpts
store CookieStore
lggr logger.SugaredLogger
}
// NewSessionCookieAuthenticator creates a SessionCookieAuthenticator using the passed config
// and builder.
func NewSessionCookieAuthenticator(config ClientOpts, store CookieStore, lggr logger.Logger) CookieAuthenticator {
return &SessionCookieAuthenticator{config: config, store: store, lggr: logger.Sugared(lggr)}
}
// Cookie Returns the previously saved authentication cookie.
func (t *SessionCookieAuthenticator) Cookie() (*http.Cookie, error) {
return t.store.Retrieve()
}
// Authenticate retrieves a session ID via a cookie and saves it to disk.
func (t *SessionCookieAuthenticator) Authenticate(sessionRequest sessions.SessionRequest) (*http.Cookie, error) {
b := new(bytes.Buffer)
err := json.NewEncoder(b).Encode(sessionRequest)
if err != nil {
return nil, err
}
url := t.config.RemoteNodeURL.String() + "/sessions"
req, err := http.NewRequest("POST", url, b)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
client := newHttpClient(t.lggr, t.config.InsecureSkipVerify)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer t.lggr.ErrorIfFn(resp.Body.Close, "Error closing Authenticate response body")
_, err = parseResponse(resp)
if err != nil {
return nil, err
}
cookies := resp.Cookies()
if len(cookies) == 0 {
return nil, errors.New("did not receive cookie with session id")
}
sc := web.FindSessionCookie(cookies)
return sc, t.store.Save(sc)
}
// Deletes any stored session
func (t *SessionCookieAuthenticator) Logout() error {
return t.store.Reset()
}
// CookieStore is a place to store and retrieve cookies.
type CookieStore interface {
Save(cookie *http.Cookie) error
Retrieve() (*http.Cookie, error)
Reset() error
}
// MemoryCookieStore keeps a single cookie in memory
type MemoryCookieStore struct {
Cookie *http.Cookie
}
// Save stores a cookie.
func (m *MemoryCookieStore) Save(cookie *http.Cookie) error {
m.Cookie = cookie
return nil
}
// Removes any stored cookie.
func (m *MemoryCookieStore) Reset() error {
m.Cookie = nil
return nil
}
// Retrieve returns any Saved cookies.
func (m *MemoryCookieStore) Retrieve() (*http.Cookie, error) {
return m.Cookie, nil
}
type DiskCookieConfig interface {
RootDir() string
}
// DiskCookieStore saves a single cookie in the local cli working directory.
type DiskCookieStore struct {
Config DiskCookieConfig
}
// Save stores a cookie.
func (d DiskCookieStore) Save(cookie *http.Cookie) error {
return os.WriteFile(d.cookiePath(), []byte(cookie.String()), 0600)
}
// Removes any stored cookie.
func (d DiskCookieStore) Reset() error {
// Write empty bytes
return os.WriteFile(d.cookiePath(), []byte(""), 0600)
}
// Retrieve returns any Saved cookies.
func (d DiskCookieStore) Retrieve() (*http.Cookie, error) {
b, err := os.ReadFile(d.cookiePath())
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, multierr.Append(errors.New("unable to retrieve credentials, you must first login through the CLI"), err)
}
header := http.Header{}
header.Add("Cookie", string(b))
request := http.Request{Header: header}
cookies := request.Cookies()
if len(cookies) == 0 {
return nil, errors.New("Cookie not in file, you must first login through the CLI")
}
return request.Cookies()[0], nil
}
func (d DiskCookieStore) cookiePath() string {
return path.Join(d.Config.RootDir(), "cookie")
}
type UserCache struct {
dir string
lggr func() logger.Logger // func b/c we don't have the final logger at construction time
ensureOnce sync.Once
}
func NewUserCache(subdir string, lggr func() logger.Logger) (*UserCache, error) {
cd, err := os.UserCacheDir()
if err != nil {
return nil, err
}
return &UserCache{dir: filepath.Join(cd, "chainlink", subdir), lggr: lggr}, nil
}
func (cs *UserCache) ensure() {
if err := os.MkdirAll(cs.dir, 0700); err != nil {
cs.lggr().Errorw("Failed to make user cache dir", "dir", cs.dir, "err", err)
}
}
func (cs *UserCache) RootDir() string {
cs.ensureOnce.Do(cs.ensure)
return cs.dir
}
// SessionRequestBuilder is an interface that returns a SessionRequest,
// abstracting how session requests are generated, whether they be from
// the prompt or from a file.
type SessionRequestBuilder interface {
Build(flag string) (sessions.SessionRequest, error)
}
type promptingSessionRequestBuilder struct {
prompter Prompter
}
// NewPromptingSessionRequestBuilder uses a prompter, often via terminal,
// to solicit information from a user to generate the SessionRequest.
func NewPromptingSessionRequestBuilder(prompter Prompter) SessionRequestBuilder {
return promptingSessionRequestBuilder{prompter}
}
func (p promptingSessionRequestBuilder) Build(string) (sessions.SessionRequest, error) {
email := p.prompter.Prompt("Enter email: ")
pwd := p.prompter.PasswordPrompt("Enter password: ")
return sessions.SessionRequest{Email: email, Password: pwd}, nil
}
type fileSessionRequestBuilder struct {
lggr logger.Logger
}
// NewFileSessionRequestBuilder pulls credentials from a file to generate a SessionRequest.
func NewFileSessionRequestBuilder(lggr logger.Logger) SessionRequestBuilder {
return &fileSessionRequestBuilder{lggr: lggr}
}
func (f *fileSessionRequestBuilder) Build(file string) (sessions.SessionRequest, error) {
return credentialsFromFile(file, f.lggr.With("file", file))
}
// APIInitializer is the interface used to create the API User credentials
// needed to access the API. Does nothing if API user already exists.
type APIInitializer interface {
// Initialize creates a new local Admin user for API access, or does nothing if one exists.
Initialize(orm sessions.BasicAdminUsersORM, lggr logger.Logger) (sessions.User, error)
}
type promptingAPIInitializer struct {
prompter Prompter
}
// NewPromptingAPIInitializer creates a concrete instance of APIInitializer
// that uses the terminal to solicit credentials from the user.
func NewPromptingAPIInitializer(prompter Prompter) APIInitializer {
return &promptingAPIInitializer{prompter: prompter}
}
// Initialize uses the terminal to get credentials that it then saves in the store.
func (t *promptingAPIInitializer) Initialize(orm sessions.BasicAdminUsersORM, lggr logger.Logger) (sessions.User, error) {
// Load list of users to determine which to assume, or if a user needs to be created
dbUsers, err := orm.ListUsers()
if err != nil {
return sessions.User{}, errors.Wrap(err, "Unable to List users for initialization")
}
// If there are no users in the database, prompt for initial admin user creation
if len(dbUsers) == 0 {
if !t.prompter.IsTerminal() {
return sessions.User{}, ErrorNoAPICredentialsAvailable
}
for {
email := t.prompter.Prompt("Enter API Email: ")
pwd := t.prompter.PasswordPrompt("Enter API Password: ")
// On a fresh DB, create an admin user
user, err2 := sessions.NewUser(email, pwd, sessions.UserRoleAdmin)
if err2 != nil {
lggr.Errorw("Error creating API user", "err", err2)
continue
}
if err = orm.CreateUser(&user); err != nil {
lggr.Errorf("Error creating API user: ", err, "err")
}
return user, err
}
}
// Attempt to contextually return the correct admin user, CLI access here implies admin
if adminUser, found := attemptAssumeAdminUser(dbUsers, lggr); found {
return adminUser, nil
}
// Otherwise, multiple admin users exist, prompt for which to use
email := t.prompter.Prompt("Enter email of API user account to assume: ")
user, err := orm.FindUser(email)
if err != nil {
return sessions.User{}, err
}
return user, nil
}
type fileAPIInitializer struct {
file string
}
// NewFileAPIInitializer creates a concrete instance of APIInitializer
// that pulls API user credentials from the passed file path.
func NewFileAPIInitializer(file string) APIInitializer {
return fileAPIInitializer{file: file}
}
func (f fileAPIInitializer) Initialize(orm sessions.BasicAdminUsersORM, lggr logger.Logger) (sessions.User, error) {
request, err := credentialsFromFile(f.file, lggr)
if err != nil {
return sessions.User{}, err
}
// Load list of users to determine which to assume, or if a user needs to be created
dbUsers, err := orm.ListUsers()
if err != nil {
return sessions.User{}, errors.Wrap(err, "Unable to List users for initialization")
}
// If there are no users in the database, create initial admin user from session request from file creds
if len(dbUsers) == 0 {
user, err2 := sessions.NewUser(request.Email, request.Password, sessions.UserRoleAdmin)
if err2 != nil {
return user, errors.Wrap(err2, "failed to instantiate new user")
}
return user, orm.CreateUser(&user)
}
// Attempt to contextually return the correct admin user, CLI access here implies admin
if adminUser, found := attemptAssumeAdminUser(dbUsers, lggr); found {
return adminUser, nil
}
// Otherwise, multiple admin users exist, attempt to load email specified in session request
user, err := orm.FindUser(request.Email)
if err != nil {
return sessions.User{}, err
}
return user, nil
}
func attemptAssumeAdminUser(users []sessions.User, lggr logger.Logger) (sessions.User, bool) {
if len(users) == 0 {
return sessions.User{}, false
}
// If there is only a single DB user, select it within the context of CLI
if len(users) == 1 {
lggr.Infow("Defaulted to assume single DB API User", "email", users[0].Email)
return users[0], true
}
// If there is only one admin user, use it within the context of CLI
var singleAdmin sessions.User
populatedUser := false
for _, user := range users {
if user.Role == sessions.UserRoleAdmin {
// If multiple admin users found, don't use assume any and clear to continue to prompt
if populatedUser {
// Clear flag to skip return
populatedUser = false
break
}
singleAdmin = user
populatedUser = true
}
}
if populatedUser {
lggr.Infow("Defaulted to assume single DB admin API User", "email", singleAdmin)
return singleAdmin, true
}
return sessions.User{}, false
}
var ErrNoCredentialFile = errors.New("no API user credential file was passed")
func credentialsFromFile(file string, lggr logger.Logger) (sessions.SessionRequest, error) {
if len(file) == 0 {
return sessions.SessionRequest{}, ErrNoCredentialFile
}
lggr.Debug("Initializing API credentials")
dat, err := os.ReadFile(file)
if err != nil {
return sessions.SessionRequest{}, err
}
lines := strings.Split(string(dat), "\n")
if len(lines) < 2 {
return sessions.SessionRequest{}, fmt.Errorf("malformed API credentials file does not have at least two lines at %s", file)
}
credentials := sessions.SessionRequest{
Email: strings.TrimSpace(lines[0]),
Password: strings.TrimSpace(lines[1]),
}
return credentials, nil
}
// ChangePasswordPrompter is an interface primarily used for DI to obtain a
// password change request from the User.
type ChangePasswordPrompter interface {
Prompt() (web.UpdatePasswordRequest, error)
}
// NewChangePasswordPrompter returns the production password change request prompter
func NewChangePasswordPrompter() ChangePasswordPrompter {
prompter := NewTerminalPrompter()
return changePasswordPrompter{prompter: prompter}
}
type changePasswordPrompter struct {
prompter Prompter
}
func (c changePasswordPrompter) Prompt() (web.UpdatePasswordRequest, error) {
fmt.Println("Changing your chainlink account password.")
fmt.Println("NOTE: This will terminate any other sessions.")
oldPassword := c.prompter.PasswordPrompt("Password:")
fmt.Println("Now enter your **NEW** password")
newPassword := c.prompter.PasswordPrompt("Password:")
confirmPassword := c.prompter.PasswordPrompt("Confirmation:")
if newPassword != confirmPassword {
return web.UpdatePasswordRequest{}, errors.New("new password and confirmation did not match")
}
return web.UpdatePasswordRequest{
OldPassword: oldPassword,
NewPassword: newPassword,
}, nil
}
// PasswordPrompter is an interface primarily used for DI to obtain a password
// from the User.
type PasswordPrompter interface {
Prompt() string
}
// NewPasswordPrompter returns the production password change request prompter
func NewPasswordPrompter() PasswordPrompter {
prompter := NewTerminalPrompter()
return passwordPrompter{prompter: prompter}
}
type passwordPrompter struct {
prompter Prompter