cdk-factory 0.8.6__py3-none-any.whl → 0.8.8__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.

@@ -6,6 +6,10 @@ MIT License. See Project Root for the license information.
6
6
 
7
7
  import aws_cdk as cdk
8
8
  from aws_cdk import aws_cognito as cognito
9
+ from aws_cdk import aws_secretsmanager as secretsmanager
10
+ from aws_cdk import aws_iam as iam
11
+ from aws_cdk import aws_lambda as _lambda
12
+ from aws_cdk import custom_resources as cr
9
13
  from constructs import Construct
10
14
  from aws_lambda_powertools import Logger
11
15
  from aws_cdk import aws_ssm as ssm
@@ -33,6 +37,8 @@ class CognitoStack(IStack, EnhancedSsmParameterMixin):
33
37
  self.stack_config: StackConfig | None = None
34
38
  self.deployment: DeploymentConfig | None = None
35
39
  self.cognito_config: CognitoConfig | None = None
40
+ self.user_pool: cognito.UserPool | None = None
41
+ self.app_clients: dict = {} # Store created app clients by name
36
42
 
37
43
  def build(
38
44
  self,
@@ -47,6 +53,10 @@ class CognitoStack(IStack, EnhancedSsmParameterMixin):
47
53
 
48
54
  # Create user pool with configuration
49
55
  self._create_user_pool_with_config()
56
+
57
+ # Create app clients if configured
58
+ if self.cognito_config.app_clients:
59
+ self._create_app_clients()
50
60
 
51
61
  def _setup_custom_attributes(self):
52
62
  attributes = {}
@@ -139,7 +149,7 @@ class CognitoStack(IStack, EnhancedSsmParameterMixin):
139
149
  # Remove None values
140
150
  kwargs = {k: v for k, v in kwargs.items() if v is not None}
141
151
 
142
- user_pool = cognito.UserPool(
152
+ self.user_pool = cognito.UserPool(
143
153
  self,
144
154
  id=self.deployment.build_resource_name(
145
155
  self.cognito_config.user_pool_name
@@ -148,9 +158,347 @@ class CognitoStack(IStack, EnhancedSsmParameterMixin):
148
158
  ),
149
159
  **kwargs,
150
160
  )
151
- logger.info(f"Created Cognito User Pool: {user_pool.user_pool_id}")
161
+ logger.info(f"Created Cognito User Pool: {self.user_pool.user_pool_id}")
162
+
163
+ self._export_ssm_parameters(self.user_pool)
164
+
165
+ def _create_app_clients(self):
166
+ """Create app clients for the user pool based on configuration"""
167
+ if not self.user_pool:
168
+ raise ValueError("User pool must be created before app clients")
169
+
170
+ for client_config in self.cognito_config.app_clients:
171
+ client_name = client_config.get("name")
172
+ if not client_name:
173
+ raise ValueError("App client name is required")
174
+
175
+ # Build authentication flows
176
+ auth_flows = self._build_auth_flows(client_config.get("auth_flows", {}))
177
+
178
+ # Build OAuth settings
179
+ oauth_settings = self._build_oauth_settings(client_config.get("oauth"))
180
+
181
+ # Build token validity settings
182
+ token_validity = self._build_token_validity(client_config)
183
+
184
+ # Build app client kwargs
185
+ client_kwargs = {
186
+ "user_pool": self.user_pool,
187
+ "user_pool_client_name": client_name,
188
+ "generate_secret": client_config.get("generate_secret", False),
189
+ "auth_flows": auth_flows,
190
+ "o_auth": oauth_settings,
191
+ "prevent_user_existence_errors": client_config.get("prevent_user_existence_errors"),
192
+ "enable_token_revocation": client_config.get("enable_token_revocation", True),
193
+ "access_token_validity": token_validity.get("access_token"),
194
+ "id_token_validity": token_validity.get("id_token"),
195
+ "refresh_token_validity": token_validity.get("refresh_token"),
196
+ "read_attributes": self._build_attributes(client_config.get("read_attributes")),
197
+ "write_attributes": self._build_attributes(client_config.get("write_attributes")),
198
+ "supported_identity_providers": self._build_identity_providers(
199
+ client_config.get("supported_identity_providers")
200
+ ),
201
+ }
202
+
203
+ # Remove None values
204
+ client_kwargs = {k: v for k, v in client_kwargs.items() if v is not None}
205
+
206
+ # Create the app client
207
+ app_client = cognito.UserPoolClient(
208
+ self,
209
+ id=self.deployment.build_resource_name(f"{client_name}-client"),
210
+ **client_kwargs,
211
+ )
212
+
213
+ # Store reference
214
+ self.app_clients[client_name] = app_client
215
+ logger.info(f"Created Cognito App Client: {client_name}")
216
+
217
+ # Store client secret in Secrets Manager if generated
218
+ if client_config.get("generate_secret", False):
219
+ self._store_client_secret_in_secrets_manager(
220
+ client_name, app_client, self.user_pool
221
+ )
222
+
223
+ def _build_auth_flows(self, auth_flows_config: dict) -> cognito.AuthFlow:
224
+ """
225
+ Build authentication flows from configuration.
226
+
227
+ Note: CDK automatically adds ALLOW_REFRESH_TOKEN_AUTH to all app clients,
228
+ which is required for token refresh functionality.
229
+ """
230
+ if not auth_flows_config:
231
+ return None
232
+
233
+ return cognito.AuthFlow(
234
+ user_password=auth_flows_config.get("user_password", False),
235
+ user_srp=auth_flows_config.get("user_srp", False),
236
+ custom=auth_flows_config.get("custom", False),
237
+ admin_user_password=auth_flows_config.get("admin_user_password", False),
238
+ )
239
+
240
+ def _build_oauth_settings(self, oauth_config: dict) -> cognito.OAuthSettings:
241
+ """Build OAuth settings from configuration"""
242
+ if not oauth_config:
243
+ return None
244
+
245
+ # Build OAuth flows
246
+ flows_config = oauth_config.get("flows", {})
247
+ flows = cognito.OAuthFlows(
248
+ authorization_code_grant=flows_config.get("authorization_code_grant", False),
249
+ implicit_code_grant=flows_config.get("implicit_code_grant", False),
250
+ client_credentials=flows_config.get("client_credentials", False),
251
+ )
252
+
253
+ # Build OAuth scopes
254
+ scopes = []
255
+ scope_list = oauth_config.get("scopes", [])
256
+ for scope in scope_list:
257
+ if scope.lower() == "openid":
258
+ scopes.append(cognito.OAuthScope.OPENID)
259
+ elif scope.lower() == "email":
260
+ scopes.append(cognito.OAuthScope.EMAIL)
261
+ elif scope.lower() == "phone":
262
+ scopes.append(cognito.OAuthScope.PHONE)
263
+ elif scope.lower() == "profile":
264
+ scopes.append(cognito.OAuthScope.PROFILE)
265
+ elif scope.lower() == "cognito_admin":
266
+ scopes.append(cognito.OAuthScope.COGNITO_ADMIN)
267
+ else:
268
+ # Custom scope
269
+ scopes.append(cognito.OAuthScope.custom(scope))
270
+
271
+ return cognito.OAuthSettings(
272
+ flows=flows,
273
+ scopes=scopes if scopes else None,
274
+ callback_urls=oauth_config.get("callback_urls"),
275
+ logout_urls=oauth_config.get("logout_urls"),
276
+ )
277
+
278
+ def _build_token_validity(self, client_config: dict) -> dict:
279
+ """Build token validity settings from configuration"""
280
+ result = {}
281
+
282
+ # Access token validity
283
+ if "access_token_validity" in client_config:
284
+ validity = client_config["access_token_validity"]
285
+ if "minutes" in validity:
286
+ result["access_token"] = cdk.Duration.minutes(validity["minutes"])
287
+ elif "hours" in validity:
288
+ result["access_token"] = cdk.Duration.hours(validity["hours"])
289
+ elif "days" in validity:
290
+ result["access_token"] = cdk.Duration.days(validity["days"])
291
+
292
+ # ID token validity
293
+ if "id_token_validity" in client_config:
294
+ validity = client_config["id_token_validity"]
295
+ if "minutes" in validity:
296
+ result["id_token"] = cdk.Duration.minutes(validity["minutes"])
297
+ elif "hours" in validity:
298
+ result["id_token"] = cdk.Duration.hours(validity["hours"])
299
+ elif "days" in validity:
300
+ result["id_token"] = cdk.Duration.days(validity["days"])
301
+
302
+ # Refresh token validity
303
+ if "refresh_token_validity" in client_config:
304
+ validity = client_config["refresh_token_validity"]
305
+ if "minutes" in validity:
306
+ result["refresh_token"] = cdk.Duration.minutes(validity["minutes"])
307
+ elif "hours" in validity:
308
+ result["refresh_token"] = cdk.Duration.hours(validity["hours"])
309
+ elif "days" in validity:
310
+ result["refresh_token"] = cdk.Duration.days(validity["days"])
311
+
312
+ return result
313
+
314
+ def _build_attributes(self, attribute_list: list) -> cognito.ClientAttributes:
315
+ """Build client attributes from configuration"""
316
+ if not attribute_list:
317
+ return None
318
+
319
+ # Standard attributes mapping
320
+ standard_attrs = {
321
+ "address": lambda: cognito.ClientAttributes().with_standard_attributes(address=True),
322
+ "birthdate": lambda: cognito.ClientAttributes().with_standard_attributes(birthdate=True),
323
+ "email": lambda: cognito.ClientAttributes().with_standard_attributes(email=True),
324
+ "email_verified": lambda: cognito.ClientAttributes().with_standard_attributes(email_verified=True),
325
+ "family_name": lambda: cognito.ClientAttributes().with_standard_attributes(family_name=True),
326
+ "gender": lambda: cognito.ClientAttributes().with_standard_attributes(gender=True),
327
+ "given_name": lambda: cognito.ClientAttributes().with_standard_attributes(given_name=True),
328
+ "locale": lambda: cognito.ClientAttributes().with_standard_attributes(locale=True),
329
+ "middle_name": lambda: cognito.ClientAttributes().with_standard_attributes(middle_name=True),
330
+ "name": lambda: cognito.ClientAttributes().with_standard_attributes(fullname=True),
331
+ "nickname": lambda: cognito.ClientAttributes().with_standard_attributes(nickname=True),
332
+ "phone_number": lambda: cognito.ClientAttributes().with_standard_attributes(phone_number=True),
333
+ "phone_number_verified": lambda: cognito.ClientAttributes().with_standard_attributes(phone_number_verified=True),
334
+ "picture": lambda: cognito.ClientAttributes().with_standard_attributes(picture=True),
335
+ "preferred_username": lambda: cognito.ClientAttributes().with_standard_attributes(preferred_username=True),
336
+ "profile": lambda: cognito.ClientAttributes().with_standard_attributes(profile=True),
337
+ "timezone": lambda: cognito.ClientAttributes().with_standard_attributes(timezone=True),
338
+ "updated_at": lambda: cognito.ClientAttributes().with_standard_attributes(last_update_time=True),
339
+ "website": lambda: cognito.ClientAttributes().with_standard_attributes(website=True),
340
+ }
341
+
342
+ # Start with empty attributes
343
+ attrs = cognito.ClientAttributes()
344
+
345
+ # Build standard attributes
346
+ standard_dict = {}
347
+ custom_list = []
348
+
349
+ for attr in attribute_list:
350
+ if attr in standard_attrs:
351
+ standard_dict[attr] = True
352
+ else:
353
+ # Custom attribute
354
+ custom_list.append(attr)
355
+
356
+ # Apply standard attributes if any
357
+ if standard_dict:
358
+ # Map attribute names to CDK parameter names
359
+ attr_mapping = {
360
+ "address": "address",
361
+ "birthdate": "birthdate",
362
+ "email": "email",
363
+ "email_verified": "email_verified",
364
+ "family_name": "family_name",
365
+ "gender": "gender",
366
+ "given_name": "given_name",
367
+ "locale": "locale",
368
+ "middle_name": "middle_name",
369
+ "name": "fullname",
370
+ "nickname": "nickname",
371
+ "phone_number": "phone_number",
372
+ "phone_number_verified": "phone_number_verified",
373
+ "picture": "picture",
374
+ "preferred_username": "preferred_username",
375
+ "profile": "profile",
376
+ "timezone": "timezone",
377
+ "updated_at": "last_update_time",
378
+ "website": "website",
379
+ }
380
+
381
+ # Convert to CDK parameter names
382
+ cdk_attrs = {attr_mapping.get(k, k): v for k, v in standard_dict.items()}
383
+ attrs = attrs.with_standard_attributes(**cdk_attrs)
384
+
385
+ # Add custom attributes if any
386
+ if custom_list:
387
+ attrs = attrs.with_custom_attributes(*custom_list)
388
+
389
+ return attrs
390
+
391
+ def _build_identity_providers(self, providers: list) -> list:
392
+ """Build identity provider list from configuration"""
393
+ if not providers:
394
+ return None
395
+
396
+ result = []
397
+ for provider in providers:
398
+ if isinstance(provider, str):
399
+ if provider.upper() == "COGNITO":
400
+ result.append(cognito.UserPoolClientIdentityProvider.COGNITO)
401
+ elif provider.upper() == "GOOGLE":
402
+ result.append(cognito.UserPoolClientIdentityProvider.GOOGLE)
403
+ elif provider.upper() == "FACEBOOK":
404
+ result.append(cognito.UserPoolClientIdentityProvider.FACEBOOK)
405
+ elif provider.upper() == "AMAZON":
406
+ result.append(cognito.UserPoolClientIdentityProvider.AMAZON)
407
+ elif provider.upper() == "APPLE":
408
+ result.append(cognito.UserPoolClientIdentityProvider.APPLE)
409
+ else:
410
+ # Custom provider
411
+ result.append(cognito.UserPoolClientIdentityProvider.custom(provider))
412
+
413
+ return result if result else None
152
414
 
153
- self._export_ssm_parameters(user_pool)
415
+ def _store_client_secret_in_secrets_manager(
416
+ self,
417
+ client_name: str,
418
+ app_client: cognito.UserPoolClient,
419
+ user_pool: cognito.UserPool
420
+ ):
421
+ """
422
+ Store Cognito app client secret in AWS Secrets Manager.
423
+ Uses a custom resource to retrieve the secret from Cognito API.
424
+ """
425
+ # Create a custom resource to retrieve the client secret
426
+ # This is necessary because CDK doesn't expose the client secret
427
+ get_client_secret = cr.AwsCustomResource(
428
+ self,
429
+ f"{client_name}-secret-retriever",
430
+ on_create=cr.AwsSdkCall(
431
+ service="CognitoIdentityServiceProvider",
432
+ action="describeUserPoolClient",
433
+ parameters={
434
+ "UserPoolId": user_pool.user_pool_id,
435
+ "ClientId": app_client.user_pool_client_id,
436
+ },
437
+ physical_resource_id=cr.PhysicalResourceId.of(
438
+ f"{client_name}-secret-{app_client.user_pool_client_id}"
439
+ ),
440
+ ),
441
+ policy=cr.AwsCustomResourcePolicy.from_statements([
442
+ iam.PolicyStatement(
443
+ actions=["cognito-idp:DescribeUserPoolClient"],
444
+ resources=[user_pool.user_pool_arn],
445
+ )
446
+ ]),
447
+ )
448
+
449
+ # Get the client secret from the custom resource response
450
+ client_secret = get_client_secret.get_response_field(
451
+ "UserPoolClient.ClientSecret"
452
+ )
453
+
454
+ # Create secret in Secrets Manager
455
+ secret = secretsmanager.Secret(
456
+ self,
457
+ f"{client_name}-client-secret",
458
+ secret_name=self.deployment.build_resource_name(
459
+ f"cognito/{client_name}/client-secret"
460
+ ),
461
+ description=f"Cognito app client secret for {client_name}",
462
+ secret_string_value=cdk.SecretValue.unsafe_plain_text(client_secret),
463
+ )
464
+
465
+ # Also store client ID in the same secret for convenience
466
+ secret_with_metadata = secretsmanager.Secret(
467
+ self,
468
+ f"{client_name}-client-credentials",
469
+ secret_name=self.deployment.build_resource_name(
470
+ f"cognito/{client_name}/credentials"
471
+ ),
472
+ description=f"Cognito app client credentials for {client_name}",
473
+ secret_object_value={
474
+ "client_id": cdk.SecretValue.unsafe_plain_text(
475
+ app_client.user_pool_client_id
476
+ ),
477
+ "client_secret": cdk.SecretValue.unsafe_plain_text(client_secret),
478
+ "user_pool_id": cdk.SecretValue.unsafe_plain_text(
479
+ user_pool.user_pool_id
480
+ ),
481
+ },
482
+ )
483
+
484
+ logger.info(
485
+ f"Stored client secret for {client_name} in Secrets Manager: "
486
+ f"{secret_with_metadata.secret_name}"
487
+ )
488
+
489
+ # Export secret ARN to SSM for cross-stack reference
490
+ if self.cognito_config.ssm.get("enabled"):
491
+ safe_client_name = client_name.replace("-", "_").replace(" ", "_")
492
+ org = self.cognito_config.ssm.get("organization", "default")
493
+ env = self.cognito_config.ssm.get("environment", "dev")
494
+
495
+ ssm.StringParameter(
496
+ self,
497
+ f"{client_name}-secret-arn-param",
498
+ parameter_name=f"/{org}/{env}/cognito/user-pool/app_client_{safe_client_name}_secret_arn",
499
+ string_value=secret_with_metadata.secret_arn,
500
+ description=f"Secrets Manager ARN for {client_name} credentials",
501
+ )
154
502
 
155
503
  def _export_ssm_parameters(self, user_pool: cognito.UserPool):
156
504
  """Export Cognito resources to SSM using enhanced SSM parameter mixin"""
@@ -172,6 +520,16 @@ class CognitoStack(IStack, EnhancedSsmParameterMixin):
172
520
  "user_pool_arn": user_pool.user_pool_arn,
173
521
  }
174
522
 
523
+ # Add app client IDs to export
524
+ for client_name, app_client in self.app_clients.items():
525
+ # Export client ID
526
+ safe_client_name = client_name.replace("-", "_").replace(" ", "_")
527
+ resource_values[f"app_client_{safe_client_name}_id"] = app_client.user_pool_client_id
528
+
529
+ # Note: Client secrets cannot be exported via SSM as they are only available
530
+ # at creation time and CDK doesn't expose them. Use AWS Secrets Manager
531
+ # or retrieve via AWS Console/CLI if needed.
532
+
175
533
  # Use enhanced SSM parameter export
176
534
  exported_params = self.auto_export_resources(resource_values)
177
535
 
File without changes