-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathhandler.go
More file actions
778 lines (694 loc) · 26.8 KB
/
Copy pathhandler.go
File metadata and controls
778 lines (694 loc) · 26.8 KB
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
package common
import (
"context"
"crypto/ecdsa"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"unicode/utf8"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/google/uuid"
"github.com/machinebox/graphql"
"github.com/rs/zerolog"
"google.golang.org/protobuf/encoding/protojson"
"gopkg.in/yaml.v2"
"github.com/smartcontractkit/chainlink-common/pkg/capabilities/actions/vault"
"github.com/smartcontractkit/chainlink-common/pkg/jsonrpc2"
"github.com/smartcontractkit/chainlink-evm/gethwrappers/workflow/generated/workflow_registry_wrapper_v2"
"github.com/smartcontractkit/chainlink/v2/core/capabilities/vault/vaulttypes"
"github.com/smartcontractkit/tdh2/go/tdh2/tdh2easy"
"github.com/smartcontractkit/cre-cli/cmd/client"
cmdCommon "github.com/smartcontractkit/cre-cli/cmd/common"
"github.com/smartcontractkit/cre-cli/internal/client/graphqlclient"
"github.com/smartcontractkit/cre-cli/internal/constants"
"github.com/smartcontractkit/cre-cli/internal/credentials"
"github.com/smartcontractkit/cre-cli/internal/environments"
"github.com/smartcontractkit/cre-cli/internal/ethkeys"
"github.com/smartcontractkit/cre-cli/internal/runtime"
"github.com/smartcontractkit/cre-cli/internal/settings"
"github.com/smartcontractkit/cre-cli/internal/types"
"github.com/smartcontractkit/cre-cli/internal/ui"
"github.com/smartcontractkit/cre-cli/internal/validation"
)
// UpsertSecretsInputs holds the secrets passed to the CLI.
type UpsertSecretsInputs []SecretItem
// SecretItem represents a single secret with its ID, value, and optional namespace.
type SecretItem struct {
ID string `json:"id" validate:"required"`
Value string `json:"value" validate:"required"`
Namespace string `json:"namespace"`
}
type SecretsYamlConfig struct {
SecretsNames map[string][]string `yaml:"secretsNames"`
}
type Handler struct {
Log *zerolog.Logger
ClientFactory client.Factory
SecretsFilePath string
PrivateKey *ecdsa.PrivateKey
OwnerAddress string
DerivedWorkflowOwner string
EnvironmentSet *environments.EnvironmentSet
Gw GatewayClient
Wrc *client.WorkflowRegistryV2Client
Credentials *credentials.Credentials
Settings *settings.Settings
}
// NewHandler creates a new handler instance.
// secretsAuth is the value of the --secrets-auth flag (e.g. "onchain" or "browser").
// For the browser OAuth flow the on-chain WorkflowRegistryV2Client is not needed and is
// intentionally skipped to avoid requiring an ethereum-mainnet RPC URL.
func NewHandler(ctx *runtime.Context, secretsFilePath, secretsAuth string) (*Handler, error) {
var pk *ecdsa.PrivateKey
var err error
if ctx.Settings.User.EthPrivateKey != "" {
pk, err = crypto.HexToECDSA(ctx.Settings.User.EthPrivateKey)
if err != nil {
return nil, fmt.Errorf("failed to decode the provided private key: %w", err)
}
} else {
ctx.Logger.Debug().Msg("No EthPrivateKey found in settings; assuming a multisig request.")
}
h := &Handler{
Log: ctx.Logger,
ClientFactory: ctx.ClientFactory,
SecretsFilePath: secretsFilePath,
PrivateKey: pk,
OwnerAddress: ctx.Settings.Workflow.UserWorkflowSettings.WorkflowOwnerAddress,
DerivedWorkflowOwner: ctx.DerivedWorkflowOwner,
EnvironmentSet: ctx.EnvironmentSet,
Credentials: ctx.Credentials,
Settings: ctx.Settings,
}
h.Gw = &HTTPClient{URL: h.EnvironmentSet.GatewayURL, Client: &http.Client{Timeout: 90 * time.Second}}
if !IsBrowserFlow(secretsAuth) {
wrc, err := h.ClientFactory.NewWorkflowRegistryV2Client()
if err != nil {
return nil, fmt.Errorf("failed to create workflow registry client: %w", err)
}
h.Wrc = wrc
}
return h, nil
}
// EnsureDeploymentRPCForOwnerKeySecrets checks project settings for an RPC URL on the workflow registry chain (owner-key / allowlist flows only).
func (h *Handler) EnsureDeploymentRPCForOwnerKeySecrets() error {
return settings.ValidateDeploymentRPC(&h.Settings.Workflow, h.EnvironmentSet.WorkflowRegistryChainName)
}
// ResolveInputs loads secrets from a YAML file.
// Errors if the path is not .yaml/.yml — MSIG step 2 is handled by `cre secrets execute`.
func (h *Handler) ResolveInputs() (UpsertSecretsInputs, error) {
ext := strings.ToLower(filepath.Ext(h.SecretsFilePath))
if ext != ".yaml" && ext != ".yml" {
return nil, fmt.Errorf("expected a YAML file; for MSIG step 2 use `cre secrets execute <bundle.json>`")
}
fileContent, err := os.ReadFile(h.SecretsFilePath)
if err != nil {
return nil, fmt.Errorf("failed to read secrets file: %w", err)
}
var cfg SecretsYamlConfig
if err := yaml.Unmarshal(fileContent, &cfg); err != nil {
return nil, fmt.Errorf("failed to parse YAML: %w", err)
}
if len(cfg.SecretsNames) == 0 {
return nil, fmt.Errorf("YAML must contain a non-empty 'secretsNames' map")
}
out := make(UpsertSecretsInputs, 0, len(cfg.SecretsNames))
for id, values := range cfg.SecretsNames {
if !utf8.ValidString(id) {
return nil, fmt.Errorf("secret id %q contains invalid UTF-8", id)
}
if len(values) == 0 {
return nil, fmt.Errorf("secret %q has no values", id)
}
if len(values) != 1 {
return nil, fmt.Errorf("secret %q must have exactly one env var name; got %d", id, len(values))
}
envName := strings.TrimSpace(values[0])
if envName == "" {
return nil, fmt.Errorf("secret %q has an empty env var name", id)
}
envVal, ok := os.LookupEnv(envName)
if !ok {
return nil, fmt.Errorf("environment variable %q for secret %q not found; please export it", envName, id)
}
if !utf8.ValidString(envVal) {
return nil, fmt.Errorf("value for secret %q (env %q) contains invalid UTF-8", id, envName)
}
out = append(out, SecretItem{
ID: id,
Value: envVal,
Namespace: "main",
})
// Enforce max payload size of 10 items.
if len(out) > constants.MaxSecretItemsPerPayload {
return nil, fmt.Errorf("cannot have more than 10 items in a single payload; check your secrets YAML")
}
}
return out, nil
}
// ValidateInputs validates the input structure.
func (h *Handler) ValidateInputs(inputs UpsertSecretsInputs) error {
validate, err := validation.NewValidator()
if err != nil {
return fmt.Errorf("failed to create validator: %w", err)
}
for i, item := range inputs {
if err := validate.Struct(item); err != nil {
return fmt.Errorf("validation failed for SecretItem at index %d: %w", i, err)
}
}
return nil
}
// TODO: use TxType interface
func (h *Handler) PackAllowlistRequestTxData(reqDigest [32]byte, duration time.Duration) (string, error) {
contractABI, err := abi.JSON(strings.NewReader(workflow_registry_wrapper_v2.WorkflowRegistryMetaData.ABI))
if err != nil {
return "", fmt.Errorf("failed to parse workflow registry v2 ABI: %w", err)
}
// #nosec G115
deadline := uint32(time.Now().Add(duration).Unix())
data, err := contractABI.Pack("allowlistRequest", reqDigest, deadline)
if err != nil {
return "", fmt.Errorf("failed to pack data for allowlistRequest: %w", err)
}
return hex.EncodeToString(data), nil
}
func (h *Handler) LogMSIGNextSteps(txData string, digest [32]byte, bundlePath string) error {
ui.Line()
ui.Success("MSIG transaction prepared!")
ui.Line()
ui.Bold("Next steps:")
ui.Line()
ui.Print(" 1. Submit the following transaction on the target chain:")
ui.Printf(" Chain: %s\n", h.EnvironmentSet.WorkflowRegistryChainName)
ui.Printf(" Contract Address: %s\n", h.EnvironmentSet.WorkflowRegistryAddress)
ui.Line()
ui.Print(" 2. Use the following transaction data:")
ui.Line()
ui.Code(txData)
ui.Line()
ui.Print(" 3. Save this bundle file; you will need it on the second run:")
ui.Printf(" Bundle Path: %s\n", bundlePath)
ui.Printf(" Digest: 0x%s\n", hex.EncodeToString(digest[:]))
ui.Line()
ui.Print(" 4. After the transaction is finalized on-chain, run:")
ui.Line()
ui.Code(fmt.Sprintf("cre secrets execute %s --unsigned", bundlePath))
ui.Line()
return nil
}
// fetchVaultMasterPublicKeyHex loads the vault master public key from the gateway (publicKey/get).
func (h *Handler) fetchVaultMasterPublicKeyHex() (string, error) {
requestID := uuid.New().String()
getPublicKeyRequest := jsonrpc2.Request[vault.GetPublicKeyRequest]{
Version: jsonrpc2.JsonRpcVersion,
ID: requestID,
Method: vaulttypes.MethodPublicKeyGet,
Params: &vault.GetPublicKeyRequest{},
}
reqBody, err := json.Marshal(getPublicKeyRequest)
if err != nil {
return "", fmt.Errorf("failed to marshal public key request: %w", err)
}
respBody, status, err := h.Gw.Post(reqBody)
if err != nil {
return "", fmt.Errorf("gateway POST failed: %w", err)
}
if status != http.StatusOK {
return "", fmt.Errorf("gateway returned non-200: %d body=%s", status, string(respBody))
}
var rpcResp jsonrpc2.Response[vault.GetPublicKeyResponse]
if err := json.Unmarshal(respBody, &rpcResp); err != nil {
return "", fmt.Errorf("failed to unmarshal public key response: %w", err)
}
if rpcResp.Error != nil {
return "", fmt.Errorf("vault public key fetch error: %s", rpcResp.Error.Error())
}
if rpcResp.Version != jsonrpc2.JsonRpcVersion {
return "", fmt.Errorf("jsonrpc version mismatch: got %q", rpcResp.Version)
}
if rpcResp.ID != requestID {
return "", fmt.Errorf("jsonrpc id mismatch: got %q want %q", rpcResp.ID, requestID)
}
if rpcResp.Method != vaulttypes.MethodPublicKeyGet {
return "", fmt.Errorf("jsonrpc method mismatch: got %q", rpcResp.Method)
}
if rpcResp.Result == nil || rpcResp.Result.PublicKey == "" {
return "", fmt.Errorf("empty result in public key response")
}
return rpcResp.Result.PublicKey, nil
}
// ResolveEffectiveOwner returns the checksummed workflow owner address for owner-key vault operations.
func (h *Handler) ResolveEffectiveOwner() (string, error) {
if !common.IsHexAddress(h.OwnerAddress) {
return "", fmt.Errorf("owner address %q is not a valid hex address", h.OwnerAddress)
}
return common.HexToAddress(h.OwnerAddress).Hex(), nil
}
// ResolveVaultIdentifierOwnerForAuth returns the owner used in vault JSON-RPC payloads
// (SecretIdentifier.Owner, list Owner, TDH2 labels). Onchain auth uses the linked EOA from
// settings; browser auth uses DerivedWorkflowOwner from runtime.Context (getCreOrganizationInfo at login).
func (h *Handler) ResolveVaultIdentifierOwnerForAuth(secretsAuth string) (string, error) {
if !IsBrowserFlow(secretsAuth) {
return h.ResolveEffectiveOwner()
}
if h.Credentials == nil {
return "", fmt.Errorf("organization information is missing from your session; sign in again or use --secrets-auth=onchain")
}
if h.Credentials.AuthType == credentials.AuthTypeApiKey {
return "", fmt.Errorf("this sign-in flow requires an interactive login; API keys are not supported")
}
owner := strings.TrimSpace(h.DerivedWorkflowOwner)
if owner == "" {
return "", fmt.Errorf("derived workflow owner is not available; sign in again with cre login")
}
return ethkeys.FormatWorkflowOwnerAddress(owner)
}
// EncryptSecrets encrypts secrets for the given workflow owner address.
// TDH2 label is the workflow owner address left-padded to 32 bytes; SecretIdentifier.Owner is the same hex address string.
func (h *Handler) EncryptSecrets(rawSecrets UpsertSecretsInputs, owner string) ([]*vault.EncryptedSecret, error) {
pubKeyHex, err := h.fetchVaultMasterPublicKeyHex()
if err != nil {
return nil, err
}
encryptedSecrets := make([]*vault.EncryptedSecret, 0, len(rawSecrets))
for _, item := range rawSecrets {
cipherHex, err := EncryptSecret(item.Value, pubKeyHex, owner)
if err != nil {
return nil, fmt.Errorf("failed to encrypt secret (key=%s ns=%s): %w", item.ID, item.Namespace, err)
}
secID := &vault.SecretIdentifier{
Key: item.ID,
Namespace: item.Namespace,
Owner: owner,
}
encryptedSecrets = append(encryptedSecrets, &vault.EncryptedSecret{
Id: secID,
EncryptedValue: cipherHex,
})
}
return encryptedSecrets, nil
}
// encryptSecretWithLabel encrypts a secret using the vault master public key and the given label.
func encryptSecretWithLabel(secret, masterPublicKeyHex string, label [32]byte) (string, error) {
masterPublicKey := tdh2easy.PublicKey{}
masterPublicKeyBytes, err := hex.DecodeString(masterPublicKeyHex)
if err != nil {
return "", fmt.Errorf("failed to decode master public key: %w", err)
}
if err = masterPublicKey.Unmarshal(masterPublicKeyBytes); err != nil {
return "", fmt.Errorf("failed to unmarshal master public key: %w", err)
}
cipher, err := tdh2easy.EncryptWithLabel(&masterPublicKey, []byte(secret), label)
if err != nil {
return "", fmt.Errorf("failed to encrypt secret: %w", err)
}
cipherBytes, err := cipher.Marshal()
if err != nil {
return "", fmt.Errorf("failed to marshal encrypted secrets to bytes: %w", err)
}
return hex.EncodeToString(cipherBytes), nil
}
// EncryptSecret encrypts for the owner-key / web3 flow using a 32-byte label derived from the EOA (12 zero bytes + 20-byte address).
func EncryptSecret(secret, masterPublicKeyHex string, ownerAddress string) (string, error) {
addr := common.HexToAddress(ownerAddress) // canonical 20-byte address
var label [32]byte
copy(label[12:], addr.Bytes()) // left-pad with 12 zero bytes
return encryptSecretWithLabel(secret, masterPublicKeyHex, label)
}
func CalculateDigest[I any](r jsonrpc2.Request[I]) ([32]byte, error) {
b, err := json.Marshal(r.Params)
if err != nil {
return [32]byte{}, fmt.Errorf("failed to marshal json request params: %w", err)
}
req := jsonrpc2.Request[json.RawMessage]{
Version: r.Version,
ID: r.ID,
Method: r.Method,
Params: (*json.RawMessage)(&b),
}
digestStr, err := req.Digest()
if err != nil {
return [32]byte{}, fmt.Errorf("failed to calculate digest: %w", err)
}
digestBytes32, err := HexToBytes32(digestStr)
if err != nil {
return [32]byte{}, fmt.Errorf("failed to convert digest hex to [32]byte: %w", err)
}
return digestBytes32, nil
}
func HexToBytes32(h string) ([32]byte, error) {
var out [32]byte
h = strings.TrimPrefix(h, "0x")
b, err := hex.DecodeString(h)
if err != nil {
return out, fmt.Errorf("invalid hex for digest: %w", err)
}
if len(b) != 32 {
return out, fmt.Errorf("digest must be 32 bytes, got %d", len(b))
}
copy(out[:], b)
return out, nil
}
// Execute implements secrets create and update from YAML (multisig bundle, owner-key with allowlist, or interactive org sign-in).
func (h *Handler) Execute(
inputs UpsertSecretsInputs,
method string,
duration time.Duration,
secretsAuth string,
) error {
if IsBrowserFlow(secretsAuth) {
return h.executeBrowserUpsert(context.Background(), inputs, method)
}
if err := h.EnsureDeploymentRPCForOwnerKeySecrets(); err != nil {
return err
}
ui.Dim("Verifying ownership...")
if err := h.EnsureOwnerLinkedOrFail(); err != nil {
return err
}
owner, err := h.ResolveVaultIdentifierOwnerForAuth(secretsAuth)
if err != nil {
return err
}
// Build from YAML inputs
encSecrets, err := h.EncryptSecrets(inputs, owner)
if err != nil {
return fmt.Errorf("failed to encrypt secrets: %w", err)
}
requestID := uuid.New().String()
var (
requestBody []byte
digest [32]byte
)
switch method {
case vaulttypes.MethodSecretsCreate:
req := jsonrpc2.Request[vault.CreateSecretsRequest]{
Version: jsonrpc2.JsonRpcVersion,
ID: requestID,
Method: method,
Params: &vault.CreateSecretsRequest{
RequestId: requestID,
EncryptedSecrets: encSecrets,
},
}
if digest, err = CalculateDigest(req); err != nil {
return fmt.Errorf("failed to calculate create digest: %w", err)
}
if requestBody, err = json.Marshal(req); err != nil {
return fmt.Errorf("failed to marshal JSON-RPC request: %w", err)
}
case vaulttypes.MethodSecretsUpdate:
req := jsonrpc2.Request[vault.UpdateSecretsRequest]{
Version: jsonrpc2.JsonRpcVersion,
ID: requestID,
Method: method,
Params: &vault.UpdateSecretsRequest{
RequestId: requestID,
EncryptedSecrets: encSecrets,
},
}
if digest, err = CalculateDigest(req); err != nil {
return fmt.Errorf("failed to calculate update digest: %w", err)
}
if requestBody, err = json.Marshal(req); err != nil {
return fmt.Errorf("failed to marshal JSON-RPC request: %w", err)
}
default:
return fmt.Errorf("unsupported method %q (expected %q or %q)", method, vaulttypes.MethodSecretsCreate, vaulttypes.MethodSecretsUpdate)
}
ownerAddr := common.HexToAddress(owner)
allowlisted, err := h.Wrc.IsRequestAllowlisted(ownerAddr, digest)
if err != nil {
return fmt.Errorf("allowlist check failed: %w", err)
}
var txOut *client.TxOutput
if !allowlisted {
if txOut, err = h.Wrc.AllowlistRequest(digest, duration); err != nil {
return fmt.Errorf("allowlist request failed: %w", err)
}
}
gatewayPost := func() error {
respBody, status, err := h.Gw.Post(requestBody)
if err != nil {
return err
}
if status != http.StatusOK {
return fmt.Errorf("gateway returned a non-200 status code: status_code=%d, body=%s", status, respBody)
}
return h.ParseVaultGatewayResponse(method, respBody)
}
if txOut == nil && allowlisted {
ui.Dim(fmt.Sprintf("Digest already allowlisted; proceeding to gateway POST: owner=%s, digest=0x%x", ownerAddr.Hex(), digest))
return gatewayPost()
}
baseDir := filepath.Dir(h.SecretsFilePath)
filename := DeriveBundleFilename(digest) // <digest>.json
bundlePath := filepath.Join(baseDir, filename)
ub := &UnsignedBundle{
RequestID: requestID,
Method: method,
DigestHex: "0x" + hex.EncodeToString(digest[:]),
RequestBody: requestBody,
CreatedAt: time.Now().UTC(),
}
switch txOut.Type {
case client.Regular:
ui.Success("Transaction confirmed")
ui.Dim(fmt.Sprintf("Digest allowlisted; proceeding to gateway POST: owner=%s, digest=0x%x", ownerAddr.Hex(), digest))
explorerURL := fmt.Sprintf("%s/tx/%s", h.EnvironmentSet.WorkflowRegistryChainExplorerURL, txOut.Hash)
ui.URL(explorerURL)
return gatewayPost()
case client.Raw:
if err := SaveBundle(bundlePath, ub); err != nil {
return fmt.Errorf("failed to save unsigned bundle at %s: %w", bundlePath, err)
}
txData, err := h.PackAllowlistRequestTxData(digest, duration)
if err != nil {
return fmt.Errorf("failed to pack allowlist tx: %w", err)
}
return h.LogMSIGNextSteps(txData, digest, bundlePath)
case client.Changeset:
chainSelector, err := settings.GetChainSelectorByChainName(h.EnvironmentSet.WorkflowRegistryChainName)
if err != nil {
return fmt.Errorf("failed to get chain selector for chain %q: %w", h.EnvironmentSet.WorkflowRegistryChainName, err)
}
mcmsConfig, err := settings.GetMCMSConfig(h.Settings, chainSelector)
if err != nil {
ui.Warning("MCMS config not found or is incorrect, skipping MCMS config in changeset")
}
cldSettings := h.Settings.CLDSettings
changesets := []types.Changeset{
{
AllowlistRequest: &types.AllowlistRequest{
Payload: types.UserAllowlistRequestInput{
ExpiryTimestamp: uint32(time.Now().Add(duration).Unix()), // #nosec G115 -- int64 to uint32 conversion; Unix() returns seconds since epoch, which fits in uint32 until 2106
RequestDigest: common.Bytes2Hex(digest[:]),
ChainSelector: chainSelector,
MCMSConfig: mcmsConfig,
WorkflowRegistryQualifier: cldSettings.WorkflowRegistryQualifier,
},
},
},
}
csFile := types.NewChangesetFile(cldSettings.Environment, cldSettings.Domain, cldSettings.MergeProposals, changesets)
var fileName string
if cldSettings.ChangesetFile != "" {
fileName = cldSettings.ChangesetFile
} else {
fileName = fmt.Sprintf("AllowlistRequest_%s_%s_%s.yaml", requestID, h.Settings.Workflow.UserWorkflowSettings.WorkflowOwnerAddress, time.Now().Format("20060102_150405"))
}
if err := SaveBundle(bundlePath, ub); err != nil {
return fmt.Errorf("failed to save unsigned bundle at %s: %w", bundlePath, err)
}
return cmdCommon.WriteChangesetFile(fileName, csFile, h.Settings)
default:
h.Log.Warn().Msgf("Unsupported transaction type: %s", txOut.Type)
}
return nil
}
// ParseVaultGatewayResponse parses the JSON-RPC response, decodes the SignedOCRResponse payload
// into the appropriate proto type (CreateSecretsResponse, UpdateSecretsResponse, DeleteSecretsResponse),
// and logs one line per secret with id/owner/namespace/success/error.
func (h *Handler) ParseVaultGatewayResponse(method string, respBody []byte) error {
// Unmarshal JSON-RPC envelope with SignedOCRResponse result
var rpcResp jsonrpc2.Response[vaulttypes.SignedOCRResponse]
if err := json.Unmarshal(respBody, &rpcResp); err != nil {
return fmt.Errorf("failed to unmarshal JSON-RPC response: %w", err)
}
// JSON-RPC error?
if rpcResp.Error != nil {
b, _ := json.Marshal(rpcResp.Error)
return fmt.Errorf("gateway returned JSON-RPC error: %s", string(b))
}
// Ensure we have a result payload
if len(rpcResp.Result.Payload) == 0 {
return fmt.Errorf("empty SignedOCRResponse payload")
}
// Decode OCR payload into the correct proto, print per-item results
switch method {
case vaulttypes.MethodSecretsCreate:
var p vault.CreateSecretsResponse
if err := protojson.Unmarshal(rpcResp.Result.Payload, &p); err != nil {
return fmt.Errorf("failed to decode create payload: %w", err)
}
for _, r := range p.GetResponses() {
id := r.GetId()
// Safeguard for nil id
key, owner, ns := "", "", ""
if id != nil {
key, owner, ns = id.GetKey(), id.GetOwner(), id.GetNamespace()
}
if r.GetSuccess() {
ui.Success(fmt.Sprintf("Secret created: secret_id=%s, owner=%s, namespace=%s", key, owner, ns))
} else {
ui.Error(fmt.Sprintf("Secret create failed: secret_id=%s owner=%s namespace=%s error=%s",
key, owner, ns, r.GetError()))
}
}
case vaulttypes.MethodSecretsUpdate:
var p vault.UpdateSecretsResponse
if err := protojson.Unmarshal(rpcResp.Result.Payload, &p); err != nil {
return fmt.Errorf("failed to decode update payload: %w", err)
}
for _, r := range p.GetResponses() {
id := r.GetId()
key, owner, ns := "", "", ""
if id != nil {
key, owner, ns = id.GetKey(), id.GetOwner(), id.GetNamespace()
}
if r.GetSuccess() {
ui.Success(fmt.Sprintf("Secret updated: secret_id=%s, owner=%s, namespace=%s", key, owner, ns))
} else {
ui.Error(fmt.Sprintf("Secret update failed: secret_id=%s owner=%s namespace=%s error=%s",
key, owner, ns, r.GetError()))
}
}
case vaulttypes.MethodSecretsDelete:
var p vault.DeleteSecretsResponse
if err := protojson.Unmarshal(rpcResp.Result.Payload, &p); err != nil {
return fmt.Errorf("failed to decode delete payload: %w", err)
}
for _, r := range p.GetResponses() {
id := r.GetId()
key, owner, ns := "", "", ""
if id != nil {
key, owner, ns = id.GetKey(), id.GetOwner(), id.GetNamespace()
}
if r.GetSuccess() {
ui.Success(fmt.Sprintf("Secret deleted: secret_id=%s, owner=%s, namespace=%s", key, owner, ns))
} else {
ui.Error(fmt.Sprintf("Secret delete failed: secret_id=%s owner=%s namespace=%s error=%s",
key, owner, ns, r.GetError()))
}
}
case vaulttypes.MethodSecretsList:
var p vault.ListSecretIdentifiersResponse
if err := protojson.Unmarshal(rpcResp.Result.Payload, &p); err != nil {
return fmt.Errorf("failed to decode list payload: %w", err)
}
if !p.GetSuccess() {
ui.Error(fmt.Sprintf("Secret list failed: error=%s", p.GetError()))
break
}
ids := p.GetIdentifiers()
if len(ids) == 0 {
ui.Dim("No secrets found")
break
}
for _, id := range ids {
key, owner, ns := "", "", ""
if id != nil {
key, owner, ns = id.GetKey(), id.GetOwner(), id.GetNamespace()
}
ui.Print(fmt.Sprintf("Secret identifier: secret_id=%s, owner=%s, namespace=%s", key, owner, ns))
}
default:
// Unknown/unsupported method — don’t fail, just surface it explicitly
h.Log.Warn().
Str("method", method).
Msg("received response for unsupported method; skipping payload decode")
}
return nil
}
// EnsureOwnerLinkedOrFail TODO this reuses the same logic as in auto_link.go which is tied to deploy; consider refactoring to avoid duplication
func (h *Handler) EnsureOwnerLinkedOrFail() error {
if !common.IsHexAddress(h.OwnerAddress) {
return fmt.Errorf("owner address %q is not a valid hex EVM address; check your workflow settings", h.OwnerAddress)
}
ownerAddr := common.HexToAddress(h.OwnerAddress)
linked, err := h.Wrc.IsOwnerLinked(ownerAddr)
if err != nil {
return fmt.Errorf("failed to check owner link status: %w", err)
}
ui.Dim(fmt.Sprintf("Workflow owner link status: owner=%s, linked=%v", ownerAddr.Hex(), linked))
if linked {
// Owner is linked on contract, now verify it's linked to the current user's account
linkedToCurrentUser, err := h.checkLinkStatusViaGraphQL(ownerAddr)
if err != nil {
return fmt.Errorf("failed to validate key ownership: %w", err)
}
if !linkedToCurrentUser {
return fmt.Errorf("key %s is linked to another account. Please use a different owner address", ownerAddr.Hex())
}
ui.Success("Key ownership verified")
return nil
}
return fmt.Errorf("owner %s not linked; run cre account link-key", ownerAddr.Hex())
}
// checkLinkStatusViaGraphQL checks if the owner is linked and verified by querying the service
func (h *Handler) checkLinkStatusViaGraphQL(ownerAddr common.Address) (bool, error) {
const query = `
query {
listWorkflowOwners(filters: { linkStatus: LINKED_ONLY }) {
linkedOwners {
workflowOwnerAddress
verificationStatus
}
}
}`
req := graphql.NewRequest(query)
var resp struct {
ListWorkflowOwners struct {
LinkedOwners []struct {
WorkflowOwnerAddress string `json:"workflowOwnerAddress"`
VerificationStatus string `json:"verificationStatus"`
} `json:"linkedOwners"`
} `json:"listWorkflowOwners"`
}
gql := graphqlclient.New(h.Credentials, h.EnvironmentSet, h.Log)
if err := gql.Execute(context.Background(), req, &resp); err != nil {
return false, fmt.Errorf("GraphQL query failed: %w", err)
}
ownerHex := strings.ToLower(ownerAddr.Hex())
for _, linkedOwner := range resp.ListWorkflowOwners.LinkedOwners {
if strings.ToLower(linkedOwner.WorkflowOwnerAddress) == ownerHex {
// Check if verification status is successful
//nolint:misspell // Intentional misspelling to match external API
if linkedOwner.VerificationStatus == "VERIFICATION_STATUS_SUCCESSFULL" {
h.Log.Debug().
Str("ownerAddress", linkedOwner.WorkflowOwnerAddress).
Str("verificationStatus", linkedOwner.VerificationStatus).
Msg("Owner found and verified")
return true, nil
}
h.Log.Debug().
Str("ownerAddress", linkedOwner.WorkflowOwnerAddress).
Str("verificationStatus", linkedOwner.VerificationStatus).
Str("expectedStatus", "VERIFICATION_STATUS_SUCCESSFULL"). //nolint:misspell // Intentional misspelling to match external API
Msg("Owner found but verification status not successful")
return false, nil
}
}
h.Log.Debug().
Str("ownerAddress", ownerAddr.Hex()).
Msg("Owner not found in linked owners list")
return false, nil
}