Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions cmd/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,22 @@ func finalizeLoginConfig(cfg *config.Config, contextName, environment, tokenName
cfg.PruneEmptyEnvironments(contextName, placeholderNames)
}

// loginFields are the values auth login writes into a context.
type loginFields struct {
environment, tokenRef string
safetyLevel config.SafetyLevel
}

// loginFieldsOf returns the login fields of context name in cfg, and whether
// cfg has that context.
func loginFieldsOf(cfg *config.Config, name string) (loginFields, bool) {
nc, err := cfg.GetContext(name)
if err != nil {
return loginFields{}, false
}
return loginFields{nc.Context.Environment, nc.Context.TokenRef, nc.Context.SafetyLevel}, true
}

// applyLoginToConfig records a login in raw, a config read without expanding
// ${VAR} references. Placeholder contexts are those whose environment expands
// to the empty string (literally empty, or an unset reference such as
Expand Down Expand Up @@ -1347,8 +1363,12 @@ Non-interactive login (CI/CD):
// meanwhile (a context added in another terminal). Apply the login's
// changes to the file as it is now, not to the copy read before the
// wait, and write it back to the file that copy came from.
var contextChanged bool
if err := updateConfigFile(cmdContext(cmd), configPath, fileExisted, func(fresh *config.Config) error {
before, existed := loginFieldsOf(fresh, contextName)
applyLoginToConfig(fresh, localFile, contextName, environment, tokenName, levels.saved)
after, _ := loginFieldsOf(fresh, contextName)
contextChanged = !existed || before != after
return nil
}); err != nil {
// The tokens are stored already; say where, so they can be used.
Expand All @@ -1363,6 +1383,16 @@ Non-interactive login (CI/CD):
}

output.FprintSuccess(currentStderr(cmdContext(cmd)), "Context '%s' configured and activated", contextName)
// configPath is the file the login read and wrote back, chosen
// before the browser wait; looking for a .dtctl.yaml again now
// could name a file the login did not write. auth login has no
// --global: the global config is logged in to with --config. A
// login that only refreshes the token of a context the project
// file already holds as it is changes nothing there worth a notice.
if localFile && contextChanged {
warnLocalWrite(cmdContext(cmd), fmt.Sprintf("Context %q", contextName), configPath,
"Log in with --config "+shellWord(config.DefaultConfigPath())+" to write there.")
}
output.FprintInfo(currentStderr(cmdContext(cmd)), "\nYou can now use dtctl commands with this context.")

return nil
Expand Down
11 changes: 9 additions & 2 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,15 @@ func warnLocalWriteTarget(ctx context.Context, what string) {
if local == "" {
return
}
output.FprintWarning(currentStderr(ctx), "%s written to the local config %s, not your global config", what, local)
output.FprintHint(currentStderr(ctx), "A local .dtctl.yaml cannot hold credentials; it resolves one through a global context that binds the same environment. Re-run with --global to write there.")
warnLocalWrite(ctx, what, local, "Re-run with --global to write there.")
}

// warnLocalWrite prints the notice of warnLocalWriteTarget for a write that
// landed in the auto-discovered .dtctl.yaml at path. rerun tells the user how
// to make the same write in the global config, which differs by command.
func warnLocalWrite(ctx context.Context, what, path, rerun string) {
output.FprintWarning(currentStderr(ctx), "%s written to the local config %s, not your global config", what, path)
output.FprintHint(currentStderr(ctx), "A local .dtctl.yaml cannot hold credentials; it resolves one through a global context that binds the same environment. %s", rerun)
}

// configCmd represents the config command
Expand Down
69 changes: 69 additions & 0 deletions cmd/config_overwrite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,75 @@ func TestAuthLogin_WritesBackTheFileItStartedFrom(t *testing.T) {
}
}

// TestAuthLogin_SaysItWroteTheProjectConfig (#824): like ctx set and config
// set-credentials, a login that adds or changes a context in an
// auto-discovered .dtctl.yaml says so, with both grants. A login that only
// refreshes the token of a context the file already holds as it is does not:
// that is the everyday re-login in a project. The same file named with
// DTCTL_CONFIG is the one the user asked for, and gets no notice either.
func TestAuthLogin_SaysItWroteTheProjectConfig(t *testing.T) {
const envURL = "https://abc12345.apps.dynatrace.com"
const otherURL = "https://xyz67890.apps.dynatrace.com"
cases := []struct {
name string
args []string
explicit bool
wantNotice string // context named in the notice; "" for none
}{
{"new context", []string{"--context", "fresh", "--environment", envURL, "--token-name", "prod-oauth"}, false, "fresh"},
{"changed environment", []string{"--context", "project", "--environment", otherURL}, false, "project"},
{"refresh", []string{"--context", "project"}, false, ""},
{"DTCTL_CONFIG", []string{"--context", "fresh", "--environment", envURL, "--token-name", "prod-oauth"}, true, ""},
}
for _, grant := range []string{"browser", "client credentials"} {
for _, tc := range cases {
t.Run(grant+"/"+tc.name, func(t *testing.T) {
global := loginConfigYAML("prod", loginTestContext{"prod", envURL, "prod-oauth", config.SafetyLevelReadOnly})
localPath := setupLoginProject(t, global,
loginConfigYAML("project", loginTestContext{"project", envURL, "prod-oauth", config.SafetyLevelReadOnly}))
stubBrowserLogin(t, nil)
if grant == "client credentials" {
t.Setenv(envLoginClientID, "dt0s02.EXAMPLE")
t.Setenv(envLoginClientSecret, "dt0s02.EXAMPLE.SECRET")
origGrant := authClientCredentialsFunc
t.Cleanup(func() { authClientCredentialsFunc = origGrant })
authClientCredentialsFunc = func(context.Context, *auth.OAuthFlow, string, string, string, []string) (*auth.TokenSet, error) {
return &auth.TokenSet{AccessToken: "test-access-token", TokenType: "Bearer", ExpiresIn: 300, ExpiresAt: time.Now().Add(5 * time.Minute)}, nil
}
}
if tc.explicit {
t.Setenv(config.EnvConfig, localPath)
}

code, stderr := runCommandLine(t, append([]string{"auth", "login"}, tc.args...)...)
if code != 0 {
t.Fatalf("auth login: exit %d\n%s", code, stderr)
}
if got := readConfigFile(t, config.DefaultConfigPath()); got != global {
t.Fatalf("the login wrote the global config:\n%s", got)
}
const noticeTail = "written to the local config"
if tc.wantNotice == "" {
if strings.Contains(stderr, noticeTail) {
t.Errorf("unexpected local-write notice:\n%s", stderr)
}
return
}
if want := fmt.Sprintf("Context %q %s %s", tc.wantNotice, noticeTail, localPath); !strings.Contains(stderr, want) {
t.Errorf("stderr lacks %q:\n%s", want, stderr)
}
// auth login has no --global; the way to the global config is --config.
if want := "Log in with --config " + shellWord(config.DefaultConfigPath()) + " to write there."; !strings.Contains(stderr, want) {
t.Errorf("stderr lacks %q:\n%s", want, stderr)
}
if strings.Contains(stderr, "Re-run with --global") {
t.Errorf("stderr suggests --global, which auth login does not have:\n%s", stderr)
}
})
}
}
}

// TestAuthLogin_PrunesTheConfigInitPlaceholder: in a project `config init`
// created, logging in to a real context removes the template's
// ${DT_ENVIRONMENT_URL} context while the variable is unset.
Expand Down
Loading