-
Notifications
You must be signed in to change notification settings - Fork 971
azkv: Allow specifying auth method and add cachable authentication methods #1777
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
daytime-saxophone
wants to merge
1
commit into
getsops:main
Choose a base branch
from
decentriq:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,14 +9,21 @@ import ( | |
"context" | ||
"encoding/base64" | ||
"fmt" | ||
"path/filepath" | ||
"regexp" | ||
"strings" | ||
"time" | ||
|
||
"encoding/json" | ||
"os" | ||
|
||
"github.com/Azure/azure-sdk-for-go/sdk/azcore" | ||
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" | ||
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to" | ||
"github.com/Azure/azure-sdk-for-go/sdk/azidentity" | ||
azidentitycache "github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache" | ||
"github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys" | ||
"github.com/pkg/browser" | ||
"github.com/sirupsen/logrus" | ||
|
||
"github.com/getsops/sops/v3/logging" | ||
|
@@ -25,6 +32,11 @@ import ( | |
const ( | ||
// KeyTypeIdentifier is the string used to identify an Azure Key Vault MasterKey. | ||
KeyTypeIdentifier = "azure_kv" | ||
|
||
SopsAzureAuthMethodEnv = "SOPS_AZURE_AUTH_METHOD" | ||
|
||
cachedBrowserAuthRecordFileName = "azure-auth-record-browser.json" | ||
cachedDeviceCodeAuthRecordFileName = "azure-auth-record-device-code.json" | ||
) | ||
|
||
var ( | ||
|
@@ -230,7 +242,142 @@ func (key *MasterKey) TypeToIdentifier() string { | |
// azidentity.NewDefaultAzureCredential. | ||
func (key *MasterKey) getTokenCredential() (azcore.TokenCredential, error) { | ||
if key.tokenCredential == nil { | ||
return azidentity.NewDefaultAzureCredential(nil) | ||
|
||
authMethod := strings.ToLower(os.Getenv(SopsAzureAuthMethodEnv)) | ||
switch authMethod { | ||
case "cached-browser": | ||
return cachedInteractiveBrowserCredentials() | ||
case "cached-device-code": | ||
return cachedDeviceCodeCredentials() | ||
case "azure-cli": | ||
return azidentity.NewAzureCLICredential(nil) | ||
case "msi": | ||
return azidentity.NewManagedIdentityCredential(nil) | ||
// If "DEFAULT" or not explicitly specified then use the default authentication chain. | ||
case "", "default": | ||
return azidentity.NewDefaultAzureCredential(nil) | ||
default: | ||
return nil, fmt.Errorf("Value `%s` is unsupported for environment variable `%s`, to resolve this either leave it unset or use one of `default`/`msi`/`azure-cli`/`cached-browser`/`cached-device-code`", authMethod, SopsAzureAuthMethodEnv) | ||
} | ||
} | ||
return key.tokenCredential, nil | ||
} | ||
|
||
func sopsCacheDir() (string, error) { | ||
userCacheDir, err := os.UserCacheDir() | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
cacheDir := filepath.Join(userCacheDir, "/sops") | ||
|
||
if err = os.MkdirAll(cacheDir, 0o700); err != nil { | ||
return "", err | ||
} | ||
|
||
return cacheDir, nil | ||
} | ||
Comment on lines
+266
to
+279
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think it would be better to create a var (
cacheDir string
cacheDirErr error
cacheDirOnce sync.Once
)
// Directory returns the path to the SOPS cache directory, creating it if it
// does not exist. The directory with the name "sops" is created in the user's
// cache directory (see [os.UserCacheDir]). Once created, it will not be
// recreated, even if the function is called multiple times. If an error occurs
// while creating the directory, it will be returned on later calls.
func Directory() (string, error) {
cacheDirOnce.Do(func() {
base, err := os.UserCacheDir()
if err != nil {
cacheDirErr = err
return
}
cacheDir = filepath.Join(base, "sops")
cacheDirErr = os.MkdirAll(cacheDir, 0o700)
})
if cacheDirErr != nil {
return "", cacheDirErr
}
return cacheDir, nil
}
// Put writes the provided data to a file in the SOPS cache directory.
// At present, no validation is performed on the file name, and it is the
// caller's responsibility to ensure that the file name is safe (i.e., does not
// contain path traversal characters or other unsafe elements).
func Put(fileName string, data []byte) error {
dir, err := Directory()
if err != nil {
return err
}
filePath := filepath.Join(dir, fileName)
if err = os.WriteFile(filePath, data, 0o600); err != nil {
return fmt.Errorf("failed to write to cache file %s: %w", filePath, err)
}
return nil
}
// Get reads the contents of a file from the SOPS cache directory.
// If the file does not exist or cannot be read, an error will be returned.
func Get(fileName string) ([]byte, error) {
dir, err := Directory()
if err != nil {
return nil, err
}
filePath := filepath.Join(dir, fileName)
data, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("failed to read cache file %s: %w", filePath, err)
}
return data, nil
}
// Exists checks if a file exists in the SOPS cache directory.
func Exists(fileName string) (bool, error) {
dir, err := Directory()
if err != nil {
return false, err
}
filePath := filepath.Join(dir, fileName)
if _, err = os.Stat(filePath); err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
return true, nil
} |
||
|
||
type CachableTokenCredential interface { | ||
Authenticate(ctx context.Context, opts *policy.TokenRequestOptions) (azidentity.AuthenticationRecord, error) | ||
GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) | ||
} | ||
|
||
func cacheStoreRecord(cachePath string, record azidentity.AuthenticationRecord) error { | ||
b, err := json.Marshal(record) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
return os.WriteFile(cachePath, b, 0600) | ||
} | ||
|
||
func cacheLoadRecord(cachePath string) (azidentity.AuthenticationRecord, error) { | ||
var record azidentity.AuthenticationRecord | ||
|
||
b, err := os.ReadFile(cachePath) | ||
if err != nil { | ||
return record, err | ||
} | ||
|
||
err = json.Unmarshal(b, &record) | ||
if err != nil { | ||
return record, err | ||
} | ||
|
||
return record, nil | ||
} | ||
|
||
func cacheTokenCredential(cachePath string, tokenCredentialFn func(cache azidentity.Cache, record azidentity.AuthenticationRecord) (CachableTokenCredential, error)) (azcore.TokenCredential, error) { | ||
cache, err := azidentitycache.New(nil) | ||
// Errors if persistent caching is not supported by the current runtime | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
cachedRecord, cacheLoadErr := cacheLoadRecord(cachePath) | ||
|
||
credential, err := tokenCredentialFn(cache, cachedRecord) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
// If loading the authenticationRecord from the cachePath failed for any reason (validation, file doesn't exist, not encoded using json, etc.) | ||
if cacheLoadErr != nil { | ||
record, err := credential.Authenticate(context.Background(), nil) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
if err = cacheStoreRecord(cachePath, record); err != nil { | ||
return nil, err | ||
} | ||
} | ||
|
||
return credential, nil | ||
} | ||
|
||
func cachedInteractiveBrowserCredentials() (azcore.TokenCredential, error) { | ||
// The default behaviour of `browser` which `azidentity` is using for the interactive browser authentication method is to write anything the browser prints to stdout to the stdout of the program running it. | ||
// This is not desired since on the initial authentication or when refreshing the cache it would pollute the output of sops. | ||
// To fix this behaviour we redirect the browser stdout -> stderr so any pertinent information written by the browser is not completely hidden from the user but it doesn't mess up the sops output. | ||
browser.Stdout = os.Stderr | ||
|
||
cacheDir, err := sopsCacheDir() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return cacheTokenCredential( | ||
filepath.Join(cacheDir, cachedBrowserAuthRecordFileName), | ||
func(cache azidentity.Cache, record azidentity.AuthenticationRecord) (CachableTokenCredential, error) { | ||
return azidentity.NewInteractiveBrowserCredential(&azidentity.InteractiveBrowserCredentialOptions{ | ||
AuthenticationRecord: record, | ||
Cache: cache, | ||
}) | ||
}, | ||
) | ||
} | ||
|
||
func cachedDeviceCodeCredentials() (azcore.TokenCredential, error) { | ||
cacheDir, err := sopsCacheDir() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return cacheTokenCredential( | ||
filepath.Join(cacheDir, cachedDeviceCodeAuthRecordFileName), | ||
func(cache azidentity.Cache, record azidentity.AuthenticationRecord) (CachableTokenCredential, error) { | ||
return azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{ | ||
AuthenticationRecord: record, | ||
Cache: cache, | ||
// Print the device code authentication information to stderr so we don't pollute the output of sops. | ||
UserPrompt: func(ctx context.Context, dc azidentity.DeviceCodeMessage) error { | ||
_, err := fmt.Fprintln(os.Stderr, dc.Message) | ||
return err | ||
|
||
}, | ||
}) | ||
}, | ||
) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These imports aren't properly ordered.