Skip to content

Commit

Permalink
Config file update fix (oktadev#22)
Browse files Browse the repository at this point in the history
* Config file update fix

Removed check on role_arn value being blank or not since this
interferes with the default profile update (which might not need a
role_arn value in the ~/.aws/config file). This parameter will not be
updated if blank in the WriteNewRoleToAssume function anyway.

* Added cross account role debug log
  • Loading branch information
raphaellondner-okta committed Jan 6, 2017
1 parent cfcd318 commit 74ea406
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 51 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@ lib/aws-java-sdk-1.10.74.jar
lib/aws-java-sdk-1.11.37.jar

.idea/workspace.xml

target/classes/log4j2.xml
99 changes: 48 additions & 51 deletions src/main/java/com/okta/tools/awscli.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public class awscli {
private static String awsIamSecret = null;
private static AuthApiClient authClient;

private static final String DefaultProfileName = "default";
private static final String DefaultProfileName = "default";

private static FactorsApiClient factorClient;
private static UserApiClient userClient;
Expand Down Expand Up @@ -407,6 +407,8 @@ private static AssumeRoleWithSAMLResult assumeAWSRole(String resultSAML) {
String principalArn = principalArns.get(selection);
String roleArn = roleArns.get(selection);
crossAccountRoleName = roleArn.substring(roleArn.indexOf("/") + 1);
logger.debug("Cross-account role is " + crossAccountRoleName);


//creates empty AWS credentials to prevent the AWSSecurityTokenServiceClient object from unintentionally loading the previous profile we just created
BasicAWSCredentials awsCreds = new BasicAWSCredentials("", "");
Expand Down Expand Up @@ -488,9 +490,9 @@ private static void GetRoleToAssume(String roleName) {
if (inlinePolicies.size() > 1) {
//ask the user to select one policy if there are more than one

logger.debug("Inline Policies: " + inlinePolicies.toString());
logger.debug("Inline Policies: " + inlinePolicies.toString());

selectedPolicyRank = SelectPolicy(inlinePolicies);
selectedPolicyRank = SelectPolicy(inlinePolicies);
}

//Have to set the role name and the policy name (both are mandatory fields
Expand Down Expand Up @@ -553,14 +555,13 @@ private static String ProcessPolicyDocument(String policyDoc) {
}
}
if (resource != null) {
if(resource.isArray()) { //if we're handling a policy with an array of AssumeRole attributes
if (resource.isArray()) { //if we're handling a policy with an array of AssumeRole attributes
ArrayList<String> lstRoles = new ArrayList<String>();
for(final JsonNode node: resource) {
for (final JsonNode node : resource) {
lstRoles.add(node.asText());
}
strRoleToAssume = SelectRole(lstRoles);
}
else {
} else {
strRoleToAssume = resource.textValue();
logger.debug("Role to assume: " + roleToAssume);
}
Expand Down Expand Up @@ -590,7 +591,7 @@ private static String SelectRole(List<String> lstRoles) {
//Prompt user for policy selection
int selection = numSelection(lstRoles.size());

if(selection < 0 && lstRoles.size() > selection) {
if (selection < 0 && lstRoles.size() > selection) {
System.out.println("\nYou entered an invalid number. Please try again.");
return SelectRole(lstRoles);
}
Expand Down Expand Up @@ -652,13 +653,11 @@ private static void UpdateCredentialsFile(String profileName, String awsAccessKe
//if we end up here, it means we were able to find a matching profile
PopulateCredentialsFile(profileNameWithBrackets, awsAccessKey, awsSecretKey, awsSessionToken);
}
}
catch(AmazonClientException ace) {
//this could happen if the default profile doesn't have a valid AWS Access Key ID
} catch (AmazonClientException ace) {
//this could happen if the default profile doesn't have a valid AWS Access Key ID
//in this case, error would be "Unable to load credentials into profile [default]: AWS Access Key ID is not specified."
PopulateCredentialsFile(profileNameWithBrackets, awsAccessKey, awsSecretKey, awsSessionToken);
}
catch (IllegalArgumentException iae) {
} catch (IllegalArgumentException iae) {
//if we end up here, it means we were not able to find a matching profile so we need to append one
PopulateCredentialsFile(profileNameWithBrackets, awsAccessKey, awsSecretKey, awsSessionToken);
//FileWriter fileWriter = new FileWriter(System.getProperty("user.home") + "/.aws/credentials", true);
Expand Down Expand Up @@ -719,54 +718,52 @@ private static void PopulateCredentialsFile(String profileNameLine, String awsAc

private static void UpdateConfigFile(String profileName, String roleToAssume) throws IOException {

if (roleToAssume != null && !roleToAssume.equals("")) {
File inFile = new File(System.getProperty("user.home") + "/.aws/config");
File inFile = new File(System.getProperty("user.home") + "/.aws/config");

FileInputStream fis = new FileInputStream(inFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
FileInputStream fis = new FileInputStream(inFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

//first, we add our refreshed profile
WriteNewRoleToAssume(pw, profileName, roleToAssume);
//first, we add our refreshed profile
WriteNewRoleToAssume(pw, profileName, roleToAssume);

String line = null;
int lineCounter = 0;
boolean bFileStart = true;
String line = null;
int lineCounter = 0;
boolean bFileStart = true;

//second, we're copying all the other profiles from the original config file
while ((line = br.readLine()) != null) {
//second, we're copying all the other profiles from the original config file
while ((line = br.readLine()) != null) {

if (line.contains(profileName)) {
//we found the section we must replace but we don't necessarily know how many lines we need to skip
while ((line = br.readLine()) != null) {
if (line.startsWith("[")) {
pw.println(line); //this is a new profile line, so we're copying it
break;
}
}
} else {
if ((!line.contains(profileName) && !line.equalsIgnoreCase("\n"))) {
pw.println(line);
logger.debug(line);
if (line.contains(profileName)) {
//we found the section we must replace but we don't necessarily know how many lines we need to skip
while ((line = br.readLine()) != null) {
if (line.startsWith("[")) {
pw.println(line); //this is a new profile line, so we're copying it
break;
}
}
} else {
if ((!line.contains(profileName) && !line.equalsIgnoreCase("\n"))) {
pw.println(line);
logger.debug(line);
}
}


}
}

pw.flush();
pw.close();
br.close();
pw.flush();
pw.close();
br.close();

//delete the original credentials file
if (!inFile.delete()) {
System.out.println("Could not delete original config file");
} else {
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
//delete the original credentials file
if (!inFile.delete()) {
System.out.println("Could not delete original config file");
} else {
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
}

Expand All @@ -781,8 +778,8 @@ public static void WriteNewProfile(PrintWriter pw, String profileNameLine, Strin
}

public static void WriteNewRoleToAssume(PrintWriter pw, String profileName, String roleToAssume) {

pw.println("[profile " + profileName + "]");
//writer.println("[" + credentialsProfileName + "]");
if (roleToAssume != null && !roleToAssume.equals(""))
pw.println("role_arn=" + roleToAssume);
pw.println("source_profile=" + profileName);
Expand Down

0 comments on commit 74ea406

Please sign in to comment.