Skip to content

Commit 71dde59

Browse files
jlaneveclaude
andcommitted
Make the plaintext credential fallback visible and refusable
The fallback to ~/.astro/credentials.json fired silently: a user asked for keychain storage, didn't get it, and had no way to find out or refuse. That is the one part of this design the GitHub CLI regrets shipping — cli/cli#10108 is still open two years on, and their maintainers now propose erroring out instead. Our exposure is worse than theirs: gh stores a non-expiring token, so a keyring failure is a one-time login annoyance, whereas we store refresh tokens and rotate, making every refresh another chance to spill to plaintext long after any login-time warning has scrolled away. - Warn on every plaintext write (once per process), naming the file and how to refuse it. Hung off the write rather than store construction because that's when secrets actually hit the disk. - Add no_insecure_fallback (config) / ASTRO_NO_INSECURE_FALLBACK (env), which makes an unavailable secure store an error instead of a downgrade. It can't be a flag: the store is built before cobra parses flags, and an env var suits the CI and container settings where the fallback actually fires. On Windows this always errors until the Credential Manager backend lands, since plaintext is currently the only option there. - Check storeErr before login returns early from the pre-run hook. login doesn't need existing credentials but does need somewhere to put new ones, and that's the moment the reason it can't is worth stating. logout still passes through: it has local context to reset even with a broken store. - Stop claiming credentials moved "to your system's secure store" during migration — on a host with no keyring that store is the plaintext file, and the message printed directly under a warning saying so. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01CBiU94fsKuCgdVfpGdL7aD
1 parent 342778f commit 71dde59

15 files changed

Lines changed: 417 additions & 36 deletions

‎cmd/root.go‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,15 @@ import (
1414
cloudCmd "github.com/astronomer/astro-cli/cmd/cloud"
1515
softwareCmd "github.com/astronomer/astro-cli/cmd/software"
1616
"github.com/astronomer/astro-cli/cmd/utils"
17+
"github.com/astronomer/astro-cli/config"
1718
"github.com/astronomer/astro-cli/context"
1819
"github.com/astronomer/astro-cli/houston"
1920
"github.com/astronomer/astro-cli/internal/telemetry"
2021
"github.com/astronomer/astro-cli/pkg/ansi"
2122
"github.com/astronomer/astro-cli/pkg/credentials"
2223
"github.com/astronomer/astro-cli/pkg/httputil"
2324
"github.com/astronomer/astro-cli/pkg/keychain"
25+
"github.com/astronomer/astro-cli/pkg/util"
2426
)
2527

2628
var (
@@ -33,13 +35,36 @@ var (
3335
const (
3436
softwarePlatform = "Astro Private Cloud"
3537
cloudPlatform = "Astro"
38+
39+
// noInsecureFallbackEnv refuses the plaintext credential fallback for a
40+
// single invocation. The secure store is constructed before cobra parses
41+
// flags, so this cannot be a flag; an env var also suits the CI and
42+
// container settings where the fallback actually fires, and matches how
43+
// ASTRO_API_TOKEN and ASTRO_DOMAIN are already read.
44+
noInsecureFallbackEnv = "ASTRO_NO_INSECURE_FALLBACK"
3645
)
3746

47+
// allowInsecureCredentialFallback reports whether credentials may be written to
48+
// a plaintext file when no OS-native secure store is available. It defaults to
49+
// true, preserving the previous config.yaml posture; users who would rather fail
50+
// than store secrets in the clear opt out via
51+
// `astro config set -g no_insecure_fallback true` or ASTRO_NO_INSECURE_FALLBACK.
52+
//
53+
// Either source can switch the protection on and neither can switch it off,
54+
// matching how SkipParse and AutoSelect combine their config and env sources.
55+
// That direction matters here: CheckEnvBool reports false for anything outside
56+
// true/1/yes/y/on, so letting the env win outright would mean a typo'd
57+
// ASTRO_NO_INSECURE_FALLBACK quietly overrode a persisted opt-out and allowed
58+
// the plaintext write it was set to prevent.
59+
func allowInsecureCredentialFallback() bool {
60+
return !config.CFG.NoInsecureFallback.GetBool() && !util.CheckEnvBool(os.Getenv(noInsecureFallbackEnv))
61+
}
62+
3863
// NewRootCmd adds all of the primary commands for the cli
3964
func NewRootCmd() *cobra.Command {
4065
var err error
4166
creds := &credentials.CurrentCredentials{}
42-
store, storeErr := newSecureStore()
67+
store, storeErr := newSecureStore(allowInsecureCredentialFallback())
4368

4469
httpClient := houston.NewHTTPClient()
4570
houstonClient = houston.NewClient(httpClient, creds)

‎cmd/root_hooks.go‎

Lines changed: 37 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,23 @@ func SetupLogging(_ *cobra.Command, _ []string) error {
3030
// pre-run hook that sets up the context and checks for the latest version.
3131
func CreateRootPersistentPreRunE(storeErr error, store keychain.SecureStore, creds *credentials.CurrentCredentials, astroV1Client astrov1.APIClient) func(cmd *cobra.Command, args []string) error {
3232
return func(cmd *cobra.Command, args []string) error {
33-
// login/logout don't need existing credentials, skip auth setup
34-
if cmd.CalledAs() == "login" || cmd.CalledAs() == "logout" {
33+
// logout doesn't need existing credentials, and still has local context
34+
// to reset even when the store is broken — let it through either way.
35+
if cmd.CalledAs() == "logout" {
3536
return nil
3637
}
3738

39+
// Checked before login returns early: login doesn't need existing
40+
// credentials, but it does need somewhere to put new ones, and this is
41+
// where the reason it can't is worth saying.
3842
if storeErr != nil {
3943
return fmt.Errorf("secure credential store unavailable: %w", storeErr)
4044
}
4145

46+
if cmd.CalledAs() == "login" {
47+
return nil
48+
}
49+
4250
// Check for latest version
4351
if config.CFG.UpgradeMessage.GetBool() {
4452
httpClient := &http.Client{Timeout: 3 * time.Second}
@@ -51,15 +59,18 @@ func CreateRootPersistentPreRunE(storeErr error, store keychain.SecureStore, cre
5159
if migrated, err := config.MigrateLegacyCredentials(store); err != nil {
5260
softwareCmd.InitDebugLogs = append(softwareCmd.InitDebugLogs, "credential migration error: "+err.Error())
5361
} else if migrated > 0 {
54-
fmt.Printf("Migrated credentials for %d context(s) to your system's secure store.\n", migrated)
62+
// Deliberately doesn't name the destination: on a host with no OS
63+
// keyring this store is the plaintext fallback, and claiming a
64+
// "secure store" would be a lie. warnInsecureWrite says so instead.
65+
fmt.Printf("Moved credentials for %d context(s) out of config.yaml into the credential store.\n", migrated)
5566
}
5667

5768
if context.IsCloudContext() {
5869
if err := handleCloudSetup(cmd, store, creds, astroV1Client); err != nil {
5970
return err
6071
}
61-
} else {
62-
loadSoftwareToken(store, creds)
72+
} else if err := loadSoftwareToken(store, creds); err != nil {
73+
return err
6374
}
6475
softwareCmd.PrintDebugLogs()
6576
return nil
@@ -81,15 +92,31 @@ func handleCloudSetup(cmd *cobra.Command, store keychain.SecureStore, creds *cre
8192
return nil
8293
}
8394

84-
func loadSoftwareToken(store keychain.SecureStore, creds *credentials.CurrentCredentials) {
95+
// loadSoftwareToken populates creds from the secure store for Software
96+
// (Houston) contexts, which have no checkToken equivalent to do it for them.
97+
//
98+
// It distinguishes "nothing stored" from "could not read what is stored". The
99+
// former is ordinary — the user isn't logged in, so leave creds empty and let
100+
// whatever needs auth say so. The latter must not be swallowed: a locked
101+
// keychain, a denied ACL prompt after a binary update, or a dead D-Bus would
102+
// otherwise leave creds empty and send unauthenticated requests to Houston,
103+
// surfacing as a baffling 401 rather than the credential problem it is.
104+
func loadSoftwareToken(store keychain.SecureStore, creds *credentials.CurrentCredentials) error {
85105
if store == nil {
86-
return
106+
return nil
87107
}
88108
c, err := context.GetCurrentContext()
89109
if err != nil {
90-
return
110+
// No context set yet, so there is nothing to load.
111+
return nil
91112
}
92-
if keyCreds, credErr := store.GetCredentials(c.Domain); credErr == nil {
93-
creds.Set(keyCreds.Token)
113+
keyCreds, err := store.GetCredentials(c.Domain)
114+
switch {
115+
case errors.Is(err, keychain.ErrNotFound):
116+
return nil
117+
case err != nil:
118+
return fmt.Errorf("could not read stored credentials for %s: %w", c.Domain, err)
94119
}
120+
creds.Set(keyCreds.Token)
121+
return nil
95122
}

‎cmd/root_hooks_test.go‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package cmd
22

33
import (
4+
"errors"
45
"testing"
56

67
"github.com/stretchr/testify/assert"
@@ -17,6 +18,42 @@ func TestLoadSoftwareToken_LoadsToken(t *testing.T) {
1718
assert.NoError(t, err)
1819

1920
holder := &credentials.CurrentCredentials{}
20-
loadSoftwareToken(store, holder)
21+
assert.NoError(t, loadSoftwareToken(store, holder))
2122
assert.Equal(t, "test-token", holder.Get())
2223
}
24+
25+
// errStore fails every read, standing in for a locked keychain, an ACL prompt
26+
// the user denied after a binary update, or a dead D-Bus session.
27+
type errStore struct{ err error }
28+
29+
func (e errStore) GetCredentials(string) (keychain.Credentials, error) {
30+
return keychain.Credentials{}, e.err
31+
}
32+
func (e errStore) SetCredentials(string, keychain.Credentials) error { return e.err }
33+
func (e errStore) DeleteCredentials(string) error { return e.err }
34+
35+
// A store that cannot be read must not look like "not logged in": swallowing
36+
// the error leaves the token holder empty and sends unauthenticated requests to
37+
// Houston, which surface as a confusing 401 instead of a credential problem.
38+
func TestLoadSoftwareToken_ReadFailureIsNotSilent(t *testing.T) {
39+
testUtil.InitTestConfig(testUtil.SoftwarePlatform)
40+
41+
holder := &credentials.CurrentCredentials{}
42+
err := loadSoftwareToken(errStore{err: errors.New("keychain is locked")}, holder)
43+
44+
assert.Error(t, err)
45+
assert.Contains(t, err.Error(), "keychain is locked")
46+
assert.Empty(t, holder.Get())
47+
}
48+
49+
// Not being logged in is ordinary, not an error — leave the holder empty and let
50+
// whatever actually needs auth report it.
51+
func TestLoadSoftwareToken_NotFoundIsNotAnError(t *testing.T) {
52+
testUtil.InitTestConfig(testUtil.SoftwarePlatform)
53+
54+
holder := &credentials.CurrentCredentials{}
55+
err := loadSoftwareToken(errStore{err: keychain.ErrNotFound}, holder)
56+
57+
assert.NoError(t, err)
58+
assert.Empty(t, holder.Get())
59+
}

‎cmd/root_test.go‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,22 @@ package cmd
22

33
import (
44
"bytes"
5+
"strconv"
56
"testing"
67

78
"github.com/spf13/cobra"
9+
"github.com/stretchr/testify/assert"
10+
"github.com/stretchr/testify/require"
811
"github.com/stretchr/testify/suite"
912

13+
"github.com/astronomer/astro-cli/config"
1014
"github.com/astronomer/astro-cli/pkg/keychain"
1115
testUtil "github.com/astronomer/astro-cli/pkg/testing"
1216
"github.com/astronomer/astro-cli/version"
1317
)
1418

1519
func init() {
16-
newSecureStore = func() (keychain.SecureStore, error) {
20+
newSecureStore = func(_ bool) (keychain.SecureStore, error) {
1721
return keychain.NewTestStore(), nil
1822
}
1923
}
@@ -98,3 +102,33 @@ func (s *CmdSuite) TestRootCommandSoftwareContext() {
98102
s.Contains(output, "run")
99103
s.NotContains(output, "Run flow commands")
100104
}
105+
106+
// Either source can switch the plaintext fallback off; neither can switch it
107+
// back on. CheckEnvBool reports false for anything outside true/1/yes/y/on, so
108+
// if the env var won outright a typo would quietly re-allow the plaintext write
109+
// a persisted opt-out was set to prevent.
110+
func TestAllowInsecureCredentialFallback(t *testing.T) {
111+
for _, tt := range []struct {
112+
name string
113+
config bool
114+
env string
115+
want bool
116+
}{
117+
{name: "default allows the fallback", want: true},
118+
{name: "config opts out", config: true, want: false},
119+
{name: "env opts out", env: "true", want: false},
120+
{name: "env opts out with 1", env: "1", want: false},
121+
{name: "both opt out", config: true, env: "true", want: false},
122+
{name: "env cannot re-enable what config disabled", config: true, env: "false", want: false},
123+
{name: "a typo cannot re-enable what config disabled", config: true, env: "treu", want: false},
124+
{name: "unset env leaves config alone", config: true, env: "", want: false},
125+
} {
126+
t.Run(tt.name, func(t *testing.T) {
127+
testUtil.InitTestConfig(testUtil.CloudPlatform)
128+
require.NoError(t, config.CFG.NoInsecureFallback.SetHomeString(strconv.FormatBool(tt.config)))
129+
t.Setenv("ASTRO_NO_INSECURE_FALLBACK", tt.env)
130+
131+
assert.Equal(t, tt.want, allowInsecureCredentialFallback())
132+
})
133+
}
134+
}

‎config/config.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ var (
9797
DevMode: newCfg("dev.mode", "docker"),
9898
DevBuildSecrets: newCfg("dev.build_secrets", ""),
9999
TelemetryEnabled: newCfg("telemetry.enabled", "true"),
100+
NoInsecureFallback: newCfg("no_insecure_fallback", "false"),
100101
TelemetryAnonymousID: newCfg("telemetry.anonymous_id", ""),
101102
TelemetryNoticeShown: newCfg("telemetry.notice_shown", ""),
102103
ProxyPort: newCfg("proxy.port", "6563"),

‎config/types.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ type cfgs struct {
5959
DevMode cfg
6060
DevBuildSecrets cfg
6161
TelemetryEnabled cfg
62+
NoInsecureFallback cfg
6263
TelemetryAnonymousID cfg
6364
TelemetryNoticeShown cfg
6465
ProxyPort cfg

‎pkg/keychain/keychain.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ const serviceName = "astro-cli"
1414
// ErrNotFound is returned when no credentials exist for the given domain.
1515
var ErrNotFound = errors.New("credentials not found")
1616

17+
// ErrInsecureFallbackRefused is returned by New when no OS-native secure store
18+
// is available and the user has set no_insecure_fallback, meaning they would
19+
// rather fail than have credentials written to disk in the clear.
20+
var ErrInsecureFallbackRefused = errors.New("no secure credential store available and the plaintext fallback is disabled")
21+
1722
// SecureStore persists and retrieves authentication credentials
1823
// using the OS-native secure store.
1924
type SecureStore interface {

‎pkg/keychain/keychain_darwin.go‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@ import (
1818
// The cachedStore wrapper (see keychain_cached.go) ensures only one keychain
1919
// access per domain per process, so the user sees at most one prompt per
2020
// command invocation.
21-
func New() (SecureStore, error) {
21+
//
22+
// macOS always has a Keychain, so there is nothing to fall back to and
23+
// allowInsecureFallback is not consulted — an unavailable Keychain is an error.
24+
func New(_ bool) (SecureStore, error) {
2225
ring, err := keyring.Open(keyring.Config{
2326
ServiceName: serviceName,
2427
KeychainTrustApplication: true,
@@ -27,5 +30,5 @@ func New() (SecureStore, error) {
2730
if err != nil {
2831
return nil, fmt.Errorf("system keychain unavailable: %w", err)
2932
}
30-
return newCachedStore(&keyringStore{ring: ring}), nil
33+
return newCachedStore(withTimeout(&keyringStore{ring: ring}, keyringTimeout)), nil
3134
}

‎pkg/keychain/keychain_file.go‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@ package keychain
55
import (
66
"encoding/json"
77
"fmt"
8+
"io"
89
"os"
910
"path/filepath"
11+
"sync"
1012
)
1113

1214
const (
@@ -15,6 +17,30 @@ const (
1517
filePerm = 0o600
1618
)
1719

20+
// insecureWarning fires the first time a plaintext write happens in a process.
21+
// It hangs off credential writes — login and each token refresh — rather than
22+
// store construction, because that is when secrets actually hit the disk. Once
23+
// per process keeps it from drowning out command output while still telling the
24+
// user on the invocation that did it.
25+
//
26+
// A pointer, not a value: resetting it in tests would otherwise copy a mutex.
27+
var (
28+
insecureWarning = &sync.Once{}
29+
insecureWarningOut io.Writer = os.Stderr
30+
)
31+
32+
// warnInsecureWrite tells the user their credentials went to disk in the clear.
33+
// A silent downgrade is the specific failure the GitHub CLI regrets shipping:
34+
// the user asks for keychain storage, does not get it, and never finds out.
35+
func warnInsecureWrite(path string) {
36+
insecureWarning.Do(func() {
37+
fmt.Fprintf(insecureWarningOut,
38+
"! No OS credential store available — authentication credentials saved in plain text at %s\n"+
39+
" To require a secure store instead, run: astro config set -g no_insecure_fallback true\n",
40+
path)
41+
})
42+
}
43+
1844
// fileStore is a plaintext JSON credential store for environments where no
1945
// OS-native secure store is available (Linux without Secret Service, Windows
2046
// before the Credential Manager backend lands). Credentials are written to
@@ -101,7 +127,11 @@ func (s *fileStore) SetCredentials(domain string, creds Credentials) error {
101127
return err
102128
}
103129
store[domain] = creds
104-
return s.write(store)
130+
if err := s.write(store); err != nil {
131+
return err
132+
}
133+
warnInsecureWrite(s.path)
134+
return nil
105135
}
106136

107137
func (s *fileStore) DeleteCredentials(domain string) error {

‎pkg/keychain/keychain_file_test.go‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
package keychain
44

55
import (
6+
"bytes"
67
"os"
78
"path/filepath"
9+
"sync"
810
"testing"
911

1012
"github.com/stretchr/testify/assert"
@@ -124,3 +126,29 @@ func TestWriteAtomic(t *testing.T) {
124126
require.Error(t, err)
125127
})
126128
}
129+
130+
// A plaintext downgrade has to announce itself. The GitHub CLI's equivalent
131+
// fallback shipped silently and is still, two years on, their most-complained-
132+
// about auth behaviour (cli/cli#10108) — the user asks for a secure store,
133+
// doesn't get one, and never finds out.
134+
func TestFileStore_WarnsOnPlaintextWrite(t *testing.T) {
135+
var buf bytes.Buffer
136+
origOut := insecureWarningOut
137+
insecureWarningOut = &buf
138+
insecureWarning = &sync.Once{}
139+
t.Cleanup(func() {
140+
insecureWarningOut = origOut
141+
insecureWarning = &sync.Once{}
142+
})
143+
144+
s := &fileStore{path: filepath.Join(t.TempDir(), "credentials.json")}
145+
require.NoError(t, s.SetCredentials("astronomer.io", Credentials{Token: "tok"}))
146+
147+
assert.Contains(t, buf.String(), "plain text")
148+
assert.Contains(t, buf.String(), "no_insecure_fallback", "the warning should say how to refuse the fallback")
149+
150+
// Once per process: a token refresh mid-command shouldn't repeat it.
151+
buf.Reset()
152+
require.NoError(t, s.SetCredentials("astronomer.io", Credentials{Token: "tok2"}))
153+
assert.Empty(t, buf.String())
154+
}

0 commit comments

Comments
 (0)