GithubHelp home page GithubHelp logo

udondan / iam-floyd Goto Github PK

View Code? Open in Web Editor NEW
544.0 4.0 20.0 19.52 MB

AWS IAM policy statement generator with fluent interface

Home Page: https://iam-floyd.readthedocs.io/

License: Apache License 2.0

Makefile 0.05% JavaScript 0.06% TypeScript 99.83% Shell 0.07%
aws iam iam-policy generator cdk aws-cdk jsii hacktoberfest

iam-floyd's Introduction

IAM Floyd

Source iam-floyd Mastodon libraries.io Documentation GitHub

AWS IAM policy statement generator with fluent interface.

Support for:

  • 401 Services
  • 17042 Actions
  • 1823 Resource Types
  • 1782 Condition keys

EXPERIMENTAL
This is an early version of the package. The API will change while I implement new features. Therefore make sure you use an exact version in your package.json before it reaches 1.0.0.

Documentation

Find the documentation at Read the Docs.

Auto completion demo

Packages

There are two different package variants available:

  • iam-floyd: Can be used in AWS SDK or for whatever you need an IAM policy statement for
    npm

  • cdk-iam-floyd: Integrates into AWS CDK and extends iam.PolicyStatement
    npm

    Starting with version 0.300.0, the packages are compatible with CDK v2. For CDK v1 you can use any version up to:
    npm CDK v1

    Find them all on libraries.io.

CDK Compatibility Matrix

CDK cdk-iam-floyd
<= 1.151.0 <= 0.285.0
>= 1.152.0 0.286.0
>= 1.158.0 No compatible version!
>= 2.0.0 >= 0.300.0
>= 2.20.0 >= 0.351.0
>= 2.26.0 >= 0.377.0
2.29.x No compatible version!
>= 2.30.0 >= 0.391.0

Legal

The code contained in the lib/generated folder is generated from the AWS documentation. The class- and function-names and their description therefore are property of AWS.

AWS and their services are trademarks, registered trademarks or trade dress of AWS in the U.S. and/or other countries.

This project is not affiliated, funded, or in any way associated with AWS.

IAM Floyd is licensed under Apache License 2.0. Dependencies might be released under different licenses.

iam-floyd's People

Contributors

actions-user avatar dependabot[bot] avatar kylelaker avatar mbonig avatar renovate[bot] avatar udondan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

iam-floyd's Issues

Service conditions override global conditions

This actually was by design but today I learned this is actually an issue. Here's an example:

There is a global condition key aws:ResourceTag. This is translated to the method ifResourceTag().

EC2 now has its own ec2:ResourceTag which also is translated to the same method ifResourceTag(). And this was alright, because if you want to allow access to EC2 instances, aws:ResourceTag and ec2:ResourceTag refer to the same thing.

If though you work across different services this gets problematic. The SSM service also has a condition key ssm:resourceTag. Again it overrides the method ifResourceTag(). In this case though it refers to tags on ssm resources.

This leaves you with no way to define a policy that, for instance, allows/denies access to StartSession on specifc EC2 instances.

We need to rename methods. Either the globals need to include "Global" or "AWS" or the service related conditions need to include the Service name. Or just both.

  • ifResourceTag()
  • ifEc2ResourceTag()
  • ifGlobalResourceTag()
  • ifAwsResourceTag()

Specific addServicePrincipal methods for services

Is there any plan to support this? For example:

const policy = new statement.Sns()
            .allow()
            .toPublish()
            .onTopic(myTopic);

// policy.addServicePrincipal('ses.amazonaws.com');
policy.addSesServicePrincipal();

Any help you need with this?
BTW: what's the reason addServicePrincipal returns void and not this?

How to add AWS:SourceOwner condition

Is there a way to add below without dealing with all the strings?

policy.addConditions({ 'StringEquals': { 'AWS:SourceOwner': props.env.account } });

I saw there's an issue about conditions, not sure if it's related. Let me know how I can help if needed.

autocomplete broken for python (pyright bug?)

I'm using the package

  • iam-floyd
  • cdk-iam-floyd

I'm using the package in language

  • TypeScript/JavaScript (npm)
  • Python (pip)

Describe the problem
When using the python package, I'm unable to get a full list of autocomplete functions for any service statement. Both of my setups depend on pyright, a language server that provides autocomplete recommendations as well as doing other functions.

Machine Details
Currently on macOS Monterey (v12.1) using Python3.10

Emacs

My primary editor is Emacs and and I use a combination of lsp and pyright to obtain autocomplete. The following is a full list of autocomplete recommendations given to me within my emacs configuration. It's quite the list but at the second location, it doesn't have relevant ones like "on_bucket", "on_objects", etc..

Specifically for this situation:

statement.S3.on_bucket(bucket_name='some_bucket') 
#           ^loc1                               ^loc2                             
all autocomplete options reported by emacs + pyright at `loc1`
all_actions  (Method)
all_list_actions  (Method)
all_matching_actions  (Method)
all_permission_management_actions  (Method)
all_read_actions  (Method)
all_tagging_actions  (Method)
all_write_actions  (Method)
allow  (Method)
compact  (Method)
deny  (Method)
effect  (Property)
for_  (Method)
for_account  (Method)
for_assumed_role_session  (Method)
for_canonical_user  (Method)
for_federated  (Method)
for_federated_amazon  (Method)
for_federated_cognito  (Method)
for_federated_facebook  (Method)
for_federated_google  (Method)
for_public  (Method)
for_role  (Method)
for_saml  (Method)
for_service  (Method)
for_user  (Method)
has_actions  (Method)
has_conditions  (Method)
has_principals  (Method)
has_resources  (Method)
if_  (Method)
if_access_point_network_origin  (Method)
if_auth_type  (Method)
if_aws_called_via  (Method)
if_aws_called_via_first  (Method)
if_aws_called_via_last  (Method)
if_aws_current_time  (Method)
if_aws_epoch_time  (Method)
if_aws_multi_factor_auth_age  (Method)
if_aws_multi_factor_auth_present  (Method)
if_aws_principal_account  (Method)
if_aws_principal_arn  (Method)
if_aws_principal_is_aws_service  (Method)
if_aws_principal_org_id  (Method)
if_aws_principal_org_paths  (Method)
if_aws_principal_service_name  (Method)
if_aws_principal_service_names_list  (Method)
if_aws_principal_tag  (Method)
if_aws_principal_type  (Method)
if_aws_referer  (Method)
if_aws_request_tag  (Method)
if_aws_requested_region  (Method)
if_aws_resource_tag  (Method)
if_aws_secure_transport  (Method)
if_aws_source_account  (Method)
if_aws_source_arn  (Method)
if_aws_source_identity  (Method)
if_aws_source_ip  (Method)
if_aws_source_vpc  (Method)
if_aws_source_vpce  (Method)
if_aws_tag_keys  (Method)
if_aws_token_issue_time  (Method)
if_aws_user_agent  (Method)
if_aws_userid  (Method)
if_aws_username  (Method)
if_aws_via_aws_service  (Method)
if_aws_vpc_source_ip  (Method)
if_data_access_point_account  (Method)
if_data_access_point_arn  (Method)
if_delimiter  (Method)
if_existing_job_operation  (Method)
if_existing_job_priority  (Method)
if_existing_object_tag  (Method)
if_job_suspended_cause  (Method)
if_location_constraint  (Method)
if_locationconstraint  (Method)
if_max_keys  (Method)
if_object_lock_legal_hold  (Method)
if_object_lock_mode  (Method)
if_object_lock_remaining_retention_days  (Method)
if_object_lock_retain_until_date  (Method)
if_prefix  (Method)
if_request_job_operation  (Method)
if_request_job_priority  (Method)
if_request_object_tag  (Method)
if_request_object_tag_keys  (Method)
if_resource_account  (Method)
if_signature_age  (Method)
if_signatureversion  (Method)
if_tls_version  (Method)
if_version_id  (Method)
if_versionid  (Method)
if_x_amz_acl  (Method)
if_x_amz_content_sha256  (Method)
if_x_amz_copy_source  (Method)
if_x_amz_grant_full_control  (Method)
if_x_amz_grant_read  (Method)
if_x_amz_grant_read_acp  (Method)
if_x_amz_grant_write  (Method)
if_x_amz_grant_write_acp  (Method)
if_x_amz_metadata_directive  (Method)
if_x_amz_object_ownership  (Method)
if_x_amz_server_side_encryption  (Method)
if_x_amz_server_side_encryption_aws_kms_key_id  (Method)
if_x_amz_storage_class  (Method)
if_x_amz_website_redirect_location  (Method)
not_actions  (Method)
not_principals  (Method)
not_resources  (Method)
on  (Method)
on_accesspoint  (Method)
on_all_resources  (Method)
on_bucket  (Method)
on_job  (Method)
on_multiregionaccesspoint  (Method)
on_multiregionaccesspointrequestarn  (Method)
on_object  (Method)
on_objectlambdaaccesspoint  (Method)
on_storagelensconfiguration  (Method)
service_prefix  (Property)
sid  (Property)
to  (Method)
to_abort_multipart_upload  (Method)
to_bypass_governance_retention  (Method)
to_create_access_point  (Method)
to_create_access_point_for_object_lambda  (Method)
to_create_bucket  (Method)
to_create_job  (Method)
to_create_multi_region_access_point  (Method)
to_delete_access_point  (Method)
to_delete_access_point_for_object_lambda  (Method)
to_delete_access_point_policy  (Method)
to_delete_access_point_policy_for_object_lambda  (Method)
to_delete_bucket  (Method)
to_delete_bucket_policy  (Method)
to_delete_bucket_website  (Method)
to_delete_job_tagging  (Method)
to_delete_multi_region_access_point  (Method)
to_delete_object  (Method)
to_delete_object_tagging  (Method)
to_delete_object_version  (Method)
to_delete_object_version_tagging  (Method)
to_delete_storage_lens_configuration  (Method)
to_delete_storage_lens_configuration_tagging  (Method)
to_describe_job  (Method)
to_describe_multi_region_access_point_operation  (Method)
to_get_accelerate_configuration  (Method)
to_get_access_point  (Method)
to_get_access_point_configuration_for_object_lambda  (Method)
to_get_access_point_for_object_lambda  (Method)
to_get_access_point_policy  (Method)
to_get_access_point_policy_for_object_lambda  (Method)
to_get_access_point_policy_status  (Method)
to_get_access_point_policy_status_for_object_lambda  (Method)
to_get_account_public_access_block  (Method)
to_get_analytics_configuration  (Method)
to_get_bucket_acl  (Method)
to_get_bucket_cors  (Method)
to_get_bucket_location  (Method)
to_get_bucket_logging  (Method)
to_get_bucket_notification  (Method)
to_get_bucket_object_lock_configuration  (Method)
to_get_bucket_ownership_controls  (Method)
to_get_bucket_policy  (Method)
to_get_bucket_policy_status  (Method)
to_get_bucket_public_access_block  (Method)
to_get_bucket_request_payment  (Method)
to_get_bucket_tagging  (Method)
to_get_bucket_versioning  (Method)
to_get_bucket_website  (Method)
to_get_encryption_configuration  (Method)
to_get_intelligent_tiering_configuration  (Method)
to_get_inventory_configuration  (Method)
to_get_job_tagging  (Method)
to_get_lifecycle_configuration  (Method)
to_get_metrics_configuration  (Method)
to_get_multi_region_access_point  (Method)
to_get_multi_region_access_point_policy  (Method)
to_get_multi_region_access_point_policy_status  (Method)
to_get_object  (Method)
to_get_object_acl  (Method)
to_get_object_legal_hold  (Method)
to_get_object_retention  (Method)
to_get_object_tagging  (Method)
to_get_object_torrent  (Method)
to_get_object_version  (Method)
to_get_object_version_acl  (Method)
to_get_object_version_for_replication  (Method)
to_get_object_version_tagging  (Method)
to_get_object_version_torrent  (Method)
to_get_replication_configuration  (Method)
to_get_storage_lens_configuration  (Method)
to_get_storage_lens_configuration_tagging  (Method)
to_get_storage_lens_dashboard  (Method)
to_json  (Method)
to_list_access_points  (Method)
to_list_access_points_for_object_lambda  (Method)
to_list_all_my_buckets  (Method)
to_list_bucket  (Method)
to_list_bucket_multipart_uploads  (Method)
to_list_bucket_versions  (Method)
to_list_jobs  (Method)
to_list_multi_region_access_points  (Method)
to_list_multipart_upload_parts  (Method)
to_list_storage_lens_configurations  (Method)
to_object_owner_override_to_bucket_owner  (Method)
to_put_accelerate_configuration  (Method)
to_put_access_point_configuration_for_object_lambda  (Method)
to_put_access_point_policy  (Method)
to_put_access_point_policy_for_object_lambda  (Method)
to_put_account_public_access_block  (Method)
to_put_analytics_configuration  (Method)
to_put_bucket_acl  (Method)
to_put_bucket_cors  (Method)
to_put_bucket_logging  (Method)
to_put_bucket_notification  (Method)
to_put_bucket_object_lock_configuration  (Method)
to_put_bucket_ownership_controls  (Method)
to_put_bucket_policy  (Method)
to_put_bucket_public_access_block  (Method)
to_put_bucket_request_payment  (Method)
to_put_bucket_tagging  (Method)
to_put_bucket_versioning  (Method)
to_put_bucket_website  (Method)
to_put_encryption_configuration  (Method)
to_put_intelligent_tiering_configuration  (Method)
to_put_inventory_configuration  (Method)
to_put_job_tagging  (Method)
to_put_lifecycle_configuration  (Method)
to_put_metrics_configuration  (Method)
to_put_multi_region_access_point_policy  (Method)
to_put_object  (Method)
to_put_object_acl  (Method)
to_put_object_legal_hold  (Method)
to_put_object_retention  (Method)
to_put_object_tagging  (Method)
to_put_object_version_acl  (Method)
to_put_object_version_tagging  (Method)
to_put_replication_configuration  (Method)
to_put_storage_lens_configuration  (Method)
to_put_storage_lens_configuration_tagging  (Method)
to_replicate_delete  (Method)
to_replicate_object  (Method)
to_replicate_tags  (Method)
to_restore_object  (Method)
to_statement_json  (Method)
to_update_job_priority  (Method)
to_update_job_status  (Method)
_access_level_list  (Property)
_actions  (Property)
_add_principal  (Method)
_cdk_applied  (Property)
_cdk_apply_principals  (Method)
_conditions  (Property)
_principals  (Property)
_resources  (Property)
_skip_auto_resource  (Property)
_use_not_principals  (Property)
__annotations__  (Variable)
__class__  (Property)
__delattr__  (Method)
__dict__  (Variable)
__dir__  (Method)
__doc__  (Variable)
__eq__  (Method)
__format__  (Method)
__getattribute__  (Method)
__hash__  (Method)
__init__  (Method)
__init_subclass__  (Method)
__module__  (Variable)
__ne__  (Method)
__new__  (Method)
__reduce__  (Method)
__reduce_ex__  (Method)
__repr__  (Method)
__setattr__  (Method)
__sizeof__  (Method)
__slots__  (Variable)
__str__  (Method)
all autocomplete options reported by emacs + pyright at `loc2` (this is a smaller list)
all_actions  (Method)
all_list_actions  (Method)
all_matching_actions  (Method)
all_permission_management_actions  (Method)
all_read_actions  (Method)
all_tagging_actions  (Method)
all_write_actions  (Method)
allow  (Method)
compact  (Method)
deny  (Method)
effect  (Property)
has_actions  (Method)
has_conditions  (Method)
has_principals  (Method)
has_resources  (Method)
if_  (Method)
if_aws_called_via  (Method)
if_aws_called_via_first  (Method)
if_aws_called_via_last  (Method)
if_aws_current_time  (Method)
if_aws_epoch_time  (Method)
if_aws_multi_factor_auth_age  (Method)
if_aws_multi_factor_auth_present  (Method)
if_aws_principal_account  (Method)
if_aws_principal_arn  (Method)
if_aws_principal_is_aws_service  (Method)
if_aws_principal_org_id  (Method)
if_aws_principal_org_paths  (Method)
if_aws_principal_service_name  (Method)
if_aws_principal_service_names_list  (Method)
if_aws_principal_tag  (Method)
if_aws_principal_type  (Method)
if_aws_referer  (Method)
if_aws_request_tag  (Method)
if_aws_requested_region  (Method)
if_aws_resource_tag  (Method)
if_aws_secure_transport  (Method)
if_aws_source_account  (Method)
if_aws_source_arn  (Method)
if_aws_source_identity  (Method)
if_aws_source_ip  (Method)
if_aws_source_vpc  (Method)
if_aws_source_vpce  (Method)
if_aws_tag_keys  (Method)
if_aws_token_issue_time  (Method)
if_aws_user_agent  (Method)
if_aws_userid  (Method)
if_aws_username  (Method)
if_aws_via_aws_service  (Method)
if_aws_vpc_source_ip  (Method)
not_actions  (Method)
not_resources  (Method)
on  (Method)
on_all_resources  (Method)
service_prefix  (Property)
sid  (Property)
to  (Method)
to_json  (Method)
to_statement_json  (Method)
_access_level_list  (Property)
_actions  (Property)
_conditions  (Property)
_resources  (Property)
_skip_auto_resource  (Property)
__annotations__  (Variable)
__class__  (Property)
__delattr__  (Method)
__dict__  (Variable)
__dir__  (Method)
__doc__  (Variable)
__eq__  (Method)
__format__  (Method)
__getattribute__  (Method)
__hash__  (Method)
__init__  (Method)
__init_subclass__  (Method)
__module__  (Variable)
__ne__  (Method)
__new__  (Method)
__reduce__  (Method)
__reduce_ex__  (Method)
__repr__  (Method)
__setattr__  (Method)
__sizeof__  (Method)
__slots__  (Variable)
__str__  (Method)

As you could inductively guess, any further chaining only show the reduced list of autocomplete recommendations as well.
I would like to see the full list.

VSCode

VSCode is performing oddly as well. I have the standard Python extension installed and this allows use of pyright+pylance for Python files. Specifically when I type:

statement.S3.on_bucket(bucket_name='some_bucket') 
#           ^loc1                               ^loc2                             

I'm able to get all relevant autocomplete at loc1 but I get nothing at loc2. Even though the return type is S3, for some reason the language server is unable to pick up any recommendations.

Final notes

I was wondering if you had any insight into this-- is this a local issue or one that's reproducible on other machines?
If it ends being a package issue, do you think the way you're generating functions and translating them into usable Python APIs may be interfering with the autocomplete here?

Overall, I am impressed with the expressibility of this library-- I'd love to have working autocomplete recommendations in my Python setup before adopting it fully. Thanks.

(Python): does not work with CDK >=2.20

I'm using the package

  • iam-floyd
  • cdk-iam-floyd

I'm using the package in language

  • TypeScript/JavaScript (npm)
  • Python (pip)

Describe the problem
After upgrading CDK from 2.19 to 2.20 (or greater), my app doesn't synth anymore, throwing an error on iam-floyd's service initialization lines.

Example code (project is a aws_codebuild.PipelineProject):

project.grant_principal.add_to_principal_policy(
     statement.Codeartifact()
     .to_get_authorization_token()
     .on_domain(
         domain_name=codeartifact.domain_name,
         account=target_env.account,
         region=codeartifact.region,
      )
)

Error:

...
    statement.Codeartifact()
  File "/home/gshpychka/venvs/mm_infra/lib/python3.10/site-packages/jsii/_runtime.py", line 86, in __call__
    inst = super().__call__(*args, **kwargs)
  File "/home/gshpychka/venvs/mm_infra/lib/python3.10/site-packages/cdk_iam_floyd/__init__.py", line 106942, in __init__
    jsii.create(self.__class__, self, [props])
  File "/home/gshpychka/venvs/mm_infra/lib/python3.10/site-packages/jsii/_kernel/__init__.py", line 290, in create
    response = self.provider.create(
  File "/home/gshpychka/venvs/mm_infra/lib/python3.10/site-packages/jsii/_kernel/providers/process.py", line 344, in create
    return self._process.send(request, CreateResponse)
  File "/home/gshpychka/venvs/mm_infra/lib/python3.10/site-packages/jsii/_kernel/providers/process.py", line 326, in send
    raise JSIIError(resp.error) from JavaScriptError(resp.stack)
jsii.errors.JSIIError: Cannot set property principals of [object Object] which has only a getter

Add support for Principal/NotPrincipal

Blocked by #17

Currently we have no handling for principals. The only way is to pass them in the props of the provider:

new statement.Ec2({
  principals: [...],
  notPrincipals: [...],
})
  .allow()
  .allActions()

We should add methods to set Principal/NotPrincipal on a statement.

Typed `to` Arguments

Given the following example:

      new statement
        .Iam()
        .deny()
        .to('DeletePolicy')
        .to('DeletePolicyVersion')
        .to('CreatePolicyVersion')
        .to('SetDefaultPolicyVersion')

It'd be great if the the argument for to would be fully typed, so that the editor / IDE could auto-complete permissions. I think it's fairly striaghtforward for the full permission names, but rather complicated for wildcards (e.g. .to('Delete*') to still be considered valid for Typescript. Perhaps literal types could help with that.

Cannot create a statement with both resources and principals

I'm using the package

  • iam-floyd
  • cdk-iam-floyd

I'm using the package in language

  • TypeScript/JavaScript (npm)
  • Python (pip)

Describe the problem

Creating a statement that contains resources and a principal does not work.

endpoint_policy_statement = (
    statement.Secretsmanager()
    .to_get_secret_value()
    .on_secret(
        account=self.account,
        region=self.region,
        secret_id=credentials.secret_name,
    )
    .for_cdk_principal(
       iam.AnyPrincipal()
    )
)

# this fails
assert endpoint_policy_statement.has_principals()

Trust policies

Is it possible to generate this?

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "rds.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

Just getting started and everything I've generated has a Resource key/value.
If it's not possible, could we consider this a feature request?

Use `Aws.PARTITION` in `cdk-iam-floyd`

When generating policies for the AWS CDK, it may be useful to reference the partition via aws-cdk-lib's Aws.PARTITION rather than hardcoding to aws. This would make cdk-iam-floyd easier to use in other partitions such as aws-us-gov and aws-cn without having to provide the partition via the argument to onX methods. I believe the same applies to forX methods.

For example as-is, to get a partition-agnostic policy, one would have to write:

import * as cdk from "aws-cdk-lib";

new statement
  .Apigateway()
  .toGET()
  .onRestApis(undefined, cdk.Aws.PARTITION);

While the same may be doable for region and account, those currently default to * and so continue to work across partitions; however, since the partition field is a hardcoded string it does break outside of aws.

The unfortunate thing would be that this same behavior can't be easily attained outside the CDK.

`Sqs.to_*_batch()` methods missing from CDK v2 supported packages

I'm using the package

  • iam-floyd
  • cdk-iam-floyd

I'm using the package in language

  • TypeScript/JavaScript (npm)
  • Python (pip)

Describe the problem
Since upgrading to a version supporting CDK v2 (currently using latest - 0.304.0), I no longer have access to methods supporting batch operations in SQS.

import cdk_iam_floyd as statement

...

statement.Sqs()
    .allow()
    .to_send_message()
    .to_send_message_batch()              # no longer exists
    .to_delete_message()
    .to_delete_message_batch()            # no longer exists
    .to_change_message_visibility()
    .to_change_message_visibility_batch() # no longer exists

Policy with effect

This is probably another usage question for you... shouldn't I automatically get "Effect": "Allow" here?

>>> import iam_floyd as statement
>>> import pprint
>>> s = statement.Autoscaling().allow().all_list_actions()
>>> s.effect
<Effect.ALLOW: 'ALLOW'>
>>> pprint.pprint(s.to_json(), width=1)
{'Action': ['autoscaling:DescribeAccountLimits',
            'autoscaling:DescribeAdjustmentTypes',
            'autoscaling:DescribeAutoScalingGroups',
            'autoscaling:DescribeAutoScalingInstances',
            'autoscaling:DescribeAutoScalingNotificationTypes',
            'autoscaling:DescribeInstanceRefreshes',
            'autoscaling:DescribeLaunchConfigurations',
            'autoscaling:DescribeLifecycleHookTypes',
            'autoscaling:DescribeLifecycleHooks',
            'autoscaling:DescribeLoadBalancerTargetGroups',
            'autoscaling:DescribeLoadBalancers',
            'autoscaling:DescribeMetricCollectionTypes',
            'autoscaling:DescribeNotificationConfigurations',
            'autoscaling:DescribePolicies',
            'autoscaling:DescribeScalingActivities',
            'autoscaling:DescribeScalingProcessTypes',
            'autoscaling:DescribeScheduledActions',
            'autoscaling:DescribeTerminationPolicyTypes'],
 'Resource': ['*']}

Delete stacks collection

Hi there! This is an awesome project, thank you very much.

I'm trying to build a policy that allows deleting stacks, but am having trouble. It would be nice to create a collection, like the allowEc2InstanceDeleteByOwner collection.

Does anybody have experience in building such a policy? There are some AWS docs here mentioning the IAM Automation assume role, but I'm a bit lost ๐Ÿค”

Hardcode "aws" as Default Partition?

I'm guessing the majority of users would deploy their infrastructure on AWS partition. So does it make sense to make it the default partition? The challenge is that it's a breaking change.

The benefit is that the generated document becomes much more readable without all Joins and Refs.
And if I want to add it manually, since the partition comes at the end in the list of method arguments, I have to put everything including account and region.

What if we provide something like onAwsFoo methods?

Happy to help if needed.

SES actions don't support ConfigurationSet as a resource

I'm using the package

  • iam-floyd
  • cdk-iam-floyd

I'm using the package in language

  • TypeScript/JavaScript (npm)
  • Python (pip)
  • .Net (NuGet)
  • Java (GitHub packages)

Describe the problem
Oddly enough, SES actions don't support ConfigurationSet as resource. For example, the following is not quite correct (it doesn't actually restrict the access):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "ses:DescribeConfigurationSet",
            "Resource": "arn:aws:ses:eu-central-1:123456789012:configuration-set/some-configset",
            "Effect": "Allow"
        }
    ]
}

Reference: https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonses.html
Also in IAM console it shows a warning:

This policy defines some actions, resources, or conditions that do not provide permissions. To grant access, policies must have an action that has an applicable resource or condition.

Add Dependent Actions to tsdoc

Some actions require other actions to work. For instance ec2:AssociateIamInstanceProfile requires iam:PassRole.

We cannot check if the dependent action is added, bc iam-floyd works on statement level, not on policy level. Also the required action might be allowed though a completely different policy.

The dependency should be mentioned proninently in the tsdoc of the action method.

  /**
   * Grants permission to associate an IAM instance profile with a running or stopped instance
   *
   * **Dependent actions: iam:PassRole**
   *
   * Access Level: Write
   *
   * https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AssociateIamInstanceProfile.html
   */
  public associateIamInstanceProfile() {
    this.add('ec2:AssociateIamInstanceProfile');
    return this;
  }

does not work on CDK >=2.26 with the @aws-cdk/aws-iam:minimizePolicies feature flag enabled

I'm using the package

  • iam-floyd
  • cdk-iam-floyd

I'm using the package in language

  • TypeScript/JavaScript (npm)
  • Python (pip)

Describe the problem
After enabling the @aws-cdk/aws-iam:minimizePolicies feature flag my app doesn't synth anymore, throwing an error on synth.

When adding enough statements that policy minimization kicks in, I get the following error:

[...path.../Role/DefaultPolicy] A PolicyStatement must specify at least one 'action' or 'notAction'.
[...path.../Role/DefaultPolicy] A PolicyStatement used in an identity-based policy must specify at least one resource.

cdk-iam-floyd version: 0.382

I am not sure if this is a bug in the feature itself or in cdk-iam-floyd.

PolicyStatements not compatible with CDK

I'm using the package

  • iam-floyd
  • cdk-iam-floyd

I'm using the package in language

  • TypeScript/JavaScript (npm)
  • Python (pip)

Describe the problem
A clear and concise description of what the bug is.

The statements generated by this library v03.11.0 aren't compatible with CDK v2 PolicyStatement - perhaps because you are generating your own PolicyStatement base classes rather than using the ones from the CDK library? Strict type checking is failing.

I had to write this helper function to convert:

import * as iam from "aws-cdk-lib/aws-iam";
import * as iamFloyd from "cdk-iam-floyd";

/**
 * Convert iam-floyd statements to standard CDK PolicyStatements
 */
export function toPermissions(...statements: iamFloyd.PolicyStatement[]): iam.PolicyStatement[] {
  return statements.map((floydStatement) => iam.PolicyStatement.fromJson(floydStatement.toJSON()));
}

Remove CDK as dependency

The package works great if you want to use it within CDK constructs. If you want use it outside of CDK or even in Terraform CDK AND want a principal in the statement, it won't work, because principals (even when created from static text) are stored as Tokens. Tokens are resolved when the CFN template is sythesized, which of course will not happen in cdktf or outside of any CDK scenario.

There is another problem in the foreseeable future: When monocdk hits the ground, even though we only use the iam package, the cdk dependency suddenly weighs additional ~20MiB, giving this package a size of ~45MiB.

Currently we use the iam.PolicyStatement as the base. The required functionality needs to be replicated within floyds policy statement. At a first glance, this appears to be:

  • addActions / addNotActions
  • addPrincipals / addNotPrincipals
  • addResources / addNotResources
  • addCondition

Of course, all the principle classes of the IAM package then no longer can be used and we need something similar.

The statement then unfortunately no longer can be directly added to a policy. Instead it must be loaded via fromJson()

iam.PolicyStatement.fromJson(
  new statement.Ec2()
    .allow()
    .allActions()
);

Blocks #11

Why Instantiate Condition Operator?

Let's say I need to have a StringEquals condition. Why do I need to instantiate an instance of Operator like this: new statements.Operator().stringEquals()? Or is there a better way to do it?

Compile action list down to the smallest possible pattern

While it is great to automatically list all actions when working with access levels, it would be great to have an option to compile the list down to a pattern.

This should be implemented as an optional method call. It's a nice feature to reduce the policy size, but might have security related implications if new actions are added in the future.

Example:

new statement.S3()
  .allow()
  .allActions(statement.AccessLevel.READ)
  .condense();

Should result in actions ['s3:List*', 's3:Describe*', 's3:Get*']

(Python): does not work with CDK >=2.26

I'm using the package

  • iam-floyd
  • cdk-iam-floyd

I'm using the package in language

  • TypeScript/JavaScript (npm)
  • Python (pip)

Describe the problem
After upgrading CDK from 2.25 to 2.26, my app doesn't synth anymore, throwing an error on iam-floyd's service initialization lines.

Example code (project is a aws_codebuild.PipelineProject):

project.grant_principal.add_to_principal_policy(
     statement.Codeartifact()
     .to_get_authorization_token()
     .on_domain(
         domain_name=codeartifact.domain_name,
         account=target_env.account,
         region=codeartifact.region,
      )
)

Error:

...
statement.Codeartifact()
  File "/home/gshpychka/venvs/mm_infra/lib/python3.10/site-packages/jsii/_runtime.py", line 86, in __call__
    inst = super().__call__(*args, **kwargs)
  File "/home/gshpychka/venvs/mm_infra/lib/python3.10/site-packages/cdk_iam_floyd/__init__.py", line 106942, in __init__
    jsii.create(self.__class__, self, [props])
  File "/home/gshpychka/venvs/mm_infra/lib/python3.10/site-packages/jsii/_kernel/__init__.py", line 290, in create
    response = self.provider.create(
  File "/home/gshpychka/venvs/mm_infra/lib/python3.10/site-packages/jsii/_kernel/providers/process.py", line 344, in create
    return self._process.send(request, CreateResponse)
  File "/home/gshpychka/venvs/mm_infra/lib/python3.10/site-packages/jsii/_kernel/providers/process.py", line 326, in send
    raise JSIIError(resp.error) from JavaScriptError(resp.stack)
jsii.errors.JSIIError: Cannot set property principals of [object Object] which has only a getter

cdk-iam-floyd version: 0.376.0

Simliar thing has happened before in #145

How to create an array of statements?

I'm not entirely sure if this is a bug or a silly mistake I'm making. I've got a stack in which I create an IAM role with some policy. I wrote some unit tests and everything works just fine. However when I try to synth the stack, it fails with

> cdk --app bin/sandbox.js "synth"

/Users/rad/work/cdk-app/node_modules/aws-cdk-lib/core/lib/private/synthesis.js:2
  `);throw new Error(`Validation failed with the following errors:
     ^

Error: Validation failed with the following errors:
  [AppsServiceAccountRolesStack/AppServiceAccountPolicy] A PolicyStatement must specify at least one 'action' or 'notAction'.
  [AppsServiceAccountRolesStack/AppServiceAccountPolicy] A PolicyStatement used in an identity-based policy must specify at least one resource.
    at validateTree (/Users/rad/work/cdk-app/node_modules/aws-cdk-lib/core/lib/private/synthesis.js:2:12)
    at Object.synthesize (/Users/rad/work/cdk-app/node_modules/aws-cdk-lib/core/lib/private/synthesis.js:1:598)
    at App.synth (/Users/rad/work/cdk-app/node_modules/aws-cdk-lib/core/lib/stage.js:1:2126)
    at Object.<anonymous> (/Users/rad/work/cdk-app/bin/sandbox.js:48:5)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Subprocess exited with error 1

Here's the code snippet (Let me know if I need to provide a sample to reproduce the issue.)

const newStatements = (
  sysName: string,
  appName: string,
  env: GenericStackEnv,
): Array<iam.PolicyStatement> => {
  const sns1 = new statements.Sns() //
    .allow()
    .toListTopics()
    .on("*");

  const sns2 = new statements.Sns() //
    .allow()
    .toPublish()
    .toGetTopicAttributes()
    .onTopic(`${appName}-*`, env.account, env.region, "aws");

  return [sns1, sns2];
};

Interestingly when I create a single statement object and return a singleton list, everything works just fine.
Also if I call toJSON() method on any of the statement or on the policy to which the statements are added, everything works just fine too.
The other thing I found out is that if I call addCondition on any of the statement, again, everything works just fine.
What am I missing? ๐Ÿ˜•
Thanks.

Python: specifying an effect is broken.

I'm using the package

  • iam-floyd
  • cdk-iam-floyd

I'm using the package in language

  • TypeScript/JavaScript (npm)
  • Python (pip)

Describe the problem

Works:
statement.Cloudwatch().to_describe_alarms()

Does not work:
statement.Cloudwatch().allow().to_describe_alarms()

Typing error: Cannot access member "to_describe_alarms" for type "PolicyStatementWithEffect". Member "to_describe_alarms" is not known.

Only thing that works with allow() is the to() method. No service-specific methods work.

I'm using the latest version of cdk-iam-floyd.

How to set the default Partition

Hello,

I'm beginning working in GovCloud (Python Pulumi IaC). I ran into an error using on_bucket because it was setting the partition to aws and not aws-us-gov. I searched in your codebase and saw that there's a parameter called "default partition", but looking through the documentation I couldn't really understand how to use it https://iam-floyd.readthedocs.io/en/latest/search.html?q=partition&check_keywords=yes&area=default

Ideally it'd be great if I could just set it once and then it would apply for all other things. Something like this in the entrypoint of the python code:


import iam_floyd as statement
statement.DEFAULT_PARTITION = 'aws-us-gov'

I'm not sure if something like that is already possible, as I couldn't quite figure out from the compiled JSII Python code exactly what was going on.

(or maybe it'd be `PolicyStatementBase.DEFAULT_PARTITION = 'aws-us-gov' ...? still trying to look through the giant single JSII compiled python file)

Thank you!

(I was able to figure out that it looks like partition is a kwarg basically everywhere, so in the meantime I can use that)

add forAccounts that accepts iterable

I've been excited when trying out this package so far, and others within my organization as well. However, we noticed one pain point at the moment. We are using a multi-account strategy (separate pipeline, dev, testing, staging, prod), and we have several cases where we need to grant IAM permissions to a list of accounts.

Would it be possible to create a forAccounts function (or an overload of the existing forAccount function) that accepts an iterable of strings?

I think this is where it would be added, but I'm still trying to understand the library organization.

public forAccount(account: string) {

Change signature of the if method

Instead of

.if('StringEquals', {
   'aws:RequestTag/Foo': 'bar',
})

it should read:

.if('aws:RequestTag/Foo', 'bar')
.if('aws:RequestTag/Foo', 'bar*', 'StringLike')

The operator should be optional with a default of StringEquals

`.ifAwsMultiFactorAuthPresent(false)` generates condition with a boolean value

I'm using the package

  • iam-floyd:
  • cdk-iam-floyd (v0.106.0)

I'm using the package in language

  • TypeScript/JavaScript (npm)
  • Python (pip)
  • .Net (NuGet)
  • Java (GitHub packages)

Describe the problem
The ifAwsMultiFactorAuthPresent(false) call generates the condition "aws:MultiFactorAuthPresent": false instead of "aws:MultiFactorAuthPresent": "false". Interestingly when I deploy the policy, on AWS IAM it's "false", (as well as the generated JSON file in cdk.out directory), however synth command generates the entry with a value of type boolean.

S3 all_list_actions should include ListObjectsV2

I'm using the package

  • iam-floyd
  • cdk-iam-floyd

I'm using the package in language

  • TypeScript/JavaScript (npm)
  • Python (pip)
  • .Net (NuGet)
  • Java (GitHub packages)

Describe the problem

>>> from iam_floyd import S3
>>> bucket = 'mybucket'
>>> s3_statement = S3().allow().all_read_actions().on(bucket)
>>> s3_statement.allow().all_list_actions().on(bucket)
<iam_floyd.S3 object at 0x10bde10d0>
>>> s3_statement.to_json()
{'Action': ['s3:DescribeJob', 's3:GetAccelerateConfiguration', 's3:GetAccessPoint', 's3:GetAccessPointPolicy', 's3:GetAccessPointPolicyStatus', 's3:GetAccountPublicAccessBlock', 's3:GetAnalyticsConfiguration', 's3:GetBucketAcl', 's3:GetBucketCORS', 's3:GetBucketLocation', 's3:GetBucketLogging', 's3:GetBucketNotification', 's3:GetBucketObjectLockConfiguration', 's3:GetBucketPolicy', 's3:GetBucketPolicyStatus', 's3:GetBucketPublicAccessBlock', 's3:GetBucketRequestPayment', 's3:GetBucketTagging', 's3:GetBucketVersioning', 's3:GetBucketWebsite', 's3:GetEncryptionConfiguration', 's3:GetInventoryConfiguration', 's3:GetJobTagging', 's3:GetLifecycleConfiguration', 's3:GetMetricsConfiguration', 's3:GetObject', 's3:GetObjectAcl', 's3:GetObjectLegalHold', 's3:GetObjectRetention', 's3:GetObjectTagging', 's3:GetObjectTorrent', 's3:GetObjectVersion', 's3:GetObjectVersionAcl', 's3:GetObjectVersionForReplication', 's3:GetObjectVersionTagging', 's3:GetObjectVersionTorrent', 's3:GetReplicationConfiguration', 's3:ListAccessPoints', 's3:ListBucketMultipartUploads', 's3:ListBucketVersions', 's3:ListJobs', 's3:ListMultipartUploadParts', 's3:ListAllMyBuckets', 's3:ListBucket'], 'Resource': ['mybucket']}

Allow with issue issue #31 - I'm trying to draft a policy as documented here:

https://docs.aws.amazon.com/neptune/latest/userguide/bulk-load-tutorial-IAM.html

I was thinking all_list_actions on s3 would include the ListObjectsV2 API.
Seems pretty reasonable to me.

Please let me know if I'm missing something.

policy size

first of all look like a great idea! and the name is genius.

will you enforce policy size limit ?

Remove jsii and python support

jsii has been such a pain in the ass over the years and I am no longer willing to deal with it. I have no capacity to permantly fix compatiblitity issues.

tenor-111401315

Also, jsii is the single blocker for implementing new features in this library.

Python support will be dropped so we no longer have a need for this jsii.

Type 'S3' is not assignable to type 'PolicyStatement'.

I'm not a TS code, it might be a silly mistake on my side. couldn't figure out what how to get it working after upgrade. So previously I had cdk-iam-floyd v0.38.0 with cdk v1.56.0:

function newS3Policy(): iam.PolicyStatement {
  return new statement.S3();
}

After upgrading to cdk-iam-floyd v0.48.0 with cdk v1.59.0, it's complaining:

Type 'S3' is not assignable to type 'PolicyStatement'.
Types have separate declarations of a private property 'action'.ts(2322)

How can I return generated statement as iam.PolicyStatement of CDK? Thanks.

Add useful standard patterns as methods

There are some standard IAM patterns, that could be provided though a helper class

For example, tag based authorization on EC2 instances:

new floyd.Policy().Ec2TagBasedAuthorization(
  floyd.AccessLevel.LIST,
  floyd.AccessLevel.READ,
);

... generates a policy close to this:

new iam.PolicyDocument({
    statements: [
        new statement.Ec2()
            .allow()
            .startInstances()
            .if('StringEquals', {
                'aws:RequestTag/Owner': '${aws:username}',
            }),
        new statement.Ec2()
            .allow()
            .stopInstances()
            .if('StringEquals', {
                'ec2:ResourceTag/Owner': '${aws:username}',
            }),
        new statement.Ec2()
            .allow()
            .allActions(
                statement.AccessLevel.LIST,
                statement.AccessLevel.READ
            ),
    ],
});

Add useful action collections based on common use cases

Granting actions based on access levels is great. In some cases though it might weaken least privilege.

It would be nice if we had some prepared collections of actions for specific use cases.

As an example: To start an EC2 instance there are many actions required:

  • ec2:StartInstances
  • ec2:AssociateIamInstanceProfile
  • ec2:AttachNetworkInterface
  • ec2:AttachVolume
  • ec2:CreateNetworkInterface
  • ec2:CreateSecurityGroup
  • ec2:CreateTags
  • ec2:CreateVolume
  • ec2:DescribeImages
  • ec2:...

This could be all added via a prepared method, e.g.

new statement.Ec2()
   .canStartInstance()

Add `-??????` suffix to secret name in `onSecret` method

I'm not sure what's the best way to do this, but it seems that when granting access to a secret, one needs to specify the random suffix added by AWS SecretsManager. Does that make sense to add it on the method? LMK if I can help with anything. Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.