agent-claw: automated task changes

This commit is contained in:
daniel
2026-05-06 18:55:16 -05:00
parent 38905bb1e9
commit 732b00fb66
8494 changed files with 2018127 additions and 4 deletions

13
cdk/node_modules/aws-cdk-lib/aws-iam/.jsiirc.json generated vendored Normal file
View File

@@ -0,0 +1,13 @@
{
"targets": {
"java": {
"package": "software.amazon.awscdk.services.iam"
},
"dotnet": {
"namespace": "Amazon.CDK.AWS.IAM"
},
"python": {
"module": "aws_cdk.aws_iam"
}
}
}

966
cdk/node_modules/aws-cdk-lib/aws-iam/README.md generated vendored Normal file
View File

@@ -0,0 +1,966 @@
# AWS Identity and Access Management Construct Library
## Security and Safety Dev Guide
For a detailed guide on CDK security and safety please see the [CDK Security And
Safety Dev Guide](https://github.com/aws/aws-cdk/wiki/Security-And-Safety-Dev-Guide)
The guide will cover topics like:
* What permissions to extend to CDK deployments
* How to control the permissions of CDK deployments via IAM identities and policies
* How to use CDK to configure the IAM identities and policies of deployed applications
* Using Permissions Boundaries with CDK
## Overview
Define a role and add permissions to it. This will automatically create and
attach an IAM policy to the role:
[attaching permissions to role](test/example.role.lit.ts)
Define a policy and attach it to groups, users and roles. Note that it is possible to attach
the policy either by calling `xxx.attachInlinePolicy(policy)` or `policy.attachToXxx(xxx)`.
[attaching policies to user and group](test/example.attaching.lit.ts)
Managed policies can be attached using `xxx.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`:
[attaching managed policies](test/example.managedpolicy.lit.ts)
## Granting permissions to resources
Many of the AWS CDK resources have grant methods (accessible via the `grants` attribute) that allow you to grant other
resources access to that resource. As an example, the following code gives a Lambda function write permissions
(Put, Update, Delete) to a DynamoDB table.
```ts
declare const fn: lambda.Function;
declare const table: dynamodb.Table;
table.grants.writeData(fn);
```
The more generic `actions` method allows you to give specific permissions to a resource:
```ts
declare const fn: lambda.Function;
declare const table: dynamodb.Table;
table.grants.actions(fn, 'dynamodb:PutItem');
```
The grant methods accept an `IGrantable` object. This interface is implemented by IAM principal resources (groups, users and roles), policies, managed policies and resources that assume a role such as a Lambda function, EC2 instance or a Codebuild project.
You can find which grant methods exist for a resource in the [AWS CDK API Reference](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html).
## Roles
Many AWS resources require *Roles* to operate. These Roles define the AWS API
calls an instance or other AWS service is allowed to make.
Creating Roles and populating them with the right permissions *Statements* is
a necessary but tedious part of setting up AWS infrastructure. In order to
help you focus on your business logic, CDK will take care of creating
roles and populating them with least-privilege permissions automatically.
All constructs that require Roles will create one for you if don't specify
one at construction time. Permissions will be added to that role
automatically if you associate the construct with other constructs from the
AWS Construct Library (for example, if you tell an *AWS CodePipeline* to trigger
an *AWS Lambda Function*, the Pipeline's Role will automatically get
`lambda:InvokeFunction` permissions on that particular Lambda Function),
or if you explicitly grant permissions using the public methods in the
`RoleGrants` class (see the previous section).
### Opting out of automatic permissions management
You may prefer to manage a Role's permissions yourself instead of having the
CDK automatically manage them for you. This may happen in one of the
following cases:
* You don't like the permissions that CDK automatically generates and
want to substitute your own set.
* The least-permissions policy that the CDK generates is becoming too
big for IAM to store, and you need to add some wildcards to keep the
policy size down.
To prevent constructs from updating your Role's policy, pass the object
returned by `myRole.withoutPolicyUpdates()` instead of `myRole` itself.
For example, to have an AWS CodePipeline *not* automatically add the required
permissions to trigger the expected targets, do the following:
```ts
const role = new iam.Role(this, 'Role', {
assumedBy: new iam.ServicePrincipal('codepipeline.amazonaws.com'),
// custom description if desired
description: 'This is a custom role...',
});
new codepipeline.Pipeline(this, 'Pipeline', {
// Give the Pipeline an immutable view of the Role
role: role.withoutPolicyUpdates(),
});
// You now have to manage the Role policies yourself
role.addToPolicy(new iam.PolicyStatement({
actions: [/* whatever actions you want */],
resources: [/* whatever resources you intend to touch */],
}));
```
### Using existing roles
If there are Roles in your account that have already been created which you
would like to use in your CDK application, you can use `Role.fromRoleArn` to
import them, as follows:
```ts
const role = iam.Role.fromRoleArn(this, 'Role', 'arn:aws:iam::123456789012:role/MyExistingRole', {
// Set 'mutable' to 'false' to use the role as-is and prevent adding new
// policies to it. The default is 'true', which means the role may be
// modified as part of the deployment.
mutable: false,
});
```
If you want to lookup roles that actually exist in your account, you can use `Role.fromLookup()`.
```ts
const role = iam.Role.fromLookup(this, 'Role', {
roleName: 'MyExistingRole',
});
```
### Customizing role creation
It is best practice to allow CDK to manage IAM roles and permissions. You can prevent CDK from
creating roles by using the `customizeRoles` method for special cases. One such case is using CDK in
an environment where role creation is not allowed or needs to be managed through a process outside
of the CDK application.
An example of how to opt in to this behavior is below:
```ts
declare const stack: Stack;
iam.Role.customizeRoles(stack);
```
CDK will not create any IAM roles or policies with the `stack` scope. `cdk synth` will fail and
it will generate a policy report to the cloud assembly (i.e. cdk.out). The `iam-policy-report.txt`
report will contain a list of IAM roles and associated permissions that would have been created.
This report can be used to create the roles with the appropriate permissions outside of
the CDK application.
Once the missing roles have been created, their names can be added to the `usePrecreatedRoles`
property, like shown below:
```ts
declare const app: App;
const stack = new Stack(app, 'MyStack');
iam.Role.customizeRoles(this, {
usePrecreatedRoles: {
'MyStack/MyRole': 'my-precreated-role-name',
},
});
new iam.Role(this, 'MyRole', {
assumedBy: new iam.ServicePrincipal('sns.amazonaws.com'),
});
```
If any IAM policies reference deploy time values (i.e. ARN of a resource that hasn't been created
yet) you will have to modify the generated report to be more generic. For example, given the
following CDK code:
```ts
declare const app: App;
const stack = new Stack(app, 'MyStack');
iam.Role.customizeRoles(stack);
const fn = new lambda.Function(this, 'MyLambda', {
code: new lambda.InlineCode('foo'),
handler: 'index.handler',
runtime: lambda.Runtime.NODEJS_LATEST,
});
const bucket = new s3.Bucket(this, 'Bucket');
bucket.grants.read(fn);
```
The following report will be generated.
```txt
<missing role> (MyStack/MyLambda/ServiceRole)
AssumeRole Policy:
[
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
}
}
]
Managed Policy ARNs:
[
"arn:(PARTITION):iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
]
Managed Policies Statements:
NONE
Identity Policy Statements:
[
{
"Action": [
"s3:GetObject*",
"s3:GetBucket*",
"s3:List*"
],
"Effect": "Allow",
"Resource": [
"(MyStack/Bucket/Resource.Arn)",
"(MyStack/Bucket/Resource.Arn)/*"
]
}
]
```
You would then need to create the role with the inline & managed policies in the report and then
come back and update the `customizeRoles` with the role name.
```ts
declare const app: App;
const stack = new Stack(app, 'MyStack');
iam.Role.customizeRoles(this, {
usePrecreatedRoles: {
'MyStack/MyLambda/ServiceRole': 'my-role-name',
}
});
```
For more information on configuring permissions see the [Security And Safety Dev
Guide](https://github.com/aws/aws-cdk/wiki/Security-And-Safety-Dev-Guide)
#### Policy report generation
When `customizeRoles` is used, the `iam-policy-report.txt` report will contain a list
of IAM roles and associated permissions that would have been created. This report is
generated in an attempt to resolve and replace any references with a more user-friendly
value.
The following are some examples of the value that will appear in the report:
```json
"Resource": {
"Fn::Join": [
"",
[
"arn:",
{
"Ref": "AWS::Partition"
},
":iam::",
{
"Ref": "AWS::AccountId"
},
":role/Role"
]
]
}
```
The policy report will instead get:
```json
"Resource": "arn:(PARTITION):iam::(ACCOUNT):role/Role"
```
If IAM policy is referencing a resource attribute:
```json
"Resource": [
{
"Fn::GetAtt": [
"SomeResource",
"Arn"
]
},
{
"Ref": "AWS::NoValue",
}
]
```
The policy report will instead get:
```json
"Resource": [
"(Path/To/SomeResource.Arn)"
"(NOVALUE)"
]
```
The following pseudo parameters will be converted:
1. `{ 'Ref': 'AWS::AccountId' }` -> `(ACCOUNT)
2. `{ 'Ref': 'AWS::Partition' }` -> `(PARTITION)
3. `{ 'Ref': 'AWS::Region' }` -> `(REGION)
4. `{ 'Ref': 'AWS::NoValue' }` -> `(NOVALUE)
#### Generating a permissions report
It is also possible to generate the report _without_ preventing the role/policy creation.
```ts
declare const stack: Stack;
iam.Role.customizeRoles(this, {
preventSynthesis: false,
});
```
## Configuring an ExternalId
If you need to create Roles that will be assumed by third parties, it is generally a good idea to [require an `ExternalId`
to assume them](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html). Configuring
an `ExternalId` works like this:
[supplying an external ID](test/example.external-id.lit.ts)
## SourceArn and SourceAccount
If you need to create resource policies using `aws:SourceArn` and `aws:SourceAccount` for cross-service resource access,
use `addSourceArnCondition` and `addSourceAccountCondition` to create the conditions.
See [Cross-service confused deputy prevention for more details](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html#cross-service-confused-deputy-prevention).
## Principals vs Identities
When we say *Principal*, we mean an entity you grant permissions to. This
entity can be an AWS Service, a Role, or something more abstract such as "all
users in this account" or even "all users in this organization". An
*Identity* is an IAM representing a single IAM entity that can have
a policy attached, one of `Role`, `User`, or `Group`.
## IAM Principals
When defining policy statements as part of an AssumeRole policy or as part of a
resource policy, statements would usually refer to a specific IAM principal
under `Principal`.
IAM principals are modeled as classes that derive from the `iam.PolicyPrincipal`
abstract class. Principal objects include principal type (string) and value
(array of string), optional set of conditions and the action that this principal
requires when it is used in an assume role policy document.
To add a principal to a policy statement you can either use the abstract
`statement.addPrincipal`, one of the concrete `addXxxPrincipal` methods:
* `addAwsPrincipal`, `addArnPrincipal` or `new ArnPrincipal(arn)` for `{ "AWS": arn }`
* `addAwsAccountPrincipal` or `new AccountPrincipal(accountId)` for `{ "AWS": account-arn }`
* `addServicePrincipal` or `new ServicePrincipal(service)` for `{ "Service": service }`
* `addAccountRootPrincipal` or `new AccountRootPrincipal()` for `{ "AWS": { "Ref: "AWS::AccountId" } }`
* `addCanonicalUserPrincipal` or `new CanonicalUserPrincipal(id)` for `{ "CanonicalUser": id }`
* `addFederatedPrincipal` or `new FederatedPrincipal(federated, conditions, assumeAction)` for
`{ "Federated": arn }` and a set of optional conditions and the assume role action to use.
* `addAnyPrincipal` or `new AnyPrincipal` for `{ "AWS": "*" }`
If multiple principals are added to the policy statement, they will be merged together:
```ts
const statement = new iam.PolicyStatement();
statement.addServicePrincipal('cloudwatch.amazonaws.com');
statement.addServicePrincipal('ec2.amazonaws.com');
statement.addArnPrincipal('arn:aws:boom:boom');
```
Will result in:
```json
{
"Principal": {
"Service": [ "cloudwatch.amazonaws.com", "ec2.amazonaws.com" ],
"AWS": "arn:aws:boom:boom"
}
}
```
The `CompositePrincipal` class can also be used to define complex principals, for example:
```ts
const role = new iam.Role(this, 'MyRole', {
assumedBy: new iam.CompositePrincipal(
new iam.ServicePrincipal('ec2.amazonaws.com'),
new iam.AccountPrincipal('1818188181818187272')
),
});
```
The `PrincipalWithConditions` class can be used to add conditions to a
principal, especially those that don't take a `conditions` parameter in their
constructor. The `principal.withConditions()` method can be used to create a
`PrincipalWithConditions` from an existing principal, for example:
```ts
const principal = new iam.AccountPrincipal('123456789000')
.withConditions({ StringEquals: { foo: "baz" } });
```
> NOTE: If you need to define an IAM condition that uses a token (such as a
> deploy-time attribute of another resource) in a JSON map key, use `CfnJson` to
> render this condition. See [this test](./test/integ.condition-with-ref.ts) for
> an example.
The `WebIdentityPrincipal` class can be used as a principal for web identities like
Cognito, Amazon, Google or Facebook, for example:
```ts
const principal = new iam.WebIdentityPrincipal('cognito-identity.amazonaws.com', {
'StringEquals': { 'cognito-identity.amazonaws.com:aud': 'us-east-2:12345678-abcd-abcd-abcd-123456' },
'ForAnyValue:StringLike': {'cognito-identity.amazonaws.com:amr': 'unauthenticated' },
});
```
If your identity provider is configured to assume a Role with [session
tags](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html), you
need to call `.withSessionTags()` to add the required permissions to the Role's
policy document:
```ts
new iam.Role(this, 'Role', {
assumedBy: new iam.WebIdentityPrincipal('cognito-identity.amazonaws.com', {
'StringEquals': {
'cognito-identity.amazonaws.com:aud': 'us-east-2:12345678-abcd-abcd-abcd-123456',
},
'ForAnyValue:StringLike': {
'cognito-identity.amazonaws.com:amr': 'unauthenticated',
},
}).withSessionTags(),
});
```
### Granting a principal permission to assume a role
A principal can be granted permission to assume a role using `assumeRole` from the `RoleGrants` class.
For convenience, an instance of this class is available via the `grants` attribute on the `Role` class.
Note that this does not apply to service principals or account principals as they must be added to the role trust policy via `assumeRolePolicy`.
```ts
const user = new iam.User(this, 'user')
const role = new iam.Role(this, 'role', {
assumedBy: new iam.AccountPrincipal(this.account)
});
role.grants.assumeRole(user);
```
### Granting service and account principals permission to assume a role
Service principals and account principals can be granted permission to assume a role using `assumeRolePolicy` which modifies the role trust policy.
```ts
const role = new iam.Role(this, 'role', {
assumedBy: new iam.AccountPrincipal(this.account),
});
role.assumeRolePolicy?.addStatements(new iam.PolicyStatement({
actions: ['sts:AssumeRole'],
principals: [
new iam.AccountPrincipal('123456789'),
new iam.ServicePrincipal('beep-boop.amazonaws.com')
],
}));
```
### Fixing the synthesized service principle for services that do not follow the IAM Pattern
In some cases, certain AWS services may not use the standard `<service>.amazonaws.com` pattern for their service principals. For these services, you can define the ServicePrincipal as following where the provided service principle name will be used as is without any changing.
```ts
const sp = iam.ServicePrincipal.fromStaticServicePrincipleName('elasticmapreduce.amazonaws.com.cn');
```
This principle can use as normal in defining any role, for example:
```ts
const emrServiceRole = new iam.Role(this, 'EMRServiceRole', {
assumedBy: iam.ServicePrincipal.fromStaticServicePrincipleName('elasticmapreduce.amazonaws.com.cn'),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AmazonElasticMapReduceRole'),
],
});
```
## Parsing JSON Policy Documents
The `PolicyDocument.fromJson` and `PolicyStatement.fromJson` static methods can be used to parse JSON objects. For example:
```ts
const policyDocument = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "FirstStatement",
"Effect": "Allow",
"Action": ["iam:ChangePassword"],
"Resource": ["*"],
},
{
"Sid": "SecondStatement",
"Effect": "Allow",
"Action": ["s3:ListAllMyBuckets"],
"Resource": ["*"],
},
{
"Sid": "ThirdStatement",
"Effect": "Allow",
"Action": [
"s3:List*",
"s3:Get*",
],
"Resource": [
"arn:aws:s3:::confidential-data",
"arn:aws:s3:::confidential-data/*",
],
"Condition": {"Bool": {"aws:MultiFactorAuthPresent": "true"}},
},
],
};
const customPolicyDocument = iam.PolicyDocument.fromJson(policyDocument);
// You can pass this document as an initial document to a ManagedPolicy
// or inline Policy.
const newManagedPolicy = new iam.ManagedPolicy(this, 'MyNewManagedPolicy', {
document: customPolicyDocument,
});
const newPolicy = new iam.Policy(this, 'MyNewPolicy', {
document: customPolicyDocument,
});
```
## Permissions Boundaries
[Permissions
Boundaries](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)
can be used as a mechanism to prevent privilege escalation by creating new
`Role`s. Permissions Boundaries are a Managed Policy, attached to Roles or
Users, that represent the *maximum* set of permissions they can have. The
effective set of permissions of a Role (or User) will be the intersection of
the Identity Policy and the Permissions Boundary attached to the Role (or
User). Permissions Boundaries are typically created by account
Administrators, and their use on newly created `Role`s will be enforced by
IAM policies.
### Bootstrap Permissions Boundary
If a permissions boundary has been enforced as part of CDK bootstrap, all IAM
Roles and Users that are created as part of the CDK application must be created
with the permissions boundary attached. The most common scenario will be to
apply the enforced permissions boundary to the entire CDK app. This can be done
either by adding the value to `cdk.json` or directly in the `App` constructor.
For example if your organization has created and is enforcing a permissions
boundary with the name
`cdk-${Qualifier}-PermissionsBoundary`
```json
{
"context": {
"@aws-cdk/core:permissionsBoundary": {
"name": "cdk-${Qualifier}-PermissionsBoundary"
}
}
}
```
OR
```ts
new App({
context: {
[PERMISSIONS_BOUNDARY_CONTEXT_KEY]: {
name: 'cdk-${Qualifier}-PermissionsBoundary',
},
},
});
```
Another scenario might be if your organization enforces different permissions
boundaries for different environments. For example your CDK application may have
* `DevStage` that deploys to a personal dev environment where you have elevated
privileges
* `BetaStage` that deploys to a beta environment which and has a relaxed
permissions boundary
* `GammaStage` that deploys to a gamma environment which has the prod
permissions boundary
* `ProdStage` that deploys to the prod environment and has the prod permissions
boundary
```ts
declare const app: App;
new Stage(app, 'DevStage');
new Stage(app, 'BetaStage', {
permissionsBoundary: PermissionsBoundary.fromName('beta-permissions-boundary'),
});
new Stage(app, 'GammaStage', {
permissionsBoundary: PermissionsBoundary.fromName('prod-permissions-boundary'),
});
new Stage(app, 'ProdStage', {
permissionsBoundary: PermissionsBoundary.fromName('prod-permissions-boundary'),
});
```
The provided name can include placeholders for the partition, region, qualifier, and account
These placeholders will be replaced with the actual values if available. This requires
that the Stack has the environment specified, it does not work with environment.
* '${AWS::Partition}'
* '${AWS::Region}'
* '${AWS::AccountId}'
* '${Qualifier}'
```ts
declare const app: App;
const prodStage = new Stage(app, 'ProdStage', {
permissionsBoundary: PermissionsBoundary.fromName('cdk-${Qualifier}-PermissionsBoundary-${AWS::AccountId}-${AWS::Region}'),
});
new Stack(prodStage, 'ProdStack', {
synthesizer: new DefaultStackSynthesizer({
qualifier: 'custom',
}),
});
```
For more information on configuring permissions see the [Security And Safety Dev
Guide](https://github.com/aws/aws-cdk/wiki/Security-And-Safety-Dev-Guide)
### Custom Permissions Boundary
It is possible to attach Permissions Boundaries to all Roles created in a construct
tree all at once:
```ts
// This imports an existing policy.
const boundary = iam.ManagedPolicy.fromManagedPolicyArn(this, 'Boundary', 'arn:aws:iam::123456789012:policy/boundary');
// This creates a new boundary
const boundary2 = new iam.ManagedPolicy(this, 'Boundary2', {
statements: [
new iam.PolicyStatement({
effect: iam.Effect.DENY,
actions: ['iam:*'],
resources: ['*'],
}),
],
});
// Directly apply the boundary to a Role you create
declare const role: iam.Role;
iam.PermissionsBoundary.of(role).apply(boundary);
// Apply the boundary to an Role that was implicitly created for you
declare const fn: lambda.Function;
iam.PermissionsBoundary.of(fn).apply(boundary);
// Apply the boundary to all Roles in a stack
iam.PermissionsBoundary.of(this).apply(boundary);
// Remove a Permissions Boundary that is inherited, for example from the Stack level
declare const customResource: CustomResource;
iam.PermissionsBoundary.of(customResource).clear();
```
## OpenID Connect Providers
OIDC identity providers are entities in IAM that describe an external identity
provider (IdP) service that supports the [OpenID Connect] (OIDC) standard, such
as Google or Salesforce. You use an IAM OIDC identity provider when you want to
establish trust between an OIDC-compatible IdP and your AWS account. This is
useful when creating a mobile app or web application that requires access to AWS
resources, but you don't want to create custom sign-in code or manage your own
user identities. For more information about this scenario, see [About Web
Identity Federation] and the relevant documentation in the [Amazon Cognito
Identity Pools Developer Guide].
[OpenID Connect]: http://openid.net/connect
[About Web Identity Federation]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc.html
[Amazon Cognito Identity Pools Developer Guide]: https://docs.aws.amazon.com/cognito/latest/developerguide/open-id.html
The following examples defines an OpenID Connect provider. Two client IDs
(audiences) are will be able to send authentication requests to
<https://openid/connect>.
The older `OpenIdConnectProvider` is still supported, but for new stacks, it is recommended to use the new `OidcProviderNative` which uses the native CloudFormation resource `AWS::IAM::OIDCProvider` over the old `OpenIdConnectProvider` which uses a custom resource. While `OidcProviderNative` does not provide new features compared to `OpenIdConnectProvider`, it offers a simpler implementation using native CloudFormation resources instead of custom resources.
```ts
const nativeProvider = new iam.OidcProviderNative(this, 'MyProvider', {
url: 'https://openid/connect',
clientIds: [ 'myclient1', 'myclient2' ],
thumbprints: ['aa00aa1122aa00aa1122aa00aa1122aa00aa1122'],
});
```
For the new `OidcProviderNative`, you must provide at least one thumbprint when creating an IAM OIDC
provider. For example, assume that the OIDC provider is server.example.com
and the provider stores its keys at
https://keys.server.example.com/openid-connect. In that case, the
thumbprint string would be the hex-encoded SHA-1 hash value of the
certificate used by https://keys.server.example.com.
The server certificate thumbprint is the hex-encoded SHA-1 hash value of
the X.509 certificate used by the domain where the OpenID Connect provider
makes its keys available. It is always a 40-character string.
Typically this list includes only one entry. However, IAM lets you have up
to five thumbprints for an OIDC provider. This lets you maintain multiple
thumbprints if the identity provider is rotating certificates.
Obtain the thumbprint of the root certificate authority from the provider's
server as described in https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html
The older `OpenIdConnectProvider` is still supported but it is recommended to use the new `OidcProviderNative` instead.
```ts
const provider = new iam.OpenIdConnectProvider(this, 'MyProvider', {
url: 'https://openid/connect',
clientIds: [ 'myclient1', 'myclient2' ],
});
```
For the older `OpenIdConnectProvider`, you can specify an optional list of `thumbprints`. If not specified, the
thumbprint of the root certificate authority (CA) will automatically be obtained
from the host as described
[here](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html).
By default, the custom resource enforces strict security practices by rejecting
any unauthorized connections when downloading CA thumbprints from the issuer URL.
If you need to connect to an unauthorized OIDC identity provider and understand the
implications, you can disable this behavior by setting the feature flag
`IAM_OIDC_REJECT_UNAUTHORIZED_CONNECTIONS` to `false` in your `cdk.context.json`
or `cdk.json`. Visit [CDK Feature Flag](https://docs.aws.amazon.com/cdk/v2/guide/featureflags.html)
for more information on how to configure feature flags.
Once you define an OpenID connect provider, you can use it with AWS services
that expect an IAM OIDC provider. For example, when you define an [Amazon
Cognito identity
pool](https://docs.aws.amazon.com/cognito/latest/developerguide/open-id.html)
you can reference the provider's ARN as follows:
```ts
import * as cognito from 'aws-cdk-lib/aws-cognito';
declare const myProvider: iam.OpenIdConnectProvider;
new cognito.CfnIdentityPool(this, 'IdentityPool', {
openIdConnectProviderArns: [myProvider.openIdConnectProviderArn],
// And the other properties for your identity pool
allowUnauthenticatedIdentities: false,
});
```
The `OpenIdConnectPrincipal` class can be used as a principal used with a `OpenIdConnectProvider`, for example:
```ts
const provider = new iam.OpenIdConnectProvider(this, 'MyProvider', {
url: 'https://openid/connect',
clientIds: [ 'myclient1', 'myclient2' ],
});
const principal = new iam.OpenIdConnectPrincipal(provider);
```
## SAML provider
An IAM SAML 2.0 identity provider is an entity in IAM that describes an external
identity provider (IdP) service that supports the SAML 2.0 (Security Assertion
Markup Language 2.0) standard. You use an IAM identity provider when you want
to establish trust between a SAML-compatible IdP such as Shibboleth or Active
Directory Federation Services and AWS, so that users in your organization can
access AWS resources. IAM SAML identity providers are used as principals in an
IAM trust policy.
```ts
new iam.SamlProvider(this, 'Provider', {
metadataDocument: iam.SamlMetadataDocument.fromFile('/path/to/saml-metadata-document.xml'),
});
```
The `SamlPrincipal` class can be used as a principal with a `SamlProvider`:
```ts
const provider = new iam.SamlProvider(this, 'Provider', {
metadataDocument: iam.SamlMetadataDocument.fromFile('/path/to/saml-metadata-document.xml'),
});
const principal = new iam.SamlPrincipal(provider, {
StringEquals: {
'SAML:iss': 'issuer',
},
});
```
When creating a role for programmatic and AWS Management Console access, use the `SamlConsolePrincipal`
class:
```ts
const provider = new iam.SamlProvider(this, 'Provider', {
metadataDocument: iam.SamlMetadataDocument.fromFile('/path/to/saml-metadata-document.xml'),
});
new iam.Role(this, 'Role', {
assumedBy: new iam.SamlConsolePrincipal(provider),
});
```
## Users
IAM manages users for your AWS account. To create a new user:
```ts
const user = new iam.User(this, 'MyUser');
```
To import an existing user by name [with path](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-friendly-names):
```ts
const user = iam.User.fromUserName(this, 'MyImportedUserByName', 'johnsmith');
```
To import an existing user by ARN:
```ts
const user = iam.User.fromUserArn(this, 'MyImportedUserByArn', 'arn:aws:iam::123456789012:user/johnsmith');
```
To import an existing user by attributes:
```ts
const user = iam.User.fromUserAttributes(this, 'MyImportedUserByAttributes', {
userArn: 'arn:aws:iam::123456789012:user/johnsmith',
});
```
### Access Keys
The ability for a user to make API calls via the CLI or an SDK is enabled by the user having an
access key pair. To create an access key:
```ts
const user = new iam.User(this, 'MyUser');
const accessKey = new iam.AccessKey(this, 'MyAccessKey', { user: user });
```
You can force CloudFormation to rotate the access key by providing a monotonically increasing `serial`
property. Simply provide a higher serial value than any number used previously:
```ts
const user = new iam.User(this, 'MyUser');
const accessKey = new iam.AccessKey(this, 'MyAccessKey', { user: user, serial: 1 });
```
An access key may only be associated with a single user and cannot be "moved" between users. Changing
the user associated with an access key replaces the access key (and its ID and secret value).
## Groups
An IAM user group is a collection of IAM users. User groups let you specify permissions for multiple users.
```ts
const group = new iam.Group(this, 'MyGroup');
```
To import an existing group by ARN:
```ts
const group = iam.Group.fromGroupArn(this, 'MyImportedGroupByArn', 'arn:aws:iam::account-id:group/group-name');
```
To import an existing group by name [with path](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-friendly-names):
```ts
const group = iam.Group.fromGroupName(this, 'MyImportedGroupByName', 'group-name');
```
To add a user to a group (both for a new and imported user/group):
```ts
const user = new iam.User(this, 'MyUser'); // or User.fromUserName(this, 'User', 'johnsmith');
const group = new iam.Group(this, 'MyGroup'); // or Group.fromGroupArn(this, 'Group', 'arn:aws:iam::account-id:group/group-name');
user.addToGroup(group);
// or
group.addUser(user);
```
## Instance Profiles
An IAM instance profile is a container for an IAM role that you can use to pass role information to an EC2 instance when the instance starts. By default, an instance profile must be created with a role:
```ts
const role = new iam.Role(this, 'Role', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});
const instanceProfile = new iam.InstanceProfile(this, 'InstanceProfile', {
role,
});
```
An instance profile can also optionally be created with an instance profile name and/or a [path](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-friendly-names) to the instance profile:
```ts
const role = new iam.Role(this, 'Role', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});
const instanceProfile = new iam.InstanceProfile(this, 'InstanceProfile', {
role,
instanceProfileName: 'MyInstanceProfile',
path: '/sample/path/',
});
```
To import an existing instance profile by name:
```ts
const instanceProfile = iam.InstanceProfile.fromInstanceProfileName(this, 'ImportedInstanceProfile', 'MyInstanceProfile');
```
To import an existing instance profile by ARN:
```ts
const instanceProfile = iam.InstanceProfile.fromInstanceProfileArn(this, 'ImportedInstanceProfile', 'arn:aws:iam::account-id:instance-profile/MyInstanceProfile');
```
To import an existing instance profile with an associated role:
```ts
const role = new iam.Role(this, 'Role', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});
const instanceProfile = iam.InstanceProfile.fromInstanceProfileAttributes(this, 'ImportedInstanceProfile', {
instanceProfileArn: 'arn:aws:iam::account-id:instance-profile/MyInstanceProfile',
role,
});
```
## Features
* Policy name uniqueness is enforced. If two policies by the same name are attached to the same
principal, the attachment will fail.
* Policy names are not required - the CDK logical ID will be used and ensured to be unique.
* Policies are validated during synthesis to ensure that they have actions, and that policies
attached to IAM principals specify relevant resources, while policies attached to resources
specify which IAM principals they apply to.

View File

@@ -0,0 +1,201 @@
/*
Alloy model to confirm the logic behind merging IAM Statements.
This proves that merging two statements based on the following conditions:
- Effects are the same
- NotAction, NotResource, NotPrincipal are the same(*)
- Of Action, Resource, Principal sets, 2 out of 3 are the same(*)
Is sound, as the model doesn't find any examples of where the meaning
of statements is changed by merging.
Find Alloy at https://alloytools.org/.
(*) Some of these sets may be empty--that is fine, the logic still works out.
*/
//-------------------------------------------------------
// Base Statement definitions
enum Effect { Allow, Deny }
enum Resource { ResourceA, ResourceB }
enum Action { ActionA, ActionB }
enum Principal { PrincipalA, PrincipalB }
sig Statement {
effect: Effect,
principal: set Principal,
notPrincipal: set Principal,
action: set Action,
notAction: set Action,
resource: set Resource,
notResource: set Resource,
} {
// Exactly one of Xxx and notXxx is non-empty
(some principal) iff not (some notPrincipal)
(some action) iff not (some notAction)
(some resource) iff not (some notResource)
}
// So that we can compare Statements using =, if two Statements have
// exactly the same properties then they are the same Statement
fact {
all a, b: Statement {
(
a.effect = b.effect and
a.principal = b.principal and
a.notPrincipal = b.notPrincipal and
a.action = b.action and
a.notAction = b.notAction and
a.resource = b.resource and
a.notResource = b.notResource) implies a = b
}
}
//-------------------------------------------------------
// Requests and evaluations
sig Request {
principal: Principal,
action: Action,
resource: Resource,
}
// Whether the statement applies to the given request
pred applies[s: Statement, req: Request] {
some s.principal implies req.principal in s.principal
some s.notPrincipal implies req.principal not in s.notPrincipal
some s.action implies req.action in s.action
some s.notAction implies req.action not in s.notAction
some s.resource implies req.resource in s.resource
some s.notResource implies req.resource not in s.notResource
}
// Whether or not to allow the given request according to the given statements
//
// A request is allowed if there's at least one statement allowing it and
// no statements denying it.
pred allow[req: Request, ss: some Statement] {
some s: ss | applies[s, req] and s.effect = Allow
no s: ss | applies[s, req] and s.effect = Deny
}
run show_some_allowed_requests {
some ss: set Statement, r: Request | allow[r, ss] and /* no useless Statements floating around */ (no s" : Statement | s" not in ss)
} for 3 but 1 Request
//-------------------------------------------------------
// Statement merging
// Assert that m is the merged version of a and b
//
// This encodes the important logic: the rules of merging.
pred merged[a: Statement, b: Statement, m: Statement] {
// Preconditions
a.effect = b.effect
a.notAction = b.notAction
a.notResource = b.notResource
a.notPrincipal = b.notPrincipal
// Merging is allowed in one of 2 cases:
// - of the pairs { Resource, Action, Principal } 2 are the same (then the 3rd pair may be merged)
// - if one statement is a full subset of the other one (then it may be subsumed) [not implemented yet]
let R = a.resource = b.resource, A = a.action = b.action, P = a.principal = b.principal {
((R and A) or (R and P) or (A and P) or
(a.resource in b.resource and a.action in b.action and a.principal in b.principal) or
(b.resource in a.resource and b.action in a.action and b.principal in a.principal))
}
// Result of merging
m.effect = a.effect
m.action = a.action + b.action
m.notAction = a.notAction
m.resource = a.resource + b.resource
m.notResource = a.notResource
m.principal = a.principal + b.principal
m.notPrincipal = a.notPrincipal
}
run show_some_nontrivial_merges {
some disj s0, s1, M: Statement | merged[s0, s1, M] and s0.action != s1.action
}
// For any pair of statements, there is only one possible merging
check merging_is_unique {
all s0, s1: Statement {
no disj m0, m1 : Statement | merged[s0, s1, m0] and merged[s0, s1, m1]
}
} for 5
// For all statements, the evaluation of the individual statements is the same as the evaluation
// of the merged statement.
check merging_does_not_change_evaluation {
all a: Statement, b: Statement, m: Statement, r: Request {
merged[a, b, m] implies (allow[r, a + b] iff allow[r, m])
}
} for 3
// There are no 3 statements such that merged(merged(s0, s1), s2) != merged(s0, merged(s1, s2))
check merging_is_associative {
no s0, s1, s2, h0, h1, m0, m1: Statement {
merged[s0, s1, h0] and merged[h0, s2, m0]
merged[s1, s2, h1] and merged[h1, s0, m1]
m0 != m1
}
} for 10
// For all statements, merged(s0, s1) = merged(s1, s0)
check merging_is_commutative {
all s0, s1, m: Statement {
merged[s0, s1, m] implies merged[s1, s0, m]
}
} for 5
//-------------------------------------------------------
// Repeated application of merging
// Whether a and b are mergeable
pred mergeable[a: Statement, b: Statement] {
some m: Statement | m != a and m != b and merged[a, b, m]
}
// Maximally merged items in a set
pred maxMerged(input: set Statement, output: set Statement) {
no disj a, b: output | mergeable[a, b]
input = output or {
#input > #output
some a, b: input | some m: Statement {
m != a
m != b
merged[a, b, m]
maxMerged[input - a - b + m, output]
}
}
}
run some_interesting_maxMerged_statements {
some input, output: set Statement {
maxMerged[input, output]
#input = 3
#output = 1
all x: output | x not in input
}
} for 5
check max_merging_does_not_change_eval {
all input, output: set Statement, r: Request {
maxMerged[input, output] implies (allow[r, input] iff allow[r, output])
}
} for 5
// This used to be written the opposite way. But you know: merging is NOT unique.
// Counterexample found by Alloy:
// {{ A, B, A }, {B, B, A} { A, B, B }}
// Reduces to either:
// {{ AB, B, A }, { A, B, B }}
// or {{ A, B, AB }, { B, B, A }}
run max_merging_is_not_unique {
some input, m0, m1: set Statement {
maxMerged[input, m0] and maxMerged[input, m1] and m0 != m1
}
} for 5

1
cdk/node_modules/aws-cdk-lib/aws-iam/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export * from './lib';

1
cdk/node_modules/aws-cdk-lib/aws-iam/index.js generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,80 @@
import type { Construct } from 'constructs';
import type { AccessKeyReference, IAccessKeyRef } from './iam.generated';
import type { IUser } from './user';
import type { IResource } from '../../core';
import { Resource, SecretValue } from '../../core';
/**
* Valid statuses for an IAM Access Key.
*/
export declare enum AccessKeyStatus {
/**
* An active access key. An active key can be used to make API calls.
*/
ACTIVE = "Active",
/**
* An inactive access key. An inactive key cannot be used to make API calls.
*/
INACTIVE = "Inactive",
/**
* An expired access key.
*/
EXPIRED = "Expired"
}
/**
* Represents an IAM Access Key.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html
*/
export interface IAccessKey extends IResource, IAccessKeyRef {
/**
* The Access Key ID.
*
* @attribute
*/
readonly accessKeyId: string;
/**
* The Secret Access Key.
*
* @attribute
*/
readonly secretAccessKey: SecretValue;
}
/**
* Properties for defining an IAM access key.
*/
export interface AccessKeyProps {
/**
* A CloudFormation-specific value that signifies the access key should be
* replaced/rotated. This value can only be incremented. Incrementing this
* value will cause CloudFormation to replace the Access Key resource.
*
* @default - No serial value
*/
readonly serial?: number;
/**
* The status of the access key. An Active access key is allowed to be used
* to make API calls; An Inactive key cannot.
*
* @default - The access key is active
*/
readonly status?: AccessKeyStatus;
/**
* The IAM user this key will belong to.
*
* Changing this value will result in the access key being deleted and a new
* access key (with a different ID and secret value) being assigned to the new
* user.
*/
readonly user: IUser;
}
/**
* Define a new IAM Access Key.
*/
export declare class AccessKey extends Resource implements IAccessKey {
/** Uniquely identifies this class. */
static readonly PROPERTY_INJECTION_ID: string;
readonly accessKeyRef: AccessKeyReference;
readonly accessKeyId: string;
readonly secretAccessKey: SecretValue;
constructor(scope: Construct, id: string, props: AccessKeyProps);
}

View File

@@ -0,0 +1 @@
"use strict";var __esDecorate=exports&&exports.__esDecorate||function(ctor,descriptorIn,decorators,contextIn,initializers,extraInitializers){function accept(f){if(f!==void 0&&typeof f!="function")throw new TypeError("Function expected");return f}for(var kind=contextIn.kind,key=kind==="getter"?"get":kind==="setter"?"set":"value",target=!descriptorIn&&ctor?contextIn.static?ctor:ctor.prototype:null,descriptor=descriptorIn||(target?Object.getOwnPropertyDescriptor(target,contextIn.name):{}),_,done=!1,i=decorators.length-1;i>=0;i--){var context={};for(var p in contextIn)context[p]=p==="access"?{}:contextIn[p];for(var p in contextIn.access)context.access[p]=contextIn.access[p];context.addInitializer=function(f){if(done)throw new TypeError("Cannot add initializers after decoration has completed");extraInitializers.push(accept(f||null))};var result=(0,decorators[i])(kind==="accessor"?{get:descriptor.get,set:descriptor.set}:descriptor[key],context);if(kind==="accessor"){if(result===void 0)continue;if(result===null||typeof result!="object")throw new TypeError("Object expected");(_=accept(result.get))&&(descriptor.get=_),(_=accept(result.set))&&(descriptor.set=_),(_=accept(result.init))&&initializers.unshift(_)}else(_=accept(result))&&(kind==="field"?initializers.unshift(_):descriptor[key]=_)}target&&Object.defineProperty(target,contextIn.name,descriptor),done=!0},__runInitializers=exports&&exports.__runInitializers||function(thisArg,initializers,value){for(var useValue=arguments.length>2,i=0;i<initializers.length;i++)value=useValue?initializers[i].call(thisArg,value):initializers[i].call(thisArg);return useValue?value:void 0};Object.defineProperty(exports,"__esModule",{value:!0}),exports.AccessKey=exports.AccessKeyStatus=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var iam_generated_1=()=>{var tmp=require("./iam.generated");return iam_generated_1=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},metadata_resource_1=()=>{var tmp=require("../../core/lib/metadata-resource");return metadata_resource_1=()=>tmp,tmp},prop_injectable_1=()=>{var tmp=require("../../core/lib/prop-injectable");return prop_injectable_1=()=>tmp,tmp},AccessKeyStatus;(function(AccessKeyStatus2){AccessKeyStatus2.ACTIVE="Active",AccessKeyStatus2.INACTIVE="Inactive",AccessKeyStatus2.EXPIRED="Expired"})(AccessKeyStatus||(exports.AccessKeyStatus=AccessKeyStatus={}));let AccessKey=(()=>{let _classDecorators=[prop_injectable_1().propertyInjectable],_classDescriptor,_classExtraInitializers=[],_classThis,_classSuper=core_1().Resource;var AccessKey2=class extends _classSuper{static{_classThis=this}static{const _metadata=typeof Symbol=="function"&&Symbol.metadata?Object.create(_classSuper[Symbol.metadata]??null):void 0;__esDecorate(null,_classDescriptor={value:_classThis},_classDecorators,{kind:"class",name:_classThis.name,metadata:_metadata},null,_classExtraInitializers),AccessKey2=_classThis=_classDescriptor.value,_metadata&&Object.defineProperty(_classThis,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:_metadata})}static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_iam.AccessKey",version:"2.252.0"};static PROPERTY_INJECTION_ID="aws-cdk-lib.aws-iam.AccessKey";accessKeyRef;accessKeyId;secretAccessKey;constructor(scope,id,props){super(scope,id);try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_AccessKeyProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,AccessKey2),error}(0,metadata_resource_1().addConstructMetadata)(this,props);const accessKey=new(iam_generated_1()).CfnAccessKey(this,"Resource",{userName:props.user.userName,serial:props.serial,status:props.status});this.accessKeyId=accessKey.ref,this.accessKeyRef=accessKey.accessKeyRef,this.secretAccessKey=core_1().SecretValue.resourceAttribute(accessKey.attrSecretAccessKey)}static{__runInitializers(_classThis,_classExtraInitializers)}};return AccessKey2=_classThis})();exports.AccessKey=AccessKey;

452
cdk/node_modules/aws-cdk-lib/aws-iam/lib/grant.d.ts generated vendored Normal file
View File

@@ -0,0 +1,452 @@
import type { IConstruct, IDependable } from 'constructs';
import { PolicyStatement } from './policy-statement';
import type { IGrantable, IPrincipal } from './principals';
import type { IEnvironmentAware } from '../../core';
import { CfnResource } from '../../core';
import * as cdk from '../../core';
/**
* Basic options for a grant operation
*
*/
export interface CommonGrantOptions {
/**
* The principal to grant to
*
* @default if principal is undefined, no work is done.
*/
readonly grantee: IGrantable;
/**
* The actions to grant
*/
readonly actions: string[];
/**
* The resource ARNs to grant to
*/
readonly resourceArns: string[];
/**
* Any conditions to attach to the grant
*
* @default - No conditions
*/
readonly conditions?: Record<string, Record<string, unknown>>;
}
/**
* Options for a grant operation
*
*/
export interface GrantWithResourceOptions extends CommonGrantOptions {
/**
* The resource with a resource policy
*
* The statement will be added to the resource policy if it couldn't be
* added to the principal policy.
*/
readonly resource: IResourceWithPolicyV2;
/**
* When referring to the resource in a resource policy, use this as ARN.
*
* (Depending on the resource type, this needs to be '*' in a resource policy).
*
* @default Same as regular resource ARNs
*/
readonly resourceSelfArns?: string[];
}
/**
* Options for a grant operation that directly adds a policy statement to a resource
*
* This differs from GrantWithResourceOptions in that it requires a pre-constructed
* PolicyStatement rather than constructing one from individual permissions.
* Use this when you need fine-grained control over the initial policy statement's contents.
*/
export interface GrantPolicyWithResourceOptions extends GrantWithResourceOptions {
/**
* The policy statement to add to the resource's policy
*
* This statement will be passed to the resource's addToResourcePolicy method.
* The actual handling of the statement depends on the specific IResourceWithPolicyV2
* implementation.
*/
readonly statement: PolicyStatement;
}
/**
* Options for a grant operation that only applies to principals
*
*/
export interface GrantOnPrincipalOptions extends CommonGrantOptions {
/**
* Construct to report warnings on in case grant could not be registered
*
* @default - the construct in which this construct is defined
* @deprecated The scope argument is currently unused.
*/
readonly scope?: IConstruct;
}
/**
* Options for a grant operation to both identity and resource
*
*/
export interface GrantOnPrincipalAndResourceOptions extends CommonGrantOptions {
/**
* The resource with a resource policy
*
* The statement will always be added to the resource policy.
*/
readonly resource: IResourceWithPolicyV2;
/**
* When referring to the resource in a resource policy, use this as ARN.
*
* (Depending on the resource type, this needs to be '*' in a resource policy).
*
* @default Same as regular resource ARNs
*/
readonly resourceSelfArns?: string[];
/**
* The principal to use in the statement for the resource policy.
*
* @default - the principal of the grantee will be used
*/
readonly resourcePolicyPrincipal?: IPrincipal;
}
/**
* Result of a grant() operation
*
* This class is not instantiable by consumers on purpose, so that they will be
* required to call the Grant factory functions.
*/
export declare class Grant implements IDependable {
/**
* Grant the given permissions to the principal
*
* The permissions will be added to the principal policy primarily, falling
* back to the resource policy if necessary. The permissions must be granted
* somewhere.
*
* - Trying to grant permissions to a principal that does not admit adding to
* the principal policy while not providing a resource with a resource policy
* is an error.
* - Trying to grant permissions to an absent principal (possible in the
* case of imported resources) leads to a warning being added to the
* resource construct.
*/
static addToPrincipalOrResource(options: GrantWithResourceOptions): Grant;
/**
* Add a pre-constructed policy statement to the resource's policy
*
* This method provides direct, low-level control over the initial policy statement being added.
* It is useful when you need to:
* - Add complex policy statements that can't be expressed through other grant methods
* - Specify the initial structure of the policy statement
* - Add statements with custom conditions or other advanced IAM features
*
* Important differences from other grant methods:
* - Only modifies the resource policy, never modifies any principal's policy
* - Takes a complete PolicyStatement rather than constructing one from parameters
* - Always attempts to add the statement, regardless of principal type or account
* - Does not attempt any automatic principal/resource policy selection logic
*
* Note: The final form of the policy statement in the resource's policy may differ
* from the provided statement, depending on the resource's implementation of
* addToResourcePolicy.
*
* @param options Contains both the target resource and the policy statement to add
* @returns A Grant object representing the result of the operation
*
* @example
*
* declare const grantee: iam.IGrantable;
* declare const actions: string[];
* declare const resourceArns: string[];
* declare const bucket: s3.Bucket;
*
* const statement = new iam.PolicyStatement({
* effect: iam.Effect.ALLOW,
* actions: actions,
* principals: [new iam.ServicePrincipal('lambda.amazonaws.com')],
* conditions: {
* StringEquals: {
* 'aws:SourceAccount': Stack.of(this).account,
* },
* },
* });
* iam.Grant.addStatementToResourcePolicy({
* grantee: grantee,
* actions: actions,
* resourceArns: resourceArns,
* resource: bucket,
* statement: statement,
* });
*
*/
static addStatementToResourcePolicy(options: GrantPolicyWithResourceOptions): Grant;
/**
* Try to grant the given permissions to the given principal
*
* Absence of a principal leads to a warning, but failing to add
* the permissions to a present principal is not an error.
*/
static addToPrincipal(options: GrantOnPrincipalOptions): Grant;
/**
* Add a grant both on the principal and on the resource
*
* As long as any principal is given, granting on the principal may fail (in
* case of a non-identity principal), but granting on the resource will
* never fail.
*
* Statement will be the resource statement.
*/
static addToPrincipalAndResource(options: GrantOnPrincipalAndResourceOptions): Grant;
/**
* Returns a "no-op" `Grant` object which represents a "dropped grant".
*
* This can be used for e.g. imported resources where you may not be able to modify
* the resource's policy or some underlying policy which you don't know about.
*
* @param grantee The intended grantee
* @param _intent The user's intent (will be ignored at the moment)
*/
static drop(grantee: IGrantable, _intent: string): Grant;
/**
* The statement that was added to the principal's policy
*
* @deprecated Use `principalStatements` instead
*/
readonly principalStatement?: PolicyStatement;
/**
* The statements that were added to the principal's policy
*/
readonly principalStatements: PolicyStatement[];
/**
* The statement that was added to the resource policy
*
* @deprecated Use `resourceStatements` instead
*/
readonly resourceStatement?: PolicyStatement;
/**
* The statements that were added to the resource policy
*/
readonly resourceStatements: PolicyStatement[];
/**
* The options originally used to set this result
*
* Private member doubles as a way to make it impossible for an object literal to
* be structurally the same as this class.
*/
private readonly options;
private readonly dependables;
private constructor();
/**
* Whether the grant operation was successful
*/
get success(): boolean;
/**
* Throw an error if this grant wasn't successful
*/
assertSuccess(): void;
/**
* Make sure this grant is applied before the given constructs are deployed
*
* The same as construct.node.addDependency(grant), but slightly nicer to read.
*/
applyBefore(...constructs: IConstruct[]): void;
/**
* Combine two grants into a new one
*/
combine(rhs: Grant): Grant;
}
/**
* Result of a call to grantOnKey().
*/
export interface GrantOnKeyResult {
/**
* The Grant object, if a grant was created.
*
* @default No grant
*/
readonly grant?: Grant;
}
/**
* Utility class for discovering and managing resource policy traits
*
* This class provides methods to retrieve IResourceWithPolicyV2 instances from constructs,
* enabling resource-based policy management during IAM grant operations.
*/
export declare class ResourceWithPolicies {
/**
* Retrieve the IResourceWithPolicyV2 associated with a construct, if available.
*/
static of(resource: IEnvironmentAware): IResourceWithPolicyV2 | undefined;
/**
* Register a factory for a specific CloudFormation resource type and scope
*/
static register(scope: IConstruct, cfnType: string, factory: IResourcePolicyFactory): void;
private static traits;
}
/**
* Utility class for discovering and registering encrypted resource traits
*
* This class provides methods to retrieve IEncryptedResource instances from constructs,
* enabling automatic KMS key permission grants during IAM grant operations.
*/
export declare class EncryptedResources {
/**
* Retrieve the IEncryptedResource associated with a construct, if available.
*/
static of(resource: IEnvironmentAware): IEncryptedResource | undefined;
/**
* Register a factory for a specific CloudFormation resource type and scope
*/
static register(scope: IConstruct, cfnType: string, factory: IEncryptedResourceFactory): void;
private static traits;
}
/**
* Factory interface for creating IResourceWithPolicyV2 instances from constructs
*
* Implementations of this interface are registered in the DefaultPolicyFactories registry
* and enable automatic resource policy support for CloudFormation resources. When a grant
* operation is performed, the factory converts L1 constructs into resources that support
* resource-based policies.
*
* Factories are typically registered during static initialization and associated with
* specific CloudFormation resource types (e.g., 'AWS::DynamoDB::Table'). The CDK's grant
* system uses these factories to determine whether a resource supports resource policies
* and to create the appropriate wrapper when needed.
*/
export interface IResourcePolicyFactory {
/**
* Create an IResourceWithPolicyV2 from a construct
* @param resource the construct to be wrapped as an IResourceWithPolicyV2.
*/
forResource(resource: CfnResource): IResourceWithPolicyV2;
}
/**
* Factory interface for creating IEncryptedResource instances from constructs
*
* Implementations of this interface are registered in the DefaultEncryptedResourceFactories
* registry and enable automatic KMS key permission grants for encrypted CloudFormation resources.
* When a grant operation is performed on an encrypted resource, the factory converts L1 constructs
* into resources that can grant permissions on their associated KMS encryption keys.
*
* Factories are typically registered during static initialization and associated with specific
* CloudFormation resource types (e.g., 'AWS::DynamoDB::Table'). The CDK's grant system uses
* these factories to automatically add necessary KMS key permissions when granting access to
* encrypted resources.
*/
export interface IEncryptedResourceFactory {
/**
* Create an IEncryptedResource from a construct
*
* @param resource the construct to be wrapped as an IEncryptedResource.
*/
forResource(resource: CfnResource): IEncryptedResource;
}
/**
* A resource that contains data that can be encrypted, using a KMS key.s
*/
export interface IEncryptedResource extends IEnvironmentAware {
/**
* Gives permissions to a grantable entity to perform actions on the encryption key.
*/
grantOnKey(grantee: IGrantable, ...actions: string[]): GrantOnKeyResult;
}
/**
* A resource with a resource policy that can be added to
*/
export interface IResourceWithPolicyV2 extends IEnvironmentAware {
/**
* Add a statement to the resource's resource policy
*/
addToResourcePolicy(statement: PolicyStatement): AddToResourcePolicyResult;
}
/**
* Utility methods to check for specific types of grantable resources
*/
export declare class GrantableResources {
/**
* Whether this resource admits a resource policy.
*/
static isResourceWithPolicy(resource: IEnvironmentAware): resource is IResourceWithPolicyV2;
/**
* Whether this resource holds data that can be encrypted using a KMS key.
*/
static isEncryptedResource(resource: IEnvironmentAware): resource is IEncryptedResource;
}
/**
* A resource with a resource policy that can be added to
*
* This interface is maintained for backwards compatibility, but should
* not be used in new code. Prefer `IResourceWithPolicyV2` instead.
*
* @deprecated Implement `IResourceWithPolicyV2` instead.
*/
export interface IResourceWithPolicy extends IResourceWithPolicyV2, cdk.IResource {
}
/**
* Result of calling addToResourcePolicy
*/
export interface AddToResourcePolicyResult {
/**
* Whether the statement was added
*/
readonly statementAdded: boolean;
/**
* Dependable which allows depending on the policy change being applied
*
* @default - If `statementAdded` is true, the resource object itself.
* Otherwise, no dependable.
*/
readonly policyDependable?: IDependable;
}
/**
* Composite dependable
*
* Not as simple as eagerly getting the dependency roots from the
* inner dependables, as they may be mutable so we need to defer
* the query.
*/
export declare class CompositeDependable implements IDependable {
constructor(...dependables: IDependable[]);
}
/**
* Default factories for resources with policies
*/
export declare class DefaultPolicyFactories {
/**
* Get the default factory for a given CloudFormation resource type
* @param type the CloudFormation resource type (e.g., 'AWS::DynamoDB::Table')
*/
static get(type: string): IResourcePolicyFactory | undefined;
/**
* Register a default factory for a given CloudFormation resource type
* @param type the CloudFormation resource type (e.g., 'AWS::DynamoDB::Table')
* @param factory the factory to register for this resource type
*/
static set(type: string, factory: IResourcePolicyFactory): void;
/**
* Check if a default factory is registered for a given CloudFormation resource type
* @param type the CloudFormation resource type (e.g., 'AWS::DynamoDB::Table')
*/
static has(type: string): boolean;
private static readonly map;
}
/**
* Default factories for encrypted resources
*/
export declare class DefaultEncryptedResourceFactories {
/**
* Get the default factory for a given CloudFormation resource type
* @param type the CloudFormation resource type (e.g., 'AWS::DynamoDB::Table')
*/
static get(type: string): IEncryptedResourceFactory | undefined;
/**
* Register a default factory for a given CloudFormation resource type
* @param type the CloudFormation resource type (e.g., 'AWS::DynamoDB::Table')
* @param factory the factory to register for this resource type
*/
static set(type: string, factory: IEncryptedResourceFactory): void;
/**
* Check if a default factory is registered for a given CloudFormation resource type
* @param type the CloudFormation resource type (e.g., 'AWS::DynamoDB::Table')
*/
static has(type: string): boolean;
private static readonly map;
}

1
cdk/node_modules/aws-cdk-lib/aws-iam/lib/grant.js generated vendored Normal file

File diff suppressed because one or more lines are too long

143
cdk/node_modules/aws-cdk-lib/aws-iam/lib/group.d.ts generated vendored Normal file
View File

@@ -0,0 +1,143 @@
import type { Construct } from 'constructs';
import type { GroupReference, IGroupRef } from './iam.generated';
import type { IIdentity } from './identity-base';
import type { IManagedPolicy } from './managed-policy';
import { Policy } from './policy';
import type { PolicyStatement } from './policy-statement';
import type { AddToPrincipalPolicyResult, IPrincipal, PrincipalPolicyFragment } from './principals';
import type { IUser } from './user';
import { Resource } from '../../core';
/**
* Represents an IAM Group.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html
*/
export interface IGroup extends IIdentity, IGroupRef {
/**
* Returns the IAM Group Name
*
* @attribute
*/
readonly groupName: string;
/**
* Returns the IAM Group ARN
*
* @attribute
*/
readonly groupArn: string;
}
/**
* Properties for defining an IAM group
*/
export interface GroupProps {
/**
* A name for the IAM group. For valid values, see the GroupName parameter
* for the CreateGroup action in the IAM API Reference. If you don't specify
* a name, AWS CloudFormation generates a unique physical ID and uses that
* ID for the group name.
*
* If you specify a name, you must specify the CAPABILITY_NAMED_IAM value to
* acknowledge your template's capabilities. For more information, see
* Acknowledging IAM Resources in AWS CloudFormation Templates.
*
* @default Generated by CloudFormation (recommended)
*/
readonly groupName?: string;
/**
* A list of managed policies associated with this role.
*
* You can add managed policies later using
* `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`.
*
* @default - No managed policies.
*/
readonly managedPolicies?: IManagedPolicy[];
/**
* The path to the group. For more information about paths, see [IAM
* Identifiers](https://docs.aws.amazon.com/IAM/latest/UserGuide/index.html?Using_Identifiers.html)
* in the IAM User Guide.
*
* @default /
*/
readonly path?: string;
}
declare abstract class GroupBase extends Resource implements IGroup {
abstract readonly groupName: string;
abstract readonly groupArn: string;
readonly grantPrincipal: IPrincipal;
readonly principalAccount: string | undefined;
readonly assumeRoleAction: string;
private readonly attachedPolicies;
private defaultPolicy?;
get policyFragment(): PrincipalPolicyFragment;
get groupRef(): GroupReference;
/**
* Attaches a policy to this group.
* @param policy The policy to attach.
*/
attachInlinePolicy(policy: Policy): void;
addManagedPolicy(_policy: IManagedPolicy): void;
/**
* Adds a user to this group.
*/
addUser(user: IUser): void;
/**
* Adds an IAM statement to the default policy.
*/
addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult;
addToPolicy(statement: PolicyStatement): boolean;
}
/**
* An IAM Group (collection of IAM users) lets you specify permissions for
* multiple users, which can make it easier to manage permissions for those users.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html
*/
export declare class Group extends GroupBase {
/** Uniquely identifies this class. */
static readonly PROPERTY_INJECTION_ID: string;
/**
* Import an external group by ARN.
*
* If the imported Group ARN is a Token (such as a
* `CfnParameter.valueAsString` or a `Fn.importValue()`) *and* the referenced
* group has a `path` (like `arn:...:group/AdminGroup/NetworkAdmin`), the
* `groupName` property will not resolve to the correct value. Instead it
* will resolve to the first path component. We unfortunately cannot express
* the correct calculation of the full path name as a CloudFormation
* expression. In this scenario the Group ARN should be supplied without the
* `path` in order to resolve the correct group resource.
*
* @param scope construct scope
* @param id construct id
* @param groupArn the ARN of the group to import (e.g. `arn:aws:iam::account-id:group/group-name`)
*/
static fromGroupArn(scope: Construct, id: string, groupArn: string): IGroup;
/**
* Import an existing group by given name (with path).
* This method has same caveats of `fromGroupArn`
*
* @param scope construct scope
* @param id construct id
* @param groupName the groupName (path included) of the existing group to import
*/
static fromGroupName(scope: Construct, id: string, groupName: string): IGroup;
/**
* The CfnGroup resource
*/
private readonly _resource;
get groupName(): string;
get groupArn(): string;
private readonly _managedPolicies;
private readonly _path?;
constructor(scope: Construct, id: string, props?: GroupProps);
/**
* Attaches a managed policy to this group. See [IAM and AWS STS quotas, name requirements, and character limits]
* (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-quotas-entities)
* for quota of managed policies attached to an IAM group.
* @param policy The managed policy to attach.
*/
addManagedPolicy(policy: IManagedPolicy): void;
private managedPoliciesExceededWarning;
}
export {};

1
cdk/node_modules/aws-cdk-lib/aws-iam/lib/group.js generated vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,22 @@
import type { IManagedPolicy } from './managed-policy';
import type { Policy } from './policy';
import type { IPrincipal } from './principals';
import type { IResource } from '../../core';
/**
* A construct that represents an IAM principal, such as a user, group or role.
*
* [awslint:interface-extends-ref]
*/
export interface IIdentity extends IPrincipal, IResource {
/**
* Attaches an inline policy to this principal.
* This is the same as calling `policy.addToXxx(principal)`.
* @param policy The policy resource to attach to this principal [disable-awslint:ref-via-interface]
*/
attachInlinePolicy(policy: Policy): void;
/**
* Attaches a managed policy to this principal.
* @param policy The managed policy
*/
addManagedPolicy(policy: IManagedPolicy): void;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});

21
cdk/node_modules/aws-cdk-lib/aws-iam/lib/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,21 @@
export * from './policy-document';
export * from './policy-statement';
export * from './managed-policy';
export * from './role';
export * from './policy';
export * from './user';
export * from './group';
export * from './lazy-role';
export * from './principals';
export * from './identity-base';
export * from './grant';
export * from './unknown-principal';
export * from './oidc-provider';
export * from './oidc-provider-native';
export * from './permissions-boundary';
export * from './saml-provider';
export * from './access-key';
export * from './utils';
export * from './instance-profile';
export * from './role-grants';
export * from './iam.generated';

1
cdk/node_modules/aws-cdk-lib/aws-iam/lib/index.js generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,140 @@
import type { Construct } from 'constructs';
import type { IInstanceProfileRef, InstanceProfileReference } from './iam.generated';
import type { IRole } from './role';
import type { IResource } from '../../core';
import { Resource } from '../../core';
/**
* Represents an IAM Instance Profile
*/
export interface IInstanceProfile extends IResource, IInstanceProfileRef {
/**
* The InstanceProfile's name.
* @attribute
*/
readonly instanceProfileName: string;
/**
* The InstanceProfile's ARN.
* @attribute
*/
readonly instanceProfileArn: string;
/**
* The role associated with the InstanceProfile.
*/
readonly role?: IRole;
}
/**
* Properties of an Instance Profile
*/
export interface InstanceProfileProps {
/**
* An IAM role to associate with the instance profile that is used by EC2 instances.
*
* The role must be assumable by the service principal `ec2.amazonaws.com`:
*
* @example
* const role = new iam.Role(this, 'MyRole', {
* assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com')
* });
*
* @default - a role will be automatically created, it can be accessed via the `role` property
*/
readonly role?: IRole;
/**
* The name of the InstanceProfile to create.
*
* @default - generated by CloudFormation
*/
readonly instanceProfileName?: string;
/**
* The path to the InstanceProfile.
*
* @default /
*/
readonly path?: string;
}
/**
* Attributes of an Instance Profile
*/
export interface InstanceProfileAttributes {
/**
* The ARN of the InstanceProfile.
*
* Format: arn:<partition>:iam::<account-id>:instance-profile/<instance-profile-name-with-path>
*/
readonly instanceProfileArn: string;
/**
* The role associated with the InstanceProfile.
*
* @default - no role
*/
readonly role?: IRole;
}
/**
* Base class for an Instance Profile
*/
declare abstract class InstanceProfileBase extends Resource implements IInstanceProfile {
abstract readonly instanceProfileName: string;
abstract readonly instanceProfileArn: string;
/**
* The role associated with the InstanceProfile.
* @internal
*/
protected _role?: IRole;
/**
* Returns the role associated with this InstanceProfile.
*/
get role(): IRole | undefined;
get instanceProfileRef(): InstanceProfileReference;
}
/**
* IAM Instance Profile
*/
export declare class InstanceProfile extends InstanceProfileBase {
/** Uniquely identifies this class. */
static readonly PROPERTY_INJECTION_ID: string;
/**
* Import an existing InstanceProfile from an InstanceProfile name.
*
* @param scope construct scope
* @param id construct id
* @param instanceProfileName the name of the existing InstanceProfile to import
*/
static fromInstanceProfileName(scope: Construct, id: string, instanceProfileName: string): IInstanceProfile;
/**
* Import an existing InstanceProfile from an InstanceProfile ARN.
*
* If the ARN comes from a Token, the InstanceProfile cannot have a path; if so, any attempt
* to reference its instanceProfileName will fail.
*
* @param scope construct scope
* @param id construct id
* @param instanceProfileArn the ARN of the exiting InstanceProfile to import
*/
static fromInstanceProfileArn(scope: Construct, id: string, instanceProfileArn: string): IInstanceProfile;
/**
* Import an existing InstanceProfile from given InstanceProfile attributes.
*
* If the ARN comes from a Token, the InstanceProfile cannot have a path; if so, any attempt
* to reference its instanceProfileName will fail.
*
* @param scope construct scope
* @param id construct id
* @param attrs the attributes of the InstanceProfile to import
*/
static fromInstanceProfileAttributes(scope: Construct, id: string, attrs: InstanceProfileAttributes): IInstanceProfile;
/**
* The CfnInstanceProfile resource
*/
private readonly _resource;
/**
* Returns the name of this InstanceProfile.
*/
get instanceProfileName(): string;
/**
* Returns the ARN of this InstanceProfile.
*/
get instanceProfileArn(): string;
private readonly _path?;
constructor(scope: Construct, id: string, props?: InstanceProfileProps);
}
export {};

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,81 @@
import type { Construct } from 'constructs';
import type { Grant } from './grant';
import type { RoleReference } from './iam.generated';
import type { IManagedPolicy } from './managed-policy';
import type { Policy } from './policy';
import type { PolicyStatement } from './policy-statement';
import type { AddToPrincipalPolicyResult, IPrincipal, PrincipalPolicyFragment } from './principals';
import type { IRole, RoleProps } from './role';
import * as cdk from '../../core';
/**
* Properties for defining a LazyRole
*/
export interface LazyRoleProps extends RoleProps {
}
/**
* An IAM role that only gets attached to the construct tree once it gets used, not before
*
* This construct can be used to simplify logic in other constructs
* which need to create a role but only if certain configurations occur
* (such as when AutoScaling is configured). The role can be configured in one
* place, but if it never gets used it doesn't get instantiated and will
* not be synthesized or deployed.
*
* @resource AWS::IAM::Role
*/
export declare class LazyRole extends cdk.Resource implements IRole {
private readonly props;
/** Uniquely identifies this class. */
static readonly PROPERTY_INJECTION_ID: string;
readonly grantPrincipal: IPrincipal;
readonly principalAccount: string | undefined;
readonly assumeRoleAction: string;
private role?;
private readonly statements;
private readonly policies;
private readonly managedPolicies;
constructor(scope: Construct, id: string, props: LazyRoleProps);
/**
* Adds a permission to the role's default policy document.
* If there is no default policy attached to this role, it will be created.
* @param statement The permission statement to add to the policy document
*/
addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult;
addToPolicy(statement: PolicyStatement): boolean;
/**
* Attaches a policy to this role.
* @param policy The policy to attach
*/
attachInlinePolicy(policy: Policy): void;
/**
* Attaches a managed policy to this role.
* @param policy The managed policy to attach.
*/
addManagedPolicy(policy: IManagedPolicy): void;
/**
* Returns the ARN of this role.
*/
get roleArn(): string;
get roleRef(): RoleReference;
/**
* Returns the stable and unique string identifying the role (i.e. AIDAJQABLZS4A3QDU576Q)
*
* @attribute
*/
get roleId(): string;
get roleName(): string;
get policyFragment(): PrincipalPolicyFragment;
/**
* Grant the actions defined in actions to the identity Principal on this resource.
*/
grant(identity: IPrincipal, ...actions: string[]): Grant;
/**
* Grant permissions to the given principal to pass this role.
*/
grantPassRole(identity: IPrincipal): Grant;
/**
* Grant permissions to the given principal to assume this role.
*/
grantAssumeRole(identity: IPrincipal): Grant;
private instantiate;
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,187 @@
import type { Construct } from 'constructs';
import type { IGroupRef, IManagedPolicyRef, IUserRef, ManagedPolicyReference } from './iam.generated';
import { PolicyDocument } from './policy-document';
import type { PolicyStatement } from './policy-statement';
import type { IGrantable, IPrincipal } from './principals';
import type { IRole } from './role';
import type { IUser } from './user';
import { Resource } from '../../core';
/**
* A managed policy
*/
export interface IManagedPolicy extends IManagedPolicyRef {
/**
* The ARN of the managed policy
* @attribute
*/
readonly managedPolicyArn: string;
}
/**
* Properties for defining an IAM managed policy
*/
export interface ManagedPolicyProps {
/**
* The name of the managed policy. If you specify multiple policies for an entity,
* specify unique names. For example, if you specify a list of policies for
* an IAM role, each policy must have a unique name.
*
* @default - A name is automatically generated.
*/
readonly managedPolicyName?: string;
/**
* A description of the managed policy. Typically used to store information about the
* permissions defined in the policy. For example, "Grants access to production DynamoDB tables."
* The policy description is immutable. After a value is assigned, it cannot be changed.
*
* @default - empty
*/
readonly description?: string;
/**
* The path for the policy. This parameter allows (through its regex pattern) a string of characters
* consisting of either a forward slash (/) by itself or a string that must begin and end with forward slashes.
* In addition, it can contain any ASCII character from the ! (\u0021) through the DEL character (\u007F),
* including most punctuation characters, digits, and upper and lowercased letters.
*
* For more information about paths, see IAM Identifiers in the IAM User Guide.
*
* @default - "/"
*/
readonly path?: string;
/**
* Users to attach this policy to.
* You can also use `attachToUser(user)` to attach this policy to a user.
*
* @default - No users.
*/
readonly users?: IUser[];
/**
* Roles to attach this policy to.
* You can also use `attachToRole(role)` to attach this policy to a role.
*
* @default - No roles.
*/
readonly roles?: IRole[];
/**
* Groups to attach this policy to.
* You can also use `attachToGroup(group)` to attach this policy to a group.
*
* @default - No groups.
*/
readonly groups?: IGroupRef[];
/**
* Initial set of permissions to add to this policy document.
* You can also use `addPermission(statement)` to add permissions later.
*
* @default - No statements.
*/
readonly statements?: PolicyStatement[];
/**
* Initial PolicyDocument to use for this ManagedPolicy. If omited, any
* `PolicyStatement` provided in the `statements` property will be applied
* against the empty default `PolicyDocument`.
*
* @default - An empty policy.
*/
readonly document?: PolicyDocument;
}
/**
* Managed policy
*
*/
export declare class ManagedPolicy extends Resource implements IManagedPolicy, IGrantable {
/** Uniquely identifies this class. */
static readonly PROPERTY_INJECTION_ID: string;
/**
* Import a customer managed policy from the managedPolicyName.
*
* For this managed policy, you only need to know the name to be able to use it.
*
*/
static fromManagedPolicyName(scope: Construct, id: string, managedPolicyName: string): IManagedPolicy;
/**
* Import an external managed policy by ARN.
*
* For this managed policy, you only need to know the ARN to be able to use it.
* This can be useful if you got the ARN from a CloudFormation Export.
*
* If the imported Managed Policy ARN is a Token (such as a
* `CfnParameter.valueAsString` or a `Fn.importValue()`) *and* the referenced
* managed policy has a `path` (like `arn:...:policy/AdminPolicy/AdminAllow`), the
* `managedPolicyName` property will not resolve to the correct value. Instead it
* will resolve to the first path component. We unfortunately cannot express
* the correct calculation of the full path name as a CloudFormation
* expression. In this scenario the Managed Policy ARN should be supplied without the
* `path` in order to resolve the correct managed policy resource.
*
* @param scope construct scope
* @param id construct id
* @param managedPolicyArn the ARN of the managed policy to import
*/
static fromManagedPolicyArn(scope: Construct, id: string, managedPolicyArn: string): IManagedPolicy;
/**
* Import a managed policy from one of the policies that AWS manages.
*
* For this managed policy, you only need to know the name to be able to use it.
*
* Some managed policy names start with "service-role/", some start with
* "job-function/", and some don't start with anything. Include the
* prefix when constructing this object.
*/
static fromAwsManagedPolicyName(managedPolicyName: string): IManagedPolicy;
/**
* The CfnManagedPolicy resource
*/
private readonly _resource?;
/**
* Returns the ARN of this managed policy.
*
* @attribute
*/
get managedPolicyArn(): string;
/**
* The policy document.
*/
readonly document: PolicyDocument;
/**
* The name of this policy.
*
* @attribute
*/
get managedPolicyName(): string;
/**
* The description of this policy.
*
* @attribute
*/
readonly description: string;
/**
* The path of this policy.
*
* @attribute
*/
readonly path: string;
readonly grantPrincipal: IPrincipal;
private readonly roles;
private readonly users;
private readonly groups;
private readonly _precreatedPolicy?;
constructor(scope: Construct, id: string, props?: ManagedPolicyProps);
get managedPolicyRef(): ManagedPolicyReference;
/**
* Adds a statement to the policy document.
*/
addStatements(...statement: PolicyStatement[]): void;
/**
* Attaches this policy to a user.
*/
attachToUser(user: IUserRef): void;
/**
* Attaches this policy to a role.
*/
attachToRole(role: IRole): void;
/**
* Attaches this policy to a group.
*/
attachToGroup(group: IGroupRef): void;
private validateManagedPolicy;
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,164 @@
import type { Construct } from 'constructs';
import type { IOIDCProviderRef, OIDCProviderReference } from './iam.generated';
import type { IResource, RemovalPolicy } from '../../core';
import { Resource } from '../../core';
/**
* Represents an IAM OpenID Connect provider.
*
*/
export interface IOidcProvider extends IResource, IOIDCProviderRef {
/**
* The Amazon Resource Name (ARN) of the IAM OpenID Connect provider.
*
* @attribute
*/
readonly oidcProviderArn: string;
/**
* The issuer for OIDC Provider
*
* @attribute
*/
readonly oidcProviderIssuer: string;
/**
* Alias for `oidcProviderArn` to maintain backwards compatibility for
* constructs which accept `iam.IOpenIdConnectProvider`.
*
* Use `oidcProviderArn` instead. This property exists for backward compatibility with existing constructs as migrating between the 2 constructs (OpenIdConnectProvider and OidcProviderNative) is not reasonably feasible as it requires a manual step (cdk import) since the resource type is changing between OpenIdConnectProvider and OidcProviderNative.
*/
readonly openIdConnectProviderArn: string;
/**
* Alias for `oidcProviderIssuer` to maintain backwards compatibility for
* constructs which accept `iam.IOpenIdConnectProvider.
*
* Use `oidcProviderIssuer` instead. This property exists for backward compatibility with existing constructs as migrating between the 2 constructs (OpenIdConnectProvider and OidcProviderNative) is not reasonably feasible as it requires a manual step (cdk import) since the resource type is changing between OpenIdConnectProvider and OidcProviderNative.
*/
readonly openIdConnectProviderIssuer: string;
}
/**
* Initialization properties for `OIDCProviderNative`.
*/
export interface OidcProviderNativeProps {
/**
* The name of the Native OIDC Provider.
*
* @default - A name is automatically generated.
*/
readonly oidcProviderName?: string;
/**
* The URL of the identity provider. The URL must begin with https:// and
* should correspond to the iss claim in the provider's OpenID Connect ID
* tokens. Per the OIDC standard, path components are allowed but query
* parameters are not. Typically the URL consists of only a hostname, like
* https://server.example.org or https://example.com.
*
* You cannot register the same provider multiple times in a single AWS
* account. If you try to submit a URL that has already been used for an
* OpenID Connect provider in the AWS account, you will get an error.
*
* Warning: This URL cannot contain any port numbers
*/
readonly url: string;
/**
* A list of client IDs (also known as audiences). When a mobile or web app
* registers with an OpenID Connect provider, they establish a value that
* identifies the application. (This is the value that's sent as the client_id
* parameter on OAuth requests.)
*
* You can register multiple client IDs with the same provider. For example,
* you might have multiple applications that use the same OIDC provider. You
* cannot register more than 100 client IDs with a single IAM OIDC provider.
*
* Client IDs are up to 255 characters long.
*
* @default - no clients are allowed
*/
readonly clientIds?: string[];
/**
* A list of server certificate thumbprints for the OpenID Connect (OIDC)
* identity provider's server certificates.
*
* Typically this list includes only 1 entry or empty. However, IAM lets
* you have up to 5 thumbprints for an OIDC provider. This lets you maintain
* multiple thumbprints if the identity provider is rotating certificates.
*
* The server certificate thumbprint is the hex-encoded SHA-1 hash value of
* the X.509 certificate used by the domain where the OpenID Connect provider
* makes its keys available. It is always a 40-character string.
*
* For example, assume that the OIDC provider is server.example.com and the
* provider stores its keys at https://keys.server.example.com/openid-connect.
* In that case, the thumbprint string would be the hex-encoded SHA-1 hash
* value of the certificate used by https://keys.server.example.com.
*
* This property is optional. If it is not included, IAM will retrieve and use
* the top intermediate certificate authority (CA) thumbprint of the OpenID
* Connect identity provider server certificate.
*
* Obtain the thumbprint of the root certificate authority from the provider's
* server as described in https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html
*
* @default - no thumbprints are allowed. IAM will retrieve and use thumbprint
* of idenity provider server cerctificate
*/
readonly thumbprints?: string[];
/**
* The removal policy to apply to the OpenID Connect Provider.
*
* @default - RemovalPolicy.DESTROY
*/
readonly removalPolicy?: RemovalPolicy;
}
/**
* IAM OIDC identity providers are entities in IAM that describe an external
* identity provider (IdP) service that supports the OpenID Connect (OIDC)
* standard, such as Google or Salesforce. You use an IAM OIDC identity provider
* when you want to establish trust between an OIDC-compatible IdP and your AWS
* account. This is useful when creating a mobile app or web application that
* requires access to AWS resources, but you don't want to create custom sign-in
* code or manage your own user identities.
*
* @see http://openid.net/connect
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc.html
*
* @resource AWS::IAM::OIDCProvider
*/
export declare class OidcProviderNative extends Resource implements IOidcProvider {
/** Uniquely identifies this class. */
static readonly PROPERTY_INJECTION_ID: string;
/**
* Imports an Open ID connect provider from an ARN.
* @param scope The definition scope
* @param id ID of the construct
* @param oidcProviderArn the ARN to import
*/
static fromOidcProviderArn(scope: Construct, id: string, oidcProviderArn: string): IOidcProvider;
private readonly resource;
get openIdConnectProviderArn(): string;
get openIdConnectProviderIssuer(): string;
/**
* Defines a Native OpenID Connect provider.
* @param scope The definition scope
* @param id Construct ID
* @param props Initialization properties
*/
constructor(scope: Construct, id: string, props: OidcProviderNativeProps);
/**
* The Amazon Resource Name (ARN) of the Native IAM OpenID Connect provider.
*
* @attribute
*/
get oidcProviderArn(): string;
/**
* The issuer for the Native OIDC Provider
*
* @attribute
*/
get oidcProviderIssuer(): string;
/**
* The thumbprints configured for this provider.
*
* @attribute
*/
get oidcProviderThumbprints(): string;
get oidcProviderRef(): OIDCProviderReference;
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,141 @@
import type { Construct } from 'constructs';
import type { IOIDCProviderRef, OIDCProviderReference } from './iam.generated';
import type { IResource, RemovalPolicy } from '../../core';
import { Resource } from '../../core';
/**
* Represents an IAM OpenID Connect provider.
*
*/
export interface IOpenIdConnectProvider extends IResource, IOIDCProviderRef {
/**
* The Amazon Resource Name (ARN) of the IAM OpenID Connect provider.
*/
readonly openIdConnectProviderArn: string;
/**
* The issuer for OIDC Provider
*/
readonly openIdConnectProviderIssuer: string;
}
/**
* Initialization properties for `OpenIdConnectProvider`.
*/
export interface OpenIdConnectProviderProps {
/**
* The URL of the identity provider. The URL must begin with https:// and
* should correspond to the iss claim in the provider's OpenID Connect ID
* tokens. Per the OIDC standard, path components are allowed but query
* parameters are not. Typically the URL consists of only a hostname, like
* https://server.example.org or https://example.com.
*
* You cannot register the same provider multiple times in a single AWS
* account. If you try to submit a URL that has already been used for an
* OpenID Connect provider in the AWS account, you will get an error.
*/
readonly url: string;
/**
* A list of client IDs (also known as audiences). When a mobile or web app
* registers with an OpenID Connect provider, they establish a value that
* identifies the application. (This is the value that's sent as the client_id
* parameter on OAuth requests.)
*
* You can register multiple client IDs with the same provider. For example,
* you might have multiple applications that use the same OIDC provider. You
* cannot register more than 100 client IDs with a single IAM OIDC provider.
*
* Client IDs are up to 255 characters long.
*
* @default - no clients are allowed
*/
readonly clientIds?: string[];
/**
* A list of server certificate thumbprints for the OpenID Connect (OIDC)
* identity provider's server certificates.
*
* Typically this list includes only one entry. However, IAM lets you have up
* to five thumbprints for an OIDC provider. This lets you maintain multiple
* thumbprints if the identity provider is rotating certificates.
*
* The server certificate thumbprint is the hex-encoded SHA-1 hash value of
* the X.509 certificate used by the domain where the OpenID Connect provider
* makes its keys available. It is always a 40-character string.
*
* You must provide at least one thumbprint when creating an IAM OIDC
* provider. For example, assume that the OIDC provider is server.example.com
* and the provider stores its keys at
* https://keys.server.example.com/openid-connect. In that case, the
* thumbprint string would be the hex-encoded SHA-1 hash value of the
* certificate used by https://keys.server.example.com.
*
* @default - If no thumbprints are specified (an empty array or `undefined`),
* the thumbprint of the root certificate authority will be obtained from the
* provider's server as described in https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html
*/
readonly thumbprints?: string[];
/**
* The removal policy to apply to the OpenID Connect Provider
*
* @default - RemovalPolicy.DESTROY
*/
readonly removalPolicy?: RemovalPolicy;
}
/**
* IAM OIDC identity providers are entities in IAM that describe an external
* identity provider (IdP) service that supports the OpenID Connect (OIDC)
* standard, such as Google or Salesforce. You use an IAM OIDC identity provider
* when you want to establish trust between an OIDC-compatible IdP and your AWS
* account. This is useful when creating a mobile app or web application that
* requires access to AWS resources, but you don't want to create custom sign-in
* code or manage your own user identities.
*
* ⚠️ **IMPORTANT NOTICE FOR CONTRIBUTORS** ⚠️
*
* **DO NOT ADD NEW FEATURES TO THIS CONSTRUCT**
*
* This construct uses a custom resource with Lambda functions and is maintained
* for backward compatibility only. We cannot deprecate it due to its usage in
* existing services like EKS (see https://github.com/aws/aws-cdk/pull/28634#discussion_r1842962697).
*
* For new functionality, developers should use `OidcProviderNative` instead, which
* utilizes the native CloudFormation resource `AWS::IAM::OIDCProvider` and provides
* the same functionality with less complexity.
*
* If you are considering adding features to this construct, please:
* 1. Consider implementing the feature in `OidcProviderNative` instead
* 2. Discuss with the CDK team before proceeding
* 3. Ensure any changes maintain strict backward compatibility
*
* @see http://openid.net/connect
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc.html
*
* @resource AWS::CloudFormation::CustomResource
*/
export declare class OpenIdConnectProvider extends Resource implements IOpenIdConnectProvider {
/** Uniquely identifies this class. */
static readonly PROPERTY_INJECTION_ID: string;
/**
* Imports an Open ID connect provider from an ARN.
* @param scope The definition scope
* @param id ID of the construct
* @param openIdConnectProviderArn the ARN to import
*/
static fromOpenIdConnectProviderArn(scope: Construct, id: string, openIdConnectProviderArn: string): IOpenIdConnectProvider;
private readonly resource;
/**
* Defines an OpenID Connect provider.
* @param scope The definition scope
* @param id Construct ID
* @param props Initialization properties
*/
constructor(scope: Construct, id: string, props: OpenIdConnectProviderProps);
/**
* The Amazon Resource Name (ARN) of the IAM OpenID Connect provider.
*/
get openIdConnectProviderArn(): string;
get openIdConnectProviderIssuer(): string;
/**
* The thumbprints configured for this provider.
*/
get openIdConnectProviderthumbprints(): string;
get oidcProviderRef(): OIDCProviderReference;
private getOrCreateProvider;
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,31 @@
import type { IConstruct } from 'constructs';
import type { IManagedPolicy } from './managed-policy';
/**
* Modify the Permissions Boundaries of Users and Roles in a construct tree
*
* ```ts
* const policy = iam.ManagedPolicy.fromAwsManagedPolicyName('ReadOnlyAccess');
* iam.PermissionsBoundary.of(this).apply(policy);
* ```
*/
export declare class PermissionsBoundary {
private readonly scope;
/**
* Access the Permissions Boundaries of a construct tree
*/
static of(scope: IConstruct): PermissionsBoundary;
private constructor();
/**
* Apply the given policy as Permissions Boundary to all Roles and Users in
* the scope.
*
* Will override any Permissions Boundaries configured previously; in case
* a Permission Boundary is applied in multiple scopes, the Boundary applied
* closest to the Role wins.
*/
apply(boundaryPolicy: IManagedPolicy): void;
/**
* Remove previously applied Permissions Boundaries
*/
clear(): void;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PermissionsBoundary=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var iam_generated_1=()=>{var tmp=require("./iam.generated");return iam_generated_1=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},aspect_prio_1=()=>{var tmp=require("../../core/lib/private/aspect-prio");return aspect_prio_1=()=>tmp,tmp};class PermissionsBoundary{scope;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_iam.PermissionsBoundary",version:"2.252.0"};static of(scope){return new PermissionsBoundary(scope)}constructor(scope){this.scope=scope}apply(boundaryPolicy){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IManagedPolicy(boundaryPolicy)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.apply),error}core_1().Aspects.of(this.scope).add({visit(node){core_1().CfnResource.isCfnResource(node)&&(node.cfnResourceType==iam_generated_1().CfnRole.CFN_RESOURCE_TYPE_NAME||node.cfnResourceType==iam_generated_1().CfnUser.CFN_RESOURCE_TYPE_NAME)&&node.addPropertyOverride("PermissionsBoundary",boundaryPolicy.managedPolicyArn)}},{priority:(0,aspect_prio_1().mutatingAspectPrio32333)(this.scope)})}clear(){core_1().Aspects.of(this.scope).add({visit(node){core_1().CfnResource.isCfnResource(node)&&(node.cfnResourceType==iam_generated_1().CfnRole.CFN_RESOURCE_TYPE_NAME||node.cfnResourceType==iam_generated_1().CfnUser.CFN_RESOURCE_TYPE_NAME)&&node.addPropertyDeletionOverride("PermissionsBoundary")}},{priority:(0,aspect_prio_1().mutatingAspectPrio32333)(this.scope)})}}exports.PermissionsBoundary=PermissionsBoundary;

View File

@@ -0,0 +1,132 @@
import type { IConstruct } from 'constructs';
import { PolicyStatement } from './policy-statement';
import * as cdk from '../../core';
/**
* Properties for a new PolicyDocument
*/
export interface PolicyDocumentProps {
/**
* Automatically assign Statement Ids to all statements
*
* @default false
*/
readonly assignSids?: boolean;
/**
* Initial statements to add to the policy document
*
* @default - No statements
*/
readonly statements?: PolicyStatement[];
/**
* Try to minimize the policy by merging statements
*
* To avoid overrunning the maximum policy size, combine statements if they produce
* the same result. Merging happens according to the following rules:
*
* - The Effect of both statements is the same
* - Neither of the statements have a 'Sid'
* - Combine Principals if the rest of the statement is exactly the same.
* - Combine Resources if the rest of the statement is exactly the same.
* - Combine Actions if the rest of the statement is exactly the same.
* - We will never combine NotPrincipals, NotResources or NotActions, because doing
* so would change the meaning of the policy document.
*
* @default - false, unless the feature flag `@aws-cdk/aws-iam:minimizePolicies` is set
*/
readonly minimize?: boolean;
}
/**
* A PolicyDocument is a collection of statements
*/
export declare class PolicyDocument implements cdk.IResolvable {
/**
* Creates a new PolicyDocument based on the object provided.
* This will accept an object created from the `.toJSON()` call
* @param obj the PolicyDocument in object form.
*/
static fromJson(obj: any): PolicyDocument;
readonly creationStack: string[];
private readonly statements;
private readonly autoAssignSids;
private readonly minimize?;
constructor(props?: PolicyDocumentProps);
resolve(context: cdk.IResolveContext): any;
/**
* Whether the policy document contains any statements.
*/
get isEmpty(): boolean;
/**
* The number of statements already added to this policy.
* Can be used, for example, to generate unique "sid"s within the policy.
*/
get statementCount(): number;
/**
* Adds a statement to the policy document.
*
* @param statement the statement to add.
*/
addStatements(...statement: PolicyStatement[]): void;
/**
* Encode the policy document as a string
*/
toString(): string;
/**
* JSON-ify the document
*
* Used when JSON.stringify() is called
*/
toJSON(): any;
/**
* Validate that all policy statements in the policy document satisfies the
* requirements for any policy.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json
*
* @returns An array of validation error messages, or an empty array if the document is valid.
*/
validateForAnyPolicy(): string[];
/**
* Validate that all policy statements in the policy document satisfies the
* requirements for a resource-based policy.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json
*
* @returns An array of validation error messages, or an empty array if the document is valid.
*/
validateForResourcePolicy(): string[];
/**
* Validate that all policy statements in the policy document satisfies the
* requirements for an identity-based policy.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json
*
* @returns An array of validation error messages, or an empty array if the document is valid.
*/
validateForIdentityPolicy(): string[];
/**
* Perform statement merging (if enabled and not done yet)
*
* @internal
*/
_maybeMergeStatements(scope: IConstruct): void;
/**
* Split the statements of the PolicyDocument into multiple groups, limited by their size
*
* We do a round of size-limited merging first (making sure to not produce statements too
* large to fit into standalone policies), so that we can most accurately estimate total
* policy size. Another final round of minimization will be done just before rendering to
* end up with minimal policies that look nice to humans.
*
* Return a map of the final set of policy documents, mapped to the ORIGINAL (pre-merge)
* PolicyStatements that ended up in the given PolicyDocument.
*
* @internal
*/
_splitDocument(scope: IConstruct, selfMaximumSize: number, splitMaximumSize: number): Map<PolicyDocument, PolicyStatement[]>;
private render;
private shouldMerge;
/**
* Freeze all statements
*/
private freezeStatements;
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,440 @@
import type { IConstruct } from 'constructs';
import type { IPrincipal, ServicePrincipalOpts } from './principals';
/**
* Represents a statement in an IAM policy document.
*/
export declare class PolicyStatement {
/**
* Uniquely identifies this class.
*/
static readonly PROPERTY_INJECTION_ID: string;
/**
* Creates a new PolicyStatement based on the object provided.
* This will accept an object created from the `.toJSON()` call
* @param obj the PolicyStatement in object form.
*/
static fromJson(obj: any): PolicyStatement;
private readonly _action;
private readonly _notAction;
private readonly _principal;
private readonly _notPrincipal;
private readonly _resource;
private readonly _notResource;
private readonly _condition;
private _sid?;
private _effect;
private principalConditionsJson?;
private readonly _principals;
private readonly _notPrincipals;
private _frozen;
constructor(props?: PolicyStatementProps);
/**
* Statement ID for this statement
*/
get sid(): string | undefined;
/**
* Set Statement ID for this statement
*/
set sid(sid: string | undefined);
/**
* Whether to allow or deny the actions in this statement
*/
get effect(): Effect;
/**
* Set effect for this statement
*/
set effect(effect: Effect);
/**
* Specify allowed actions into the "Action" section of the policy statement.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html
*
* @param actions actions that will be allowed.
*/
addActions(...actions: string[]): void;
/**
* Explicitly allow all actions except the specified list of actions into the "NotAction" section
* of the policy document.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notaction.html
*
* @param notActions actions that will be denied. All other actions will be permitted.
*/
addNotActions(...notActions: string[]): void;
/**
* Indicates if this permission has a "Principal" section.
*/
get hasPrincipal(): boolean;
/**
* Adds principals to the "Principal" section of a policy statement.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html
*
* @param principals IAM principals that will be added
*/
addPrincipals(...principals: IPrincipal[]): void;
/**
* Specify principals that is not allowed or denied access to the "NotPrincipal" section of
* a policy statement.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html
*
* @param notPrincipals IAM principals that will be denied access
*/
addNotPrincipals(...notPrincipals: IPrincipal[]): void;
private validatePolicyActions;
private validatePolicyPrincipal;
/**
* Specify AWS account ID as the principal entity to the "Principal" section of a policy statement.
*/
addAwsAccountPrincipal(accountId: string): void;
/**
* Specify a principal using the ARN identifier of the principal.
* You cannot specify IAM groups and instance profiles as principals.
*
* @param arn ARN identifier of AWS account, IAM user, or IAM role (i.e. arn:aws:iam::123456789012:user/user-name)
*/
addArnPrincipal(arn: string): void;
/**
* Adds a service principal to this policy statement.
*
* @param service the service name for which a service principal is requested (e.g: `s3.amazonaws.com`).
* @param opts options for adding the service principal (such as specifying a principal in a different region)
*/
addServicePrincipal(service: string, opts?: ServicePrincipalOpts): void;
/**
* Adds a federated identity provider such as Amazon Cognito to this policy statement.
*
* @param federated federated identity provider (i.e. 'cognito-identity.amazonaws.com')
* @param conditions The conditions under which the policy is in effect.
* See [the IAM documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html).
*/
addFederatedPrincipal(federated: any, conditions: Conditions): void;
/**
* Adds an AWS account root user principal to this policy statement
*/
addAccountRootPrincipal(): void;
/**
* Adds a canonical user ID principal to this policy document
*
* @param canonicalUserId unique identifier assigned by AWS for every account
*/
addCanonicalUserPrincipal(canonicalUserId: string): void;
/**
* Adds all identities in all accounts ("*") to this policy statement
*/
addAnyPrincipal(): void;
/**
* Specify resources that this policy statement applies into the "Resource" section of
* this policy statement.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html
*
* @param arns Amazon Resource Names (ARNs) of the resources that this policy statement applies to
*/
addResources(...arns: string[]): void;
/**
* Specify resources that this policy statement will not apply to in the "NotResource" section
* of this policy statement. All resources except the specified list will be matched.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notresource.html
*
* @param arns Amazon Resource Names (ARNs) of the resources that this policy statement does not apply to
*/
addNotResources(...arns: string[]): void;
/**
* Adds a ``"*"`` resource to this statement.
*/
addAllResources(): void;
/**
* Indicates if this permission has at least one resource associated with it.
*/
get hasResource(): boolean;
/**
* Add a condition to the Policy
*
* If multiple calls are made to add a condition with the same operator and field, only
* the last one wins. For example:
*
* ```ts
* declare const stmt: iam.PolicyStatement;
*
* stmt.addCondition('StringEquals', { 'aws:SomeField': '1' });
* stmt.addCondition('StringEquals', { 'aws:SomeField': '2' });
* ```
*
* Will end up with the single condition `StringEquals: { 'aws:SomeField': '2' }`.
*
* If you meant to add a condition to say that the field can be *either* `1` or `2`, write
* this:
*
* ```ts
* declare const stmt: iam.PolicyStatement;
*
* stmt.addCondition('StringEquals', { 'aws:SomeField': ['1', '2'] });
* ```
*/
addCondition(key: string, value: Condition): void;
/**
* Add multiple conditions to the Policy
*
* See the `addCondition` function for a caveat on calling this method multiple times.
*/
addConditions(conditions: Conditions): void;
/**
* Add a `StringEquals` condition that limits to a given account from `sts:ExternalId`.
*
* This method can only be called once: subsequent calls will overwrite earlier calls.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html
*/
addAccountCondition(accountId: string): void;
/**
* Add an `StringEquals` condition that limits to a given account from `aws:SourceAccount`.
*
* This method can only be called once: subsequent calls will overwrite earlier calls.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount
*/
addSourceAccountCondition(accountId: string): void;
/**
* Add an `ArnEquals` condition that limits to a given resource arn from `aws:SourceArn`.
*
* This method can only be called once: subsequent calls will overwrite earlier calls.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn
*/
addSourceArnCondition(arn: string): void;
/**
* Create a new `PolicyStatement` with the same exact properties
* as this one, except for the overrides
*/
copy(overrides?: PolicyStatementProps): PolicyStatement;
/**
* JSON-ify the policy statement
*
* Used when JSON.stringify() is called
*/
toStatementJson(): any;
/**
* String representation of this policy statement
*/
toString(): string;
/**
* JSON-ify the statement
*
* Used when JSON.stringify() is called
*/
toJSON(): any;
/**
* Add a principal's conditions
*
* For convenience, principals have been modeled as both a principal
* and a set of conditions. This makes it possible to have a single
* object represent e.g. an "SNS Topic" (SNS service principal + aws:SourcArn
* condition) or an Organization member (* + aws:OrgId condition).
*
* However, when using multiple principals in the same policy statement,
* they must all have the same conditions or the OR samentics
* implied by a list of principals cannot be guaranteed (user needs to
* add multiple statements in that case).
*/
private addPrincipalConditions;
/**
* Validate that the policy statement satisfies base requirements for a policy.
*
* @returns An array of validation error messages, or an empty array if the statement is valid.
*/
validateForAnyPolicy(): string[];
/**
* Validate that the policy statement satisfies all requirements for a resource-based policy.
*
* @returns An array of validation error messages, or an empty array if the statement is valid.
*/
validateForResourcePolicy(): string[];
/**
* Validate that the policy statement satisfies all requirements for an identity-based policy.
*
* @returns An array of validation error messages, or an empty array if the statement is valid.
*/
validateForIdentityPolicy(): string[];
/**
* The Actions added to this statement
*/
get actions(): string[];
/**
* The NotActions added to this statement
*/
get notActions(): string[];
/**
* The Principals added to this statement
*/
get principals(): IPrincipal[];
/**
* The NotPrincipals added to this statement
*/
get notPrincipals(): IPrincipal[];
/**
* The Resources added to this statement
*/
get resources(): string[];
/**
* The NotResources added to this statement
*/
get notResources(): string[];
/**
* The conditions added to this statement
*/
get conditions(): any;
/**
* Make the PolicyStatement immutable
*
* After calling this, any of the `addXxx()` methods will throw an exception.
*
* Libraries that lazily generate statement bodies can override this method to
* fill the actual PolicyStatement fields. Be aware that this method may be called
* multiple times.
*/
freeze(): PolicyStatement;
/**
* Whether the PolicyStatement has been frozen
*
* The statement object is frozen when `freeze()` is called.
*/
get frozen(): boolean;
/**
* Estimate the size of this policy statement
*
* By necessity, this will not be accurate. We'll do our best to overestimate
* so we won't have nasty surprises.
*
* @internal
*/
_estimateSize(options: EstimateSizeOptions): number;
/**
* Throw an exception when the object is frozen
*/
private assertNotFrozen;
}
/**
* The Effect element of an IAM policy
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_effect.html
*/
export declare enum Effect {
/**
* Allows access to a resource in an IAM policy statement. By default, access to resources are denied.
*/
ALLOW = "Allow",
/**
* Explicitly deny access to a resource. By default, all requests are denied implicitly.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html
*/
DENY = "Deny"
}
/**
* Condition for when an IAM policy is in effect. Maps from the keys in a request's context to
* a string value or array of string values. See the Conditions interface for more details.
*/
export type Condition = unknown;
/**
* Conditions for when an IAM Policy is in effect, specified in the following structure:
*
* `{ "Operator": { "keyInRequestContext": "value" } }`
*
* The value can be either a single string value or an array of string values.
*
* For more information, including which operators are supported, see [the IAM
* documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html).
*/
export type Conditions = Record<string, Condition>;
/**
* Interface for creating a policy statement
*/
export interface PolicyStatementProps {
/**
* The Sid (statement ID) is an optional identifier that you provide for the
* policy statement. You can assign a Sid value to each statement in a
* statement array. In services that let you specify an ID element, such as
* SQS and SNS, the Sid value is just a sub-ID of the policy document's ID. In
* IAM, the Sid value must be unique within a JSON policy.
*
* @default - no sid
*/
readonly sid?: string;
/**
* List of actions to add to the statement
*
* @default - no actions
*/
readonly actions?: string[];
/**
* List of not actions to add to the statement
*
* @default - no not-actions
*/
readonly notActions?: string[];
/**
* List of principals to add to the statement
*
* @default - no principals
*/
readonly principals?: IPrincipal[];
/**
* List of not principals to add to the statement
*
* @default - no not principals
*/
readonly notPrincipals?: IPrincipal[];
/**
* Resource ARNs to add to the statement
*
* @default - no resources
*/
readonly resources?: string[];
/**
* NotResource ARNs to add to the statement
*
* @default - no not-resources
*/
readonly notResources?: string[];
/**
* Conditions to add to the statement
*
* @default - no condition
*/
readonly conditions?: {
[key: string]: any;
};
/**
* Whether to allow or deny the actions in this statement
*
* @default Effect.ALLOW
*/
readonly effect?: Effect;
}
/**
* Options for _estimateSize
*
* These can optionally come from context, but it's too expensive to look
* them up every time so we bundle them into a struct first.
*
* @internal
*/
export interface EstimateSizeOptions {
/**
* Estimated size of an unresolved ARN
*/
readonly arnEstimate: number;
/**
* Estimated size of an unresolved action
*/
readonly actionEstimate: number;
}
/**
* Derive the size estimation options from context
*
* @internal
*/
export declare function deriveEstimateSizeOptions(scope: IConstruct): EstimateSizeOptions;

File diff suppressed because one or more lines are too long

145
cdk/node_modules/aws-cdk-lib/aws-iam/lib/policy.d.ts generated vendored Normal file
View File

@@ -0,0 +1,145 @@
import type { Construct } from 'constructs';
import type { IGroup } from './group';
import type { IPolicyRef, PolicyReference } from './iam.generated';
import { PolicyDocument } from './policy-document';
import type { PolicyStatement } from './policy-statement';
import type { IGrantable, IPrincipal } from './principals';
import type { IRole } from './role';
import type { IUser } from './user';
import type { IResource } from '../../core';
import { Resource } from '../../core';
/**
* Represents an IAM Policy
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html
*/
export interface IPolicy extends IResource, IPolicyRef {
/**
* The name of this policy.
*
* @attribute
*/
readonly policyName: string;
}
/**
* Properties for defining an IAM inline policy document
*/
export interface PolicyProps {
/**
* The name of the policy. If you specify multiple policies for an entity,
* specify unique names. For example, if you specify a list of policies for
* an IAM role, each policy must have a unique name.
*
* @default - Uses the logical ID of the policy resource, which is ensured
* to be unique within the stack.
*/
readonly policyName?: string;
/**
* Users to attach this policy to.
* You can also use `attachToUser(user)` to attach this policy to a user.
*
* @default - No users.
*/
readonly users?: IUser[];
/**
* Roles to attach this policy to.
* You can also use `attachToRole(role)` to attach this policy to a role.
*
* @default - No roles.
*/
readonly roles?: IRole[];
/**
* Groups to attach this policy to.
* You can also use `attachToGroup(group)` to attach this policy to a group.
*
* @default - No groups.
*/
readonly groups?: IGroup[];
/**
* Initial set of permissions to add to this policy document.
* You can also use `addStatements(...statement)` to add permissions later.
*
* @default - No statements.
*/
readonly statements?: PolicyStatement[];
/**
* Force creation of an `AWS::IAM::Policy`
*
* Unless set to `true`, this `Policy` construct will not materialize to an
* `AWS::IAM::Policy` CloudFormation resource in case it would have no effect
* (for example, if it remains unattached to an IAM identity or if it has no
* statements). This is generally desired behavior, since it prevents
* creating invalid--and hence undeployable--CloudFormation templates.
*
* In cases where you know the policy must be created and it is actually
* an error if no statements have been added to it or it remains unattached to
* an IAM identity, you can set this to `true`.
*
* @default false
*/
readonly force?: boolean;
/**
* Initial PolicyDocument to use for this Policy. If omited, any
* `PolicyStatement` provided in the `statements` property will be applied
* against the empty default `PolicyDocument`.
*
* @default - An empty policy.
*/
readonly document?: PolicyDocument;
}
/**
* The AWS::IAM::Policy resource associates an [inline](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#inline)
* IAM policy with IAM users, roles, or groups. For more information about IAM policies, see
* [Overview of IAM Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies_overview.html)
* in the IAM User Guide guide.
*/
export declare class Policy extends Resource implements IPolicy, IGrantable {
/**
* Uniquely identifies this class.
*/
static readonly PROPERTY_INJECTION_ID: string;
/**
* Import a policy in this app based on its name
*/
static fromPolicyName(scope: Construct, id: string, policyName: string): IPolicy;
/**
* The policy document.
*/
readonly document: PolicyDocument;
readonly grantPrincipal: IPrincipal;
readonly policyRef: PolicyReference;
private readonly _policyName;
private readonly roles;
private readonly users;
private readonly groups;
private readonly force;
private referenceTaken;
constructor(scope: Construct, id: string, props?: PolicyProps);
/**
* Adds a statement to the policy document.
*/
addStatements(...statement: PolicyStatement[]): void;
/**
* Attaches this policy to a user.
*/
attachToUser(user: IUser): void;
/**
* Attaches this policy to a role.
*/
attachToRole(role: IRole): void;
/**
* Attaches this policy to a group.
*/
attachToGroup(group: IGroup): void;
/**
* The name of this policy.
*
* @attribute
*/
get policyName(): string;
private validatePolicy;
/**
* Whether the policy resource has been attached to any identity
*/
private get isAttached();
}

1
cdk/node_modules/aws-cdk-lib/aws-iam/lib/policy.js generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,566 @@
import type { IDependable } from 'constructs';
import type { IOIDCProviderRef, ISAMLProviderRef } from './iam.generated';
import type { PolicyDocument } from './policy-document';
import type { Condition, Conditions } from './policy-statement';
import { PolicyStatement } from './policy-statement';
import type { ISamlProvider } from './saml-provider';
/**
* Any object that has an associated principal that a permission can be granted to
*/
export interface IGrantable {
/**
* The principal to grant permissions to
*/
readonly grantPrincipal: IPrincipal;
}
/**
* Represents a logical IAM principal.
*
* An IPrincipal describes a logical entity that can perform AWS API calls
* against sets of resources, optionally under certain conditions.
*
* Examples of simple principals are IAM objects that you create, such
* as Users or Roles.
*
* An example of a more complex principals is a `ServicePrincipal` (such as
* `new ServicePrincipal("sns.amazonaws.com")`, which represents the Simple
* Notifications Service).
*
* A single logical Principal may also map to a set of physical principals.
* For example, `new OrganizationPrincipal('o-12345abcde')` represents all
* identities that are part of the given AWS Organization.
*/
export interface IPrincipal extends IGrantable {
/**
* When this Principal is used in an AssumeRole policy, the action to use.
*/
readonly assumeRoleAction: string;
/**
* Return the policy fragment that identifies this principal in a Policy.
*/
readonly policyFragment: PrincipalPolicyFragment;
/**
* The AWS account ID of this principal.
* Can be undefined when the account is not known
* (for example, for service principals).
* Can be a Token - in that case,
* it's assumed to be AWS::AccountId.
*/
readonly principalAccount?: string | undefined;
/**
* Add to the policy of this principal.
*/
addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult;
}
/**
* Interface for principals that can be compared.
*
* This only needs to be implemented for principals that could potentially be value-equal.
* Identity-equal principals will be handled correctly by default.
*/
export interface IComparablePrincipal extends IPrincipal {
/**
* Return a string format of this principal which should be identical if the two
* principals are the same.
*/
dedupeString(): string | undefined;
}
/**
* Helper class for working with `IComparablePrincipal`s
*/
export declare class ComparablePrincipal {
/**
* Whether or not the given principal is a comparable principal
*/
static isComparablePrincipal(this: void, x: IPrincipal): x is IComparablePrincipal;
/**
* Return the dedupeString of the given principal, if available
*/
static dedupeStringFor(this: void, x: IPrincipal): string | undefined;
}
/**
* A type of principal that has more control over its own representation in AssumeRolePolicyDocuments
*
* More complex types of identity providers need more control over Role's policy documents
* than simply `{ Effect: 'Allow', Action: 'AssumeRole', Principal: <Whatever> }`.
*
* If that control is necessary, they can implement `IAssumeRolePrincipal` to get full
* access to a Role's AssumeRolePolicyDocument.
*/
export interface IAssumeRolePrincipal extends IPrincipal {
/**
* Add the principal to the AssumeRolePolicyDocument
*
* Add the statements to the AssumeRolePolicyDocument necessary to give this principal
* permissions to assume the given role.
*/
addToAssumeRolePolicy(document: PolicyDocument): void;
}
/**
* Result of calling `addToPrincipalPolicy`
*/
export interface AddToPrincipalPolicyResult {
/**
* Whether the statement was added to the identity's policies.
*
*/
readonly statementAdded: boolean;
/**
* Dependable which allows depending on the policy change being applied
*
* @default - Required if `statementAdded` is true.
*/
readonly policyDependable?: IDependable;
}
/**
* Base class for policy principals
*/
export declare abstract class PrincipalBase implements IAssumeRolePrincipal, IComparablePrincipal {
readonly grantPrincipal: IPrincipal;
readonly principalAccount: string | undefined;
/**
* Return the policy fragment that identifies this principal in a Policy.
*/
abstract readonly policyFragment: PrincipalPolicyFragment;
/**
* When this Principal is used in an AssumeRole policy, the action to use.
*/
readonly assumeRoleAction: string;
addToPolicy(statement: PolicyStatement): boolean;
addToPrincipalPolicy(_statement: PolicyStatement): AddToPrincipalPolicyResult;
addToAssumeRolePolicy(document: PolicyDocument): void;
toString(): string;
/**
* JSON-ify the principal
*
* Used when JSON.stringify() is called
*/
toJSON(): {
[key: string]: string[];
};
/**
* Returns a new PrincipalWithConditions using this principal as the base, with the
* passed conditions added.
*
* When there is a value for the same operator and key in both the principal and the
* conditions parameter, the value from the conditions parameter will be used.
*
* @returns a new PrincipalWithConditions object.
*/
withConditions(conditions: Conditions): PrincipalBase;
/**
* Returns a new principal using this principal as the base, with session tags enabled.
*
* @returns a new SessionTagsPrincipal object.
*/
withSessionTags(): PrincipalBase;
/**
* Return whether or not this principal is equal to the given principal
*/
abstract dedupeString(): string | undefined;
}
/**
* Base class for Principals that wrap other principals
*/
declare abstract class PrincipalAdapter extends PrincipalBase {
protected readonly wrapped: IPrincipal;
readonly assumeRoleAction: IPrincipal['assumeRoleAction'];
readonly principalAccount: IPrincipal['principalAccount'];
constructor(wrapped: IPrincipal);
get policyFragment(): PrincipalPolicyFragment;
addToPolicy(statement: PolicyStatement): boolean;
addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult;
/**
* Append the given string to the wrapped principal's dedupe string (if available)
*/
protected appendDedupe(append: string): string | undefined;
}
/**
* An IAM principal with additional conditions specifying when the policy is in effect.
*
* For more information about conditions, see:
* https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html
*/
export declare class PrincipalWithConditions extends PrincipalAdapter {
private additionalConditions;
constructor(principal: IPrincipal, conditions: Conditions);
addToAssumeRolePolicy(doc: PolicyDocument): void;
/**
* Add a condition to the principal
*/
addCondition(key: string, value: Condition): void;
/**
* Adds multiple conditions to the principal
*
* Values from the conditions parameter will overwrite existing values with the same operator
* and key.
*/
addConditions(conditions: Conditions): void;
/**
* The conditions under which the policy is in effect.
* See [the IAM documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html).
*/
get conditions(): Conditions;
get policyFragment(): PrincipalPolicyFragment;
toString(): string;
/**
* JSON-ify the principal
*
* Used when JSON.stringify() is called
*/
toJSON(): {
[key: string]: string[];
};
dedupeString(): string | undefined;
private mergeConditions;
}
/**
* Enables session tags on role assumptions from a principal
*
* For more information on session tags, see:
* https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html
*/
export declare class SessionTagsPrincipal extends PrincipalAdapter {
constructor(principal: IPrincipal);
addToAssumeRolePolicy(doc: PolicyDocument): void;
dedupeString(): string | undefined;
}
/**
* A collection of the fields in a PolicyStatement that can be used to identify a principal.
*
* This consists of the JSON used in the "Principal" field, and optionally a
* set of "Condition"s that need to be applied to the policy.
*
* Generally, a principal looks like:
*
* { '<TYPE>': ['ID', 'ID', ...] }
*
* And this is also the type of the field `principalJson`. However, there is a
* special type of principal that is just the string '*', which is treated
* differently by some services. To represent that principal, `principalJson`
* should contain `{ 'LiteralString': ['*'] }`.
*/
export declare class PrincipalPolicyFragment {
readonly principalJson: {
[key: string]: string[];
};
/**
* The conditions under which the policy is in effect.
* See [the IAM documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html).
*/
readonly conditions: Conditions;
/**
*
* @param principalJson JSON of the "Principal" section in a policy statement
* @param conditions conditions that need to be applied to this policy
*/
constructor(principalJson: {
[key: string]: string[];
},
/**
* The conditions under which the policy is in effect.
* See [the IAM documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html).
*/
conditions?: Conditions);
}
/**
* Specify a principal by the Amazon Resource Name (ARN).
* You can specify AWS accounts, IAM users, Federated SAML users, IAM roles, and specific assumed-role sessions.
* You cannot specify IAM groups or instance profiles as principals
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html
*/
export declare class ArnPrincipal extends PrincipalBase {
readonly arn: string;
/**
*
* @param arn Amazon Resource Name (ARN) of the principal entity (i.e. arn:aws:iam::123456789012:user/user-name)
*/
constructor(arn: string);
get policyFragment(): PrincipalPolicyFragment;
toString(): string;
/**
* A convenience method for adding a condition that the principal is part of the specified
* AWS Organization.
*/
inOrganization(organizationId: string): PrincipalBase;
dedupeString(): string | undefined;
}
/**
* Specify AWS account ID as the principal entity in a policy to delegate authority to the account.
*/
export declare class AccountPrincipal extends ArnPrincipal {
readonly accountId: any;
readonly principalAccount: string | undefined;
/**
*
* @param accountId AWS account ID (i.e. '123456789012')
*/
constructor(accountId: any);
toString(): string;
}
/**
* Options for a service principal.
*/
export interface ServicePrincipalOpts {
/**
* The region in which you want to reference the service
*
* This is only necessary for *cross-region* references to *opt-in* regions. In those
* cases, the region name needs to be included to reference the correct service principal.
* In all other cases, the global service principal name is sufficient.
*
* This field behaves differently depending on whether the `@aws-cdk/aws-iam:standardizedServicePrincipals`
* flag is set or not:
*
* - If the flag is set, the input service principal is assumed to be of the form `SERVICE.amazonaws.com`.
* That value will always be returned, unless the given region is an opt-in region and the service
* principal is rendered in a stack in a different region, in which case `SERVICE.REGION.amazonaws.com`
* will be rendered. Under this regime, there is no downside to always specifying the region property:
* it will be rendered only if necessary.
* - If the flag is not set, the service principal will resolve to a single principal
* whose name comes from the `@aws-cdk/region-info` package, using the region to override
* the stack region. If there is no entry for this service principal in the database,, the input
* service name is returned literally. This is legacy behavior and is not recommended.
*
* @default - the resolving Stack's region.
*/
readonly region?: string;
/**
* Additional conditions to add to the Service Principal
*
* @default - No conditions
*/
readonly conditions?: {
[key: string]: any;
};
}
/**
* An IAM principal that represents an AWS service (i.e. `sqs.amazonaws.com`).
*/
export declare class ServicePrincipal extends PrincipalBase {
readonly service: string;
private readonly opts;
/**
* Return the service principal name based on the region it's used in.
*
* Some service principal names used to be different for different partitions,
* and some were not. This method would return the appropriate region-specific
* service principal name, getting that information from the `region-info`
* module.
*
* These days all service principal names are standardized, and they are all
* of the form `<servicename>.amazonaws.com`.
*
* To avoid breaking changes, handling is provided for services added with the formats below,
* however, no additional handling will be added for new regions or partitions.
* - s3
* - s3.amazonaws.com
* - s3.amazonaws.com.cn
* - s3.c2s.ic.gov
* - s3.sc2s.sgov.gov
*
* @example
* const principalName = iam.ServicePrincipal.servicePrincipalName('ec2.amazonaws.com');
*/
static servicePrincipalName(service: string): string;
/**
* Return the service principal using the service principal name as it is passed to the function without
* any change regardless of the region used in the stack if it is Opted in or not.
*
* @example
* const principalName = iam.ServicePrincipal.fromStaticServicePrincipleName('elasticmapreduce.amazonaws.com.cn');
*/
static fromStaticServicePrincipleName(servicePrincipalName: string): ServicePrincipal;
/**
* Reference an AWS service, optionally in a given region
*
* @param service AWS service (i.e. sqs.amazonaws.com)
*/
constructor(service: string, opts?: ServicePrincipalOpts);
get policyFragment(): PrincipalPolicyFragment;
toString(): string;
dedupeString(): string | undefined;
}
/**
* A principal that represents an AWS Organization
*/
export declare class OrganizationPrincipal extends PrincipalBase {
readonly organizationId: string;
/**
*
* @param organizationId The unique identifier (ID) of an organization (i.e. o-12345abcde)
* It must match regex pattern ^o-[a-z0-9]{10,32}$
* @see https://docs.aws.amazon.com/organizations/latest/APIReference/API_Organization.html
*/
constructor(organizationId: string);
get policyFragment(): PrincipalPolicyFragment;
toString(): string;
dedupeString(): string | undefined;
}
/**
* A policy principal for canonicalUserIds - useful for S3 bucket policies that use
* Origin Access identities.
*
* See https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html
*
* and
*
* https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html
*
* for more details.
*
*/
export declare class CanonicalUserPrincipal extends PrincipalBase {
readonly canonicalUserId: string;
/**
*
* @param canonicalUserId unique identifier assigned by AWS for every account.
* root user and IAM users for an account all see the same ID.
* (i.e. 79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be)
*/
constructor(canonicalUserId: string);
get policyFragment(): PrincipalPolicyFragment;
toString(): string;
dedupeString(): string | undefined;
}
/**
* Principal entity that represents a federated identity provider such as Amazon Cognito,
* that can be used to provide temporary security credentials to users who have been authenticated.
* Additional condition keys are available when the temporary security credentials are used to make a request.
* You can use these keys to write policies that limit the access of federated users.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-wif
*/
export declare class FederatedPrincipal extends PrincipalBase {
readonly federated: string;
readonly assumeRoleAction: string;
/**
* The conditions under which the policy is in effect.
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html
*/
readonly conditions: Conditions;
/**
*
* @param federated federated identity provider (i.e. 'cognito-identity.amazonaws.com' for users authenticated through Cognito)
* @param sessionTags Whether to enable session tagging (see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html)
*/
constructor(federated: string, conditions?: Conditions, assumeRoleAction?: string);
get policyFragment(): PrincipalPolicyFragment;
toString(): string;
dedupeString(): string | undefined;
}
/**
* A principal that represents a federated identity provider as Web Identity such as Cognito, Amazon,
* Facebook, Google, etc.
*/
export declare class WebIdentityPrincipal extends FederatedPrincipal {
/**
*
* @param identityProvider identity provider (i.e. 'cognito-identity.amazonaws.com' for users authenticated through Cognito)
* @param conditions The conditions under which the policy is in effect.
* See [the IAM documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html).
* @param sessionTags Whether to enable session tagging (see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html)
*/
constructor(identityProvider: string, conditions?: Conditions);
get policyFragment(): PrincipalPolicyFragment;
toString(): string;
}
/**
* A principal that represents a federated identity provider as from a OpenID Connect provider.
*/
export declare class OpenIdConnectPrincipal extends WebIdentityPrincipal {
/**
*
* @param openIdConnectProvider OpenID Connect provider
* @param conditions The conditions under which the policy is in effect.
* See [the IAM documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html).
*/
constructor(openIdConnectProvider: IOIDCProviderRef, conditions?: Conditions);
get policyFragment(): PrincipalPolicyFragment;
toString(): string;
}
/**
* Principal entity that represents a SAML federated identity provider
*/
export declare class SamlPrincipal extends FederatedPrincipal {
constructor(samlProvider: ISAMLProviderRef, conditions: Conditions);
toString(): string;
}
/**
* Principal entity that represents a SAML federated identity provider for
* programmatic and AWS Management Console access.
*/
export declare class SamlConsolePrincipal extends SamlPrincipal {
constructor(samlProvider: ISamlProvider, conditions?: Conditions);
toString(): string;
}
/**
* Use the AWS account into which a stack is deployed as the principal entity in a policy
*/
export declare class AccountRootPrincipal extends AccountPrincipal {
constructor();
toString(): string;
}
/**
* A principal representing all AWS identities in all accounts
*
* Some services behave differently when you specify `Principal: '*'`
* or `Principal: { AWS: "*" }` in their resource policy.
*
* `AnyPrincipal` renders to `Principal: { AWS: "*" }`. This is correct
* most of the time, but in cases where you need the other principal,
* use `StarPrincipal` instead.
*/
export declare class AnyPrincipal extends ArnPrincipal {
constructor();
toString(): string;
}
/**
* A principal that uses a literal '*' in the IAM JSON language
*
* Some services behave differently when you specify `Principal: "*"`
* or `Principal: { AWS: "*" }` in their resource policy.
*
* `StarPrincipal` renders to `Principal: *`. Most of the time, you
* should use `AnyPrincipal` instead.
*/
export declare class StarPrincipal extends PrincipalBase {
readonly policyFragment: PrincipalPolicyFragment;
toString(): string;
dedupeString(): string | undefined;
}
/**
* Represents a principal that has multiple types of principals. A composite principal cannot
* have conditions. i.e. multiple ServicePrincipals that form a composite principal
*/
export declare class CompositePrincipal extends PrincipalBase {
readonly assumeRoleAction: string;
private readonly _principals;
constructor(...principals: IPrincipal[]);
/**
* Adds IAM principals to the composite principal. Composite principals cannot have
* conditions.
*
* @param principals IAM principals that will be added to the composite principal
*/
addPrincipals(...principals: IPrincipal[]): this;
addToAssumeRolePolicy(doc: PolicyDocument): void;
get policyFragment(): PrincipalPolicyFragment;
toString(): string;
dedupeString(): string | undefined;
/**
* Returns the principals that make up the CompositePrincipal
*/
get principals(): IPrincipal[];
}
/**
* Validate that the given value is a valid Condition object
*
* The type of `Condition` should have been different, but it's too late for that.
*
* Also, the IAM library relies on being able to pass in a `CfnJson` instance for
* a `Condition`.
*/
export declare function validateConditionObject(x: unknown): asserts x is Record<string, unknown>;
export {};

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
import type { PolicyDocument } from '../policy-document';
import type { IPrincipal } from '../principals';
/**
* Add a principal to an AssumeRolePolicyDocument in the right way
*
* Delegate to the principal if it can do the job itself, do a default job if it can't.
*/
export declare function defaultAddPrincipalToAssumeRole(principal: IPrincipal, doc: PolicyDocument): void;

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.defaultAddPrincipalToAssumeRole=defaultAddPrincipalToAssumeRole;var policy_statement_1=()=>{var tmp=require("../policy-statement");return policy_statement_1=()=>tmp,tmp};function defaultAddPrincipalToAssumeRole(principal,doc){isAssumeRolePrincipal(principal)?principal.addToAssumeRolePolicy(doc):doc.addStatements(new(policy_statement_1()).PolicyStatement({actions:[principal.assumeRoleAction],principals:[principal]}))}function isAssumeRolePrincipal(principal){return!!principal.addToAssumeRolePolicy}

View File

@@ -0,0 +1,6 @@
import type { IPrincipal } from '../principals';
export declare function partitionPrincipals(xs: IPrincipal[]): PartitionResult;
export interface PartitionResult {
readonly nonComparable: IPrincipal[];
readonly comparable: Record<string, IPrincipal>;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.partitionPrincipals=partitionPrincipals;var principals_1=()=>{var tmp=require("../principals");return principals_1=()=>tmp,tmp};function partitionPrincipals(xs){const nonComparable=[],comparable={};for(const x of xs){const dedupe=principals_1().ComparablePrincipal.dedupeStringFor(x);dedupe?comparable[dedupe]=x:nonComparable.push(x)}return{comparable,nonComparable}}

View File

@@ -0,0 +1,45 @@
import type { Construct } from 'constructs';
import { Resource } from '../../../core';
import type { Grant } from '../grant';
import type { RoleReference } from '../iam.generated';
import type { IManagedPolicy } from '../managed-policy';
import type { Policy } from '../policy';
import type { PolicyStatement } from '../policy-statement';
import type { AddToPrincipalPolicyResult, IPrincipal } from '../principals';
import type { IRole } from '../role';
/**
* An immutable wrapper around an IRole
*
* This wrapper ignores all mutating operations, like attaching policies or
* adding policy statements.
*
* Useful in cases where you want to turn off CDK's automatic permissions
* management, and instead have full control over all permissions.
*
* Note: if you want to ignore all mutations for an externally defined role
* which was imported into the CDK with `Role.fromRoleArn`, you don't have to use this class -
* simply pass the property mutable = false when calling `Role.fromRoleArn`.
*/
export declare class ImmutableRole extends Resource implements IRole {
private readonly role;
private readonly addGrantsToResources;
/** Uniquely identifies this class. */
static readonly PROPERTY_INJECTION_ID: string;
readonly assumeRoleAction: string;
readonly policyFragment: any;
readonly grantPrincipal: IPrincipal;
readonly principalAccount: string | undefined;
readonly roleArn: string;
readonly roleName: string;
private readonly _stack;
constructor(scope: Construct, id: string, role: IRole, addGrantsToResources: boolean);
get stack(): import("../../../core").Stack;
get roleRef(): RoleReference;
attachInlinePolicy(_policy: Policy): void;
addManagedPolicy(_policy: IManagedPolicy): void;
addToPolicy(statement: PolicyStatement): boolean;
addToPrincipalPolicy(_statement: PolicyStatement): AddToPrincipalPolicyResult;
grant(grantee: IPrincipal, ...actions: string[]): Grant;
grantPassRole(grantee: IPrincipal): Grant;
grantAssumeRole(identity: IPrincipal): Grant;
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,37 @@
import type { Construct } from 'constructs';
import { Resource } from '../../../core';
import { Grant } from '../grant';
import type { RoleReference } from '../iam.generated';
import type { IManagedPolicy } from '../managed-policy';
import { Policy } from '../policy';
import type { PolicyStatement } from '../policy-statement';
import type { AddToPrincipalPolicyResult, IComparablePrincipal, IPrincipal, PrincipalPolicyFragment } from '../principals';
import type { FromRoleArnOptions, IRole } from '../role';
export interface ImportedRoleProps extends FromRoleArnOptions {
readonly roleArn: string;
readonly roleName: string;
readonly account?: string;
}
export declare class ImportedRole extends Resource implements IRole, IComparablePrincipal {
/** Uniquely identifies this class. */
static readonly PROPERTY_INJECTION_ID: string;
readonly grantPrincipal: IPrincipal;
readonly principalAccount?: string;
readonly assumeRoleAction: string;
readonly policyFragment: PrincipalPolicyFragment;
readonly roleArn: string;
readonly roleName: string;
private readonly attachedPolicies;
private readonly defaultPolicyName?;
private defaultPolicy?;
constructor(scope: Construct, id: string, props: ImportedRoleProps);
get roleRef(): RoleReference;
addToPolicy(statement: PolicyStatement): boolean;
addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult;
attachInlinePolicy(policy: Policy): void;
addManagedPolicy(policy: IManagedPolicy): void;
grantPassRole(identity: IPrincipal): Grant;
grantAssumeRole(identity: IPrincipal): Grant;
grant(grantee: IPrincipal, ...actions: string[]): Grant;
dedupeString(): string | undefined;
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,44 @@
import type { IConstruct } from 'constructs';
import type { PolicyStatement } from '../policy-statement';
/**
* Options for the mergeStatement command
*/
export interface MergeStatementOptions {
/**
* Scope to derive configuration flags from
*/
readonly scope: IConstruct;
/**
* Do not merge statements if the result would be bigger than MAX_MERGE_SIZE
*
* @default false
*/
readonly limitSize?: boolean;
/**
* Merge statements if they can be combined to produce the same effects.
*
* If false, statements are only merged if they are exactly equal.
*
* @default true
*/
readonly mergeIfCombinable?: boolean;
}
/**
* Merge as many statements as possible to shrink the total policy doc, modifying the input array in place
*
* We compare and merge all pairs of statements (O(N^2) complexity), opportunistically
* merging them. This is not guaranteed to produce the optimal output, but it's probably
* Good Enough(tm). If it merges anything, it's at least going to produce a smaller output
* than the input.
*/
export declare function mergeStatements(statements: PolicyStatement[], options: MergeStatementOptions): MergeStatementResult;
export interface MergeStatementResult {
/**
* The list of maximally merged statements
*/
readonly mergedStatements: PolicyStatement[];
/**
* Mapping of old to new statements
*/
readonly originsMap: Map<PolicyStatement, PolicyStatement[]>;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.mergeStatements=mergeStatements;var comparable_principal_1=()=>{var tmp=require("./comparable-principal");return comparable_principal_1=()=>tmp,tmp},policy_statement_1=()=>{var tmp=require("../policy-statement");return policy_statement_1=()=>tmp,tmp},util_1=()=>{var tmp=require("../util");return util_1=()=>tmp,tmp};const MAX_MERGE_SIZE=2e3;function mergeStatements(statements,options){const sizeOptions=(0,policy_statement_1().deriveEstimateSizeOptions)(options.scope),compStatements=statements.map(makeComparable),mergeFn=options?.mergeIfCombinable??!0?mergeIfCombinable:mergeIfEqual;for(;onePass(););const mergedStatements=new Array,originsMap=new Map;for(const comp of compStatements){const statement=renderComparable(comp);mergedStatements.push(statement),originsMap.set(statement,comp.originals)}return{mergedStatements,originsMap};function onePass(){let ret=!1;for(let i=0;i<compStatements.length;i++){let j=i+1;for(;j<compStatements.length;){const merged=mergeFn(compStatements[i],compStatements[j],!!options.limitSize,sizeOptions);merged?(compStatements[i]=merged,compStatements.splice(j,1),ret=!0):j++}}return ret}}function mergeIfCombinable(a,b,limitSize,options){if(a.statement.effect!==b.statement.effect||a.statement.sid||b.statement.sid||a.conditionString!==b.conditionString||!setEqual(a.statement.notActions,b.statement.notActions)||!setEqual(a.statement.notResources,b.statement.notResources)||!setEqualPrincipals(a.statement.notPrincipals,b.statement.notPrincipals)||(setEqual(a.statement.actions,b.statement.actions)?1:0)+(setEqual(a.statement.resources,b.statement.resources)?1:0)+(setEqualPrincipals(a.statement.principals,b.statement.principals)?1:0)<2||unmergeablePrincipals(a,b))return;const combined=a.statement.copy({actions:setMerge(a.statement.actions,b.statement.actions),resources:setMerge(a.statement.resources,b.statement.resources),principals:setMergePrincipals(a.statement.principals,b.statement.principals)});if(!(limitSize&&combined._estimateSize(options)>MAX_MERGE_SIZE))return{originals:[...a.originals,...b.originals],statement:combined,conditionString:a.conditionString}}function mergeIfEqual(a,b){if(a.statement.effect===b.statement.effect&&a.statement.sid===b.statement.sid&&a.conditionString===b.conditionString&&!(!setEqual(a.statement.notActions,b.statement.notActions)||!setEqual(a.statement.notResources,b.statement.notResources)||!setEqualPrincipals(a.statement.notPrincipals,b.statement.notPrincipals))&&!(!setEqual(a.statement.actions,b.statement.actions)||!setEqual(a.statement.resources,b.statement.resources)||!setEqualPrincipals(a.statement.principals,b.statement.principals)))return{originals:[...a.originals,...b.originals],statement:a.statement,conditionString:a.conditionString}}function makeComparable(s){return{originals:[s],statement:s,conditionString:JSON.stringify(s.conditions)}}function unmergeablePrincipals(a,b){const aHasLiteral=a.statement.principals.some(v=>util_1().LITERAL_STRING_KEY in v.policyFragment.principalJson),bHasLiteral=b.statement.principals.some(v=>util_1().LITERAL_STRING_KEY in v.policyFragment.principalJson);return aHasLiteral!==bHasLiteral}function renderComparable(s){return s.statement}function setEqual(a,b){const bSet=new Set(b);return a.length===b.length&&a.every(k=>bSet.has(k))}function setMerge(x,y){return Array.from(new Set([...x,...y])).sort()}function setEqualPrincipals(xs,ys){const xPrincipals=(0,comparable_principal_1().partitionPrincipals)(xs),yPrincipals=(0,comparable_principal_1().partitionPrincipals)(ys),nonComp=setEqual(xPrincipals.nonComparable,yPrincipals.nonComparable),comp=setEqual(Object.keys(xPrincipals.comparable),Object.keys(yPrincipals.comparable));return nonComp&&comp}function setMergePrincipals(xs,ys){const xPrincipals=(0,comparable_principal_1().partitionPrincipals)(xs),yPrincipals=(0,comparable_principal_1().partitionPrincipals)(ys),comparable={...xPrincipals.comparable,...yPrincipals.comparable};return[...Object.values(comparable),...xPrincipals.nonComparable,...yPrincipals.nonComparable]}

View File

@@ -0,0 +1,11 @@
import { PolicyDocument } from '../policy-document';
import type { PolicyStatement } from '../policy-statement';
/**
* A PolicyDocument adapter that can modify statements flowing through it
*/
export declare class MutatingPolicyDocumentAdapter extends PolicyDocument {
private readonly wrapped;
private readonly mutator;
constructor(wrapped: PolicyDocument, mutator: (s: PolicyStatement) => PolicyStatement);
addStatements(...statements: PolicyStatement[]): void;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MutatingPolicyDocumentAdapter=void 0;var policy_document_1=()=>{var tmp=require("../policy-document");return policy_document_1=()=>tmp,tmp};class MutatingPolicyDocumentAdapter extends policy_document_1().PolicyDocument{wrapped;mutator;constructor(wrapped,mutator){super(),this.wrapped=wrapped,this.mutator=mutator}addStatements(...statements){for(const st of statements)this.wrapped.addStatements(this.mutator(st))}}exports.MutatingPolicyDocumentAdapter=MutatingPolicyDocumentAdapter;

View File

@@ -0,0 +1,29 @@
import * as cdk from '../../../core';
/**
* A Token postprocesser for policy documents
*
* Removes duplicate statements, and assign Sids if necessary
*
* Because policy documents can contain all kinds of crazy things,
* we do all the necessary work here after the document has been mostly resolved
* into a predictable CloudFormation form.
*/
export declare class PostProcessPolicyDocument implements cdk.IPostProcessor {
private readonly autoAssignSids;
private readonly sort;
constructor(autoAssignSids: boolean, sort: boolean);
postProcess(input: any, _context: cdk.IResolveContext): any;
}
export type IamValue = string | Record<string, any> | Array<string | Record<string, any>>;
export interface StatementSchema {
Sid?: string;
Effect?: string;
Principal?: string | string[] | Record<string, IamValue>;
NotPrincipal?: string | string[] | Record<string, IamValue>;
Resource?: IamValue;
NotResource?: IamValue;
Action?: IamValue;
NotAction?: IamValue;
Condition?: unknown;
}
export declare function normalizeStatement(s: StatementSchema): any;

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostProcessPolicyDocument=void 0,exports.normalizeStatement=normalizeStatement;var cdk=()=>{var tmp=require("../../../core");return cdk=()=>tmp,tmp},util_1=()=>{var tmp=require("../util");return util_1=()=>tmp,tmp};class PostProcessPolicyDocument{autoAssignSids;sort;constructor(autoAssignSids,sort){this.autoAssignSids=autoAssignSids,this.sort=sort}postProcess(input,_context){if(!input||!input.Statement)return input;const jsonStatements=new Set,uniqueStatements=[];for(const statement of input.Statement){const jsonStatement=JSON.stringify(statement);jsonStatements.has(jsonStatement)||(uniqueStatements.push(statement),jsonStatements.add(jsonStatement))}const statements=uniqueStatements.map((s,i)=>(this.autoAssignSids&&!s.Sid&&(s.Sid=i.toString()),this.sort&&(s.Action&&(s.Action=sortByJson(s.Action)),s.Resource&&(s.Resource=sortByJson(s.Resource)),s.Principal&&(s.Principal=sortPrincipals(s.Principal))),s));return{...input,Statement:statements}}}exports.PostProcessPolicyDocument=PostProcessPolicyDocument;function normalizeStatement(s){return noUndef({Action:_norm(s.Action,{unique:!0}),NotAction:_norm(s.NotAction,{unique:!0}),Condition:_norm(s.Condition),Effect:_norm(s.Effect),Principal:_normPrincipal(s.Principal),NotPrincipal:_normPrincipal(s.NotPrincipal),Resource:_norm(s.Resource,{unique:!0}),NotResource:_norm(s.NotResource,{unique:!0}),Sid:_norm(s.Sid)});function _norm(values,{unique=!1}={unique:!1}){if(values!=null){if(cdk().Token.isUnresolved(values))return values;if(Array.isArray(values))return!values||values.length===0?void 0:values.length===1?values[0]:unique?Array.from(new Set(values)):values;if(!(values&&typeof values=="object"&&Object.keys(values).length===0))return values}}function _normPrincipal(principal){if(!principal||Array.isArray(principal)||typeof principal!="object")return;const keys=Object.keys(principal);if(keys.length===0)return;if(util_1().LITERAL_STRING_KEY in principal)return principal[util_1().LITERAL_STRING_KEY][0];const result={};for(const key of keys){const normVal=_norm(principal[key]);normVal&&(result[key]=normVal)}return result}}function noUndef(x){const ret={};for(const[key,value]of Object.entries(x))value!==void 0&&(ret[key]=value);return ret}function sortPrincipals(xs){if(!xs||Array.isArray(xs)||typeof xs!="object")return xs;const ret={};for(const k of Object.keys(xs).sort())ret[k]=sortByJson(xs[k]);return ret}function sortByJson(xs){if(!Array.isArray(xs))return xs;const intermediate=new Map;for(const x of xs)intermediate.set(JSON.stringify(x),x);const sorted=Array.from(intermediate.keys()).sort().map(k=>intermediate.get(k));return xs.splice(0,xs.length,...sorted),xs.length!==1?xs:xs[0]}

View File

@@ -0,0 +1,76 @@
import type { Construct } from 'constructs';
import { Resource, Stack } from '../../../core';
import type { Grant } from '../grant';
import type { RoleReference } from '../iam.generated';
import type { IManagedPolicy } from '../managed-policy';
import type { Policy } from '../policy';
import type { PolicyDocument } from '../policy-document';
import type { PolicyStatement } from '../policy-statement';
import type { AddToPrincipalPolicyResult, IPrincipal, PrincipalPolicyFragment } from '../principals';
import type { IRole } from '../role';
/**
* Options for a precreated role
*/
export interface PrecreatedRoleProps {
/**
* The base role to use for the precreated role. In most cases this will be
* the `Role` or `IRole` that is being created by a construct. For example,
* users (or constructs) will create an IAM role with `new Role(this, 'MyRole', {...})`.
* That `Role` will be used as the base role for the `PrecreatedRole` meaning it be able
* to access any methods and properties on the base role.
*/
readonly role: IRole;
/**
* The assume role (trust) policy for the precreated role.
*
* @default - no assume role policy
*/
readonly assumeRolePolicy?: PolicyDocument;
/**
* If the role is missing from the precreatedRole context
*
* @default false
*/
readonly missing?: boolean;
/**
* The construct path to display in the report.
* This should be the path that the user can trace to the
* role being created in their application
*
* @default the construct path of this construct
*/
readonly rolePath?: string;
}
/**
* An IAM role that has been created outside of CDK and can be
* used in place of a role that CDK _is_ creating.
*
* When any policy is attached to a precreated role the policy will be
* synthesized into a separate report and will _not_ be synthesized in
* the CloudFormation template.
*/
export declare class PrecreatedRole extends Resource implements IRole {
/** Uniquely identifies this class. */
static readonly PROPERTY_INJECTION_ID: string;
readonly assumeRoleAction: string;
readonly policyFragment: PrincipalPolicyFragment;
readonly grantPrincipal: this;
readonly principalAccount?: string;
readonly roleArn: string;
readonly roleName: string;
private readonly _stack;
private readonly policySynthesizer;
private readonly policyStatements;
private readonly managedPolicies;
private readonly role;
constructor(scope: Construct, id: string, props: PrecreatedRoleProps);
get stack(): Stack;
get roleRef(): RoleReference;
attachInlinePolicy(policy: Policy): void;
addManagedPolicy(policy: IManagedPolicy): void;
addToPolicy(statement: PolicyStatement): boolean;
addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult;
grant(grantee: IPrincipal, ...actions: string[]): Grant;
grantPassRole(grantee: IPrincipal): Grant;
grantAssumeRole(identity: IPrincipal): Grant;
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,58 @@
import type { IConstruct } from 'constructs';
import type { IPostProcessor, IResolvable, IResolveContext } from '../../../core';
import type { IPolicy } from '../policy';
export declare const MAX_POLICY_NAME_LEN = 128;
export declare const LITERAL_STRING_KEY = "LiteralString";
export declare function undefinedIfEmpty(f: () => string[]): string[];
/**
* Used to generate a unique policy name based on the policy resource construct.
* The logical ID of the resource is a great candidate as long as it doesn't exceed
* 128 characters, so we take the last 128 characters (in order to make sure the hash
* is there).
*/
export declare function generatePolicyName(scope: IConstruct, logicalId: string): string;
/**
* Helper class that maintains the set of attached policies for a principal.
*/
export declare class AttachedPolicies {
private policies;
/**
* Adds a policy to the list of attached policies.
*
* If this policy is already, attached, returns false.
* If there is another policy attached with the same name, throws an exception.
*/
attach(policy: IPolicy): void;
}
/**
* Merge two dictionaries that represent IAM principals
*
* Does an in-place merge.
*/
export declare function mergePrincipal(target: {
[key: string]: string[];
}, source: {
[key: string]: string[];
}): {
[key: string]: string[];
};
/**
* Lazy string set token that dedupes entries
*
* Needs to operate post-resolve, because the inputs could be
* `[ '${Token[TOKEN.9]}', '${Token[TOKEN.10]}', '${Token[TOKEN.20]}' ]`, which
* still all resolve to the same string value.
*
* Needs to JSON.stringify() results because strings could resolve to literal
* strings but could also resolve to `{ Fn::Join: [...] }`.
*/
export declare class UniqueStringSet implements IResolvable, IPostProcessor {
private readonly fn;
static from(fn: () => string[]): string[];
readonly creationStack: string[];
private constructor();
resolve(context: IResolveContext): string[];
postProcess(input: any, _context: IResolveContext): any;
toString(): string;
}
export declare function sum(xs: number[]): number;

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UniqueStringSet=exports.AttachedPolicies=exports.LITERAL_STRING_KEY=exports.MAX_POLICY_NAME_LEN=void 0,exports.undefinedIfEmpty=undefinedIfEmpty,exports.generatePolicyName=generatePolicyName,exports.mergePrincipal=mergePrincipal,exports.sum=sum;var core_1=()=>{var tmp=require("../../../core");return core_1=()=>tmp,tmp},literal_string_1=()=>{var tmp=require("../../../core/lib/private/literal-string");return literal_string_1=()=>tmp,tmp};exports.MAX_POLICY_NAME_LEN=128,exports.LITERAL_STRING_KEY="LiteralString";function undefinedIfEmpty(f){return core_1().Lazy.list({produce:()=>{const array=f();return array&&array.length>0?array:void 0}})}function generatePolicyName(scope,logicalId){const resolvedLogicalId=core_1().Tokenization.resolve(logicalId,{scope,resolver:new(core_1()).DefaultTokenResolver(new(core_1()).StringConcat)});return lastNCharacters(resolvedLogicalId,exports.MAX_POLICY_NAME_LEN)}function lastNCharacters(str,n){const startIndex=Math.max(str.length-n,0);return str.substring(startIndex,str.length)}class AttachedPolicies{policies=new Array;attach(policy){if(!this.policies.find(p=>p===policy)){if(this.policies.find(p=>p.policyName===policy.policyName))throw new(core_1()).ValidationError((0,literal_string_1().lit)`PolicyNamedAlreadyAttached`,`A policy named "${policy.policyName}" is already attached`,policy);this.policies.push(policy)}}}exports.AttachedPolicies=AttachedPolicies;function mergePrincipal(target,source){const sourceKeys=Object.keys(source),targetKeys=Object.keys(target);if(exports.LITERAL_STRING_KEY in source&&targetKeys.some(k=>k!==exports.LITERAL_STRING_KEY)||exports.LITERAL_STRING_KEY in target&&sourceKeys.some(k=>k!==exports.LITERAL_STRING_KEY))throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`CannotMustBeCannotMerge`,`Cannot merge principals ${JSON.stringify(target)} and ${JSON.stringify(source)}; if one uses a literal principal string the other one must be empty`);for(const key of sourceKeys){target[key]=target[key]??[];let value=source[key];Array.isArray(value)||(value=[value]),target[key].push(...value)}return target}class UniqueStringSet{fn;static from(fn){return core_1().Token.asList(new UniqueStringSet(fn))}creationStack=["Token stack traces are no longer captured"];constructor(fn){this.fn=fn}resolve(context){return context.registerPostProcessor(this),this.fn()}postProcess(input,_context){if(!Array.isArray(input))return input;if(input.length===0)return;const uniq={};for(const el of input)uniq[JSON.stringify(el)]=el;return Object.values(uniq)}toString(){return core_1().Token.asString(this)}}exports.UniqueStringSet=UniqueStringSet;function sum(xs){return xs.reduce((a,b)=>a+b,0)}

View File

@@ -0,0 +1,22 @@
import { Grant } from './grant';
import type { IRoleRef } from './iam.generated';
import type { IPrincipal } from './principals';
/**
* Collection of grant methods for a IRoleRef
*/
export declare class RoleGrants {
private readonly role;
/**
* Creates grants for IRoleRef
*/
static fromRole(role: IRoleRef): RoleGrants;
private constructor();
/**
* Grant permissions to the given principal to assume this role.
*/
assumeRole(identity: IPrincipal): Grant;
/**
* Grant permissions to the given principal to pass this role.
*/
passRole(identity: IPrincipal): Grant;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RoleGrants=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var grant_1=()=>{var tmp=require("./grant");return grant_1=()=>tmp,tmp},principals_1=()=>{var tmp=require("./principals");return principals_1=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},literal_string_1=()=>{var tmp=require("../../core/lib/private/literal-string");return literal_string_1=()=>tmp,tmp};class RoleGrants{role;static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_iam.RoleGrants",version:"2.252.0"};static fromRole(role){try{jsiiDeprecationWarnings().aws_cdk_lib_interfaces_aws_iam_IRoleRef(role)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.fromRole),error}return new RoleGrants(role)}constructor(role){this.role=role}assumeRole(identity){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IPrincipal(identity)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.assumeRole),error}if(identity instanceof principals_1().ServicePrincipal||identity instanceof principals_1().AccountPrincipal)throw new(core_1()).ValidationError((0,literal_string_1().lit)`CannotServiceAccountPrincipalGrant`,"Cannot use a service or account principal with grantAssumeRole, use assumeRolePolicy instead.",this.role);return grant_1().Grant.addToPrincipal({grantee:identity,actions:["sts:AssumeRole"],resourceArns:[this.role.roleRef.roleArn]})}passRole(identity){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IPrincipal(identity)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.passRole),error}return grant_1().Grant.addToPrincipal({grantee:identity,actions:["iam:PassRole"],resourceArns:[this.role.roleRef.roleArn]})}}exports.RoleGrants=RoleGrants;

441
cdk/node_modules/aws-cdk-lib/aws-iam/lib/role.d.ts generated vendored Normal file
View File

@@ -0,0 +1,441 @@
import type { Construct } from 'constructs';
import { Grant } from './grant';
import type { IRoleRef, RoleReference } from './iam.generated';
import type { IIdentity } from './identity-base';
import type { IManagedPolicy } from './managed-policy';
import { Policy } from './policy';
import { PolicyDocument } from './policy-document';
import type { PolicyStatement } from './policy-statement';
import type { AddToPrincipalPolicyResult, IPrincipal, PrincipalPolicyFragment } from './principals';
import { RoleGrants } from './role-grants';
import type { Duration, RemovalPolicy } from '../../core';
import { Resource } from '../../core';
/**
* Properties for defining an IAM Role
*/
export interface RoleProps {
/**
* The IAM principal (i.e. `new ServicePrincipal('sns.amazonaws.com')`)
* which can assume this role.
*
* You can later modify the assume role policy document by accessing it via
* the `assumeRolePolicy` property.
*/
readonly assumedBy: IPrincipal;
/**
* List of IDs that the role assumer needs to provide one of when assuming this role
*
* If the configured and provided external IDs do not match, the
* AssumeRole operation will fail.
*
* @default No external ID required
*/
readonly externalIds?: string[];
/**
* A list of managed policies associated with this role.
*
* You can add managed policies later using
* `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`.
*
* @default - No managed policies.
*/
readonly managedPolicies?: IManagedPolicy[];
/**
* A list of named policies to inline into this role. These policies will be
* created with the role, whereas those added by ``addToPolicy`` are added
* using a separate CloudFormation resource (allowing a way around circular
* dependencies that could otherwise be introduced).
*
* @default - No policy is inlined in the Role resource.
*/
readonly inlinePolicies?: {
[name: string]: PolicyDocument;
};
/**
* The path associated with this role. For information about IAM paths, see
* Friendly Names and Paths in IAM User Guide.
*
* @default /
*/
readonly path?: string;
/**
* AWS supports permissions boundaries for IAM entities (users or roles).
* A permissions boundary is an advanced feature for using a managed policy
* to set the maximum permissions that an identity-based policy can grant to
* an IAM entity. An entity's permissions boundary allows it to perform only
* the actions that are allowed by both its identity-based policies and its
* permissions boundaries.
*
* @link https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#cfn-iam-role-permissionsboundary
* @link https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html
*
* @default - No permissions boundary.
*/
readonly permissionsBoundary?: IManagedPolicy;
/**
* A name for the IAM role. For valid values, see the RoleName parameter for
* the CreateRole action in the IAM API Reference.
*
* IMPORTANT: If you specify a name, you cannot perform updates that require
* replacement of this resource. You can perform updates that require no or
* some interruption. If you must replace the resource, specify a new name.
*
* If you specify a name, you must specify the CAPABILITY_NAMED_IAM value to
* acknowledge your template's capabilities. For more information, see
* Acknowledging IAM Resources in AWS CloudFormation Templates.
*
* @default - AWS CloudFormation generates a unique physical ID and uses that ID
* for the role name.
*/
readonly roleName?: string;
/**
* The maximum session duration that you want to set for the specified role.
* This setting can have a value from 1 hour (3600sec) to 12 (43200sec) hours.
*
* Anyone who assumes the role from the AWS CLI or API can use the
* DurationSeconds API parameter or the duration-seconds CLI parameter to
* request a longer session. The MaxSessionDuration setting determines the
* maximum duration that can be requested using the DurationSeconds
* parameter.
*
* If users don't specify a value for the DurationSeconds parameter, their
* security credentials are valid for one hour by default. This applies when
* you use the AssumeRole* API operations or the assume-role* CLI operations
* but does not apply when you use those operations to create a console URL.
*
* @link https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html
*
* @default Duration.hours(1)
*/
readonly maxSessionDuration?: Duration;
/**
* A description of the role. It can be up to 1000 characters long.
*
* @default - No description.
*/
readonly description?: string;
}
/**
* Options allowing customizing the behavior of `Role.fromRoleArn`.
*/
export interface FromRoleArnOptions {
/**
* Whether the imported role can be modified by attaching policy resources to it.
*
* @default true
*/
readonly mutable?: boolean;
/**
* For immutable roles: add grants to resources instead of dropping them
*
* If this is `false` or not specified, grant permissions added to this role are ignored.
* It is your own responsibility to make sure the role has the required permissions.
*
* If this is `true`, any grant permissions will be added to the resource instead.
*
* @default false
*/
readonly addGrantsToResources?: boolean;
/**
* Any policies created by this role will use this value as their ID, if specified.
* Specify this if importing the same role in multiple stacks, and granting it
* different permissions in at least two stacks. If this is not specified
* (or if the same name is specified in more than one stack),
* a CloudFormation issue will result in the policy created in whichever stack
* is deployed last overwriting the policies created by the others.
*
* @default 'Policy'
*/
readonly defaultPolicyName?: string;
}
/**
* Options for customizing IAM role creation
*/
export interface CustomizeRolesOptions {
/**
* Whether or not to synthesize the resource into the CFN template.
*
* Set this to `false` if you still want to create the resources _and_
* you also want to create the policy report.
*
* @default true
*/
readonly preventSynthesis?: boolean;
/**
* A list of precreated IAM roles to substitute for roles
* that CDK is creating.
*
* The constructPath can be either a relative or absolute path
* from the scope that `customizeRoles` is used on to the role being created.
*
* @example
* declare const app: App;
*
* const stack = new Stack(app, 'MyStack');
* new iam.Role(stack, 'MyRole', {
* assumedBy: new iam.AccountPrincipal('1111111111'),
* });
*
* iam.Role.customizeRoles(stack, {
* usePrecreatedRoles: {
* // absolute path
* 'MyStack/MyRole': 'my-precreated-role-name',
* // or relative path from `stack`
* 'MyRole': 'my-precreated-role',
* },
* });
*
* @default - there are no precreated roles. Synthesis will fail if `preventSynthesis=true`
*/
readonly usePrecreatedRoles?: {
[constructPath: string]: string;
};
}
/**
* Options allowing customizing the behavior of `Role.fromRoleName`.
*/
export interface FromRoleNameOptions extends FromRoleArnOptions {
}
/**
* Properties for looking up an existing Role.
*/
export interface RoleLookupOptions extends FromRoleArnOptions {
/**
* The name of the role to lookup.
*
* If the role you want to lookup is a service role, you need to specify
* the role name without the 'service-role' prefix. For example, if the role arn is
* 'arn:aws:iam::123456789012:role/service-role/ExampleServiceExecutionRole',
* you need to specify the role name as 'ExampleServiceExecutionRole'.
*/
readonly roleName: string;
}
/**
* IAM Role
*
* Defines an IAM role. The role is created with an assume policy document associated with
* the specified AWS service principal defined in `serviceAssumeRole`.
*/
export declare class Role extends Resource implements IRole {
/**
* Uniquely identifies this class.
*/
static readonly PROPERTY_INJECTION_ID: string;
/**
* Lookup an existing Role.
*/
static fromLookup(scope: Construct, id: string, options: RoleLookupOptions): IRole;
/**
* Import an external role by ARN.
*
* If the imported Role ARN is a Token (such as a
* `CfnParameter.valueAsString` or a `Fn.importValue()`) *and* the referenced
* role has a `path` (like `arn:...:role/AdminRoles/Alice`), the
* `roleName` property will not resolve to the correct value. Instead it
* will resolve to the first path component. We unfortunately cannot express
* the correct calculation of the full path name as a CloudFormation
* expression. In this scenario the Role ARN should be supplied without the
* `path` in order to resolve the correct role resource.
*
* @param scope construct scope
* @param id construct id
* @param roleArn the ARN of the role to import
* @param options allow customizing the behavior of the returned role
*/
static fromRoleArn(scope: Construct, id: string, roleArn: string, options?: FromRoleArnOptions): IRole;
/**
* Return whether the given object is a Role
*/
static isRole(x: any): x is Role;
/**
* Import an external role by name.
*
* The imported role is assumed to exist in the same account as the account
* the scope's containing Stack is being deployed to.
*
* @param scope construct scope
* @param id construct id
* @param roleName the name of the role to import
* @param options allow customizing the behavior of the returned role
*/
static fromRoleName(scope: Construct, id: string, roleName: string, options?: FromRoleNameOptions): IRole;
/**
* Customize the creation of IAM roles within the given scope
*
* It is recommended that you **do not** use this method and instead allow
* CDK to manage role creation. This should only be used
* in environments where CDK applications are not allowed to created IAM roles.
*
* This can be used to prevent the CDK application from creating roles
* within the given scope and instead replace the references to the roles with
* precreated role names. A report will be synthesized in the cloud assembly (i.e. cdk.out)
* that will contain the list of IAM roles that would have been created along with the
* IAM policy statements that the role should contain. This report can then be used
* to create the IAM roles outside of CDK and then the created role names can be provided
* in `usePrecreatedRoles`.
*
* @example
* declare const app: App;
* iam.Role.customizeRoles(app, {
* usePrecreatedRoles: {
* 'ConstructPath/To/Role': 'my-precreated-role-name',
* },
* });
*
* @param scope construct scope to customize role creation
* @param options options for configuring role creation
*/
static customizeRoles(scope: Construct, options?: CustomizeRolesOptions): void;
readonly grantPrincipal: IPrincipal;
readonly principalAccount: string | undefined;
readonly assumeRoleAction: string;
/**
* The assume role policy document associated with this role.
*/
readonly assumeRolePolicy?: PolicyDocument;
/**
* The CfnRole resource
*/
private readonly _resource?;
/**
* Returns the ARN of this role.
*/
get roleArn(): string;
/**
* Returns the name of the role.
*/
get roleName(): string;
/**
* Returns the role.
*/
readonly policyFragment: PrincipalPolicyFragment;
/**
* Returns the permissions boundary attached to this role
*/
readonly permissionsBoundary?: IManagedPolicy;
/**
* Collection of grant methods for a Role
*/
readonly grants: RoleGrants;
private defaultPolicy?;
private readonly managedPolicies;
private readonly attachedPolicies;
private readonly inlinePolicies;
private readonly dependables;
private immutableRole?;
private _didSplit;
private readonly _roleId?;
private readonly _path?;
private readonly _precreatedRole?;
constructor(scope: Construct, id: string, props: RoleProps);
get roleRef(): RoleReference;
/**
* Adds a permission to the role's default policy document.
* If there is no default policy attached to this role, it will be created.
* @param statement The permission statement to add to the policy document
*/
addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult;
addToPolicy(statement: PolicyStatement): boolean;
/**
* Attaches a managed policy to this role.
* @param policy The the managed policy to attach.
*/
addManagedPolicy(policy: IManagedPolicy): void;
/**
* Attaches a policy to this role.
* @param policy The policy to attach
*/
attachInlinePolicy(policy: Policy): void;
/**
* Grant the actions defined in actions to the identity Principal on this resource.
*/
grant(grantee: IPrincipal, ...actions: string[]): Grant;
/**
* Grant permissions to the given principal to pass this role.
*/
grantPassRole(identity: IPrincipal): Grant;
/**
* Grant permissions to the given principal to assume this role.
*/
grantAssumeRole(identity: IPrincipal): Grant;
/**
* Returns the stable and unique string identifying the role. For example,
* AIDAJQABLZS4A3QDU576Q.
*
* @attribute
*/
get roleId(): string;
/**
* Return a copy of this Role object whose Policies will not be updated
*
* Use the object returned by this method if you want this Role to be used by
* a construct without it automatically updating the Role's Policies.
*
* If you do, you are responsible for adding the correct statements to the
* Role's policies yourself.
*/
withoutPolicyUpdates(options?: WithoutPolicyUpdatesOptions): IRole;
/**
* Skip applyRemovalPolicy if role synthesis is prevented by customizeRoles.
* Because in this case, this construct does not have a CfnResource in the tree.
* @override
* @param policy RemovalPolicy
*/
applyRemovalPolicy(policy: RemovalPolicy): void;
private validateRole;
/**
* Split large inline policies into managed policies
*
* This gets around the 10k bytes limit on role policies.
*/
private splitLargePolicy;
/**
* Return configuration for precreated roles
*/
private getPrecreatedRoleConfig;
}
/**
* A Role object
*/
export interface IRole extends IIdentity, IRoleRef {
/**
* Returns the ARN of this role.
*
* @attribute
*/
readonly roleArn: string;
/**
* Returns the name of this role.
*
* @attribute
*/
readonly roleName: string;
/**
* Grant the actions defined in actions to the identity Principal on this resource.
*/
grant(grantee: IPrincipal, ...actions: string[]): Grant;
/**
* Grant permissions to the given principal to pass this role.
*/
grantPassRole(grantee: IPrincipal): Grant;
/**
* Grant permissions to the given principal to assume this role.
*/
grantAssumeRole(grantee: IPrincipal): Grant;
}
/**
* Options for the `withoutPolicyUpdates()` modifier of a Role
*/
export interface WithoutPolicyUpdatesOptions {
/**
* Add grants to resources instead of dropping them
*
* If this is `false` or not specified, grant permissions added to this role are ignored.
* It is your own responsibility to make sure the role has the required permissions.
*
* If this is `true`, any grant permissions will be added to the resource instead.
*
* @default false
*/
readonly addGrantsToResources?: boolean;
}

1
cdk/node_modules/aws-cdk-lib/aws-iam/lib/role.js generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,72 @@
import type { Construct } from 'constructs';
import type { ISAMLProviderRef, SAMLProviderReference } from './iam.generated';
import type { IResource } from '../../core';
import { Resource } from '../../core';
/**
* A SAML provider
*/
export interface ISamlProvider extends IResource, ISAMLProviderRef {
/**
* The Amazon Resource Name (ARN) of the provider
*
* @attribute
*/
readonly samlProviderArn: string;
}
/**
* Properties for a SAML provider
*/
export interface SamlProviderProps {
/**
* The name of the provider to create.
*
* This parameter allows a string of characters consisting of upper and
* lowercase alphanumeric characters with no spaces. You can also include
* any of the following characters: _+=,.@-
*
* Length must be between 1 and 128 characters.
*
* @default - a CloudFormation generated name
*/
readonly name?: string;
/**
* An XML document generated by an identity provider (IdP) that supports
* SAML 2.0. The document includes the issuer's name, expiration information,
* and keys that can be used to validate the SAML authentication response
* (assertions) that are received from the IdP. You must generate the metadata
* document using the identity management software that is used as your
* organization's IdP.
*/
readonly metadataDocument: SamlMetadataDocument;
}
/**
* A SAML metadata document
*/
export declare abstract class SamlMetadataDocument {
/**
* Create a SAML metadata document from a XML string
*/
static fromXml(xml: string): SamlMetadataDocument;
/**
* Create a SAML metadata document from a XML file
*/
static fromFile(path: string): SamlMetadataDocument;
/**
* The XML content of the metadata document
*/
abstract readonly xml: string;
}
/**
* A SAML provider
*/
export declare class SamlProvider extends Resource implements ISamlProvider {
/** Uniquely identifies this class. */
static readonly PROPERTY_INJECTION_ID: string;
/**
* Import an existing provider
*/
static fromSamlProviderArn(scope: Construct, id: string, samlProviderArn: string): ISamlProvider;
readonly samlProviderArn: string;
constructor(scope: Construct, id: string, props: SamlProviderProps);
get samlProviderRef(): SAMLProviderReference;
}

View File

@@ -0,0 +1 @@
"use strict";var __esDecorate=exports&&exports.__esDecorate||function(ctor,descriptorIn,decorators,contextIn,initializers,extraInitializers){function accept(f){if(f!==void 0&&typeof f!="function")throw new TypeError("Function expected");return f}for(var kind=contextIn.kind,key=kind==="getter"?"get":kind==="setter"?"set":"value",target=!descriptorIn&&ctor?contextIn.static?ctor:ctor.prototype:null,descriptor=descriptorIn||(target?Object.getOwnPropertyDescriptor(target,contextIn.name):{}),_,done=!1,i=decorators.length-1;i>=0;i--){var context={};for(var p in contextIn)context[p]=p==="access"?{}:contextIn[p];for(var p in contextIn.access)context.access[p]=contextIn.access[p];context.addInitializer=function(f){if(done)throw new TypeError("Cannot add initializers after decoration has completed");extraInitializers.push(accept(f||null))};var result=(0,decorators[i])(kind==="accessor"?{get:descriptor.get,set:descriptor.set}:descriptor[key],context);if(kind==="accessor"){if(result===void 0)continue;if(result===null||typeof result!="object")throw new TypeError("Object expected");(_=accept(result.get))&&(descriptor.get=_),(_=accept(result.set))&&(descriptor.set=_),(_=accept(result.init))&&initializers.unshift(_)}else(_=accept(result))&&(kind==="field"?initializers.unshift(_):descriptor[key]=_)}target&&Object.defineProperty(target,contextIn.name,descriptor),done=!0},__runInitializers=exports&&exports.__runInitializers||function(thisArg,initializers,value){for(var useValue=arguments.length>2,i=0;i<initializers.length;i++)value=useValue?initializers[i].call(thisArg,value):initializers[i].call(thisArg);return useValue?value:void 0};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SamlProvider=exports.SamlMetadataDocument=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var fs=()=>{var tmp=require("fs");return fs=()=>tmp,tmp},iam_generated_1=()=>{var tmp=require("./iam.generated");return iam_generated_1=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},metadata_resource_1=()=>{var tmp=require("../../core/lib/metadata-resource");return metadata_resource_1=()=>tmp,tmp},literal_string_1=()=>{var tmp=require("../../core/lib/private/literal-string");return literal_string_1=()=>tmp,tmp},prop_injectable_1=()=>{var tmp=require("../../core/lib/prop-injectable");return prop_injectable_1=()=>tmp,tmp};class SamlMetadataDocument{static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_iam.SamlMetadataDocument",version:"2.252.0"};static fromXml(xml){return{xml}}static fromFile(path){return{xml:fs().readFileSync(path,"utf-8")}}}exports.SamlMetadataDocument=SamlMetadataDocument;let SamlProvider=(()=>{let _classDecorators=[prop_injectable_1().propertyInjectable],_classDescriptor,_classExtraInitializers=[],_classThis,_classSuper=core_1().Resource;var SamlProvider2=class extends _classSuper{static{_classThis=this}static{const _metadata=typeof Symbol=="function"&&Symbol.metadata?Object.create(_classSuper[Symbol.metadata]??null):void 0;__esDecorate(null,_classDescriptor={value:_classThis},_classDecorators,{kind:"class",name:_classThis.name,metadata:_metadata},null,_classExtraInitializers),SamlProvider2=_classThis=_classDescriptor.value,_metadata&&Object.defineProperty(_classThis,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:_metadata})}static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_iam.SamlProvider",version:"2.252.0"};static PROPERTY_INJECTION_ID="aws-cdk-lib.aws-iam.SamlProvider";static fromSamlProviderArn(scope,id,samlProviderArn){class Import extends core_1().Resource{samlProviderArn=samlProviderArn;samlProviderRef={samlProviderArn}}return new Import(scope,id)}samlProviderArn;constructor(scope,id,props){super(scope,id);try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_SamlProviderProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,SamlProvider2),error}if((0,metadata_resource_1().addConstructMetadata)(this,props),props.name&&!core_1().Token.isUnresolved(props.name)&&!/^[\w+=,.@-]{1,128}$/.test(props.name))throw new(core_1()).ValidationError((0,literal_string_1().lit)`InvalidSamlProviderName`,"Invalid SAML provider name. The name must be a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: _+=,.@-. Length must be between 1 and 128 characters.",this);const samlProvider=new(iam_generated_1()).CfnSAMLProvider(this,"Resource",{name:props.name,samlMetadataDocument:props.metadataDocument.xml});this.samlProviderArn=samlProvider.ref}get samlProviderRef(){return{samlProviderArn:this.samlProviderArn}}static{__runInitializers(_classThis,_classExtraInitializers)}};return SamlProvider2=_classThis})();exports.SamlProvider=SamlProvider;

View File

@@ -0,0 +1,32 @@
import type { IConstruct } from 'constructs';
import type { PolicyStatement } from './policy-statement';
import type { AddToPrincipalPolicyResult, IPrincipal, PrincipalPolicyFragment } from './principals';
/**
* Properties for an UnknownPrincipal
*/
export interface UnknownPrincipalProps {
/**
* The resource the role proxy is for
*/
readonly resource: IConstruct;
}
/**
* A principal for use in resources that need to have a role but it's unknown
*
* Some resources have roles associated with them which they assume, such as
* Lambda Functions, CodeBuild projects, StepFunctions machines, etc.
*
* When those resources are imported, their actual roles are not always
* imported with them. When that happens, we use an instance of this class
* instead, which will add user warnings when statements are attempted to be
* added to it.
*/
export declare class UnknownPrincipal implements IPrincipal {
readonly assumeRoleAction: string;
readonly grantPrincipal: IPrincipal;
private readonly resource;
constructor(props: UnknownPrincipalProps);
get policyFragment(): PrincipalPolicyFragment;
addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult;
addToPolicy(statement: PolicyStatement): boolean;
}

View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UnknownPrincipal=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var constructs_1=()=>{var tmp=require("constructs");return constructs_1=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},literal_string_1=()=>{var tmp=require("../../core/lib/private/literal-string");return literal_string_1=()=>tmp,tmp};class UnknownPrincipal{static[JSII_RTTI_SYMBOL_1]={fqn:"aws-cdk-lib.aws_iam.UnknownPrincipal",version:"2.252.0"};assumeRoleAction="sts:AssumeRole";grantPrincipal;resource;constructor(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_UnknownPrincipalProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,UnknownPrincipal),error}this.resource=props.resource,this.grantPrincipal=this}get policyFragment(){throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`CannotPolicyFragment`,`Cannot get policy fragment of ${constructs_1().Node.of(this.resource).path}, resource imported without a role`)}addToPrincipalPolicy(statement){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_PolicyStatement(statement)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addToPrincipalPolicy),error}const stack=core_1().Stack.of(this.resource),repr=JSON.stringify(stack.resolve(statement));return core_1().Annotations.of(this.resource).addWarningV2("@aws-cdk/aws-iam:unknownPrincipalAddStatementToRole",`Add statement to this resource's role: ${repr}`),{statementAdded:!0,policyDependable:new(constructs_1()).DependencyGroup}}addToPolicy(statement){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_PolicyStatement(statement)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addToPolicy),error}return this.addToPrincipalPolicy(statement).statementAdded}}exports.UnknownPrincipal=UnknownPrincipal;

210
cdk/node_modules/aws-cdk-lib/aws-iam/lib/user.d.ts generated vendored Normal file
View File

@@ -0,0 +1,210 @@
import type { Construct } from 'constructs';
import type { IGroup } from './group';
import type { IUserRef, UserReference } from './iam.generated';
import type { IIdentity } from './identity-base';
import type { IManagedPolicy } from './managed-policy';
import { Policy } from './policy';
import type { PolicyStatement } from './policy-statement';
import type { AddToPrincipalPolicyResult, IPrincipal, PrincipalPolicyFragment } from './principals';
import type { SecretValue } from '../../core';
import { Resource } from '../../core';
/**
* Represents an IAM user
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html
*/
export interface IUser extends IIdentity, IUserRef {
/**
* The user's name
* @attribute
*/
readonly userName: string;
/**
* The user's ARN
* @attribute
*/
readonly userArn: string;
/**
* Adds this user to a group.
*/
addToGroup(group: IGroup): void;
}
/**
* Properties for defining an IAM user
*/
export interface UserProps {
/**
* Groups to add this user to. You can also use `addToGroup` to add this
* user to a group.
*
* @default - No groups.
*/
readonly groups?: IGroup[];
/**
* A list of managed policies associated with this role.
*
* You can add managed policies later using
* `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`.
*
* @default - No managed policies.
*/
readonly managedPolicies?: IManagedPolicy[];
/**
* The path for the user name. For more information about paths, see IAM
* Identifiers in the IAM User Guide.
*
* @default /
*/
readonly path?: string;
/**
* AWS supports permissions boundaries for IAM entities (users or roles).
* A permissions boundary is an advanced feature for using a managed policy
* to set the maximum permissions that an identity-based policy can grant to
* an IAM entity. An entity's permissions boundary allows it to perform only
* the actions that are allowed by both its identity-based policies and its
* permissions boundaries.
*
* @link https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#cfn-iam-role-permissionsboundary
* @link https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html
*
* @default - No permissions boundary.
*/
readonly permissionsBoundary?: IManagedPolicy;
/**
* A name for the IAM user. For valid values, see the UserName parameter for
* the CreateUser action in the IAM API Reference. If you don't specify a
* name, AWS CloudFormation generates a unique physical ID and uses that ID
* for the user name.
*
* If you specify a name, you cannot perform updates that require
* replacement of this resource. You can perform updates that require no or
* some interruption. If you must replace the resource, specify a new name.
*
* If you specify a name, you must specify the CAPABILITY_NAMED_IAM value to
* acknowledge your template's capabilities. For more information, see
* Acknowledging IAM Resources in AWS CloudFormation Templates.
*
* @default - Generated by CloudFormation (recommended)
*/
readonly userName?: string;
/**
* The password for the user. This is required so the user can access the
* AWS Management Console.
*
* You can use `SecretValue.unsafePlainText` to specify a password in plain text or
* use `secretsmanager.Secret.fromSecretAttributes` to reference a secret in
* Secrets Manager.
*
* @default - User won't be able to access the management console without a password.
*/
readonly password?: SecretValue;
/**
* Specifies whether the user is required to set a new password the next
* time the user logs in to the AWS Management Console.
*
* If this is set to 'true', you must also specify "initialPassword".
*
* @default false
*/
readonly passwordResetRequired?: boolean;
}
/**
* Represents a user defined outside of this stack.
*/
export interface UserAttributes {
/**
* The ARN of the user.
*
* Format: arn:<partition>:iam::<account-id>:user/<user-name-with-path>
*/
readonly userArn: string;
}
/**
* Define a new IAM user
*/
export declare class User extends Resource implements IIdentity, IUser {
/**
* Uniquely identifies this class.
*/
static readonly PROPERTY_INJECTION_ID: string;
/**
* Import an existing user given a username.
*
* @param scope construct scope
* @param id construct id
* @param userName the username of the existing user to import
*/
static fromUserName(scope: Construct, id: string, userName: string): IUser;
/**
* Import an existing user given a user ARN.
*
* If the ARN comes from a Token, the User cannot have a path; if so, any attempt
* to reference its username will fail.
*
* @param scope construct scope
* @param id construct id
* @param userArn the ARN of an existing user to import
*/
static fromUserArn(scope: Construct, id: string, userArn: string): IUser;
/**
* Import an existing user given user attributes.
*
* If the ARN comes from a Token, the User cannot have a path; if so, any attempt
* to reference its username will fail.
*
* @param scope construct scope
* @param id construct id
* @param attrs the attributes of the user to import
*/
static fromUserAttributes(scope: Construct, id: string, attrs: UserAttributes): IUser;
readonly grantPrincipal: IPrincipal;
readonly principalAccount: string | undefined;
readonly assumeRoleAction: string;
/**
* The CfnUser resource
*/
private readonly _resource;
/**
* An attribute that represents the user name.
* @attribute
*/
get userName(): string;
/**
* An attribute that represents the user's ARN.
* @attribute
*/
get userArn(): string;
/**
* Returns the permissions boundary attached to this user
*/
readonly permissionsBoundary?: IManagedPolicy;
readonly policyFragment: PrincipalPolicyFragment;
private readonly groups;
private readonly _managedPolicies;
private readonly attachedPolicies;
private defaultPolicy?;
private readonly _path?;
constructor(scope: Construct, id: string, props?: UserProps);
get userRef(): UserReference;
/**
* Adds this user to a group.
*/
addToGroup(group: IGroup): void;
/**
* Attaches a managed policy to the user.
* @param policy The managed policy to attach.
*/
addManagedPolicy(policy: IManagedPolicy): void;
/**
* Attaches a policy to this user.
*/
attachInlinePolicy(policy: Policy): void;
/**
* Adds an IAM statement to the default policy.
*
* @returns true
*/
addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult;
addToPolicy(statement: PolicyStatement): boolean;
private parseLoginProfile;
}

1
cdk/node_modules/aws-cdk-lib/aws-iam/lib/user.js generated vendored Normal file

File diff suppressed because one or more lines are too long

57
cdk/node_modules/aws-cdk-lib/aws-iam/lib/util.d.ts generated vendored Normal file
View File

@@ -0,0 +1,57 @@
import type { IConstruct } from 'constructs';
import type { IPolicy } from './policy';
import type { IPostProcessor, IResolvable, IResolveContext } from '../../core';
export declare const LITERAL_STRING_KEY = "LiteralString";
export declare function undefinedIfEmpty(f: () => string[]): string[];
/**
* Used to generate a unique policy name based on the policy resource construct.
* The logical ID of the resource is a great candidate as long as it doesn't exceed
* 128 characters, so we take the last 128 characters (in order to make sure the hash
* is there).
*/
export declare function generatePolicyName(scope: IConstruct, logicalId: string): string;
/**
* Helper class that maintains the set of attached policies for a principal.
*/
export declare class AttachedPolicies {
private policies;
/**
* Adds a policy to the list of attached policies.
*
* If this policy is already, attached, returns false.
* If there is another policy attached with the same name, throws an exception.
*/
attach(policy: IPolicy): void;
}
/**
* Merge two dictionaries that represent IAM principals
*
* Does an in-place merge.
*/
export declare function mergePrincipal(target: {
[key: string]: string[];
}, source: {
[key: string]: string[];
}): {
[key: string]: string[];
};
/**
* Lazy string set token that dedupes entries
*
* Needs to operate post-resolve, because the inputs could be
* `[ '${Token[TOKEN.9]}', '${Token[TOKEN.10]}', '${Token[TOKEN.20]}' ]`, which
* still all resolve to the same string value.
*
* Needs to JSON.stringify() results because strings could resolve to literal
* strings but could also resolve to `{ Fn::Join: [...] }`.
*/
export declare class UniqueStringSet implements IResolvable, IPostProcessor {
private readonly fn;
static from(fn: () => string[]): string[];
readonly creationStack: string[];
private constructor();
resolve(context: IResolveContext): string[];
postProcess(input: any, _context: IResolveContext): any;
toString(): string;
}
export declare function sum(xs: number[]): number;

1
cdk/node_modules/aws-cdk-lib/aws-iam/lib/util.js generated vendored Normal file
View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UniqueStringSet=exports.AttachedPolicies=exports.LITERAL_STRING_KEY=void 0,exports.undefinedIfEmpty=undefinedIfEmpty,exports.generatePolicyName=generatePolicyName,exports.mergePrincipal=mergePrincipal,exports.sum=sum;var core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},literal_string_1=()=>{var tmp=require("../../core/lib/private/literal-string");return literal_string_1=()=>tmp,tmp};const MAX_POLICY_NAME_LEN=128;exports.LITERAL_STRING_KEY="LiteralString";function undefinedIfEmpty(f){return core_1().Lazy.list({produce:()=>{const array=f();return array&&array.length>0?array:void 0}})}function generatePolicyName(scope,logicalId){const resolvedLogicalId=core_1().Tokenization.resolve(logicalId,{scope,resolver:new(core_1()).DefaultTokenResolver(new(core_1()).StringConcat)});return lastNCharacters(resolvedLogicalId,MAX_POLICY_NAME_LEN)}function lastNCharacters(str,n){const startIndex=Math.max(str.length-n,0);return str.substring(startIndex,str.length)}class AttachedPolicies{policies=new Array;attach(policy){if(!this.policies.find(p=>p===policy)){if(this.policies.find(p=>p.policyName===policy.policyName))throw new(core_1()).ValidationError((0,literal_string_1().lit)`PolicyNamedAlreadyAttached`,`A policy named "${policy.policyName}" is already attached`,policy);this.policies.push(policy)}}}exports.AttachedPolicies=AttachedPolicies;function mergePrincipal(target,source){const sourceKeys=Object.keys(source),targetKeys=Object.keys(target);if(exports.LITERAL_STRING_KEY in source&&targetKeys.some(k=>k!==exports.LITERAL_STRING_KEY)||exports.LITERAL_STRING_KEY in target&&sourceKeys.some(k=>k!==exports.LITERAL_STRING_KEY))throw new(core_1()).UnscopedValidationError((0,literal_string_1().lit)`CannotMustBeCannotMerge`,`Cannot merge principals ${JSON.stringify(target)} and ${JSON.stringify(source)}; if one uses a literal principal string the other one must be empty`);for(const key of sourceKeys){target[key]=target[key]??[];let value=source[key];Array.isArray(value)||(value=[value]),target[key].push(...value)}return target}class UniqueStringSet{fn;static from(fn){return core_1().Token.asList(new UniqueStringSet(fn))}creationStack=["Token stack traces are no longer captured"];constructor(fn){this.fn=fn}resolve(context){return context.registerPostProcessor(this),this.fn()}postProcess(input,_context){if(!Array.isArray(input))return input;if(input.length===0)return;const uniq={};for(const el of input)uniq[JSON.stringify(el)]=el;return Object.values(uniq)}toString(){return core_1().Token.asString(this)}}exports.UniqueStringSet=UniqueStringSet;function sum(xs){return xs.reduce((a,b)=>a+b,0)}

12
cdk/node_modules/aws-cdk-lib/aws-iam/lib/utils.d.ts generated vendored Normal file
View File

@@ -0,0 +1,12 @@
import type { IConstruct } from 'constructs';
import type { IPrincipal } from './principals';
/**
* Determines whether the given Principal is a newly created resource managed by the CDK,
* or if it's a referenced existing resource.
*
* @param principal the Principal to check
* @returns true if the Principal is a newly created resource, false otherwise.
* Additionally, the type of the principal will now also be IConstruct
* (because a newly created resource must be a construct)
*/
export declare function principalIsOwnedResource(principal: IPrincipal): principal is IPrincipal & IConstruct;

1
cdk/node_modules/aws-cdk-lib/aws-iam/lib/utils.js generated vendored Normal file
View File

@@ -0,0 +1 @@
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.principalIsOwnedResource=principalIsOwnedResource;var constructs_1=()=>{var tmp=require("constructs");return constructs_1=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp};function principalIsOwnedResource(principal){return isConstruct(principal)?core_1().Resource.isOwnedResource(principal):!1}function isConstruct(x){const sym=Symbol.for("constructs.Construct.node");return typeof x=="object"&&x&&(x instanceof constructs_1().Construct||!!x.node||!!x[sym])}