cdk-factory 0.15.11__py3-none-any.whl → 0.15.13__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of cdk-factory might be problematic. Click here for more details.

@@ -4,9 +4,16 @@ Maintainers: Eric Wilson
4
4
  MIT License. See Project Root for license information.
5
5
  """
6
6
 
7
- from typing import Any, Dict, List, Optional
7
+ import re
8
+ from typing import Any, Dict, List, Optional, Tuple, Literal
9
+ from aws_lambda_powertools import Logger
8
10
  from cdk_factory.configurations.enhanced_base_config import EnhancedBaseConfig
9
11
 
12
+ logger = Logger(service="RdsConfig")
13
+
14
+ # Supported RDS engines
15
+ Engine = Literal["mysql", "mariadb", "postgres", "aurora-mysql", "aurora-postgres", "sqlserver", "oracle"]
16
+
10
17
 
11
18
  class RdsConfig(EnhancedBaseConfig):
12
19
  """
@@ -23,6 +30,74 @@ class RdsConfig(EnhancedBaseConfig):
23
30
  def name(self) -> str:
24
31
  """RDS instance name"""
25
32
  return self.__config.get("name", "database")
33
+
34
+ @property
35
+ def identifier(self) -> str:
36
+ """RDS DB instance identifier (sanitized)"""
37
+ raw_id = self.__config.get("identifier", self.name)
38
+ return self._sanitize_instance_identifier(raw_id)
39
+
40
+ def _sanitize_instance_identifier(self, identifier: str) -> str:
41
+ """
42
+ Sanitize DB instance identifier to meet RDS requirements:
43
+ - 1-63 chars, lowercase letters/digits/hyphen
44
+ - Must start with letter, can't end with hyphen, no consecutive hyphens
45
+ """
46
+ if not identifier:
47
+ raise ValueError("Instance identifier cannot be empty")
48
+
49
+ sanitized, notes = self._sanitize_instance_identifier_impl(identifier)
50
+
51
+ if notes:
52
+ logger.info(f"Sanitized instance identifier from '{identifier}' to '{sanitized}': {', '.join(notes)}")
53
+
54
+ return sanitized
55
+
56
+ def _sanitize_instance_identifier_impl(self, identifier: str) -> Tuple[str, List[str]]:
57
+ """
58
+ DB instance identifier rules (all engines):
59
+ - 1-63 chars, lowercase letters/digits/hyphen
60
+ - Must start with letter
61
+ - Can't end with hyphen
62
+ - No consecutive hyphens (--)
63
+ """
64
+ notes: List[str] = []
65
+ s = identifier.lower()
66
+
67
+ # Keep only lowercase letters, digits, hyphen
68
+ s_clean = re.sub(r"[^a-z0-9-]", "", s)
69
+ if s_clean != s:
70
+ notes.append("removed invalid characters (only a-z, 0-9, '-' allowed)")
71
+ s = s_clean
72
+
73
+ if not s:
74
+ raise ValueError(f"Instance identifier '{identifier}' contains no valid characters")
75
+
76
+ # Must start with letter
77
+ if not re.match(r"^[a-z]", s):
78
+ s = f"db{s}"
79
+ notes.append("prefixed with 'db' to start with a letter")
80
+
81
+ # Collapse consecutive hyphens
82
+ s_collapsed = re.sub(r"-{2,}", "-", s)
83
+ if s_collapsed != s:
84
+ s = s_collapsed
85
+ notes.append("collapsed consecutive hyphens")
86
+
87
+ # Can't end with hyphen
88
+ if s.endswith("-"):
89
+ s = s.rstrip("-")
90
+ notes.append("removed trailing hyphen")
91
+
92
+ # Truncate to 63 characters
93
+ if len(s) > 63:
94
+ s = s[:63]
95
+ # Make sure we didn't truncate to a trailing hyphen
96
+ if s.endswith("-"):
97
+ s = s.rstrip("-")
98
+ notes.append("truncated to 63 characters")
99
+
100
+ return s, notes
26
101
 
27
102
  @property
28
103
  def engine(self) -> str:
@@ -44,13 +119,15 @@ class RdsConfig(EnhancedBaseConfig):
44
119
 
45
120
  @property
46
121
  def database_name(self) -> str:
47
- """Name of the database to create"""
48
- return self.__config.get("database_name", "appdb")
122
+ """Name of the database to create (sanitized for RDS requirements)"""
123
+ raw_name = self.__config.get("database_name", "appdb")
124
+ return self._sanitize_database_name(raw_name)
49
125
 
50
126
  @property
51
127
  def username(self) -> str:
52
- """Master username for the database"""
53
- return self.__config.get("username", "appuser")
128
+ """Master username for the database (sanitized for RDS requirements)"""
129
+ raw_username = self.__config.get("username", "appuser")
130
+ return self._sanitize_username(raw_username)
54
131
 
55
132
  @property
56
133
  def secret_name(self) -> str:
@@ -146,3 +223,160 @@ class RdsConfig(EnhancedBaseConfig):
146
223
  if "ssm" in self.__config and "exports" in self.__config["ssm"]:
147
224
  return self.__config["ssm"]["exports"]
148
225
  return self.__config.get("ssm_exports", {})
226
+
227
+ def _sanitize_database_name(self, name: str) -> str:
228
+ """
229
+ Sanitize database name to meet RDS requirements (engine-specific).
230
+ Implements rules from RDS documentation for each engine type.
231
+
232
+ Args:
233
+ name: Raw database name from config
234
+
235
+ Returns:
236
+ Sanitized database name
237
+
238
+ Raises:
239
+ ValueError: If name cannot be sanitized to meet requirements
240
+ """
241
+ if not name:
242
+ raise ValueError("Database name cannot be empty")
243
+
244
+ engine = self.engine.lower()
245
+ sanitized, notes = self._sanitize_db_name_impl(engine, name)
246
+
247
+ if notes:
248
+ logger.info(f"Sanitized database name from '{name}' to '{sanitized}': {', '.join(notes)}")
249
+
250
+ return sanitized
251
+
252
+ def _sanitize_db_name_impl(self, engine: str, name: str) -> Tuple[str, List[str]]:
253
+ """
254
+ Engine-specific database name sanitization.
255
+ Based on AWS RDS naming requirements:
256
+ - MySQL/MariaDB: 1-64 chars, start with letter, letters/digits/underscore
257
+ - PostgreSQL: 1-63 chars, start with letter, letters/digits/underscore
258
+ - SQL Server: 1-128 chars, start with letter, letters/digits/underscore
259
+ - Oracle: 1-8 chars (SID), alphanumeric only, start with letter
260
+ """
261
+ notes: List[str] = []
262
+
263
+ # Determine engine-specific limits
264
+ if engine in ("mysql", "mariadb", "aurora-mysql"):
265
+ allowed_chars = r"A-Za-z0-9_"
266
+ max_len = 64
267
+ elif engine in ("postgres", "postgresql", "aurora-postgres", "aurora-postgresql"):
268
+ allowed_chars = r"A-Za-z0-9_"
269
+ max_len = 63
270
+ elif engine in ("sqlserver", "sqlserver-ee", "sqlserver-se", "sqlserver-ex", "sqlserver-web"):
271
+ allowed_chars = r"A-Za-z0-9_"
272
+ max_len = 128
273
+ elif engine in ("oracle", "oracle-ee", "oracle-se2", "oracle-se1"):
274
+ allowed_chars = r"A-Za-z0-9" # No underscore for Oracle SID
275
+ max_len = 8
276
+ else:
277
+ # Default to conservative rules
278
+ allowed_chars = r"A-Za-z0-9_"
279
+ max_len = 64
280
+ notes.append(f"unknown engine '{engine}', using default MySQL rules")
281
+
282
+ # Replace hyphens with underscores (except Oracle which doesn't allow underscores)
283
+ s = name
284
+ if "oracle" not in engine:
285
+ s = s.replace("-", "_")
286
+ if "_" in name and "-" in name:
287
+ notes.append("replaced hyphens with underscores")
288
+
289
+ # Strip disallowed characters
290
+ s_clean = re.sub(f"[^{allowed_chars}]", "", s)
291
+ if s_clean != s:
292
+ notes.append("removed invalid characters")
293
+ s = s_clean
294
+
295
+ if not s:
296
+ raise ValueError(f"Database name '{name}' contains no valid characters after sanitization")
297
+
298
+ # Must start with a letter
299
+ if not re.match(r"^[A-Za-z]", s):
300
+ s = f"db{s}"
301
+ notes.append("prefixed with 'db' to start with a letter")
302
+
303
+ # Truncate to max length
304
+ if len(s) > max_len:
305
+ s = s[:max_len]
306
+ notes.append(f"truncated to {max_len} characters")
307
+
308
+ # SQL Server: can't start with 'rdsadmin'
309
+ if "sqlserver" in engine and s.lower().startswith("rdsadmin"):
310
+ s = f"db_{s}"
311
+ notes.append("prefixed to avoid 'rdsadmin' (SQL Server restriction)")
312
+
313
+ return s, notes
314
+
315
+ def _sanitize_username(self, username: str) -> str:
316
+ """
317
+ Sanitize master username to meet RDS requirements:
318
+ - Must begin with a letter (a-z, A-Z)
319
+ - Can contain alphanumeric characters and underscores
320
+ - Max 16 characters (AWS RDS master username limit)
321
+ - Cannot be a reserved word
322
+
323
+ Args:
324
+ username: Raw username from config
325
+
326
+ Returns:
327
+ Sanitized username
328
+
329
+ Raises:
330
+ ValueError: If username is invalid
331
+ """
332
+ if not username:
333
+ raise ValueError("Username cannot be empty")
334
+
335
+ sanitized, notes = self._sanitize_master_username_impl(username)
336
+
337
+ if notes:
338
+ logger.info(f"Sanitized username from '{username}' to '{sanitized}': {', '.join(notes)}")
339
+
340
+ return sanitized
341
+
342
+ def _sanitize_master_username_impl(self, username: str) -> Tuple[str, List[str]]:
343
+ """
344
+ Sanitize master username according to AWS RDS rules:
345
+ - 1-16 characters
346
+ - Start with a letter
347
+ - Letters, digits, underscore only
348
+ - Not a reserved word
349
+ """
350
+ notes: List[str] = []
351
+ s = username
352
+
353
+ # Replace hyphens with underscores, remove other invalid chars
354
+ s = s.replace("-", "_")
355
+ s_clean = re.sub(r"[^A-Za-z0-9_]", "", s)
356
+ if s_clean != s:
357
+ notes.append("removed invalid characters")
358
+ s = s_clean
359
+
360
+ if not s:
361
+ raise ValueError(f"Username '{username}' contains no valid characters after sanitization")
362
+
363
+ # Must start with a letter
364
+ if not re.match(r"^[A-Za-z]", s):
365
+ s = f"user{s}"
366
+ notes.append("prefixed with 'user' to start with a letter")
367
+
368
+ # Truncate to 16 characters
369
+ if len(s) > 16:
370
+ s = s[:16]
371
+ notes.append("truncated to 16 characters")
372
+
373
+ # Check against common reserved words
374
+ reserved = {"postgres", "mysql", "root", "admin", "rdsadmin", "system", "sa", "user"}
375
+ if s.lower() in reserved:
376
+ s = f"{s}_usr"
377
+ # Re-truncate if needed after adding suffix
378
+ if len(s) > 16:
379
+ s = s[:16]
380
+ notes.append("appended '_usr' to avoid reserved username")
381
+
382
+ return s, notes
@@ -305,6 +305,7 @@ class PipelineFactoryStack(IStack):
305
305
  scope=pipeline_stage,
306
306
  id=stack_config.name,
307
307
  deployment=deployment,
308
+ stack_config=stack_config,
308
309
  add_env_context=self.add_env_context,
309
310
  **kwargs,
310
311
  )
@@ -11,10 +11,28 @@ from cdk_factory.interfaces.istack import IStack
11
11
  from cdk_factory.stack.stack_module_loader import ModuleLoader
12
12
  from cdk_factory.stack.stack_module_registry import modules
13
13
  from cdk_factory.configurations.deployment import DeploymentConfig
14
+ from cdk_factory.configurations.stack import StackConfig
14
15
 
15
16
 
16
17
  class StackFactory:
17
18
  """Stack Factory"""
19
+
20
+ # Default descriptions by module type
21
+ DEFAULT_DESCRIPTIONS = {
22
+ "vpc_stack": "VPC infrastructure with public and private subnets across multiple availability zones",
23
+ "security_group_stack": "Security groups for network access control",
24
+ "security_group_full_stack": "Security groups for ALB, ECS, RDS, and monitoring",
25
+ "rds_stack": "Managed relational database instance with automated backups",
26
+ "s3_bucket_stack": "S3 bucket for object storage",
27
+ "media_bucket_stack": "S3 bucket for media asset storage with CDN integration",
28
+ "static_website_stack": "Static website hosted on S3 with CloudFront distribution",
29
+ "ecs_service_stack": "ECS service with auto-scaling and load balancing",
30
+ "lambda_stack": "Lambda function for serverless compute",
31
+ "api_gateway_stack": "API Gateway for REST API endpoints",
32
+ "cloudfront_stack": "CloudFront CDN distribution",
33
+ "monitoring_stack": "CloudWatch monitoring, alarms, and dashboards",
34
+ "ecr_stack": "Elastic Container Registry for Docker images",
35
+ }
18
36
 
19
37
  def __init__(self):
20
38
  ml: ModuleLoader = ModuleLoader()
@@ -27,6 +45,7 @@ class StackFactory:
27
45
  scope,
28
46
  id: str, # pylint: disable=redefined-builtin
29
47
  deployment: Optional[DeploymentConfig] = None,
48
+ stack_config: Optional[StackConfig] = None,
30
49
  add_env_context: bool = True,
31
50
  **kwargs,
32
51
  ) -> IStack:
@@ -40,6 +59,12 @@ class StackFactory:
40
59
  if deployment and add_env_context:
41
60
  env_kwargs = self._get_environment_kwargs(deployment)
42
61
  kwargs.update(env_kwargs)
62
+
63
+ # Add description if not already provided in kwargs
64
+ if "description" not in kwargs:
65
+ description = self._get_stack_description(module_name, stack_config)
66
+ if description:
67
+ kwargs["description"] = description
43
68
 
44
69
  module = stack_class(scope=scope, id=id, **kwargs)
45
70
 
@@ -52,3 +77,12 @@ class StackFactory:
52
77
  region=deployment.region
53
78
  )
54
79
  return {"env": env}
80
+
81
+ def _get_stack_description(self, module_name: str, stack_config: Optional[StackConfig] = None) -> Optional[str]:
82
+ """Get stack description from config or default"""
83
+ # First check if stack_config has a description
84
+ if stack_config and stack_config.description:
85
+ return stack_config.description
86
+
87
+ # Otherwise use default description based on module type
88
+ return self.DEFAULT_DESCRIPTIONS.get(module_name)
cdk_factory/version.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.15.11"
1
+ __version__ = "0.15.13"
@@ -124,6 +124,7 @@ class WorkloadFactory:
124
124
  scope=self.app,
125
125
  id=stack.name,
126
126
  deployment=deployment,
127
+ stack_config=stack,
127
128
  add_env_context=self.add_env_context,
128
129
  **kwargs,
129
130
  )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cdk_factory
3
- Version: 0.15.11
3
+ Version: 0.15.13
4
4
  Summary: CDK Factory. A QuickStarter and best practices setup for CDK projects
5
5
  Author-email: Eric Wilson <eric.wilson@geekcafe.com>
6
6
  License: MIT License
@@ -2,7 +2,7 @@ cdk_factory/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
2
  cdk_factory/app.py,sha256=RnX0-pwdTAPAdKJK_j13Zl8anf9zYKBwboR0KA8K8xM,10346
3
3
  cdk_factory/cdk.json,sha256=SKZKhJ2PBpFH78j-F8S3VDYW-lf76--Q2I3ON-ZIQfw,3106
4
4
  cdk_factory/cli.py,sha256=FGbCTS5dYCNsfp-etshzvFlGDCjC28r6rtzYbe7KoHI,6407
5
- cdk_factory/version.py,sha256=Bw5DUxQ3jqdKvFLsxUsxaKKMc-9Ywbelea4Rftx-Kj0,24
5
+ cdk_factory/version.py,sha256=6AIqVLeKq3uS7QeuesqvTQrN9gWiCBFTAygmSJRA6-0,24
6
6
  cdk_factory/builds/README.md,sha256=9BBWd7bXpyKdMU_g2UljhQwrC9i5O_Tvkb6oPvndoZk,90
7
7
  cdk_factory/commands/command_loader.py,sha256=QbLquuP_AdxtlxlDy-2IWCQ6D-7qa58aphnDPtp_uTs,3744
8
8
  cdk_factory/configurations/base_config.py,sha256=JKjhNsy0RCUZy1s8n5D_aXXI-upR9izaLtCTfKYiV9k,9624
@@ -38,7 +38,7 @@ cdk_factory/configurations/resources/lambda_layers.py,sha256=gVeP_-LC3Eq0lkPaG_J
38
38
  cdk_factory/configurations/resources/lambda_triggers.py,sha256=MD7cdMNKEulNBhtMLIFnWJuJ5R-yyIqa0LHUgbSQerA,834
39
39
  cdk_factory/configurations/resources/load_balancer.py,sha256=idpKdvkkCM7J9J2pNjMBOY1DNaFR1tk1tFjTg76bvrY,5267
40
40
  cdk_factory/configurations/resources/monitoring.py,sha256=zsfDMa7yph33Ql8iP7lIqqLAyixh-Mesi0imtZJFdcE,2310
41
- cdk_factory/configurations/resources/rds.py,sha256=is_odfCoe3kyiz8DpDxDayt1aVICJoNWuhuaHZ98qQo,5197
41
+ cdk_factory/configurations/resources/rds.py,sha256=lSj6BqAmx1knpu3Kv1Fq-tw-lTF94NFzEFGgWcMMIFI,14009
42
42
  cdk_factory/configurations/resources/resource_mapping.py,sha256=cwv3n63RJ6E59ErsmSTdkW4i-g8huhHtKI0ExbRhJxA,2182
43
43
  cdk_factory/configurations/resources/resource_naming.py,sha256=VE9S2cpzp11qqPL2z1sX79wXH0o1SntO2OG74nEmWC8,5508
44
44
  cdk_factory/configurations/resources/resource_types.py,sha256=1WQHyDoErb-M-tETZZzyLDtbq_jdC85-I403dM48pgE,2317
@@ -68,12 +68,12 @@ cdk_factory/interfaces/ssm_parameter_mixin.py,sha256=uA2j8HmAOpuEA9ynRj51s0WjUHM
68
68
  cdk_factory/lambdas/health_handler.py,sha256=dd40ykKMxWCFEIyp2ZdQvAGNjw_ylI9CSm1N24Hp2ME,196
69
69
  cdk_factory/lambdas/edge/ip_gate/handler.py,sha256=YrXO42gEhJoBTaH6jS7EWqjHe9t5Fpt4WLgY8vjtou0,10474
70
70
  cdk_factory/pipeline/path_utils.py,sha256=fvWdrcb4onmpIu1APkHLhXg8zWfK74HcW3Ra2ynxfXM,2586
71
- cdk_factory/pipeline/pipeline_factory.py,sha256=rvtkdlTPJG477nTVRN8S2ksWt4bwpd9eVLFd9WO02pM,17248
71
+ cdk_factory/pipeline/pipeline_factory.py,sha256=tY-uaJa_51CnWHb4KEvYMT-pZ_7cWy5DNnTfXHWUoHY,17295
72
72
  cdk_factory/pipeline/stage.py,sha256=Be7ExMB9A-linRM18IQDOzQ-cP_I2_ThRNzlT4FIrUg,437
73
73
  cdk_factory/pipeline/security/policies.py,sha256=H3-S6nipz3UtF9Pc5eJYr4-aREUTCaJWMjOUyd6Rdv4,4406
74
74
  cdk_factory/pipeline/security/roles.py,sha256=ZB_O5H_BXgotvVspS2kVad9EMcY-a_-vU7Nm1_Z5MB8,4985
75
75
  cdk_factory/stack/istack.py,sha256=-n0FTLvG7uvLxkyqRGjqFTguZeTRuXwFxGzcAIqbsj8,174
76
- cdk_factory/stack/stack_factory.py,sha256=zn4JwfpZidxkYLmv6uT1GaFPFRidTFj0NUGKWDNFRb8,1701
76
+ cdk_factory/stack/stack_factory.py,sha256=PfFzKxfM_5JPhK33_acEvpT4gll_AFCqZP7-lPifbJk,3649
77
77
  cdk_factory/stack/stack_module_loader.py,sha256=EA7ceb8qyktzkYgPYaixQdPJsi8FwTsMU-NrgtXwXcw,1144
78
78
  cdk_factory/stack/stack_module_registry.py,sha256=J14-A75VZESzRQa8p-Fepdap7Z8T7mradTu3sVzuBx8,378
79
79
  cdk_factory/stack/stack_modules.py,sha256=kgEK-j0smZPozVwTCfM1g1V17EyTBT0TXAQZq4vZz0o,784
@@ -128,9 +128,9 @@ cdk_factory/utilities/json_loading_utility.py,sha256=YRgzA1I-B_HwZm1eWJTeQ1JLkeb
128
128
  cdk_factory/utilities/lambda_function_utilities.py,sha256=S1GvBsY_q2cyUiaud3HORJMnLhI5cRi31fbeaktY-_Q,15826
129
129
  cdk_factory/utilities/os_execute.py,sha256=5Op0LY_8Y-pUm04y1k8MTpNrmQvcLmQHPQITEP7EuSU,1019
130
130
  cdk_factory/utils/api_gateway_utilities.py,sha256=If7Xu5s_UxmuV-kL3JkXxPLBdSVUKoLtohm0IUFoiV8,4378
131
- cdk_factory/workload/workload_factory.py,sha256=mM8GU_5mKq_0OyK060T3JrUSUiGAcKf0eqNlT9mfaws,6028
132
- cdk_factory-0.15.11.dist-info/METADATA,sha256=vTtRFsbZLXHxMN6sy2U_8V906n9u8k-RREbUOY_mefI,2452
133
- cdk_factory-0.15.11.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
134
- cdk_factory-0.15.11.dist-info/entry_points.txt,sha256=S1DPe0ORcdiwEALMN_WIo3UQrW_g4YdQCLEsc_b0Swg,53
135
- cdk_factory-0.15.11.dist-info/licenses/LICENSE,sha256=NOtdOeLwg2il_XBJdXUPFPX8JlV4dqTdDGAd2-khxT8,1066
136
- cdk_factory-0.15.11.dist-info/RECORD,,
131
+ cdk_factory/workload/workload_factory.py,sha256=yDI3cRhVI5ELNDcJPLpk9UY54Uind1xQoV3spzT4z7E,6068
132
+ cdk_factory-0.15.13.dist-info/METADATA,sha256=ZEIwXiuhfk9EeWo0OgSz3-yK3sl2l7rVPLPLE9cVC2w,2452
133
+ cdk_factory-0.15.13.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
134
+ cdk_factory-0.15.13.dist-info/entry_points.txt,sha256=S1DPe0ORcdiwEALMN_WIo3UQrW_g4YdQCLEsc_b0Swg,53
135
+ cdk_factory-0.15.13.dist-info/licenses/LICENSE,sha256=NOtdOeLwg2il_XBJdXUPFPX8JlV4dqTdDGAd2-khxT8,1066
136
+ cdk_factory-0.15.13.dist-info/RECORD,,