Attach a bucket policy to app bucket.
433040
def _put_bucket_policy(self):
        """"""
        if self.s3props['bucket_policy']:
            policy_str = json.dumps(self.s3props['bucket_policy'])
            _response = self.s3client.put_bucket_policy(Bucket=self.bucket, Policy=policy_str)
        else:
            _response = self.s3client.delete_bucket_policy(Bucket=self.bucket)
        LOG.debug('Response adding bucket policy: %s', _response)
        LOG.info('S3 Bucket Policy Attached')
144474
def touch():
    """"""
    from .models import Bucket
    bucket = Bucket.create()
    db.session.commit()
    click.secho(str(bucket), fg='green')
340503
def _attach_inline_policy(self, username, policy_document):
        """"""
        response = self.client.put_user_policy(
            UserName=username,
            PolicyName="threatresponse-temporal-key-revocation",
            PolicyDocument=policy_document
        )
        logger.info(
            'An inline policy has been attached for'
            ' {u} revoking sts tokens.'.format(u=username)
        )
        return response
367056
function configurePolicyForBucket(aws, bucketName, customPolicy) {
  const policy = customPolicy || {
    Version: '2012-10-17',
    Statement: [
      {
        Effect: 'Allow',
        Principal: {
          AWS: '*'
        },
        Action: 's3:GetObject',
        Resource: `arn:aws:s3:::${bucketName}/*`
      }
    ]
  };

  const params = {
    Bucket: bucketName,
    Policy: JSON.stringify(policy)
  };

  return aws.request('S3', 'putBucketPolicy', params);
}
1362908
def add_bucket(self, bucket, bucket_type=None):
        
        if not riak.disable_list_exceptions:
            raise riak.ListError()
        self._input_mode = 'bucket'
        if isinstance(bucket, riak.RiakBucket):
            if bucket.bucket_type.is_default():
                self._inputs = {'bucket': bucket.name}
            else:
                self._inputs = {'bucket': [bucket.bucket_type.name,
                                           bucket.name]}
        elif bucket_type is not None and bucket_type != "default":
            self._inputs = {'bucket': [bucket_type, bucket]}
        else:
            self._inputs = {'bucket': bucket}
        return self
839070
def set_acl(self, acl_or_str, key_name='', validate=True, headers=None,
                version_id=None):
        """"""
        if not self.bucket_name:
            raise InvalidUriError('set_acl on bucket-less URI (%s)' %
                                  self.uri)
        self.get_bucket(validate, headers).set_acl(acl_or_str, key_name,
                                                   headers, version_id)
689843
def bucket_dict_to_policy(args, bucket_name, d):
    

    import json

    iam = get_resource(args, 'iam')

    statements = make_bucket_policy_statements(bucket_name)

    user_stats = set()  # statement tripples

    for (user, prefix), mode in d.items():

        user_stats.add((user, 'list'))
        user_stats.add((user, 'bucket'))

        if mode == 'R':
            user_stats.add((user, 'Read' + prefix.title()))
            user_stats.add((user, 'List' + prefix.title()))
        elif mode == 'W':
            user_stats.add((user, 'List' + prefix.title()))
            user_stats.add((user, 'Read' + prefix.title()))
            user_stats.add((user, 'Write' + prefix.title()))

    users_arns = {}

    for user_name, section in user_stats:
        section = statements[section]

        if user_name not in users_arns:
            user = iam.User(user_name)
            users_arns[user.name] = user
        else:
            user = users_arns[user_name]

        section['Principal']['AWS'].append(user.arn)

    for sid in list(statements.keys()):
        if not statements[sid]['Principal']['AWS']:
            del statements[sid]

    return json.dumps(dict(Version="2012-10-17", Statement=list(statements.values())), indent=4)
834304
def cloudtrail_policy(original, bucket_name, account_id, bucket_region):
    ''''''
    ct_actions = [
        {
            'Action': 's3:GetBucketAcl',
            'Effect': 'Allow',
            'Principal': {'Service': 'cloudtrail.amazonaws.com'},
            'Resource': generate_arn(
                service='s3', resource=bucket_name, region=bucket_region),
            'Sid': 'AWSCloudTrailAclCheck20150319',
        },
        {
            'Action': 's3:PutObject',
            'Condition': {
                'StringEquals':
                {'s3:x-amz-acl': 'bucket-owner-full-control'},
            },
            'Effect': 'Allow',
            'Principal': {'Service': 'cloudtrail.amazonaws.com'},
            'Resource': generate_arn(
                service='s3', resource=bucket_name, region=bucket_region),
            'Sid': 'AWSCloudTrailWrite20150319',
        },
    ]
    # parse original policy
    if original is None:
        policy = {
            'Statement': [],
            'Version': '2012-10-17',
        }
    else:
        policy = json.loads(original['Policy'])
    original_actions = [a.get('Action') for a in policy['Statement']]
    for cta in ct_actions:
        if cta['Action'] not in original_actions:
            policy['Statement'].append(cta)
    return json.dumps(policy)
1036564
def bucket_policy_to_dict(policy):
    """"""
    import json

    if not isinstance(policy, dict):
        policy = json.loads(policy)

    statements = {s['Sid']: s for s in policy['Statement']}

    d = {}

    for rw in ('Read', 'Write'):
        for prefix in TOP_LEVEL_DIRS:
            sid = rw.title() + prefix.title()

            if sid in statements:

                if isinstance(statements[sid]['Principal']['AWS'], list):

                    for principal in statements[sid]['Principal']['AWS']:
                        user_name = principal.split('/').pop()
                        d[(user_name, prefix)] = rw[0]
                else:
                    user_name = statements[sid]['Principal']['AWS'].split('/').pop()
                    d[(user_name, prefix)] = rw[0]

    return d
219902
def attach_schema(self, schem):
    """"""
    self.tuple_schema = schema.AndSchema.make(self.tuple_schema, schem)
1275138
public Policy addBucketIamMember(String bucketName, Role role, Identity identity) {
    // [START add_bucket_iam_member]
    // Initialize a Cloud Storage client
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // Get IAM Policy for a bucket
    Policy policy = storage.getIamPolicy(bucketName);

    // Add identity to Bucket-level IAM role
    Policy updatedPolicy =
        storage.setIamPolicy(bucketName, policy.toBuilder().addIdentity(role, identity).build());

    if (updatedPolicy.getBindings().get(role).contains(identity)) {
      System.out.printf("Added %s with role %s to %s\n", identity, role, bucketName);
    }
    // [END add_bucket_iam_member]
    return updatedPolicy;
  }
381576
def init_app(self, app):
        """"""
        app.add_url_rule(self.request_token_url, view_func=self.request_token,
                         methods=[u'POST'])
        app.add_url_rule(self.access_token_url, view_func=self.access_token,
                         methods=[u'POST'])
        app.add_url_rule(self.register_url, view_func=self.register,
                         methods=[u'GET', u'POST'])
        app.add_url_rule(self.authorize_url, view_func=self.authorize,
                         methods=[u'GET', u'POST'])
923172
def set_bucket_policy(self, bucket_name, policy):
        
        is_valid_policy_type(policy)

        is_valid_bucket_name(bucket_name)

        headers = {
            'Content-Length': str(len(policy)),
            'Content-Md5': get_md5_base64digest(policy)
        }
        content_sha256_hex = get_sha256_hexdigest(policy)
        self._url_open("PUT",
                        bucket_name=bucket_name,
                        query={"policy": ""},
                        headers=headers,
                        body=policy,
                        content_sha256=content_sha256_hex)
144436
def add_listener_policy(self, json_data):
        
        env = boto3.session.Session(profile_name=self.env, region_name=self.region)
        elbclient = env.client('elb')

        # create stickiness policy if set in configs
        stickiness = {}
        elb_settings = self.properties['elb']
        if elb_settings.get('ports'):
            ports = elb_settings['ports']
            for listener in ports:
                if listener.get("stickiness"):
                    stickiness = self.add_stickiness()
                    LOG.info('Stickiness Found: %s', stickiness)
                    break

        # Attach policies to created ELB
        for job in json.loads(json_data)['job']:
            for listener in job['listeners']:
                policies = []
                ext_port = listener['externalPort']
                if listener['listenerPolicies']:
                    policies.extend(listener['listenerPolicies'])
                if stickiness.get(ext_port):
                    policies.append(stickiness.get(ext_port))
                if policies:
                    LOG.info('Adding listener policies: %s', policies)
                    elbclient.set_load_balancer_policies_of_listener(
                        LoadBalancerName=self.app, LoadBalancerPort=ext_port, PolicyNames=policies)
70427
def zip_and_upload(app_dir, bucket, key, session=None):
    """"""
    if session:
        s3_client = session.client('s3')
    else:
        s3_client = boto3.client('s3')
    transfer = S3Transfer(s3_client)

    filedes, temp_file = tempfile.mkstemp()
    os.close(filedes)
    LOGGER.info("staticsite: archiving app at %s to s3://%s/%s",
                app_dir, bucket, key)
    with zipfile.ZipFile(temp_file, 'w', zipfile.ZIP_DEFLATED) as filehandle:
        with change_dir(app_dir):
            for dirname, _subdirs, files in os.walk('./'):
                if dirname != './':
                    filehandle.write(dirname)
                for filename in files:
                    filehandle.write(os.path.join(dirname, filename))
    transfer.upload_file(temp_file, bucket, key)
    os.remove(temp_file)
1131942
def mount(self, url, app):
        ""
        # Inspired by Bottle. It might seem that dispatching to
        # subapps would rather be handled by normal routes, but
        # arguably, that's less efficient. Taking into account
        # that paradigmatically there's difference between handing
        # an action and delegating responisibilities to another
        # app, Bottle's way was followed.
        app.url = url
        self.mounts.append(app)
356801
def _add_iam_policy_binding(service_account, roles):
    """"""
    project_id = service_account["projectId"]
    email = service_account["email"]
    member_id = "serviceAccount:" + email

    policy = crm.projects().getIamPolicy(resource=project_id).execute()

    already_configured = True

    for role in roles:
        role_exists = False
        for binding in policy["bindings"]:
            if binding["role"] == role:
                if member_id not in binding["members"]:
                    binding["members"].append(member_id)
                    already_configured = False
                role_exists = True

        if not role_exists:
            already_configured = False
            policy["bindings"].append({
                "members": [member_id],
                "role": role,
            })

    if already_configured:
        # In some managed environments, an admin needs to grant the
        # roles, so only call setIamPolicy if needed.
        return

    result = crm.projects().setIamPolicy(
        resource=project_id, body={
            "policy": policy,
        }).execute()

    return result