Build a role with permissions to lambda, CloudWatch events and API Gateways is needed.
195175
function buildRole(options, roleName='LambdaCfnRole') {
  let role = {
    Resources: {}
  };

  role.Resources[roleName] = {
    Type: 'AWS::IAM::Role',
    Properties: {
      AssumeRolePolicyDocument: {
        Statement: [
          {
            Sid: '',
            Effect: 'Allow',
            Principal: {
              Service: 'lambda.amazonaws.com'
            },
            Action: 'sts:AssumeRole'
          },
          {
            Sid: '',
            Effect: 'Allow',
            Principal: {
              Service: 'events.amazonaws.com'
            },
            Action: 'sts:AssumeRole'
          }
        ]
      },
      Path: '/',
      Policies: [
        {
          PolicyName: 'basic',
          PolicyDocument: {
            Statement: [
              {
                Effect: 'Allow',
                Action: [
                  'logs:*'
                ],
                Resource: cf.join(['arn:aws:logs:*:', cf.accountId, ':*'])
              },
              {
                Effect: 'Allow',
                Action: [
                  'sns:Publish'
                ],
                Resource: cf.ref('ServiceAlarmSNSTopic')
              },
              {
                Effect: 'Allow',
                Action: [
                  'iam:SimulateCustomPolicy'
                ],
                Resource: '*'
              }
            ]
          }
        },
      ]
    }
  };

  if (options.eventSources && options.eventSources.webhook) {
    role.Resources[roleName].Properties.AssumeRolePolicyDocument.Statement.push({
      Sid: '',
      Effect: 'Allow',
      Principal: {
        Service: 'apigateway.amazonaws.com'
      },
      Action: 'sts:AssumeRole'
    });
  }

  if (options.statements) {
    statementValidation(options);

    role.Resources[roleName].Properties.Policies.push({
      PolicyName: options.name,
      PolicyDocument: {
        Statement: options.statements
      }
    });
  }

  return role;
}
197109
private void newPermissions(
            final ApplicationPermissionRule rule,
            final ApplicationPermissionMode mode,
            final ApplicationFeatureType featureType,
            final Iterable<String> featureFqns) {

        if(featureFqns == null) {
            return;
        }

        ApplicationRole securityRole = applicationRoleRepository.findByName(roleName);
        if(securityRole == null) {
            securityRole = applicationRoleRepository.newRole(roleName, roleDescription);
        }
        for (String featureFqn : featureFqns) {
            // can't use role#addPackage because that does a check for existence of the package, which is
            // not guaranteed to exist yet (the SecurityFeatures#init() may not have run).
            applicationPermissionRepository.newPermissionNoCheck(
                    securityRole,
                    rule,
                    mode,
                    featureType, featureFqn);
        }
    }
245143
def role(args):
    
    src_acct, src_username, dst_acct, dst_role = \
        "205134639408 htang 114692162163 mvrad-datasci-role".split()

    p = OptionParser(role.__doc__)
    p.add_option("--profile", default="mvrad-datasci-role", help="Profile name")
    p.add_option('--device',
                    default="arn:aws:iam::" + src_acct + ":mfa/" + src_username,
                    metavar='arn:aws:iam::123456788990:mfa/dudeman',
                    help="The MFA Device ARN. This value can also be "
                    "provided via the environment variable 'MFA_DEVICE' or"
                    " the ~/.aws/credentials variable 'aws_mfa_device'.")
    p.add_option('--duration',
                    type=int, default=3600,
                    help="The duration, in seconds, that the temporary "
                            "credentials should remain valid. Minimum value: "
                            "900 (15 minutes). Maximum: 129600 (36 hours). "
                            "Defaults to 43200 (12 hours), or 3600 (one "
                            "hour) when using '--assume-role'. This value "
                            "can also be provided via the environment "
                            "variable 'MFA_STS_DURATION'. ")
    p.add_option('--assume-role', '--assume',
                    default="arn:aws:iam::" + dst_acct + ":role/" + dst_role,
                    metavar='arn:aws:iam::123456788990:role/RoleName',
                    help="The ARN of the AWS IAM Role you would like to "
                    "assume, if specified. This value can also be provided"
                    " via the environment variable 'MFA_ASSUME_ROLE'")
    p.add_option('--role-session-name',
                    help="Friendly session name required when using "
                    "--assume-role",
                    default=getpass.getuser())
    p.add_option('--force',
                    help="Refresh credentials even if currently valid.",
                    action="store_true")
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    # Use a config to check the expiration of session token
    config = get_config(AWS_CREDS_PATH)
    validate(opts, config)
1112995
protected Collection<? extends GrantedAuthority> buildGrantedAuthorities(PortletRequest context) {
        Collection<String> portletUserRoles = getUserRoles(context);
        Collection<? extends GrantedAuthority> userGas = portletUserRoles2GrantedAuthoritiesMapper.getGrantedAuthorities(portletUserRoles);

        if (logger.isDebugEnabled()) {
            logger.debug("Portlet roles [" + portletUserRoles + "] mapped to Granted Authorities: [" + userGas + "]");
        }
        return userGas;
    }
401401
def authorize_role(self, role, protocol, from_port, to_port, cidr_ip):
    
    if (protocol != 'tcp' and protocol != 'udp'):
      raise RuntimeError('error: expected protocol to be tcp or udp '\
                         'but got %s' % (protocol))
    
    self._check_role_name(role)
    role_group_name = self._group_name_for_role(role)
    # Revoke first to avoid InvalidPermission.Duplicate error
    self.ec2.revoke_security_group(role_group_name,
                                             ip_protocol=protocol,
                                             from_port=from_port,
                                             to_port=to_port, cidr_ip=cidr_ip)
    self.ec2.authorize_security_group(role_group_name,
                                                ip_protocol=protocol,
                                                from_port=from_port,
                                                to_port=to_port,
                                                cidr_ip=cidr_ip)
1278999
function hasRole(rbac, role, cb) {
  if (!this.role) {
    cb(null, false);
    return this;
  }

  // check existance of permission
  rbac.hasRole(this.role, role, cb);
  return this;
}
1295766
def role_create(auth=None, **kwargs):
    '''
    
    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(keep_name=True, **kwargs)
    return cloud.create_role(**kwargs)
1362535
def set_permissions(vhost, user, conf='.*', write='.*', read='.*', runas=None):
    '''
    
    '''
    if runas is None and not salt.utils.platform.is_windows():
        runas = salt.utils.user.get_user()
    res = __salt__['cmd.run_all'](
        [RABBITMQCTL, 'set_permissions', '-p',
         vhost, user, conf, write, read],
        reset_system_locale=False,
        runas=runas,
        python_shell=False)
    msg = 'Permissions Set'
    return _format_response(res, msg)
985210
def role_update(auth=None, **kwargs):
    '''
    
    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(**kwargs)
    if 'new_name' in kwargs:
        kwargs['name'] = kwargs.pop('new_name')
    return cloud.update_role(**kwargs)
590681
def create(self, permission):
        
        parent_url = self.client.get_url(self.parent_object._manager._URL_KEY, 'GET', 'single', {'id': self.parent_object.id})
        target_url = parent_url + self.client.get_url_path(self._URL_KEY, 'POST', 'single')
        r = self.client.request('POST', target_url, json=permission._serialize())
        return permission._deserialize(r.json(), self)
12646
def lambda_handler(event, context):
    print("Client token: " + event['authorizationToken'])
    print("Method ARN: " + event['methodArn'])
    """and produce the principal user identifier associated with the tokenthis could be accomplished in a number of ways:1. Call out to OAuth provider2. Decode a JWT token inline3. Lookup in a self-managed DB"""
    principalId = "user|a1b2c3d4"

    """you can send a 401 Unauthorized response to the client by failing like so:raise Exception('Unauthorized')if the token is valid, a policy must be generated which will allow or deny access to the clientif access is denied, the client will receive a 403 Access Denied responseif access is allowed, API Gateway will proceed with the backend integration configured on the method that was calledthis function must generate a policy that is associated with the recognized principal user identifier.depending on your use case, you might store policies in a DB, or generate them on the flykeep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer)and will apply to subsequent calls to any method/resource in the RestApimade with the same tokenthe example policy below denies access to all resources in the RestApi"""
    tmp = event['methodArn'].split(':')
    apiGatewayArnTmp = tmp[5].split('/')
    awsAccountId = tmp[4]

    policy = AuthPolicy(principalId, awsAccountId)
    policy.restApiId = apiGatewayArnTmp[0]
    policy.region = tmp[3]
    policy.stage = apiGatewayArnTmp[1]

    # Blueprint denies all methods by default
    # policy.denyAllMethods()

    # Example allows all methods
    policy.allowAllMethods()

    """policy.allowMethod(HttpVerb.GET, "/pets/*")finally, build the policy and exit the function using return"""
    return policy.build()
582768
function Lambda(config, fsPath) {
  this.identifier = config.identifier;
  this.config = config;
  this.fsPath = fsPath;

  this.config.params = this.config.params || {};
  this.config.params = _.merge({
    FunctionName: this.identifier,
    Role: 'PLEASE-CONFIGURE-AN-EXECUTION-ROLE-FOR-' + this.identifier,
    Timeout: 15,
    Publish: false
  }, this.config.params);

  let runtimeLanguage;
  _.forEach(runtimes, (versions, language) => {
    if (versions.indexOf(this.config.params.Runtime) !== -1) {
      runtimeLanguage = language;
    }
  });
  if (!runtimeLanguage) { throw new Error(this.config.params.Runtime + ' is not a valid runtime'); }
  this.runtimeMethod = runtimeMethods[runtimeLanguage];

  this.config.modules = this.config.modules || [];
}
1337935
def get_permissions(self, role):
        """"""
        target_role = AuthGroup.objects(role=role, creator=self.client).first()
        if not target_role:
            return '[]'
        targets = AuthPermission.objects(groups=target_role, creator=self.client).only('name')
        return json.loads(targets.to_json())
1009004
def create_cloud_user(cfg, args):
    """"""
    url = cfg['api_server'] + "admin/add-user"
    params = {'user_email': args.user_email, 'user_name': args.user_name,
              'user_role': args.user_role, 'email': cfg['email'],
              'api_key': cfg['api_key']}
    headers = {'Content-Type': 'application/json'}
    response = requests.post(url, data=json.dumps(params),
                             headers=headers)
    if response.status_code not in range(200, 299):
        raise Exception("Errors contacting the cloud node: %s" % (response.content))
    loaded = json.loads(response.content)
    return loaded
858722
@POST
  @Path("/db/{authorizerName}/roles/{roleName}/permissions")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  @ResourceFilters(BasicSecurityResourceFilter.class)
  public Response setRolePermissions(
      @Context HttpServletRequest req,
      @PathParam("authorizerName") final String authorizerName,
      @PathParam("roleName") String roleName,
      List<ResourceAction> permissions
  )
  {
    return resourceHandler.setRolePermissions(authorizerName, roleName, permissions);
  }
128152
def _setup_default_permissions(instance):
    """"""
    from abilian.services import get_service

    security = get_service("security")
    for permission, roles in instance.__default_permissions__:
        if permission == "create":
            # use str for comparison instead of `abilian.services.security.CREATE`
            # symbol to avoid imports that quickly become circular.
            #
            # FIXME: put roles and permissions in a separate, isolated module.
            continue
        for role in roles:
            security.add_permission(permission, role, obj=instance)
1134528
def _role_create(name,
                 user=None,
                 host=None,
                 port=None,
                 maintenance_db=None,
                 password=None,
                 createdb=None,
                 createroles=None,
                 encrypted=None,
                 superuser=None,
                 login=None,
                 connlimit=None,
                 inherit=None,
                 replication=None,
                 rolepassword=None,
                 valid_until=None,
                 typ_='role',
                 groups=None,
                 runas=None):
    '''
    
    '''

    # check if role exists
    if user_exists(name, user, host, port, maintenance_db,
                   password=password, runas=runas):
        log.info('%s \'%s\' already exists', typ_.capitalize(), name)
        return False

    sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name)
    sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args(
        name,
        typ_=typ_,
        encrypted=encrypted,
        login=login,
        connlimit=connlimit,
        inherit=inherit,
        createdb=createdb,
        createroles=createroles,
        superuser=superuser,
        groups=groups,
        replication=replication,
        rolepassword=rolepassword,
        valid_until=valid_until
    ))
    ret = _psql_prepare_and_run(['-c', sub_cmd],
                                runas=runas, host=host, user=user, port=port,
                                maintenance_db=maintenance_db,
                                password=password)

    return ret['retcode'] == 0