-
Notifications
You must be signed in to change notification settings - Fork 43
feat(pam): add AWS IAM CLI access #285
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
saifsmailbox98
wants to merge
3
commits into
pam-revamp
Choose a base branch
from
saif/pam-261-aws-web-and-cli-access
base: pam-revamp
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
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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 |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| package pam | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "os" | ||
| "os/signal" | ||
| "path/filepath" | ||
| "syscall" | ||
| "time" | ||
|
|
||
| "github.com/go-resty/resty/v2" | ||
| "github.com/rs/zerolog/log" | ||
| "gopkg.in/ini.v1" | ||
|
|
||
| "github.com/Infisical/infisical-merge/packages/api" | ||
| "github.com/Infisical/infisical-merge/packages/util" | ||
| ) | ||
|
|
||
| func startAWSAccess(_ *resty.Client, response *api.PAMAccessResponse, path, _ string, _ int) { | ||
| expiresAtStr := response.Metadata["expiresAt"] | ||
| accessKeyId := response.Metadata["accessKeyId"] | ||
| secretAccessKey := response.Metadata["secretAccessKey"] | ||
| sessionToken := response.Metadata["sessionToken"] | ||
|
|
||
| if accessKeyId == "" || secretAccessKey == "" || sessionToken == "" || expiresAtStr == "" { | ||
| util.PrintErrorMessageAndExit("Backend did not return AWS IAM credentials in session metadata") | ||
| return | ||
| } | ||
|
|
||
| expiresAt, err := time.Parse(time.RFC3339, expiresAtStr) | ||
| if err != nil { | ||
| util.PrintErrorMessageAndExit(fmt.Sprintf("Failed to parse credential expiry time: %v", err)) | ||
| return | ||
| } | ||
|
|
||
| remaining := time.Until(expiresAt) | ||
| if remaining <= 0 { | ||
| util.PrintErrorMessageAndExit("AWS credentials returned by the backend are already expired") | ||
| return | ||
| } | ||
|
|
||
| folder, account := parsePath(path) | ||
| profileName := fmt.Sprintf("infisical-pam/%s/%s", folder, account) | ||
|
|
||
| credFilePath := awsCredentialsFilePath() | ||
| createdFile := false | ||
|
|
||
| dir := filepath.Dir(credFilePath) | ||
| if err := os.MkdirAll(dir, 0o700); err != nil { | ||
| util.PrintErrorMessageAndExit(fmt.Sprintf("Failed to create directory %s: %v", dir, err)) | ||
| return | ||
| } | ||
|
|
||
| if _, statErr := os.Stat(credFilePath); os.IsNotExist(statErr) { | ||
| createdFile = true | ||
| } | ||
|
|
||
| cfg, err := ini.LooseLoad(credFilePath) | ||
| if err != nil { | ||
| util.PrintErrorMessageAndExit(fmt.Sprintf("Failed to load AWS credentials file: %v", err)) | ||
| return | ||
| } | ||
|
|
||
| section := cfg.Section(profileName) | ||
| section.Key("aws_access_key_id").SetValue(accessKeyId) | ||
| section.Key("aws_secret_access_key").SetValue(secretAccessKey) | ||
| section.Key("aws_session_token").SetValue(sessionToken) | ||
|
|
||
| if err := cfg.SaveTo(credFilePath); err != nil { | ||
| util.PrintErrorMessageAndExit(fmt.Sprintf("Failed to write AWS credentials file: %v", err)) | ||
| return | ||
| } | ||
|
|
||
| _ = os.Chmod(credFilePath, 0o600) | ||
|
|
||
| log.Info().Str("profile", profileName).Str("file", credFilePath).Msg("AWS credentials written") | ||
|
|
||
| printAWSSessionInfo(folder, account, remaining, profileName, expiresAt) | ||
|
saifsmailbox98 marked this conversation as resolved.
|
||
|
|
||
| cleanup := func() { | ||
| removeAWSProfile(credFilePath, profileName, createdFile) | ||
| } | ||
|
|
||
| sigChan := make(chan os.Signal, 1) | ||
| signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) | ||
|
|
||
| select { | ||
| case sig := <-sigChan: | ||
| log.Info().Msgf("Received signal %v, cleaning up...", sig) | ||
| cleanup() | ||
| case <-time.After(remaining): | ||
| fmt.Printf("\n AWS session expired. Cleaning up credentials...\n\n") | ||
| cleanup() | ||
| } | ||
| } | ||
|
|
||
| func removeAWSProfile(credFilePath, profileName string, createdFile bool) { | ||
| cfg, err := ini.LooseLoad(credFilePath) | ||
| if err != nil { | ||
| log.Error().Err(err).Msg("Failed to load AWS credentials file for cleanup") | ||
| return | ||
| } | ||
|
|
||
| cfg.DeleteSection(profileName) | ||
|
|
||
| // If we created the file and it's now empty (only DEFAULT section with no keys), remove it | ||
| if createdFile && len(cfg.Sections()) <= 1 && len(cfg.Section("DEFAULT").Keys()) == 0 { | ||
| if removeErr := os.Remove(credFilePath); removeErr != nil { | ||
| log.Error().Err(removeErr).Msg("Failed to remove AWS credentials file") | ||
| } else { | ||
| log.Info().Str("file", credFilePath).Msg("Removed AWS credentials file (created by this session)") | ||
| } | ||
| return | ||
| } | ||
|
|
||
| if err := cfg.SaveTo(credFilePath); err != nil { | ||
| log.Error().Err(err).Msg("Failed to save AWS credentials file after cleanup") | ||
| return | ||
| } | ||
|
|
||
| log.Info().Str("profile", profileName).Msg("Removed AWS credentials profile") | ||
| } | ||
|
|
||
| func awsCredentialsFilePath() string { | ||
| if envPath := os.Getenv("AWS_SHARED_CREDENTIALS_FILE"); envPath != "" { | ||
| return envPath | ||
| } | ||
| home, err := os.UserHomeDir() | ||
| if err != nil { | ||
| return filepath.Join(".", ".aws", "credentials") | ||
| } | ||
| return filepath.Join(home, ".aws", "credentials") | ||
| } | ||
|
|
||
| func printAWSSessionInfo(folder, account string, duration time.Duration, profileName string, expiresAt time.Time) { | ||
| fmt.Printf("\n") | ||
| fmt.Printf("**********************************************************************\n") | ||
| fmt.Printf(" AWS IAM Session Started! \n") | ||
| fmt.Printf("**********************************************************************\n") | ||
| fmt.Printf("\n") | ||
| if folder != "" { | ||
| fmt.Printf(" Folder: %s\n", folder) | ||
| } | ||
| fmt.Printf(" Account: %s\n", account) | ||
| fmt.Printf(" Duration: %s\n", duration.Round(time.Second).String()) | ||
| fmt.Printf(" Expires: %s\n", expiresAt.Local().Format("2006-01-02 15:04:05 MST")) | ||
| fmt.Printf("\n") | ||
| fmt.Printf("----------------------------------------------------------------------\n") | ||
| fmt.Printf(" Connection Details \n") | ||
| fmt.Printf("----------------------------------------------------------------------\n") | ||
| fmt.Printf("\n") | ||
| fmt.Printf(" AWS credentials written to: %s\n", awsCredentialsFilePath()) | ||
| fmt.Printf(" Profile name: %s\n", profileName) | ||
| fmt.Printf("\n") | ||
| fmt.Printf("----------------------------------------------------------------------\n") | ||
| fmt.Printf(" How to Connect \n") | ||
| fmt.Printf("----------------------------------------------------------------------\n") | ||
| fmt.Printf("\n") | ||
| fmt.Printf(" Use the AWS CLI with the profile:\n") | ||
| util.PrintfStderr(" $ aws s3 ls --profile \"%s\"\n", profileName) | ||
| fmt.Printf("\n") | ||
| fmt.Printf(" Or set the AWS_PROFILE environment variable:\n") | ||
| util.PrintfStderr(" $ export AWS_PROFILE=\"%s\"\n", profileName) | ||
| util.PrintfStderr(" $ aws sts get-caller-identity\n") | ||
| fmt.Printf("\n") | ||
| fmt.Printf(" Press Ctrl+C to stop and remove the credentials profile.\n") | ||
| fmt.Printf("\n") | ||
| fmt.Printf("**********************************************************************\n") | ||
| fmt.Printf("\n") | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.