/
backend.go
1829 lines (1556 loc) · 61.2 KB
/
backend.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
// Copyright 2016-2022, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package httpstate
import (
"context"
cryptorand "crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path"
"regexp"
"strconv"
"strings"
"sync"
"time"
opentracing "github.com/opentracing/opentracing-go"
"github.com/pulumi/pulumi/pkg/v3/backend"
"github.com/pulumi/pulumi/pkg/v3/backend/display"
"github.com/pulumi/pulumi/pkg/v3/backend/filestate"
"github.com/pulumi/pulumi/pkg/v3/backend/httpstate/client"
"github.com/pulumi/pulumi/pkg/v3/engine"
"github.com/pulumi/pulumi/pkg/v3/operations"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy"
"github.com/pulumi/pulumi/pkg/v3/secrets"
"github.com/pulumi/pulumi/sdk/v3/go/common/apitype"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag/colors"
sdkDisplay "github.com/pulumi/pulumi/sdk/v3/go/common/display"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/config"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/logging"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/result"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/retry"
"github.com/pulumi/pulumi/sdk/v3/go/common/workspace"
"github.com/skratchdot/open-golang/open"
)
const (
// defaultAPIEnvVar can be set to override the default cloud chosen, if `--cloud` is not present.
defaultURLEnvVar = "PULUMI_API"
// AccessTokenEnvVar is the environment variable used to bypass a prompt on login.
AccessTokenEnvVar = "PULUMI_ACCESS_TOKEN"
)
// Name validation rules enforced by the Pulumi Service.
var (
stackOwnerRegexp = regexp.MustCompile("^[a-zA-Z0-9][a-zA-Z0-9-_]{1,38}[a-zA-Z0-9]$")
stackNameAndProjectRegexp = regexp.MustCompile("^[A-Za-z0-9_.-]{1,100}$")
)
// DefaultURL returns the default cloud URL. This may be overridden using the PULUMI_API environment
// variable. If no override is found, and we are authenticated with a cloud, choose that. Otherwise,
// we will default to the https://api.pulumi.com/ endpoint.
func DefaultURL() string {
return ValueOrDefaultURL("")
}
// ValueOrDefaultURL returns the value if specified, or the default cloud URL otherwise.
func ValueOrDefaultURL(cloudURL string) string {
// If we have a cloud URL, just return it.
if cloudURL != "" {
return strings.TrimSuffix(cloudURL, "/")
}
// Otherwise, respect the PULUMI_API override.
if cloudURL := os.Getenv(defaultURLEnvVar); cloudURL != "" {
return cloudURL
}
// If that didn't work, see if we have a current cloud, and use that. Note we need to be careful
// to ignore the local cloud.
if creds, err := workspace.GetStoredCredentials(); err == nil {
if creds.Current != "" && !filestate.IsFileStateBackendURL(creds.Current) {
return creds.Current
}
}
// If none of those led to a cloud URL, simply return the default.
return PulumiCloudURL
}
// Backend extends the base backend interface with specific information about cloud backends.
type Backend interface {
backend.Backend
CloudURL() string
StackConsoleURL(stackRef backend.StackReference) (string, error)
Client() *client.Client
RunDeployment(ctx context.Context, stackRef backend.StackReference, req apitype.CreateDeploymentRequest,
opts display.Options) error
}
type cloudBackend struct {
d diag.Sink
url string
client *client.Client
currentProject *workspace.Project
capabilities func(context.Context) capabilities
}
// Assert we implement the backend.Backend and backend.SpecificDeploymentExporter interfaces.
var _ backend.SpecificDeploymentExporter = &cloudBackend{}
// New creates a new Pulumi backend for the given cloud API URL and token.
func New(d diag.Sink, cloudURL string) (Backend, error) {
cloudURL = ValueOrDefaultURL(cloudURL)
account, err := workspace.GetAccount(cloudURL)
if err != nil {
return nil, fmt.Errorf("getting stored credentials: %w", err)
}
apiToken := account.AccessToken
// When stringifying backend references, we take the current project (if present) into account.
currentProject, err := workspace.DetectProject()
if err != nil {
currentProject = nil
}
client := client.NewClient(cloudURL, apiToken, d)
capabilities := detectCapabilities(d, client)
return &cloudBackend{
d: d,
url: cloudURL,
client: client,
currentProject: currentProject,
capabilities: capabilities,
}, nil
}
// loginWithBrowser uses a web-browser to log into the cloud and returns the cloud backend for it.
func loginWithBrowser(ctx context.Context, d diag.Sink, cloudURL string, opts display.Options) (Backend, error) {
// Locally, we generate a nonce and spin up a web server listening on a random port on localhost. We then open a
// browser to a special endpoint on the Pulumi.com console, passing the generated nonce as well as the port of the
// webserver we launched. This endpoint does the OAuth flow and when it completes, redirects to localhost passing
// the nonce and the pulumi access token we created as part of the OAuth flow. If the nonces match, we set the
// access token that was passed to us and the redirect to a special welcome page on Pulumi.com
loginURL := cloudConsoleURL(cloudURL, "cli-login")
finalWelcomeURL := cloudConsoleURL(cloudURL, "welcome", "cli")
if loginURL == "" || finalWelcomeURL == "" {
return nil, errors.New("could not determine login url")
}
// Listen on localhost, have the kernel pick a random port for us
c := make(chan string)
l, err := net.Listen("tcp", "127.0.0.1:")
if err != nil {
return nil, fmt.Errorf("could not start listener: %w", err)
}
// Extract the port
_, port, err := net.SplitHostPort(l.Addr().String())
if err != nil {
return nil, fmt.Errorf("could not determine port: %w", err)
}
// Generate a nonce we'll send with the request.
nonceBytes := make([]byte, 32)
_, err = cryptorand.Read(nonceBytes)
contract.AssertNoErrorf(err, "could not get random bytes")
nonce := hex.EncodeToString(nonceBytes)
u, err := url.Parse(loginURL)
contract.AssertNoError(err)
// Generate a description to associate with the access token we'll generate, for display on the Account Settings
// page.
var tokenDescription string
if host, hostErr := os.Hostname(); hostErr == nil {
tokenDescription = fmt.Sprintf("Generated by pulumi login on %s at %s", host, time.Now().Format(time.RFC822))
} else {
tokenDescription = fmt.Sprintf("Generated by pulumi login at %s", time.Now().Format(time.RFC822))
}
// Pass our state around as query parameters on the URL we'll open the user's preferred browser to
q := u.Query()
q.Add("cliSessionPort", port)
q.Add("cliSessionNonce", nonce)
q.Add("cliSessionDescription", tokenDescription)
u.RawQuery = q.Encode()
// Start the webserver to listen to handle the response
go serveBrowserLoginServer(l, nonce, finalWelcomeURL, c)
// Launch the web browser and navigate to the login URL.
if openErr := open.Run(u.String()); openErr != nil {
fmt.Printf("We couldn't launch your web browser for some reason. Please visit:\n\n%s\n\n"+
"to finish the login process.", u)
} else {
fmt.Println("We've launched your web browser to complete the login process.")
}
fmt.Println("\nWaiting for login to complete...")
accessToken := <-c
username, organizations, err := client.NewClient(cloudURL, accessToken, d).GetPulumiAccountDetails(ctx)
if err != nil {
return nil, err
}
// Save the token and return the backend
account := workspace.Account{
AccessToken: accessToken,
Username: username,
Organizations: organizations,
LastValidatedAt: time.Now(),
}
if err = workspace.StoreAccount(cloudURL, account, true); err != nil {
return nil, err
}
// Welcome the user since this was an interactive login.
WelcomeUser(opts)
return New(d, cloudURL)
}
// LoginManager provides a slim wrapper around functions related to backend logins.
type LoginManager interface {
// Current returns the current cloud backend if one is already logged in.
Current(ctx context.Context, d diag.Sink, cloudURL string) (Backend, error)
// Login logs into the target cloud URL and returns the cloud backend for it.
Login(ctx context.Context, d diag.Sink, cloudURL string, opts display.Options) (Backend, error)
}
// NewLoginManager returns a LoginManager for handling backend logins.
func NewLoginManager() LoginManager {
return newLoginManager()
}
// newLoginManager creates a new LoginManager for handling logins. It is a variable instead of a regular
// function so it can be set to a different implementation at runtime, if necessary.
var newLoginManager = func() LoginManager {
return defaultLoginManager{}
}
type defaultLoginManager struct{}
// Current returns the current cloud backend if one is already logged in.
func (m defaultLoginManager) Current(ctx context.Context, d diag.Sink, cloudURL string) (Backend, error) {
cloudURL = ValueOrDefaultURL(cloudURL)
// If we have a saved access token, and it is valid, use it.
existingAccount, err := workspace.GetAccount(cloudURL)
if err == nil && existingAccount.AccessToken != "" {
// If the account was last verified less than an hour ago, assume the token is valid.
valid, username, organizations := true, existingAccount.Username, existingAccount.Organizations
if username == "" || existingAccount.LastValidatedAt.Add(1*time.Hour).Before(time.Now()) {
valid, username, organizations, err = IsValidAccessToken(ctx, cloudURL, existingAccount.AccessToken)
if err != nil {
return nil, err
}
existingAccount.LastValidatedAt = time.Now()
}
if valid {
// Save the token. While it hasn't changed this will update the current cloud we are logged into, as well.
existingAccount.Username = username
existingAccount.Organizations = organizations
if err = workspace.StoreAccount(cloudURL, existingAccount, true); err != nil {
return nil, err
}
return New(d, cloudURL)
}
}
// We intentionally don't accept command-line args for the user's access token. Having it in
// .bash_history is not great, and specifying it via flag isn't of much use.
accessToken := os.Getenv(AccessTokenEnvVar)
if accessToken == "" {
// No access token available, this isn't an error per-se but we don't have a backend
return nil, nil
}
// If there's already a token from the environment, use it.
_, err = fmt.Fprintf(os.Stderr, "Logging in using access token from %s\n", AccessTokenEnvVar)
contract.IgnoreError(err)
// Try and use the credentials to see if they are valid.
valid, username, organizations, err := IsValidAccessToken(ctx, cloudURL, accessToken)
if err != nil {
return nil, err
} else if !valid {
return nil, fmt.Errorf("invalid access token")
}
// Save them.
account := workspace.Account{
AccessToken: accessToken,
Username: username,
Organizations: organizations,
LastValidatedAt: time.Now(),
}
if err = workspace.StoreAccount(cloudURL, account, true); err != nil {
return nil, err
}
return New(d, cloudURL)
}
// Login logs into the target cloud URL and returns the cloud backend for it.
func (m defaultLoginManager) Login(
ctx context.Context, d diag.Sink, cloudURL string, opts display.Options) (Backend, error) {
current, err := m.Current(ctx, d, cloudURL)
if err != nil {
return nil, err
}
if current != nil {
return current, nil
}
cloudURL = ValueOrDefaultURL(cloudURL)
var accessToken string
accountLink := cloudConsoleURL(cloudURL, "account", "tokens")
if !cmdutil.Interactive() {
// If interactive mode isn't enabled, the only way to specify a token is through the environment variable.
// Fail the attempt to login.
return nil, fmt.Errorf("%s must be set for login during non-interactive CLI sessions", AccessTokenEnvVar)
}
// If no access token is available from the environment, and we are interactive, prompt and offer to
// open a browser to make it easy to generate and use a fresh token.
line1 := "Manage your Pulumi stacks by logging in."
line1len := len(line1)
line1 = colors.Highlight(line1, "Pulumi stacks", colors.Underline+colors.Bold)
fmt.Printf(opts.Color.Colorize(line1) + "\n")
maxlen := line1len
line2 := "Run `pulumi login --help` for alternative login options."
line2len := len(line2)
fmt.Printf(opts.Color.Colorize(line2) + "\n")
if line2len > maxlen {
maxlen = line2len
}
// In the case where we could not construct a link to the pulumi console based on the API server's hostname,
// don't offer magic log-in or text about where to find your access token.
if accountLink == "" {
for {
if accessToken, err = cmdutil.ReadConsoleNoEcho("Enter your access token"); err != nil {
return nil, err
}
if accessToken != "" {
break
}
}
} else {
line3 := fmt.Sprintf("Enter your access token from %s", accountLink)
line3len := len(line3)
line3 = colors.Highlight(line3, "access token", colors.BrightCyan+colors.Bold)
line3 = colors.Highlight(line3, accountLink, colors.BrightBlue+colors.Underline+colors.Bold)
fmt.Printf(opts.Color.Colorize(line3) + "\n")
if line3len > maxlen {
maxlen = line3len
}
line4 := " or hit <ENTER> to log in using your browser"
var padding string
if pad := maxlen - len(line4); pad > 0 {
padding = strings.Repeat(" ", pad)
}
line4 = colors.Highlight(line4, "<ENTER>", colors.BrightCyan+colors.Bold)
if accessToken, err = cmdutil.ReadConsoleNoEcho(opts.Color.Colorize(line4) + padding); err != nil {
return nil, err
}
if accessToken == "" {
return loginWithBrowser(ctx, d, cloudURL, opts)
}
// Welcome the user since this was an interactive login.
WelcomeUser(opts)
}
// Try and use the credentials to see if they are valid.
valid, username, organizations, err := IsValidAccessToken(ctx, cloudURL, accessToken)
if err != nil {
return nil, err
} else if !valid {
return nil, fmt.Errorf("invalid access token")
}
// Save them.
account := workspace.Account{
AccessToken: accessToken,
Username: username,
Organizations: organizations,
LastValidatedAt: time.Now(),
}
if err = workspace.StoreAccount(cloudURL, account, true); err != nil {
return nil, err
}
return New(d, cloudURL)
}
// WelcomeUser prints a Welcome to Pulumi message.
func WelcomeUser(opts display.Options) {
fmt.Printf(`
%s
Pulumi helps you create, deploy, and manage infrastructure on any cloud using
your favorite language. You can get started today with Pulumi at:
https://www.pulumi.com/docs/get-started/
%s Resources you create with Pulumi are given unique names (a randomly
generated suffix) by default. To learn more about auto-naming or customizing resource
names see https://www.pulumi.com/docs/intro/concepts/resources/#autonaming.
`,
opts.Color.Colorize(colors.SpecHeadline+"Welcome to Pulumi!"+colors.Reset),
opts.Color.Colorize(colors.SpecSubHeadline+"Tip of the day:"+colors.Reset))
}
func (b *cloudBackend) StackConsoleURL(stackRef backend.StackReference) (string, error) {
stackID, err := b.getCloudStackIdentifier(stackRef)
if err != nil {
return "", err
}
path := b.cloudConsoleStackPath(stackID)
url := b.CloudConsoleURL(path)
if url == "" {
return "", errors.New("could not determine cloud console URL")
}
return url, nil
}
func (b *cloudBackend) Name() string {
if b.url == PulumiCloudURL {
return "pulumi.com"
}
return b.url
}
func (b *cloudBackend) URL() string {
user, _, err := b.CurrentUser()
if err != nil {
return cloudConsoleURL(b.url)
}
return cloudConsoleURL(b.url, user)
}
func (b *cloudBackend) CurrentUser() (string, []string, error) {
return b.currentUser(context.Background())
}
func (b *cloudBackend) currentUser(ctx context.Context) (string, []string, error) {
account, err := workspace.GetAccount(b.CloudURL())
if err != nil {
return "", nil, err
}
if account.Username != "" {
logging.V(1).Infof("found username for access token")
return account.Username, account.Organizations, nil
}
logging.V(1).Infof("no username for access token")
name, orgs, err := b.client.GetPulumiAccountDetails(ctx)
return name, orgs, err
}
func (b *cloudBackend) CloudURL() string { return b.url }
func (b *cloudBackend) parsePolicyPackReference(s string) (backend.PolicyPackReference, error) {
split := strings.Split(s, "/")
var orgName string
var policyPackName string
switch len(split) {
case 2:
orgName = split[0]
policyPackName = split[1]
default:
return nil, fmt.Errorf("could not parse policy pack name '%s'; must be of the form "+
"<org-name>/<policy-pack-name>", s)
}
if orgName == "" {
currentUser, _, userErr := b.CurrentUser()
if userErr != nil {
return nil, userErr
}
orgName = currentUser
}
return newCloudBackendPolicyPackReference(b.CloudConsoleURL(), orgName, tokens.QName(policyPackName)), nil
}
func (b *cloudBackend) GetPolicyPack(ctx context.Context, policyPack string,
d diag.Sink) (backend.PolicyPack, error) {
policyPackRef, err := b.parsePolicyPackReference(policyPack)
if err != nil {
return nil, err
}
account, err := workspace.GetAccount(b.CloudURL())
if err != nil {
return nil, err
}
apiToken := account.AccessToken
return &cloudPolicyPack{
ref: newCloudBackendPolicyPackReference(b.CloudConsoleURL(),
policyPackRef.OrgName(), policyPackRef.Name()),
b: b,
cl: client.NewClient(b.CloudURL(), apiToken, d)}, nil
}
func (b *cloudBackend) ListPolicyGroups(ctx context.Context, orgName string, inContToken backend.ContinuationToken) (
apitype.ListPolicyGroupsResponse, backend.ContinuationToken, error) {
return b.client.ListPolicyGroups(ctx, orgName, inContToken)
}
func (b *cloudBackend) ListPolicyPacks(ctx context.Context, orgName string, inContToken backend.ContinuationToken) (
apitype.ListPolicyPacksResponse, backend.ContinuationToken, error) {
return b.client.ListPolicyPacks(ctx, orgName, inContToken)
}
func (b *cloudBackend) SupportsTags() bool {
return true
}
func (b *cloudBackend) SupportsOrganizations() bool {
return true
}
// qualifiedStackReference describes a qualified stack on the Pulumi Service. The Owner or Project
// may be "" if unspecified, e.g. "pulumi/production" specifies the Owner and Name, but not the
// Project. We infer the missing data and try to make things work as best we can in ParseStackReference.
type qualifiedStackReference struct {
Owner string
Project string
Name string
}
// parseStackName parses the stack name into a potentially qualifiedStackReference. Any omitted
// portions will be left as "". For example:
//
// "alpha" - will just set the Name, but ignore Owner and Project.
// "alpha/beta" - will set the Owner and Name, but not Project.
// "alpha/beta/gamma" - will set Owner, Name, and Project.
func (b *cloudBackend) parseStackName(s string) (qualifiedStackReference, error) {
var q qualifiedStackReference
split := strings.Split(s, "/")
switch len(split) {
case 1:
q.Name = split[0]
case 2:
q.Owner = split[0]
q.Name = split[1]
case 3:
q.Owner = split[0]
q.Project = split[1]
q.Name = split[2]
default:
return qualifiedStackReference{}, fmt.Errorf("could not parse stack name '%s'", s)
}
return q, nil
}
func (b *cloudBackend) ParseStackReference(s string) (backend.StackReference, error) {
// Parse the input as a qualified stack name.
qualifiedName, err := b.parseStackName(s)
if err != nil {
return nil, err
}
// If the provided stack name didn't include the Owner or Project, infer them from the
// local environment.
if qualifiedName.Owner == "" {
// if the qualifiedName doesn't include an owner then let's check to see if there is a default org which *will*
// be the stack owner. If there is no defaultOrg, then we revert to checking the CurrentUser
defaultOrg, err := workspace.GetBackendConfigDefaultOrg()
if err != nil {
return nil, err
}
if defaultOrg != "" {
qualifiedName.Owner = defaultOrg
} else {
currentUser, _, userErr := b.CurrentUser()
if userErr != nil {
return nil, userErr
}
qualifiedName.Owner = currentUser
}
}
if qualifiedName.Project == "" {
currentProject, projectErr := workspace.DetectProject()
if projectErr != nil {
return nil, fmt.Errorf("If you're using the --stack flag, "+
"pass the fully qualified name (org/project/stack): %w", projectErr)
}
qualifiedName.Project = currentProject.Name.String()
}
if !tokens.IsName(qualifiedName.Name) {
return nil, errors.New("stack names may only contain alphanumeric, hyphens, underscores, and periods")
}
return cloudBackendReference{
owner: qualifiedName.Owner,
project: qualifiedName.Project,
name: tokens.Name(qualifiedName.Name),
b: b,
}, nil
}
func (b *cloudBackend) ValidateStackName(s string) error {
qualifiedName, err := b.parseStackName(s)
if err != nil {
return err
}
// The Pulumi Service enforces specific naming restrictions for organizations,
// projects, and stacks. Though ignore any values that need to be inferred later.
if qualifiedName.Owner != "" {
if err := validateOwnerName(qualifiedName.Owner); err != nil {
return err
}
}
if qualifiedName.Project != "" {
if err := validateProjectName(qualifiedName.Project); err != nil {
return err
}
}
return validateStackName(qualifiedName.Name)
}
// validateOwnerName checks if a stack owner name is valid. An "owner" is simply the namespace
// a stack may exist within, which for the Pulumi Service is the user account or organization.
func validateOwnerName(s string) error {
if !stackOwnerRegexp.MatchString(s) {
return errors.New("invalid stack owner")
}
return nil
}
// validateStackName checks if a stack name is valid, returning a user-suitable error if needed.
func validateStackName(s string) error {
if len(s) > 100 {
return errors.New("stack names must be less than 100 characters")
}
if !stackNameAndProjectRegexp.MatchString(s) {
return errors.New("stack names may only contain alphanumeric, hyphens, underscores, and periods")
}
return nil
}
// validateProjectName checks if a project name is valid, returning a user-suitable error if needed.
//
// NOTE: Be careful when requiring a project name be valid. The Pulumi.yaml file may contain
// an invalid project name like "r@bid^W0MBAT!!", but we try to err on the side of flexibility by
// implicitly "cleaning" the project name before we send it to the Pulumi Service. So when we go
// to make HTTP requests, we use a more palitable name like "r_bid_W0MBAT__".
//
// The projects canonical name will be the sanitized "r_bid_W0MBAT__" form, but we do not require the
// Pulumi.yaml file be updated.
//
// So we should only call validateProject name when creating _new_ stacks or creating _new_ projects.
// We should not require that project names be valid when reading what is in the current workspace.
func validateProjectName(s string) error {
if len(s) > 100 {
return errors.New("project names must be less than 100 characters")
}
if !stackNameAndProjectRegexp.MatchString(s) {
return errors.New("project names may only contain alphanumeric, hyphens, underscores, and periods")
}
return nil
}
// CloudConsoleURL returns a link to the cloud console with the given path elements. If a console link cannot be
// created, we return the empty string instead (this can happen if the endpoint isn't a recognized pattern).
func (b *cloudBackend) CloudConsoleURL(paths ...string) string {
return cloudConsoleURL(b.CloudURL(), paths...)
}
// serveBrowserLoginServer hosts the server that completes the browser based login flow.
func serveBrowserLoginServer(l net.Listener, expectedNonce string, destinationURL string, c chan<- string) {
handler := func(res http.ResponseWriter, req *http.Request) {
tok := req.URL.Query().Get("accessToken")
nonce := req.URL.Query().Get("nonce")
if tok == "" || nonce != expectedNonce {
res.WriteHeader(400)
return
}
http.Redirect(res, req, destinationURL, http.StatusTemporaryRedirect)
c <- tok
}
mux := &http.ServeMux{}
mux.HandleFunc("/", handler)
contract.IgnoreError(http.Serve(l, mux)) // nolint gosec
}
// CloudConsoleStackPath returns the stack path components for getting to a stack in the cloud console. This path
// must, of course, be combined with the actual console base URL by way of the CloudConsoleURL function above.
func (b *cloudBackend) cloudConsoleStackPath(stackID client.StackIdentifier) string {
return path.Join(stackID.Owner, stackID.Project, stackID.Stack)
}
// Logout logs out of the target cloud URL.
func (b *cloudBackend) Logout() error {
return workspace.DeleteAccount(b.CloudURL())
}
// LogoutAll logs out of all accounts
func (b *cloudBackend) LogoutAll() error {
return workspace.DeleteAllAccounts()
}
// DoesProjectExist returns true if a project with the given name exists in this backend, or false otherwise.
func (b *cloudBackend) DoesProjectExist(ctx context.Context, projectName string) (bool, error) {
owner, _, err := b.currentUser(ctx)
if err != nil {
return false, err
}
return b.client.DoesProjectExist(ctx, owner, projectName)
}
func (b *cloudBackend) GetStack(ctx context.Context, stackRef backend.StackReference) (backend.Stack, error) {
stackID, err := b.getCloudStackIdentifier(stackRef)
if err != nil {
return nil, err
}
// GetStack is typically the initial call to a series of calls to the backend. Although logically unrelated,
// this is a good time to start detecting capabilities so that capability request is not on the critical path.
go b.capabilities(ctx)
stack, err := b.client.GetStack(ctx, stackID)
if err != nil {
// If this was a 404, return nil, nil as per this method's contract.
if errResp, ok := err.(*apitype.ErrorResponse); ok && errResp.Code == http.StatusNotFound {
return nil, nil
}
return nil, err
}
return newStack(stack, b), nil
}
// Confirm the specified stack's project doesn't contradict the Pulumi.yaml of the current project.
// if the CWD is not in a Pulumi project,
//
// does not contradict
//
// if the project name in Pulumi.yaml is "foo".
//
// a stack with a name of foo/bar/foo should not work.
func currentProjectContradictsWorkspace(stack client.StackIdentifier) bool {
projPath, err := workspace.DetectProjectPath()
if err != nil {
return false
}
if projPath == "" {
return false
}
proj, err := workspace.LoadProject(projPath)
if err != nil {
return false
}
return proj.Name.String() != stack.Project
}
func (b *cloudBackend) CreateStack(
ctx context.Context, stackRef backend.StackReference, _ interface{} /* No custom options for httpstate backend. */) (
backend.Stack, error) {
stackID, err := b.getCloudStackIdentifier(stackRef)
if err != nil {
return nil, err
}
if currentProjectContradictsWorkspace(stackID) {
return nil, fmt.Errorf("provided project name %q doesn't match Pulumi.yaml", stackID.Project)
}
tags, err := backend.GetEnvironmentTagsForCurrentStack()
if err != nil {
return nil, fmt.Errorf("error determining initial tags: %w", err)
}
apistack, err := b.client.CreateStack(ctx, stackID, tags)
if err != nil {
// Wire through well-known error types.
if errResp, ok := err.(*apitype.ErrorResponse); ok && errResp.Code == http.StatusConflict {
// A 409 error response is returned when per-stack organizations are over their limit,
// so we need to look at the message to differentiate.
if strings.Contains(errResp.Message, "already exists") {
return nil, &backend.StackAlreadyExistsError{StackName: stackID.String()}
}
if strings.Contains(errResp.Message, "you are using") {
return nil, &backend.OverStackLimitError{Message: errResp.Message}
}
}
return nil, err
}
stack := newStack(apistack, b)
fmt.Printf("Created stack '%s'\n", stack.Ref())
return stack, nil
}
func (b *cloudBackend) ListStacks(
ctx context.Context, filter backend.ListStacksFilter, inContToken backend.ContinuationToken) (
[]backend.StackSummary, backend.ContinuationToken, error) {
// Sanitize the project name as needed, so when communicating with the Pulumi Service we
// always use the name the service expects. (So that a similar, but not technically valid
// name may be put in Pulumi.yaml without causing problems.)
if filter.Project != nil {
cleanedProj := cleanProjectName(*filter.Project)
filter.Project = &cleanedProj
}
// Duplicate type to avoid circular dependency.
clientFilter := client.ListStacksFilter{
Organization: filter.Organization,
Project: filter.Project,
TagName: filter.TagName,
TagValue: filter.TagValue,
}
apiSummaries, outContToken, err := b.client.ListStacks(ctx, clientFilter, inContToken)
if err != nil {
return nil, nil, err
}
// Convert []apitype.StackSummary into []backend.StackSummary.
var backendSummaries []backend.StackSummary
for _, apiSummary := range apiSummaries {
backendSummary := cloudStackSummary{
summary: apiSummary,
b: b,
}
backendSummaries = append(backendSummaries, backendSummary)
}
return backendSummaries, outContToken, nil
}
func (b *cloudBackend) RemoveStack(ctx context.Context, stack backend.Stack, force bool) (bool, error) {
stackID, err := b.getCloudStackIdentifier(stack.Ref())
if err != nil {
return false, err
}
return b.client.DeleteStack(ctx, stackID, force)
}
func (b *cloudBackend) RenameStack(ctx context.Context, stack backend.Stack,
newName tokens.QName) (backend.StackReference, error) {
stackID, err := b.getCloudStackIdentifier(stack.Ref())
if err != nil {
return nil, err
}
// Support a qualified stack name, which would also rename the stack's project too.
// e.g. if you want to change the project name on the Pulumi Console to reflect a
// new value in Pulumi.yaml.
newRef, err := b.ParseStackReference(string(newName))
if err != nil {
return nil, err
}
newIdentity, err := b.getCloudStackIdentifier(newRef)
if err != nil {
return nil, err
}
if stackID.Owner != newIdentity.Owner {
errMsg := fmt.Sprintf(
"New stack owner, %s, does not match existing owner, %s.\n\n",
stackID.Owner, newIdentity.Owner)
// Re-parse the name using the parseStackName function to avoid the logic in ParseStackReference
// that auto-populates the owner property with the currently logged in account. We actually want to
// give a different error message if the raw stack name itself didn't include an owner part.
parsedName, err := b.parseStackName(string(newName))
contract.IgnoreError(err)
if parsedName.Owner == "" {
errMsg += fmt.Sprintf(
" Did you forget to include the owner name? If yes, rerun the command as follows:\n\n"+
" $ pulumi stack rename %s/%s\n\n",
stackID.Owner, newName)
}
errMsgSuffix := "."
if consoleURL, err := b.StackConsoleURL(stack.Ref()); err == nil {
errMsgSuffix = ":\n\n " + consoleURL + "/settings/options"
}
errMsg += " You cannot transfer stack ownership via a rename. If you wish to transfer ownership\n" +
" of a stack to another organization, you can do so in the Pulumi Console by going to the\n" +
" \"Settings\" page of the stack and then clicking the \"Transfer Stack\" button"
return nil, errors.New(errMsg + errMsgSuffix)
}
if err = b.client.RenameStack(ctx, stackID, newIdentity); err != nil {
return nil, err
}
return newRef, nil
}
func (b *cloudBackend) Preview(ctx context.Context, stack backend.Stack,
op backend.UpdateOperation) (*deploy.Plan, sdkDisplay.ResourceChanges, result.Result) {
// We can skip PreviewtThenPromptThenExecute, and just go straight to Execute.
opts := backend.ApplierOptions{
DryRun: true,
ShowLink: true,
}
return b.apply(
ctx, apitype.PreviewUpdate, stack, op, opts, nil /*events*/)
}
func (b *cloudBackend) Update(ctx context.Context, stack backend.Stack,
op backend.UpdateOperation) (sdkDisplay.ResourceChanges, result.Result) {
return backend.PreviewThenPromptThenExecute(ctx, apitype.UpdateUpdate, stack, op, b.apply)
}
func (b *cloudBackend) Import(ctx context.Context, stack backend.Stack,
op backend.UpdateOperation, imports []deploy.Import) (sdkDisplay.ResourceChanges, result.Result) {
op.Imports = imports
return backend.PreviewThenPromptThenExecute(ctx, apitype.ResourceImportUpdate, stack, op, b.apply)
}
func (b *cloudBackend) Refresh(ctx context.Context, stack backend.Stack,
op backend.UpdateOperation) (sdkDisplay.ResourceChanges, result.Result) {
return backend.PreviewThenPromptThenExecute(ctx, apitype.RefreshUpdate, stack, op, b.apply)
}
func (b *cloudBackend) Destroy(ctx context.Context, stack backend.Stack,
op backend.UpdateOperation) (sdkDisplay.ResourceChanges, result.Result) {
return backend.PreviewThenPromptThenExecute(ctx, apitype.DestroyUpdate, stack, op, b.apply)
}
func (b *cloudBackend) Watch(ctx context.Context, stack backend.Stack,
op backend.UpdateOperation, paths []string) result.Result {
return backend.Watch(ctx, b, stack, op, b.apply, paths)
}
func (b *cloudBackend) Query(ctx context.Context, op backend.QueryOperation) result.Result {
return b.query(ctx, op, nil /*events*/)
}
func (b *cloudBackend) createAndStartUpdate(
ctx context.Context, action apitype.UpdateKind, stack backend.Stack,
op *backend.UpdateOperation, dryRun bool) (client.UpdateIdentifier, int, string, error) {