Helper function that returns `true` if getting the security credentials from the metadata service is needed or `false` otherwise.

@method needsToLoadEC2IAMRoleCredentials
@private
760494
function needsToLoadEC2IAMRoleCredentials() {
		if (!accessKey || !secretKey) return true;
		if (credentialsExpiration === null) return false;
		return (credentialsExpiration.getTime() - Date.now()) < CREDENTIALS_EXPIRATION_THRESHOLD;
	}
663238
function loadNowJSON(secrets = {}, required = {}) {
  const NOW_PATH = resolve(process.env.NOW_CONFIG || './now.json')

  try {
    const nowFile = require(NOW_PATH)

    if (nowFile.env) {
      applyEnv(nowFile.env, secrets, required)
    }

    return true
  } catch (error) {
    if (isModuleMissing(error)) {
      return false
    }
    throw error
  }
}
729667
def assume_role(role_name, credentials, role_arn, role_session_name, silent = False):
    
    external_id = credentials.pop('ExternalId') if 'ExternalId' in credentials else None
    # Connect to STS
    sts_client = connect_service('sts', credentials, silent = silent)
    # Set required arguments for assume role call
    sts_args = {
      'RoleArn': role_arn,
      'RoleSessionName': role_session_name
    }
    # MFA used ?
    if 'mfa_serial' in credentials and 'mfa_code' in credentials:
      sts_args['TokenCode'] = credentials['mfa_code']
      sts_args['SerialNumber'] = credentials['mfa_serial']
    # External ID used ?
    if external_id:
      sts_args['ExternalId'] = external_id
    # Assume the role
    sts_response = sts_client.assume_role(**sts_args)
    credentials = sts_response['Credentials']
    cached_credentials_filename = get_cached_credentials_filename(role_name, role_arn)
    #with open(cached_credentials_filename, 'wt+') as f:
    #   write_data_to_file(f, sts_response, True, False)
    cached_credentials_path = os.path.dirname(cached_credentials_filename)
    if not os.path.isdir(cached_credentials_path):
        os.makedirs(cached_credentials_path)
    save_blob_as_json(cached_credentials_filename, sts_response, True, False) # blob, force_write, debug):
    return credentials
1289021
private boolean isAuthorized() {
        SecurityService securityService = securityServiceRef.getService();
        AuthorizationService authzService = securityService.getAuthorizationService();
        boolean isAuthorized = authzService.isAuthorized(ManagementSecurityConstants.ADMIN_RESOURCE_NAME,
                                                         requiredRoles, null);
        return isAuthorized;
    }
1150372
function() {
        var allow_navigations = this.doc.findall('./allow-navigation');
        return allow_navigations.map(function(allow_navigation){
            var minimum_tls_version = allow_navigation.attrib['minimum-tls-version']; /* String */
            var requires_forward_secrecy = allow_navigation.attrib['requires-forward-secrecy']; /* Boolean */
            var requires_certificate_transparency = allow_navigation.attrib['requires-certificate-transparency']; /* Boolean */

            return {
                'href': allow_navigation.attrib.href,
                'minimum_tls_version': minimum_tls_version,
                'requires_forward_secrecy' : requires_forward_secrecy,
                'requires_certificate_transparency' : requires_certificate_transparency
            };
        });
    }
6320
function() {
    this.header = undefined;
    this.credentials = undefined;
    this.meta = undefined;
    this.xml = undefined;
    this.binaries = new KdbxBinaries();
    this.groups = [];
    this.deletedObjects = [];
    Object.preventExtensions(this);
}
136240
function loadMetaSet(root) {
            var paths = innerCore.getMemberPaths(root, CONSTANTS.META_SET_NAME),
                i,
                metaNodes = [];

            return TASYNC.call(function () {
                for (i = 0; i < paths.length; i += 1) {
                    metaNodes.push(innerCore.loadByPath(root, paths[i]));
                }

                return TASYNC.lift(metaNodes);
            }, self.loadPaths(self.getHash(root), JSON.parse(JSON.stringify(paths))));
        }
130101
function buildBastionIamRole({ name = 'BastionIamRole' } = {}) {
  return {
    [name]: {
      Type: 'AWS::IAM::Role',
      Properties: {
        AssumeRolePolicyDocument: {
          Statement: [
            {
              Effect: 'Allow',
              Principal: {
                Service: 'ec2.amazonaws.com',
              },
              Action: 'sts:AssumeRole',
            },
          ],
        },
        Policies: [
          {
            PolicyName: 'AllowEIPAssociation',
            PolicyDocument: {
              Version: '2012-10-17',
              Statement: [
                {
                  Action: 'ec2:AssociateAddress',
                  Resource: '*',
                  Effect: 'Allow',
                },
              ],
            },
          },
        ],
        ManagedPolicyArns: ['arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM'],
      },
    },
  };
}
825005
function (callback) {
    fs.readFile(clientSecretPath, function processClientSecrets(err, content) {
        if (err) {
            debug('Error loading client secret file: ' + err);
            return callback(err);
        } else {
            credentials = JSON.parse(content);
            return callback();
        }
    });
}
158012
private AuthConfig getAuthConfigFromEC2InstanceRole() throws IOException {
        log.debug("No user and password set for ECR, checking EC2 instance role");
        try (CloseableHttpClient client = HttpClients.custom().useSystemProperties().build()) {
            // we can set very low timeouts because the request returns almost instantly on
            // an EC2 instance
            // on a non-EC2 instance we can fail early
            RequestConfig conf = RequestConfig.custom().setConnectionRequestTimeout(1000).setConnectTimeout(1000)
                    .setSocketTimeout(1000).build();

            // get instance role - if available
            HttpGet request = new HttpGet("http://169.254.169.254/latest/meta-data/iam/security-credentials");
            request.setConfig(conf);
            String instanceRole;
            try (CloseableHttpResponse response = client.execute(request)) {
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    // no instance role found
                    log.debug("No instance role found, return code was %d", response.getStatusLine().getStatusCode());
                    return null;
                }

                // read instance role
                try (InputStream is = response.getEntity().getContent()) {
                    instanceRole = IOUtils.toString(is, StandardCharsets.UTF_8);
                }
            }
            log.debug("Found instance role %s, getting temporary security credentials", instanceRole);

            // get temporary credentials
            request = new HttpGet("http://169.254.169.254/latest/meta-data/iam/security-credentials/"
                    + UrlEscapers.urlPathSegmentEscaper().escape(instanceRole));
            request.setConfig(conf);
            try (CloseableHttpResponse response = client.execute(request)) {
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    log.debug("No security credential found, return code was %d",
                            response.getStatusLine().getStatusCode());
                    // no instance role found
                    return null;
                }

                // read instance role
                try (Reader r = new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)) {
                    JsonObject securityCredentials = new Gson().fromJson(r, JsonObject.class);

                    String user = securityCredentials.getAsJsonPrimitive("AccessKeyId").getAsString();
                    String password = securityCredentials.getAsJsonPrimitive("SecretAccessKey").getAsString();
                    String token = securityCredentials.getAsJsonPrimitive("Token").getAsString();

                    log.debug("Received temporary access key %s...", user.substring(0, 8));
                    return new AuthConfig(user, password, "none", token);
                }
            }
        }
    }
388823
def GetCredentials(package_name, scopes, client_id, client_secret, user_agent,
                   credentials_filename=None,
                   api_key=None,  # pylint: disable=unused-argument
                   client=None,  # pylint: disable=unused-argument
                   oauth2client_args=None,
                   **kwds):
    """"""
    scopes = util.NormalizeScopes(scopes)
    client_info = {
        'client_id': client_id,
        'client_secret': client_secret,
        'scope': ' '.join(sorted(scopes)),
        'user_agent': user_agent or '%s-generated/0.1' % package_name,
    }
    for method in _CREDENTIALS_METHODS:
        credentials = method(client_info, **kwds)
        if credentials is not None:
            return credentials
    credentials_filename = credentials_filename or os.path.expanduser(
        '~/.apitools.token')
    credentials = CredentialsFromFile(credentials_filename, client_info,
                                      oauth2client_args=oauth2client_args)
    if credentials is not None:
        return credentials
    raise exceptions.CredentialsError('Could not create valid credentials')
519057
def get_sp_metadata(self):
        
        metadata = OneLogin_Saml2_Metadata.builder(
            self.__sp, self.__security['authnRequestsSigned'],
            self.__security['wantAssertionsSigned'],
            self.__security['metadataValidUntil'],
            self.__security['metadataCacheDuration'],
            self.get_contacts(), self.get_organization()
        )

        add_encryption = self.__security['wantNameIdEncrypted'] or self.__security['wantAssertionsEncrypted']

        cert_new = self.get_sp_cert_new()
        metadata = OneLogin_Saml2_Metadata.add_x509_key_descriptors(metadata, cert_new, add_encryption)

        cert = self.get_sp_cert()
        metadata = OneLogin_Saml2_Metadata.add_x509_key_descriptors(metadata, cert, add_encryption)

        # Sign metadata
        if 'signMetadata' in self.__security and self.__security['signMetadata'] is not False:
            if self.__security['signMetadata'] is True:
                # Use the SP's normal key to sign the metadata:
                if not cert:
                    raise OneLogin_Saml2_Error(
                        'Cannot sign metadata: missing SP public key certificate.',
                        OneLogin_Saml2_Error.PUBLIC_CERT_FILE_NOT_FOUND
                    )
                cert_metadata = cert
                key_metadata = self.get_sp_key()
                if not key_metadata:
                    raise OneLogin_Saml2_Error(
                        'Cannot sign metadata: missing SP private key.',
                        OneLogin_Saml2_Error.PRIVATE_KEY_FILE_NOT_FOUND
                    )
            else:
                # Use a custom key to sign the metadata:
                if ('keyFileName' not in self.__security['signMetadata'] or
                        'certFileName' not in self.__security['signMetadata']):
                    raise OneLogin_Saml2_Error(
                        'Invalid Setting: signMetadata value of the sp is not valid',
                        OneLogin_Saml2_Error.SETTINGS_INVALID_SYNTAX
                    )
                key_file_name = self.__security['signMetadata']['keyFileName']
                cert_file_name = self.__security['signMetadata']['certFileName']
                key_metadata_file = self.__paths['cert'] + key_file_name
                cert_metadata_file = self.__paths['cert'] + cert_file_name

                try:
                    with open(key_metadata_file, 'r') as f_metadata_key:
                        key_metadata = f_metadata_key.read()
                except IOError:
                    raise OneLogin_Saml2_Error(
                        'Private key file not readable: %s',
                        OneLogin_Saml2_Error.PRIVATE_KEY_FILE_NOT_FOUND,
                        key_metadata_file
                    )

                try:
                    with open(cert_metadata_file, 'r') as f_metadata_cert:
                        cert_metadata = f_metadata_cert.read()
                except IOError:
                    raise OneLogin_Saml2_Error(
                        'Public cert file not readable: %s',
                        OneLogin_Saml2_Error.PUBLIC_CERT_FILE_NOT_FOUND,
                        cert_metadata_file
                    )

            signature_algorithm = self.__security['signatureAlgorithm']
            digest_algorithm = self.__security['digestAlgorithm']

            metadata = OneLogin_Saml2_Metadata.sign_metadata(metadata, key_metadata, cert_metadata, signature_algorithm, digest_algorithm)

        return metadata
670220
private boolean checkForSecureAccess() {
        Class[] classContext = getClassContext();
        for (Class clazz : classContext) {
            if (clazz.equals(SecureAccess.class) || clazz.equals(SecurityBreachHandler.class)
                    || clazz.equals(SecurityFunctions.class) || clazz.equals(SecureStorageImpl.class)) {
                return true;
            }
        }
        return false;
    }
850750
function validateUpdatedCredentialProperties (type, credentialDetails) {
  const newCredentialProperties = {};
  const credentialConfig = config.models.credentials.properties[type];

  for (const prop in credentialConfig.properties) {
    if (prop === 'scopes') {
      continue;
    }
    if (credentialDetails[prop]) {
      if (typeof credentialDetails[prop] !== 'string') {
        throw new Error('credential property must be a string'); // TODO: replace with validation error
      }
      if (credentialConfig.properties[prop].isMutable !== false) {
        newCredentialProperties[prop] = credentialDetails[prop];
      } else throw new Error(`${prop} is immutable`);
    }
  }

  return Object.keys(newCredentialProperties).length > 0 ? Promise.resolve(newCredentialProperties) : Promise.resolve(null);
}
362419
def load_metadata(self, metadata_conf):
        

        acs = self.attribute_converters

        if acs is None:
            raise ConfigurationError(
                "Missing attribute converter specification")

        try:
            ca_certs = self.ca_certs
        except:
            ca_certs = None
        try:
            disable_validation = self.disable_ssl_certificate_validation
        except:
            disable_validation = False

        mds = MetadataStore(acs, self, ca_certs,
            disable_ssl_certificate_validation=disable_validation)

        mds.imp(metadata_conf)

        return mds
1110730
function loadViaCredentialProcess(profile, callback) {
    proc.exec(profile['credential_process'], function(err, stdOut, stdErr) {
      if (err) {
        callback(AWS.util.error(
          new Error('credential_process returned error'),
          { code: 'ProcessCredentialsProviderFailure'}
        ), null);
      } else {
        try {
          var credData = JSON.parse(stdOut);
          if (credData.Expiration) {
            var currentTime = AWS.util.date.getDate();
            var expireTime = new Date(credData.Expiration);
            if (expireTime < currentTime) {
              throw Error('credential_process returned expired credentials');
            }
          }

          if (credData.Version !== 1) {
            throw Error('credential_process does not return Version == 1');
          }
          callback(null, credData);
        } catch (err) {
          callback(AWS.util.error(
            new Error(err.message),
            { code: 'ProcessCredentialsProviderFailure'}
          ), null);
        }
      }
    });
  }
782258
function validateNewCredentialProperties (credentialConfig, credentialDetail) {
  // Tmp — horrible hack to remove.
  const credentialDetails = JSON.parse(JSON.stringify(credentialDetail));
  delete credentialDetails.scopes;

  const validationResult = validate(credentialConfig, credentialDetails);
  if (!validationResult.isValid) {
    return Promise.reject(new Error(validationResult.error));
  };

  return Promise.resolve(credentialDetails);
}