private static AWSCredentials GetCredentialSourceAWSCredentials(string credentialSourceType, bool throwIfInvalid)
        {
            AWSCredentials       credentials;
            CredentialSourceType type;

            try
            {
                type = (CredentialSourceType)Enum.Parse(typeof(CredentialSourceType), credentialSourceType, true);
            }
            catch
            {
                return(ThrowOrReturnNull(string.Format(CultureInfo.InvariantCulture,
                                                       "Credential source [{0}] is invalid.", credentialSourceType), null, throwIfInvalid));
            }

            switch (type)
            {
            case CredentialSourceType.Ec2InstanceMetadata:
                credentials = DefaultInstanceProfileAWSCredentials.Instance;
                break;

            case CredentialSourceType.Environment:
                credentials = new EnvironmentVariablesAWSCredentials();
                break;

            case CredentialSourceType.EcsContainer:
                string uri = Environment.GetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsURIEnvVariable);
                if (string.IsNullOrEmpty(uri))
                {
                    return(ThrowOrReturnNull(string.Format(CultureInfo.InvariantCulture,
                                                           "Container environment variable {0} is not set.", ECSTaskCredentials.ContainerCredentialsURIEnvVariable), null, throwIfInvalid));
                }

                credentials = new ECSTaskCredentials(null);
                break;

            default:
                return(ThrowOrReturnNull(string.Format(CultureInfo.InvariantCulture,
                                                       "Credential source [{0}] is not implemented.", credentialSourceType), null, throwIfInvalid));
            }

            return(credentials);
        }
        public void TestECSCredentialsLocal()
        {
            string uri        = "/ECS/Test/Endpoint/";
            string accessKey  = "SomeKey";
            string secretKey  = "SomeSecretKey";
            string token      = "Token";
            string expiration = DateTime.UtcNow.AddHours(1).ToString("s") + "Z";

            System.Environment.SetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsURIEnvVariable, uri);

            using (ResponseTestServlet servlet = new ResponseTestServlet(uri))
            {
                string server = "http://*****:*****@"{{
    ""AccessKeyId"" : ""{0}"",
    ""SecretAccessKey"" : ""{1}"",
    ""Token"" : ""{2}"",
    ""Expiration"" : ""{3}""
}}", accessKey, secretKey, token, expiration);

                ECSTaskCredentials generator = new ECSTaskCredentials();

                FieldInfo serverField = generator.GetType().GetField("Server", BindingFlags.Instance | BindingFlags.NonPublic);
                Assert.IsNotNull(serverField);
                serverField.SetValue(generator, server);

                ImmutableCredentials credentials = generator.GetCredentials();

                Assert.AreEqual(accessKey, credentials.AccessKey);
                Assert.AreEqual(secretKey, credentials.SecretKey);
                Assert.AreEqual(token, credentials.Token);
            }

            System.Environment.SetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsURIEnvVariable, "");
        }
Exemplo n.º 3
0
        public static bool TryGetCredentials(
            this IAWSCredentialsArguments self,
            PSHost psHost,
            out AWSPSCredentials credentials,
            SessionState sessionState)
        {
            if (self == null)
            {
                throw new ArgumentNullException("self");
            }

            credentials = null;
            string name   = null;
            var    source = CredentialsSource.Unknown;
            var    userSpecifiedProfile = !string.IsNullOrEmpty(self.ProfileName);

            var profileChain = new CredentialProfileStoreChain(self.ProfileLocation);

            // we probe for credentials by first checking the bound parameters to see if explicit credentials
            // were supplied (keys, profile name, credential object), overriding anything in the shell environment
            if (AWSCredentialsFactory.TryGetAWSCredentials(
                    self.GetCredentialProfileOptions(),
                    profileChain,
                    out var innerCredentials))
            {
                source = CredentialsSource.Strings;
                name   = "Supplied Key Parameters";
                SetProxyAndCallbackIfNecessary(innerCredentials, self, psHost, sessionState);
            }

            // user gave us the profile name?
            if (innerCredentials == null && userSpecifiedProfile)
            {
                if (profileChain.TryGetProfile(self.ProfileName, out var credentialProfile))
                {
                    innerCredentials = AWSCredentialsFactory.GetAWSCredentials(credentialProfile, profileChain);
                    source           = CredentialsSource.Profile;
                    name             = self.ProfileName;
                    SetProxyAndCallbackIfNecessary(innerCredentials, self, psHost, sessionState);
                }
                else
                {
                    // if the user gave us an explicit profile name (and optional location) it's an error if we
                    // don't find it as otherwise we could drop through and pick up a 'default' profile that is
                    // for a different account
                    return(false);
                }
            }

            // how about an aws credentials object?
            if (innerCredentials == null && self.Credential != null)
            {
                innerCredentials = self.Credential;
                source           = CredentialsSource.CredentialsObject;
                name             = "Credentials Object";

                // don't set proxy and callback, use self.Credential as-is
            }

            // shell session variable set (this allows override of machine-wide environment variables)
            if (innerCredentials == null && sessionState != null)
            {
                if (TryGetAWSPSCredentialsFromConflictingType(
                        sessionState.PSVariable.GetValue(SessionKeys.AWSCredentialsVariableName),
                        out var psCredentials))
                {
                    credentials      = psCredentials;
                    source           = CredentialsSource.Session;
                    innerCredentials = credentials.Credentials; // so remaining probes are skipped

                    // don't set proxy and callback, use credentials.Credentials as-is
                }
            }

            // no explicit command-level or shell instance override set, start to inspect the environment
            // starting environment variables
            if (innerCredentials == null)
            {
                try
                {
                    var environmentCredentials = new EnvironmentVariablesAWSCredentials();
                    innerCredentials = environmentCredentials;
                    source           = CredentialsSource.Environment;
                    name             = "Environment Variables";

                    // no need to set proxy and callback - only basic or session credentials
                }
                catch
                {
                }
            }

            // get credentials from a 'default' profile?
            if (innerCredentials == null && !userSpecifiedProfile)
            {
                if (profileChain.TryGetProfile(SettingsStore.PSDefaultSettingName, out var credentialProfile) &&
                    credentialProfile.CanCreateAWSCredentials)
                {
                    innerCredentials = AWSCredentialsFactory.GetAWSCredentials(credentialProfile, profileChain);
                    source           = CredentialsSource.Profile;
                    name             = SettingsStore.PSDefaultSettingName;
                    SetProxyAndCallbackIfNecessary(innerCredentials, self, psHost, sessionState);
                }
            }

            // get credentials from a legacy default profile name?
            if (innerCredentials == null)
            {
                if (profileChain.TryGetProfile(SettingsStore.PSLegacyDefaultSettingName, out var credentialProfile) &&
                    credentialProfile.CanCreateAWSCredentials)
                {
                    if (AWSCredentialsFactory.TryGetAWSCredentials(
                            credentialProfile,
                            profileChain,
                            out innerCredentials))
                    {
                        source = CredentialsSource.Profile;
                        name   = SettingsStore.PSLegacyDefaultSettingName;
                        SetProxyAndCallbackIfNecessary(innerCredentials, self, psHost, sessionState);
                    }
                }
            }

            if (innerCredentials == null)
            {
                // try and load credentials from ECS endpoint (if the relevant environment variable is set)
                // or EC2 Instance Profile as a last resort
                try
                {
                    var relativeUri =
                        Environment.GetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsURIEnvVariable);
                    var fullUri = Environment.GetEnvironmentVariable(
                        ECSTaskCredentials.ContainerCredentialsFullURIEnvVariable);

                    if (!string.IsNullOrEmpty(relativeUri) || !string.IsNullOrEmpty(fullUri))
                    {
                        innerCredentials = new ECSTaskCredentials();
                        source           = CredentialsSource.Container;
                        name             = "Container";

                        // no need to set proxy and callback
                    }
                    else
                    {
                        innerCredentials = new InstanceProfileAWSCredentials();
                        source           = CredentialsSource.InstanceProfile;
                        name             = "Instance Profile";

                        // no need to set proxy and callback
                    }
                }
                catch
                {
                    innerCredentials = null;
                }
            }

            if (credentials == null && innerCredentials != null)
            {
                credentials = new AWSPSCredentials(innerCredentials, name, source);
            }

            return(credentials != null);
        }
Exemplo n.º 4
0
        public void TestECSCredentialsLocal()
        {

            string uri = "/ECS/Test/Endpoint/";
            string accessKey = "SomeKey";
            string secretKey = "SomeSecretKey";
            string token = "Token";
            string expiration = DateTime.UtcNow.AddHours(1).ToString("s") + "Z";

            System.Environment.SetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsURIEnvVariable, uri);

            using (ResponseTestServlet servlet = new ResponseTestServlet(uri))
            {
                string server = "http://*****:*****@"{{
    ""AccessKeyId"" : ""{0}"",
    ""SecretAccessKey"" : ""{1}"",
    ""Token"" : ""{2}"",
    ""Expiration"" : ""{3}""
}}", accessKey, secretKey, token, expiration);

                ECSTaskCredentials generator = new ECSTaskCredentials();

                FieldInfo serverField = generator.GetType().GetField("Server", BindingFlags.Instance | BindingFlags.NonPublic );
                Assert.IsNotNull(serverField);
                serverField.SetValue(generator, server);

                ImmutableCredentials credentials = generator.GetCredentials();

                Assert.AreEqual(accessKey, credentials.AccessKey);
                Assert.AreEqual(secretKey, credentials.SecretKey);
                Assert.AreEqual(token, credentials.Token);
            }

            System.Environment.SetEnvironmentVariable(ECSTaskCredentials.ContainerCredentialsURIEnvVariable, "");
        }