Skip to content

Validation mixins for models

AwsTypesValidationMixin

Mixin class providing validation for AWS CDK resource types and interfaces.

Provides centralized validation logic for AWS CDK construct interfaces and types to ensure that configuration models receive valid AWS resource objects. This mixin prevents runtime errors by validating that provided objects implement the expected AWS CDK interfaces and have required attributes for proper resource integration.

AWS CDK Compatibility
  • Works with both concrete CDK classes and interface types
  • Validates attribute presence rather than exact type inheritance
  • Compatible with CDK construct lookup and import patterns
  • Supports cross-stack resource references
Source code in mare_aws_common_lib/models/mixins.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
class AwsTypesValidationMixin:
    """Mixin class providing validation for AWS CDK resource types and interfaces.

    Provides centralized validation logic for AWS CDK construct interfaces and types
    to ensure that configuration models receive valid AWS resource objects. This mixin
    prevents runtime errors by validating that provided objects implement the expected
    AWS CDK interfaces and have required attributes for proper resource integration.

    AWS CDK Compatibility:
        - Works with both concrete CDK classes and interface types
        - Validates attribute presence rather than exact type inheritance
        - Compatible with CDK construct lookup and import patterns
        - Supports cross-stack resource references
    """

    @staticmethod
    def validate_vpc(value: Any) -> Any:
        """Validate that the provided object implements the ec2.IVpc interface.

        Ensures that the VPC object has the required attributes for AWS CDK VPC
        operations including network configuration, subnet access, and availability
        zone information. This validation prevents runtime errors when the VPC
        is used for resource deployment in private subnets or network configuration.

        Args:
            value: Object to validate as an ec2.IVpc implementation. Expected to be
                  an AWS CDK VPC construct or interface that provides network
                  infrastructure for resource deployment.

        Returns:
            The original VPC object if validation passes, unchanged for use in
                CDK resource configuration and network operations.

        Raises:
            ValueError: If value is None - VPC is required for network-dependent resources
            ValueError: If object doesn't implement IVpc interface - missing required
                       vpc_id or availability_zones attributes needed for CDK operations

        Required Attributes:
            vpc_id: Unique identifier for the VPC used in resource configuration  
            availability_zones: List of AZs for subnet and resource placement
        """
        if value is None:
            raise ValueError("VPC must be set")
        if not (hasattr(value, 'vpc_id') and hasattr(value, 'availability_zones')):
            raise ValueError("Must be a valid ec2.IVpc object")
        return value

    @staticmethod
    def validate_role(value: Any, required: bool = True) -> Any:
        """Validate that the provided object implements the iam.IRole interface.

        Ensures that the IAM role object has the required attributes for AWS CDK
        role operations including policy attachment, resource assignment, and
        permission management. Supports both required and optional role validation
        based on the configuration requirements.

        Args:
            value: Object to validate as an iam.IRole implementation. Expected to be
                  an AWS CDK IAM role construct that provides permissions for AWS
                  resource operations and service integration.
            required: Whether the role is mandatory for the configuration. When True,
                     None values will raise validation errors. When False, allows
                     None values for optional role configurations.

        Returns:
            The original IAM role object if validation passes, unchanged for use in
                CDK resource configuration and permission assignment.

        Raises:
            ValueError: If required=True and value is None - role is mandatory
            ValueError: If object doesn't implement IRole interface - missing required
                       role_arn or role_name attributes needed for CDK operations

        Required Attributes:
            role_arn: Amazon Resource Name for the IAM role used in policy references  
            role_name: Human-readable name for the role used in AWS console and logging
        """
        if required and value is None:
            raise ValueError("IAM Role must be set")
        if value is not None and not (hasattr(value, 'role_arn') and hasattr(value, 'role_name')):
            raise ValueError("Must be a valid iam.IRole object")
        return value

    @staticmethod
    def validate_repository(value: Any, type: str, valid_object_type: str, required: bool = True) -> Any:
        """Validate repository objects for ECR, CodeCommit, or other repository types.

        Generic validation method for AWS repository interfaces ensuring that
        repository objects have the required attributes for CDK operations including
        image pulling, code checkout, and repository policy management. Supports
        different repository types with customizable error messages.

        Args:
            value: Object to validate as a repository interface implementation.
                  Expected to be an AWS CDK repository construct (ECR, CodeCommit, etc.)
                  that provides source code or container image access.
            type: Human-readable repository type for error messages (e.g., "ECR", "CodeCommit").
                 Used to generate specific error messages that help developers understand
                 which repository type is expected.
            valid_object_type: Expected CDK interface or class name for error messages
                              (e.g., "ecr.IRepository", "codecommit.IRepository").
                              Provides specific type information in validation errors.
            required: Whether the repository is mandatory for the configuration. When True,
                     None values will raise validation errors. When False, allows None
                     values for optional repository configurations.

        Returns:
            The original repository object if validation passes, unchanged for use in
                CDK resource configuration and source/image operations.

        Raises:
            ValueError: If required=True and value is None - repository is mandatory  
            ValueError: If object doesn't implement repository interface - missing required
                       repository_arn or repository_name attributes needed for CDK operations

        Required Attributes:
            repository_arn: Amazon Resource Name for the repository used in policy references  
            repository_name: Human-readable name for the repository used in configuration
        """
        if required and value is None:
            raise ValueError(f"{type.capitalize()} repository must be set")
        if value is not None and not (hasattr(value, 'repository_arn') and hasattr(value, 'repository_name')):
            raise ValueError(f"{type.capitalize()} repository must be a valid {valid_object_type} object")
        return value

    @staticmethod
    def validate_application_load_balancer(value: Any) -> Any:
        """Validate that the provided object implements the elbv2.IApplicationLoadBalancer interface.

        Ensures that the Application Load Balancer object has the required attributes for AWS CDK
        load balancer operations including traffic routing, target group management, and listener
        configuration. This validation is essential for configurations that use ALBs for distributing
        incoming traffic, SSL termination, and backend service integration.

        Args:
            value: Object to validate as an elbv2.IApplicationLoadBalancer implementation. Expected to be
                  an AWS CDK Application Load Balancer construct that provides Layer 7 load balancing
                  capabilities. Cannot be None as ALB is required for origin configuration.

        Returns:
            The original Application Load Balancer object if validation passes, unchanged for use in
                CDK resource configuration and traffic routing operations.

        Raises:
            ValueError: If object doesn't implement IApplicationLoadBalancer interface - missing required
                       load_balancer_arn or load_balancer_dns_name attributes needed for CDK operations

        Required Attributes:
            load_balancer_arn: Amazon Resource Name for the ALB used in policy and target references  
            load_balancer_dns_name: DNS name for the load balancer used in origin configuration

        Note:
            This validator does not allow None values since the ALB is a required component for
            CloudFront origin configuration and traffic routing to backend services.
        """
        if not (hasattr(value, 'load_balancer_arn') and hasattr(value, 'load_balancer_dns_name')):
            raise ValueError("ALB must be a valid elbv2.IApplicationLoadBalancer object")
        return value

    @staticmethod
    def validate_cloudfront_distribution(value: Any) -> Any:
        """Validate that the provided object implements the cloudfront.IDistribution interface.

        Ensures that the CloudFront distribution object has the required attributes for AWS CDK
        distribution operations including content delivery, cache management, and origin integration.
        This validation is essential for configurations that reference existing CloudFront distributions
        for CDN functionality, geographic distribution, and performance optimization.

        Args:
            value: Object to validate as a cloudfront.IDistribution implementation. Expected to be
                an AWS CDK CloudFront distribution construct that provides global content delivery
                capabilities. Cannot be None as the distribution is required for CDN operations.

        Returns:
            The original CloudFront distribution object if validation passes, unchanged for use in
                CDK resource configuration and content delivery operations.

        Raises:
            ValueError: If object doesn't implement IDistribution interface - missing required
                    distribution_arn attribute needed for CDK operations and resource references

        Required Attributes:
            distribution_arn: Amazon Resource Name for the CloudFront distribution used in policy
                            references, monitoring, and cross-service integration
        """
        if not hasattr(value, 'distribution_arn'):
            raise ValueError("CloudFront distribution must be a valid cloudfront.IDistribution object with distribution_arn attribute")
        return value


    @staticmethod
    def validate_bucket(value: Any) -> Any:
        """Validate that the provided object implements the s3.IBucket interface.

        Ensures that the S3 bucket object has the required attributes for AWS CDK
        bucket operations including object storage, policy management, and cross-service
        integration. This validation is essential for configurations that use S3 buckets
        for data storage, static website hosting, or backup operations.

        Args:
            value: Object to validate as an s3.IBucket implementation. Expected to be
                  an AWS CDK S3 bucket construct that provides object storage capabilities.
                  Can be None for optional bucket configurations.

        Returns:
            The original S3 bucket object if validation passes, unchanged for use in
                CDK resource configuration and storage operations. Returns None unchanged
                if bucket is optional and not provided.

        Raises:
            ValueError: If object doesn't implement IBucket interface - missing required
                       bucket_arn or bucket_name attributes needed for CDK operations

        Required Attributes:
            When not none:  
            bucket_arn: Amazon Resource Name for the S3 bucket used in policy references  
            bucket_name: Globally unique name for the bucket used in object operations

        Note:
            Unlike other validation methods, this allows None values by default since
            many AWS resources have optional S3 bucket configurations for features
            like logging, backup, or artifact storage.
        """
        if value is not None and not (hasattr(value, 'bucket_arn') and hasattr(value, 'bucket_name')):
            raise ValueError("Bucket must be a valid s3.IBucket object")
        return value

    @staticmethod
    def validate_vars(value: Any) -> Any | Dict:
        """Validate CodeBuild environment variable dictionary structure and types.

        Ensures that environment variables for CodeBuild projects are properly structured
        as a dictionary with string keys and valid BuildEnvironmentVariable objects as values.
        This validation prevents runtime errors in CodeBuild projects by ensuring that
        environment variables conform to the expected AWS CDK interface requirements.

        Args:
            value: Dictionary of environment variables to validate. Expected to be a
                  mapping of string keys to AWS CDK BuildEnvironmentVariable objects
                  that define environment variables for CodeBuild project execution.
                  Can be None for projects without custom environment variables.

        Returns:
            The original environment variables dictionary if validation passes, unchanged
                for use in CodeBuild project configuration. Returns None unchanged if no
                environment variables are provided.

        Raises:
            ValueError: If value is not a dictionary when provided - environment variables
                       must be key-value mappings for CodeBuild compatibility
            ValueError: If any dictionary key is not a string - environment variable names
                       must be strings for proper shell environment integration
            ValueError: If any dictionary value doesn't implement BuildEnvironmentVariable
                       interface - missing required "value" attribute for variable content

        Required Structure:
            - Dictionary type with string keys
            - Values must be BuildEnvironmentVariable objects with "value" attribute
            - Optional "type" attribute for variable type specification (PLAINTEXT, PARAMETER_STORE, SECRETS_MANAGER)


        CodeBuild Integration:
            - Used in codebuild.Project environment configuration
            - Supports PLAINTEXT, PARAMETER_STORE, and SECRETS_MANAGER variable types
            - Compatible with CodePipeline build action environment overrides
            - Validates variables for buildspec.yml environment section

        Environment Variable Types:
            PLAINTEXT: Direct string values stored in the build environment  
            PARAMETER_STORE: Values retrieved from AWS Systems Manager Parameter Store  
            SECRETS_MANAGER: Values retrieved from AWS Secrets Manager
        """
        if value is None:
            return value 

        if not isinstance(value, dict):
            raise ValueError("Environment variables must be a dictionary")

        # Validate each environment variable
        for key, env_var in value.items():
            if not isinstance(key, str):
                raise ValueError(f"Environment variable key '{key}' must be a string")

            # Check if it"s a proper CodeBuild BuildEnvironmentVariable
            # These objects typically have "value" and optionally "type" attributes
            if not hasattr(env_var, "value"):
                raise ValueError(f"Environment variable '{key}' must be a valid CodeBuild BuildEnvironmentVariable object")

        return value 

validate_application_load_balancer(value) staticmethod

Validate that the provided object implements the elbv2.IApplicationLoadBalancer interface.

Ensures that the Application Load Balancer object has the required attributes for AWS CDK load balancer operations including traffic routing, target group management, and listener configuration. This validation is essential for configurations that use ALBs for distributing incoming traffic, SSL termination, and backend service integration.

Parameters:

Name Type Description Default
value Any

Object to validate as an elbv2.IApplicationLoadBalancer implementation. Expected to be an AWS CDK Application Load Balancer construct that provides Layer 7 load balancing capabilities. Cannot be None as ALB is required for origin configuration.

required

Returns:

Type Description
Any

The original Application Load Balancer object if validation passes, unchanged for use in CDK resource configuration and traffic routing operations.

Raises:

Type Description
ValueError

If object doesn't implement IApplicationLoadBalancer interface - missing required load_balancer_arn or load_balancer_dns_name attributes needed for CDK operations

Required Attributes

load_balancer_arn: Amazon Resource Name for the ALB used in policy and target references
load_balancer_dns_name: DNS name for the load balancer used in origin configuration

Note

This validator does not allow None values since the ALB is a required component for CloudFront origin configuration and traffic routing to backend services.

Source code in mare_aws_common_lib/models/mixins.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
@staticmethod
def validate_application_load_balancer(value: Any) -> Any:
    """Validate that the provided object implements the elbv2.IApplicationLoadBalancer interface.

    Ensures that the Application Load Balancer object has the required attributes for AWS CDK
    load balancer operations including traffic routing, target group management, and listener
    configuration. This validation is essential for configurations that use ALBs for distributing
    incoming traffic, SSL termination, and backend service integration.

    Args:
        value: Object to validate as an elbv2.IApplicationLoadBalancer implementation. Expected to be
              an AWS CDK Application Load Balancer construct that provides Layer 7 load balancing
              capabilities. Cannot be None as ALB is required for origin configuration.

    Returns:
        The original Application Load Balancer object if validation passes, unchanged for use in
            CDK resource configuration and traffic routing operations.

    Raises:
        ValueError: If object doesn't implement IApplicationLoadBalancer interface - missing required
                   load_balancer_arn or load_balancer_dns_name attributes needed for CDK operations

    Required Attributes:
        load_balancer_arn: Amazon Resource Name for the ALB used in policy and target references  
        load_balancer_dns_name: DNS name for the load balancer used in origin configuration

    Note:
        This validator does not allow None values since the ALB is a required component for
        CloudFront origin configuration and traffic routing to backend services.
    """
    if not (hasattr(value, 'load_balancer_arn') and hasattr(value, 'load_balancer_dns_name')):
        raise ValueError("ALB must be a valid elbv2.IApplicationLoadBalancer object")
    return value

validate_bucket(value) staticmethod

Validate that the provided object implements the s3.IBucket interface.

Ensures that the S3 bucket object has the required attributes for AWS CDK bucket operations including object storage, policy management, and cross-service integration. This validation is essential for configurations that use S3 buckets for data storage, static website hosting, or backup operations.

Parameters:

Name Type Description Default
value Any

Object to validate as an s3.IBucket implementation. Expected to be an AWS CDK S3 bucket construct that provides object storage capabilities. Can be None for optional bucket configurations.

required

Returns:

Type Description
Any

The original S3 bucket object if validation passes, unchanged for use in CDK resource configuration and storage operations. Returns None unchanged if bucket is optional and not provided.

Raises:

Type Description
ValueError

If object doesn't implement IBucket interface - missing required bucket_arn or bucket_name attributes needed for CDK operations

Required Attributes

When not none:
bucket_arn: Amazon Resource Name for the S3 bucket used in policy references
bucket_name: Globally unique name for the bucket used in object operations

Note

Unlike other validation methods, this allows None values by default since many AWS resources have optional S3 bucket configurations for features like logging, backup, or artifact storage.

Source code in mare_aws_common_lib/models/mixins.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
@staticmethod
def validate_bucket(value: Any) -> Any:
    """Validate that the provided object implements the s3.IBucket interface.

    Ensures that the S3 bucket object has the required attributes for AWS CDK
    bucket operations including object storage, policy management, and cross-service
    integration. This validation is essential for configurations that use S3 buckets
    for data storage, static website hosting, or backup operations.

    Args:
        value: Object to validate as an s3.IBucket implementation. Expected to be
              an AWS CDK S3 bucket construct that provides object storage capabilities.
              Can be None for optional bucket configurations.

    Returns:
        The original S3 bucket object if validation passes, unchanged for use in
            CDK resource configuration and storage operations. Returns None unchanged
            if bucket is optional and not provided.

    Raises:
        ValueError: If object doesn't implement IBucket interface - missing required
                   bucket_arn or bucket_name attributes needed for CDK operations

    Required Attributes:
        When not none:  
        bucket_arn: Amazon Resource Name for the S3 bucket used in policy references  
        bucket_name: Globally unique name for the bucket used in object operations

    Note:
        Unlike other validation methods, this allows None values by default since
        many AWS resources have optional S3 bucket configurations for features
        like logging, backup, or artifact storage.
    """
    if value is not None and not (hasattr(value, 'bucket_arn') and hasattr(value, 'bucket_name')):
        raise ValueError("Bucket must be a valid s3.IBucket object")
    return value

validate_cloudfront_distribution(value) staticmethod

Validate that the provided object implements the cloudfront.IDistribution interface.

Ensures that the CloudFront distribution object has the required attributes for AWS CDK distribution operations including content delivery, cache management, and origin integration. This validation is essential for configurations that reference existing CloudFront distributions for CDN functionality, geographic distribution, and performance optimization.

Parameters:

Name Type Description Default
value Any

Object to validate as a cloudfront.IDistribution implementation. Expected to be an AWS CDK CloudFront distribution construct that provides global content delivery capabilities. Cannot be None as the distribution is required for CDN operations.

required

Returns:

Type Description
Any

The original CloudFront distribution object if validation passes, unchanged for use in CDK resource configuration and content delivery operations.

Raises:

Type Description
ValueError

If object doesn't implement IDistribution interface - missing required distribution_arn attribute needed for CDK operations and resource references

Required Attributes

distribution_arn: Amazon Resource Name for the CloudFront distribution used in policy references, monitoring, and cross-service integration

Source code in mare_aws_common_lib/models/mixins.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
@staticmethod
def validate_cloudfront_distribution(value: Any) -> Any:
    """Validate that the provided object implements the cloudfront.IDistribution interface.

    Ensures that the CloudFront distribution object has the required attributes for AWS CDK
    distribution operations including content delivery, cache management, and origin integration.
    This validation is essential for configurations that reference existing CloudFront distributions
    for CDN functionality, geographic distribution, and performance optimization.

    Args:
        value: Object to validate as a cloudfront.IDistribution implementation. Expected to be
            an AWS CDK CloudFront distribution construct that provides global content delivery
            capabilities. Cannot be None as the distribution is required for CDN operations.

    Returns:
        The original CloudFront distribution object if validation passes, unchanged for use in
            CDK resource configuration and content delivery operations.

    Raises:
        ValueError: If object doesn't implement IDistribution interface - missing required
                distribution_arn attribute needed for CDK operations and resource references

    Required Attributes:
        distribution_arn: Amazon Resource Name for the CloudFront distribution used in policy
                        references, monitoring, and cross-service integration
    """
    if not hasattr(value, 'distribution_arn'):
        raise ValueError("CloudFront distribution must be a valid cloudfront.IDistribution object with distribution_arn attribute")
    return value

validate_repository(value, type, valid_object_type, required=True) staticmethod

Validate repository objects for ECR, CodeCommit, or other repository types.

Generic validation method for AWS repository interfaces ensuring that repository objects have the required attributes for CDK operations including image pulling, code checkout, and repository policy management. Supports different repository types with customizable error messages.

Parameters:

Name Type Description Default
value Any

Object to validate as a repository interface implementation. Expected to be an AWS CDK repository construct (ECR, CodeCommit, etc.) that provides source code or container image access.

required
type str

Human-readable repository type for error messages (e.g., "ECR", "CodeCommit"). Used to generate specific error messages that help developers understand which repository type is expected.

required
valid_object_type str

Expected CDK interface or class name for error messages (e.g., "ecr.IRepository", "codecommit.IRepository"). Provides specific type information in validation errors.

required
required bool

Whether the repository is mandatory for the configuration. When True, None values will raise validation errors. When False, allows None values for optional repository configurations.

True

Returns:

Type Description
Any

The original repository object if validation passes, unchanged for use in CDK resource configuration and source/image operations.

Raises:

Type Description
ValueError

If required=True and value is None - repository is mandatory

ValueError

If object doesn't implement repository interface - missing required repository_arn or repository_name attributes needed for CDK operations

Required Attributes

repository_arn: Amazon Resource Name for the repository used in policy references
repository_name: Human-readable name for the repository used in configuration

Source code in mare_aws_common_lib/models/mixins.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
@staticmethod
def validate_repository(value: Any, type: str, valid_object_type: str, required: bool = True) -> Any:
    """Validate repository objects for ECR, CodeCommit, or other repository types.

    Generic validation method for AWS repository interfaces ensuring that
    repository objects have the required attributes for CDK operations including
    image pulling, code checkout, and repository policy management. Supports
    different repository types with customizable error messages.

    Args:
        value: Object to validate as a repository interface implementation.
              Expected to be an AWS CDK repository construct (ECR, CodeCommit, etc.)
              that provides source code or container image access.
        type: Human-readable repository type for error messages (e.g., "ECR", "CodeCommit").
             Used to generate specific error messages that help developers understand
             which repository type is expected.
        valid_object_type: Expected CDK interface or class name for error messages
                          (e.g., "ecr.IRepository", "codecommit.IRepository").
                          Provides specific type information in validation errors.
        required: Whether the repository is mandatory for the configuration. When True,
                 None values will raise validation errors. When False, allows None
                 values for optional repository configurations.

    Returns:
        The original repository object if validation passes, unchanged for use in
            CDK resource configuration and source/image operations.

    Raises:
        ValueError: If required=True and value is None - repository is mandatory  
        ValueError: If object doesn't implement repository interface - missing required
                   repository_arn or repository_name attributes needed for CDK operations

    Required Attributes:
        repository_arn: Amazon Resource Name for the repository used in policy references  
        repository_name: Human-readable name for the repository used in configuration
    """
    if required and value is None:
        raise ValueError(f"{type.capitalize()} repository must be set")
    if value is not None and not (hasattr(value, 'repository_arn') and hasattr(value, 'repository_name')):
        raise ValueError(f"{type.capitalize()} repository must be a valid {valid_object_type} object")
    return value

validate_role(value, required=True) staticmethod

Validate that the provided object implements the iam.IRole interface.

Ensures that the IAM role object has the required attributes for AWS CDK role operations including policy attachment, resource assignment, and permission management. Supports both required and optional role validation based on the configuration requirements.

Parameters:

Name Type Description Default
value Any

Object to validate as an iam.IRole implementation. Expected to be an AWS CDK IAM role construct that provides permissions for AWS resource operations and service integration.

required
required bool

Whether the role is mandatory for the configuration. When True, None values will raise validation errors. When False, allows None values for optional role configurations.

True

Returns:

Type Description
Any

The original IAM role object if validation passes, unchanged for use in CDK resource configuration and permission assignment.

Raises:

Type Description
ValueError

If required=True and value is None - role is mandatory

ValueError

If object doesn't implement IRole interface - missing required role_arn or role_name attributes needed for CDK operations

Required Attributes

role_arn: Amazon Resource Name for the IAM role used in policy references
role_name: Human-readable name for the role used in AWS console and logging

Source code in mare_aws_common_lib/models/mixins.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
@staticmethod
def validate_role(value: Any, required: bool = True) -> Any:
    """Validate that the provided object implements the iam.IRole interface.

    Ensures that the IAM role object has the required attributes for AWS CDK
    role operations including policy attachment, resource assignment, and
    permission management. Supports both required and optional role validation
    based on the configuration requirements.

    Args:
        value: Object to validate as an iam.IRole implementation. Expected to be
              an AWS CDK IAM role construct that provides permissions for AWS
              resource operations and service integration.
        required: Whether the role is mandatory for the configuration. When True,
                 None values will raise validation errors. When False, allows
                 None values for optional role configurations.

    Returns:
        The original IAM role object if validation passes, unchanged for use in
            CDK resource configuration and permission assignment.

    Raises:
        ValueError: If required=True and value is None - role is mandatory
        ValueError: If object doesn't implement IRole interface - missing required
                   role_arn or role_name attributes needed for CDK operations

    Required Attributes:
        role_arn: Amazon Resource Name for the IAM role used in policy references  
        role_name: Human-readable name for the role used in AWS console and logging
    """
    if required and value is None:
        raise ValueError("IAM Role must be set")
    if value is not None and not (hasattr(value, 'role_arn') and hasattr(value, 'role_name')):
        raise ValueError("Must be a valid iam.IRole object")
    return value

validate_vars(value) staticmethod

Validate CodeBuild environment variable dictionary structure and types.

Ensures that environment variables for CodeBuild projects are properly structured as a dictionary with string keys and valid BuildEnvironmentVariable objects as values. This validation prevents runtime errors in CodeBuild projects by ensuring that environment variables conform to the expected AWS CDK interface requirements.

Parameters:

Name Type Description Default
value Any

Dictionary of environment variables to validate. Expected to be a mapping of string keys to AWS CDK BuildEnvironmentVariable objects that define environment variables for CodeBuild project execution. Can be None for projects without custom environment variables.

required

Returns:

Type Description
Any | Dict

The original environment variables dictionary if validation passes, unchanged for use in CodeBuild project configuration. Returns None unchanged if no environment variables are provided.

Raises:

Type Description
ValueError

If value is not a dictionary when provided - environment variables must be key-value mappings for CodeBuild compatibility

ValueError

If any dictionary key is not a string - environment variable names must be strings for proper shell environment integration

ValueError

If any dictionary value doesn't implement BuildEnvironmentVariable interface - missing required "value" attribute for variable content

Required Structure
  • Dictionary type with string keys
  • Values must be BuildEnvironmentVariable objects with "value" attribute
  • Optional "type" attribute for variable type specification (PLAINTEXT, PARAMETER_STORE, SECRETS_MANAGER)
CodeBuild Integration
  • Used in codebuild.Project environment configuration
  • Supports PLAINTEXT, PARAMETER_STORE, and SECRETS_MANAGER variable types
  • Compatible with CodePipeline build action environment overrides
  • Validates variables for buildspec.yml environment section
Environment Variable Types

PLAINTEXT: Direct string values stored in the build environment
PARAMETER_STORE: Values retrieved from AWS Systems Manager Parameter Store
SECRETS_MANAGER: Values retrieved from AWS Secrets Manager

Source code in mare_aws_common_lib/models/mixins.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
@staticmethod
def validate_vars(value: Any) -> Any | Dict:
    """Validate CodeBuild environment variable dictionary structure and types.

    Ensures that environment variables for CodeBuild projects are properly structured
    as a dictionary with string keys and valid BuildEnvironmentVariable objects as values.
    This validation prevents runtime errors in CodeBuild projects by ensuring that
    environment variables conform to the expected AWS CDK interface requirements.

    Args:
        value: Dictionary of environment variables to validate. Expected to be a
              mapping of string keys to AWS CDK BuildEnvironmentVariable objects
              that define environment variables for CodeBuild project execution.
              Can be None for projects without custom environment variables.

    Returns:
        The original environment variables dictionary if validation passes, unchanged
            for use in CodeBuild project configuration. Returns None unchanged if no
            environment variables are provided.

    Raises:
        ValueError: If value is not a dictionary when provided - environment variables
                   must be key-value mappings for CodeBuild compatibility
        ValueError: If any dictionary key is not a string - environment variable names
                   must be strings for proper shell environment integration
        ValueError: If any dictionary value doesn't implement BuildEnvironmentVariable
                   interface - missing required "value" attribute for variable content

    Required Structure:
        - Dictionary type with string keys
        - Values must be BuildEnvironmentVariable objects with "value" attribute
        - Optional "type" attribute for variable type specification (PLAINTEXT, PARAMETER_STORE, SECRETS_MANAGER)


    CodeBuild Integration:
        - Used in codebuild.Project environment configuration
        - Supports PLAINTEXT, PARAMETER_STORE, and SECRETS_MANAGER variable types
        - Compatible with CodePipeline build action environment overrides
        - Validates variables for buildspec.yml environment section

    Environment Variable Types:
        PLAINTEXT: Direct string values stored in the build environment  
        PARAMETER_STORE: Values retrieved from AWS Systems Manager Parameter Store  
        SECRETS_MANAGER: Values retrieved from AWS Secrets Manager
    """
    if value is None:
        return value 

    if not isinstance(value, dict):
        raise ValueError("Environment variables must be a dictionary")

    # Validate each environment variable
    for key, env_var in value.items():
        if not isinstance(key, str):
            raise ValueError(f"Environment variable key '{key}' must be a string")

        # Check if it"s a proper CodeBuild BuildEnvironmentVariable
        # These objects typically have "value" and optionally "type" attributes
        if not hasattr(env_var, "value"):
            raise ValueError(f"Environment variable '{key}' must be a valid CodeBuild BuildEnvironmentVariable object")

    return value 

validate_vpc(value) staticmethod

Validate that the provided object implements the ec2.IVpc interface.

Ensures that the VPC object has the required attributes for AWS CDK VPC operations including network configuration, subnet access, and availability zone information. This validation prevents runtime errors when the VPC is used for resource deployment in private subnets or network configuration.

Parameters:

Name Type Description Default
value Any

Object to validate as an ec2.IVpc implementation. Expected to be an AWS CDK VPC construct or interface that provides network infrastructure for resource deployment.

required

Returns:

Type Description
Any

The original VPC object if validation passes, unchanged for use in CDK resource configuration and network operations.

Raises:

Type Description
ValueError

If value is None - VPC is required for network-dependent resources

ValueError

If object doesn't implement IVpc interface - missing required vpc_id or availability_zones attributes needed for CDK operations

Required Attributes

vpc_id: Unique identifier for the VPC used in resource configuration
availability_zones: List of AZs for subnet and resource placement

Source code in mare_aws_common_lib/models/mixins.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
@staticmethod
def validate_vpc(value: Any) -> Any:
    """Validate that the provided object implements the ec2.IVpc interface.

    Ensures that the VPC object has the required attributes for AWS CDK VPC
    operations including network configuration, subnet access, and availability
    zone information. This validation prevents runtime errors when the VPC
    is used for resource deployment in private subnets or network configuration.

    Args:
        value: Object to validate as an ec2.IVpc implementation. Expected to be
              an AWS CDK VPC construct or interface that provides network
              infrastructure for resource deployment.

    Returns:
        The original VPC object if validation passes, unchanged for use in
            CDK resource configuration and network operations.

    Raises:
        ValueError: If value is None - VPC is required for network-dependent resources
        ValueError: If object doesn't implement IVpc interface - missing required
                   vpc_id or availability_zones attributes needed for CDK operations

    Required Attributes:
        vpc_id: Unique identifier for the VPC used in resource configuration  
        availability_zones: List of AZs for subnet and resource placement
    """
    if value is None:
        raise ValueError("VPC must be set")
    if not (hasattr(value, 'vpc_id') and hasattr(value, 'availability_zones')):
        raise ValueError("Must be a valid ec2.IVpc object")
    return value

NameValidationMixin

Mixin class providing standardized name validation for AWS resource naming.

Provides centralized validation logic for AWS resource names across different service requirements and organizational naming standards. Supports multiple validation modes to accommodate varying AWS service naming restrictions while maintaining consistent validation patterns throughout the infrastructure codebase.

Validation Modes
  • DEFAULT: General AWS resource naming (letters, numbers, hyphens, dots, underscores)
  • DB: Database-specific naming (must start with letter, letters/numbers/underscores only)
  • ORIGIN: Cloudfront orgin naming (must start and end with alphanumeric, letters/numbers/underscores/hyphens/dots )
AWS Service Compatibility
  • DEFAULT mode: S3 buckets, ECR repositories, DynamoDB tables, Lambda functions
  • DB mode: RDS databases, ElastiCache clusters, Redshift clusters
  • ORIGIN: Cloudfront origins
  • PARAMETER: SSM parameter store

Attributes:

Name Type Description
NAME_PATTERNS

Compiled regex patterns for each validation mode

ERROR_MSG

User-friendly error messages for validation failures

Source code in mare_aws_common_lib/models/mixins.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
class NameValidationMixin:
    """Mixin class providing standardized name validation for AWS resource naming.

    Provides centralized validation logic for AWS resource names across different service
    requirements and organizational naming standards. Supports multiple validation modes
    to accommodate varying AWS service naming restrictions while maintaining consistent
    validation patterns throughout the infrastructure codebase.

    Validation Modes:
        - DEFAULT: General AWS resource naming (letters, numbers, hyphens, dots, underscores)
        - DB: Database-specific naming (must start with letter, letters/numbers/underscores only)
        - ORIGIN: Cloudfront orgin naming (must start and end with alphanumeric, letters/numbers/underscores/hyphens/dots )

    AWS Service Compatibility:
        - DEFAULT mode: S3 buckets, ECR repositories, DynamoDB tables, Lambda functions
        - DB mode: RDS databases, ElastiCache clusters, Redshift clusters
        - ORIGIN: Cloudfront origins
        - PARAMETER: SSM parameter store

    Attributes:
        NAME_PATTERNS: Compiled regex patterns for each validation mode
        ERROR_MSG: User-friendly error messages for validation failures
    """

    NAME_PATTERNS = {
        "DEFAULT": re.compile(r'^[a-zA-Z0-9._-]+$'),
        "DB": re.compile(r'^[a-zA-Z][a-zA-Z0-9_]*$'),
        "ORIGIN": re.compile(r'^[a-zA-Z0-9]([a-zA-Z0-9._-]*[a-zA-Z0-9])?'),
        "PARAMETER": re.compile(r'^[a-zA-Z0-9/_.-]+$')
    }

    ERROR_MSG = {
        "DEFAULT": "Name can contain only letters, numbers, hyphens, dots and underscores",
        "DB": "Name must start with a letter and contain only letters, numbers and underscores",
        "ORIGIN": "Name must start and end with alphanumeric characters and contain letters, numbers, hyphens, underscores and dots.",
        "PARAMETER": "Name must contain only alphanumeric characters, forward slashes, underscores, periods, and hyphens"
    }

    @classmethod
    def validate_name(cls, value: str, mode: str = "DEFAULT") -> str:
        """Validate and return a resource name according to specified naming convention.

        This method provides centralized validation logic that can be used across all
        resource configuration models, ensuring consistent naming validation and preventing
        deployment failures due to invalid resource names.

        Args:
            value: The resource name to validate. Must be a non-empty string that will be
                  used as an AWS resource identifier or the base name for it. 
            mode: Validation mode (case-insensitive) determining which naming pattern to apply.
                 Must be one of the keys in NAME_PATTERNS. 

        Returns:
            The original name string if validation passes.

        Raises:
            ValueError: If the validation mode is not recognized. Includes list of valid
                       modes in the error message for developer guidance.
            ValueError: If the name doesn't match the specified pattern. Uses the
                       corresponding error message from ERROR_MSG for clear user feedback.

        Validation Modes:
            DEFAULT: For most AWS resources (S3, ECR, DynamoDB, Lambda, etc.)  
                    - Pattern: Letters, numbers, hyphens, dots, underscores  
                    - Length: Minimum 1 character (additional service limits may apply)

            DB: For database services (RDS, ElastiCache, Redshift, etc.)  
                    - Pattern: Must start with letter, then letters/numbers/underscores  
                    - Length: Minimum 1 character (additional service limits may apply)  

            ORIGIN: For Cloudfront origins  
                    - Pattern: Must start and end with alphanumeric characters, can contain letters, numbers, hyphens, underscores and dots  
                    - Length: Minimum 1 character (additional service limits may apply)  
        """
        pattern = cls.NAME_PATTERNS.get(mode.upper(), None)
        if pattern is None:
            raise ValueError(f"Unknown validation mode: {mode.upper()}. Valid modes are: {list(cls.NAME_PATTERNS.keys())}")
        if not pattern.match(value):
            raise ValueError(cls.ERROR_MSG.get(mode.upper()))
        return value

validate_name(value, mode='DEFAULT') classmethod

Validate and return a resource name according to specified naming convention.

This method provides centralized validation logic that can be used across all resource configuration models, ensuring consistent naming validation and preventing deployment failures due to invalid resource names.

Parameters:

Name Type Description Default
value str

The resource name to validate. Must be a non-empty string that will be used as an AWS resource identifier or the base name for it.

required
mode str

Validation mode (case-insensitive) determining which naming pattern to apply. Must be one of the keys in NAME_PATTERNS.

'DEFAULT'

Returns:

Type Description
str

The original name string if validation passes.

Raises:

Type Description
ValueError

If the validation mode is not recognized. Includes list of valid modes in the error message for developer guidance.

ValueError

If the name doesn't match the specified pattern. Uses the corresponding error message from ERROR_MSG for clear user feedback.

Validation Modes

DEFAULT: For most AWS resources (S3, ECR, DynamoDB, Lambda, etc.)
- Pattern: Letters, numbers, hyphens, dots, underscores
- Length: Minimum 1 character (additional service limits may apply)

DB: For database services (RDS, ElastiCache, Redshift, etc.)
- Pattern: Must start with letter, then letters/numbers/underscores
- Length: Minimum 1 character (additional service limits may apply)

ORIGIN: For Cloudfront origins
- Pattern: Must start and end with alphanumeric characters, can contain letters, numbers, hyphens, underscores and dots
- Length: Minimum 1 character (additional service limits may apply)

Source code in mare_aws_common_lib/models/mixins.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
@classmethod
def validate_name(cls, value: str, mode: str = "DEFAULT") -> str:
    """Validate and return a resource name according to specified naming convention.

    This method provides centralized validation logic that can be used across all
    resource configuration models, ensuring consistent naming validation and preventing
    deployment failures due to invalid resource names.

    Args:
        value: The resource name to validate. Must be a non-empty string that will be
              used as an AWS resource identifier or the base name for it. 
        mode: Validation mode (case-insensitive) determining which naming pattern to apply.
             Must be one of the keys in NAME_PATTERNS. 

    Returns:
        The original name string if validation passes.

    Raises:
        ValueError: If the validation mode is not recognized. Includes list of valid
                   modes in the error message for developer guidance.
        ValueError: If the name doesn't match the specified pattern. Uses the
                   corresponding error message from ERROR_MSG for clear user feedback.

    Validation Modes:
        DEFAULT: For most AWS resources (S3, ECR, DynamoDB, Lambda, etc.)  
                - Pattern: Letters, numbers, hyphens, dots, underscores  
                - Length: Minimum 1 character (additional service limits may apply)

        DB: For database services (RDS, ElastiCache, Redshift, etc.)  
                - Pattern: Must start with letter, then letters/numbers/underscores  
                - Length: Minimum 1 character (additional service limits may apply)  

        ORIGIN: For Cloudfront origins  
                - Pattern: Must start and end with alphanumeric characters, can contain letters, numbers, hyphens, underscores and dots  
                - Length: Minimum 1 character (additional service limits may apply)  
    """
    pattern = cls.NAME_PATTERNS.get(mode.upper(), None)
    if pattern is None:
        raise ValueError(f"Unknown validation mode: {mode.upper()}. Valid modes are: {list(cls.NAME_PATTERNS.keys())}")
    if not pattern.match(value):
        raise ValueError(cls.ERROR_MSG.get(mode.upper()))
    return value
    heading_level: 2

PathValidationMixin

Validation mixin for URL path pattern formatting and compliance.

Provides standardized validation methods for URL path patterns used in web routing, API endpoints, and CDN configurations. Ensures path patterns follow standard URL conventions with proper leading slash formatting for consistent routing behavior across AWS services.

This mixin is designed to be used with Pydantic models to validate path-related fields in CloudFront origins, API Gateway routes, and other AWS services that require URL path specifications.

Source code in mare_aws_common_lib/models/mixins.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class PathValidationMixin:
    """Validation mixin for URL path pattern formatting and compliance.

    Provides standardized validation methods for URL path patterns used in
    web routing, API endpoints, and CDN configurations. Ensures path patterns
    follow standard URL conventions with proper leading slash formatting
    for consistent routing behavior across AWS services.

    This mixin is designed to be used with Pydantic models to validate
    path-related fields in CloudFront origins, API Gateway routes, and
    other AWS services that require URL path specifications.
    """
    @classmethod
    def validate_path_pattern(cls, value: str) -> str:
        """Validate URL path pattern format and structure.

        Ensures that path patterns follow standard URL conventions by requiring
        a leading forward slash when a path is specified. This validation prevents
        routing errors and ensures consistent path handling across AWS services
        like CloudFront distributions and API Gateway configurations.

        Args:
            value: Path pattern string to validate (can be None)

        Returns:
            Validated path pattern with proper formatting, or None if not provided

        Raises:
            ValueError: If path pattern is provided but doesn't start with "/"
        """
        if value is not None and not value.startswith('/'):
            raise ValueError('Path pattern must start with "/"')
        return value

validate_path_pattern(value) classmethod

Validate URL path pattern format and structure.

Ensures that path patterns follow standard URL conventions by requiring a leading forward slash when a path is specified. This validation prevents routing errors and ensures consistent path handling across AWS services like CloudFront distributions and API Gateway configurations.

Parameters:

Name Type Description Default
value str

Path pattern string to validate (can be None)

required

Returns:

Type Description
str

Validated path pattern with proper formatting, or None if not provided

Raises:

Type Description
ValueError

If path pattern is provided but doesn't start with "/"

Source code in mare_aws_common_lib/models/mixins.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@classmethod
def validate_path_pattern(cls, value: str) -> str:
    """Validate URL path pattern format and structure.

    Ensures that path patterns follow standard URL conventions by requiring
    a leading forward slash when a path is specified. This validation prevents
    routing errors and ensures consistent path handling across AWS services
    like CloudFront distributions and API Gateway configurations.

    Args:
        value: Path pattern string to validate (can be None)

    Returns:
        Validated path pattern with proper formatting, or None if not provided

    Raises:
        ValueError: If path pattern is provided but doesn't start with "/"
    """
    if value is not None and not value.startswith('/'):
        raise ValueError('Path pattern must start with "/"')
    return value
    heading_level: 2