cloud-foundry 0.5.3__tar.gz → 0.5.5__tar.gz

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.
Files changed (44) hide show
  1. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/PKG-INFO +1 -1
  2. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/__init__.py +1 -1
  3. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/python_function.py +2 -0
  4. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/rest_api.py +7 -1
  5. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/websocket_api.py +13 -3
  6. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/python_archive_builder.py +11 -3
  7. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/services/authorization_api/security_lambda.py +154 -175
  8. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/services/mail_publisher.py +29 -27
  9. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/utils/idle_reaper_client.py +5 -1
  10. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/.gitignore +0 -0
  11. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/LICENSE +0 -0
  12. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/README.md +0 -0
  13. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/archive_builder.py +0 -0
  14. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/mail_publisher.py +0 -0
  15. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/migrations/__init__.py +0 -0
  16. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/migrations/forget_site_objects.py +0 -0
  17. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/__init__.py +0 -0
  18. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/api_waf.py +0 -0
  19. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/cdn.py +0 -0
  20. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/cdn_api_origin.py +0 -0
  21. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/cdn_site_origin.py +0 -0
  22. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/connection_store.py +0 -0
  23. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/custom_domain.py +0 -0
  24. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/document_repository.py +0 -0
  25. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/domain.py +0 -0
  26. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/function.py +0 -0
  27. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/idle_reaper.py +0 -0
  28. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/postgres_schema.py +0 -0
  29. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/publisher.py +0 -0
  30. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/queue.py +0 -0
  31. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/schedule.py +0 -0
  32. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/site_bucket.py +0 -0
  33. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/topic.py +0 -0
  34. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/topic_subscription.py +0 -0
  35. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/ui_publisher.py +0 -0
  36. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/pulumi/websocket_function.py +0 -0
  37. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/services/postgres_schema_bootstrap.py +0 -0
  38. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/utils/aws_openapi_editor.py +0 -0
  39. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/utils/hash_comparator.py +0 -0
  40. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/utils/logger.py +0 -0
  41. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/utils/names.py +0 -0
  42. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/utils/openapi_editor.py +0 -0
  43. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/cloud_foundry/utils/websocket_utils.py +0 -0
  44. {cloud_foundry-0.5.3 → cloud_foundry-0.5.5}/pyproject.toml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cloud-foundry
3
- Version: 0.5.3
3
+ Version: 0.5.5
4
4
  Summary: cloud-foundry is a curated set of cloud components that can be used to assemble cloud-based applications.
5
5
  Project-URL: Documentation, https://github.com/DanRepik/cloud-foundry
6
6
  Project-URL: Source, https://github.com/DanRepik/cloud-foundry
@@ -35,4 +35,4 @@ from cloud_foundry.utils.idle_reaper_client import request_mapping_enable # noq
35
35
  from cloud_foundry.utils.names import resource_id # noqa: F401
36
36
  from cloud_foundry.utils.names import project_slug # noqa: F401
37
37
 
38
- version = "0.5.3"
38
+ version = "0.5.5"
@@ -38,6 +38,8 @@ def python_function(
38
38
  requirements=requirements,
39
39
  working_dir="temp",
40
40
  target_architecture=resolved_architecture,
41
+ # "python3.13" -> "3.13"; Function defaults the runtime to python3.12.
42
+ python_version=(runtime or "python3.12").removeprefix("python"),
41
43
  )
42
44
  return Function(
43
45
  name=name,
@@ -29,6 +29,7 @@ class RestAPI(pulumi.ComponentResource):
29
29
  rest_api: Optional[aws.apigateway.RestApi] = None
30
30
  rest_api_id: pulumi.Output[str] = None # The REST API identifier
31
31
  domain: Optional[str] = None # The custom domain name for the API
32
+ _gateway_role: Optional[aws.iam.Role] = None # built once, see _get_gateway_role
32
33
 
33
34
  def __init__(
34
35
  self,
@@ -371,7 +372,6 @@ class RestAPI(pulumi.ComponentResource):
371
372
  "resourcePath": "$context.resourcePath",
372
373
  "status": "$context.status",
373
374
  "origin": "$context.request.header.Origin",
374
- "authorization": "$context.request.header.Authorization",
375
375
  "protocol": "$context.protocol",
376
376
  "responseLength": "$context.responseLength",
377
377
  }
@@ -548,6 +548,11 @@ class RestAPI(pulumi.ComponentResource):
548
548
  if not self.content:
549
549
  return None
550
550
 
551
+ # Called from _collect_arns and _create_cognito_permissions; the
552
+ # second call must not declare the same named resources again.
553
+ if self._gateway_role is not None:
554
+ return self._gateway_role
555
+
551
556
  content_with_bucket = [item for item in self.content if "bucket_name" in item]
552
557
  prefixes = [item.get("prefix") for item in content_with_bucket]
553
558
 
@@ -618,6 +623,7 @@ class RestAPI(pulumi.ComponentResource):
618
623
  )
619
624
  log.info("S3 access policy attached successfully: %s", api_gateway_role)
620
625
 
626
+ self._gateway_role = api_gateway_role
621
627
  return api_gateway_role
622
628
 
623
629
  def get_endpoint(self):
@@ -60,9 +60,8 @@ class WebSocketAPI(pulumi.ComponentResource):
60
60
  - require_auth (bool, optional): Whether this route
61
61
  requires authorization
62
62
  authorizer (Optional[dict]): Authorizer configuration with:
63
- - type (str): "lambda" or "cognito"
64
- - function: Lambda function for lambda authorizer
65
- - user_pool_arns: List of Cognito user pool ARNs
63
+ - type (str): "lambda" (the only supported type)
64
+ - function: Lambda function for the authorizer
66
65
  - identity_source: Identity source expression
67
66
  (e.g., "route.request.querystring.token")
68
67
  hosted_zone_id (Optional[str]): Route 53 hosted zone ID
@@ -148,6 +147,17 @@ class WebSocketAPI(pulumi.ComponentResource):
148
147
  if "function" not in route:
149
148
  raise ValueError(f"Route '{route_key}' must have a 'function' defined")
150
149
 
150
+ # Only a lambda authorizer is built; anything else would leave
151
+ # the route silently open.
152
+ if (
153
+ route.get("require_auth")
154
+ and (self.authorizer or {}).get("type") != "lambda"
155
+ ):
156
+ raise ValueError(
157
+ f"Route '{route_key}' has require_auth but no "
158
+ "authorizer of type 'lambda' is configured"
159
+ )
160
+
151
161
  # Check if required routes are defined
152
162
  missing_routes = required_routes - seen_routes
153
163
  if missing_routes:
@@ -47,6 +47,7 @@ class PythonArchiveBuilder(ArchiveBuilder):
47
47
  requirements: list[str],
48
48
  working_dir: str,
49
49
  target_architecture: str = "x86_64",
50
+ python_version: str = "3.12",
50
51
  ):
51
52
  """
52
53
  Initialize the PythonArchiveBuilder with necessary parameters.
@@ -65,6 +66,8 @@ class PythonArchiveBuilder(ArchiveBuilder):
65
66
  self._requirements = requirements or []
66
67
  self._working_dir = working_dir
67
68
  self._target_architecture = self._normalize_architecture(target_architecture)
69
+ # Wheels must match the Lambda runtime's ABI, not the build interpreter.
70
+ self._python_version = python_version
68
71
 
69
72
  # Base directory where Lambda-related files will be stored
70
73
  self._base_dir = os.path.join(self._working_dir, f"{self.name}-lambda")
@@ -187,7 +190,9 @@ class PythonArchiveBuilder(ArchiveBuilder):
187
190
  info = zipfile.ZipInfo(relative_path, date_time=_ZIP_EPOCH)
188
191
  info.compress_type = zipfile.ZIP_DEFLATED
189
192
  executable = os.stat(full_path).st_mode & 0o111
190
- info.external_attr = (0o100755 if executable else 0o100644) << 16
193
+ info.external_attr = (
194
+ 0o100755 if executable else 0o100644
195
+ ) << 16
191
196
  with open(full_path, "rb") as source:
192
197
  archive.writestr(info, source.read())
193
198
 
@@ -252,9 +257,10 @@ class PythonArchiveBuilder(ArchiveBuilder):
252
257
  for index, wheel_platform in enumerate(wheel_platforms, start=1):
253
258
  strategy_name = f"Strategy {index}"
254
259
  log.info(
255
- "%s: Attempting %s platform wheels for Python 3.12",
260
+ "%s: Attempting %s platform wheels for Python %s",
256
261
  strategy_name,
257
262
  wheel_platform,
263
+ self._python_version,
258
264
  )
259
265
  try:
260
266
  subprocess.check_call(
@@ -271,7 +277,7 @@ class PythonArchiveBuilder(ArchiveBuilder):
271
277
  "--implementation",
272
278
  "cp",
273
279
  "--python-version",
274
- "3.12",
280
+ self._python_version,
275
281
  "--upgrade",
276
282
  "--no-compile",
277
283
  "-r",
@@ -442,6 +448,8 @@ class PythonArchiveBuilder(ArchiveBuilder):
442
448
  self._get_file_resource(file_path, destination_path)
443
449
  elif source_path.startswith(("http://", "https://")):
444
450
  self._get_network_resource(source_path, destination_path)
451
+ elif os.path.exists(source_path):
452
+ self._get_file_resource(source_path, destination_path)
445
453
  else: # Inline content
446
454
  os.makedirs(os.path.dirname(destination_path), exist_ok=True)
447
455
  with open(destination_path, "w") as f:
@@ -16,6 +16,37 @@ log.setLevel(os.environ.get("LOGGING_LEVEL", "INFO"))
16
16
  cognito_client = boto3.client("cognito-idp")
17
17
 
18
18
 
19
+ # Cognito error code -> HTTP status. Other client errors stay 400, and
20
+ # Cognito's own server errors become 500.
21
+ COGNITO_STATUS = {
22
+ "NotAuthorizedException": 401,
23
+ "UserNotConfirmedException": 403,
24
+ "PasswordResetRequiredException": 403,
25
+ "UserNotFoundException": 404,
26
+ "ResourceNotFoundException": 404,
27
+ "UsernameExistsException": 409,
28
+ "TooManyRequestsException": 429,
29
+ "TooManyFailedAttemptsException": 429,
30
+ "LimitExceededException": 429,
31
+ }
32
+
33
+
34
+ def error_response(e: ClientError, overrides: Optional[dict] = None) -> dict:
35
+ code = e.response["Error"]["Code"]
36
+ status = {**COGNITO_STATUS, **(overrides or {})}.get(code)
37
+ if status is None:
38
+ upstream = e.response.get("ResponseMetadata", {}).get("HTTPStatusCode", 400)
39
+ status = 500 if upstream >= 500 else 400
40
+ return {
41
+ "statusCode": status,
42
+ "body": json.dumps({"message": e.response["Error"]["Message"]}),
43
+ }
44
+
45
+
46
+ def bad_request(message: str) -> dict:
47
+ return {"statusCode": 400, "body": json.dumps({"message": message})}
48
+
49
+
19
50
  class AuthorizationServices:
20
51
  def __init__(
21
52
  self,
@@ -28,48 +59,59 @@ class AuthorizationServices:
28
59
  self.user_pool_id = user_pool_id or os.getenv("USER_POOL_ID")
29
60
  self.client_id = client_id or os.getenv("CLIENT_ID")
30
61
  self.client_secret = client_secret or os.getenv("CLIENT_SECRET")
62
+ # Preferred over CLIENT_SECRET: a Lambda's environment is readable by
63
+ # anyone with lambda:GetFunctionConfiguration. Read on first use.
64
+ self.client_secret_arn = os.getenv("CLIENT_SECRET_ARN")
31
65
  self.user_admin_group = user_admin_group or os.getenv("USER_ADMIN_GROUP")
32
66
  self.user_default_group = user_default_group or os.getenv("USER_DEFAULT_GROUP")
33
67
  region = os.getenv("AWS_REGION")
34
68
  self.cognito_client = boto3.client("cognito-idp", region_name=region)
35
69
 
36
70
  def handler(self, event, context):
37
- log.info(f"event: {event}")
38
-
71
+ if not self.client_secret and self.client_secret_arn:
72
+ self.client_secret = boto3.client("secretsmanager").get_secret_value(
73
+ SecretId=self.client_secret_arn
74
+ )["SecretString"]
39
75
  assert (
40
76
  self.user_pool_id and self.client_id and self.client_secret
41
- ), "USER_POOL_ID, CLIENT_ID, and CLIENT_SECRET must be set"
77
+ ), "USER_POOL_ID, CLIENT_ID, and CLIENT_SECRET (or CLIENT_SECRET_ARN) must be set"
42
78
 
43
79
  path = event.get("resource", "")
44
80
  http_method = event.get("httpMethod", "").upper()
45
81
  log.info(f"Path: {path}, HTTP Method: {http_method}")
46
82
 
47
- if path.endswith("/users") and http_method == "POST":
48
- return self.create_user(event)
49
- elif path.endswith("/users/{username}") and http_method == "GET":
50
- return self.get_user(event)
51
- elif path.endswith("/users/{username}") and http_method == "DELETE":
52
- return self.delete_user(event)
53
- elif path.endswith("/users/me/password") and http_method == "PUT":
54
- return self.change_user_password(event)
55
- elif path.endswith("/users/{username}/groups") and http_method == "PUT":
56
- return self.change_user_groups(event)
57
- elif path.endswith("/sessions") and http_method == "POST":
58
- return self.create_session(event)
59
- elif path.endswith("/sessions/me") and http_method == "DELETE":
60
- return self.delete_session(event)
61
- elif path.endswith("/sessions/refresh") and http_method == "POST":
62
- return self.refresh_session(event)
63
- else:
64
- return {
65
- "statusCode": 400,
66
- "body": json.dumps({"message": "Invalid action or method"}),
67
- }
83
+ try:
84
+ if path.endswith("/users") and http_method == "POST":
85
+ return self.create_user(event)
86
+ elif path.endswith("/users/{username}") and http_method == "GET":
87
+ return self.get_user(event)
88
+ elif path.endswith("/users/{username}") and http_method == "DELETE":
89
+ return self.delete_user(event)
90
+ elif path.endswith("/users/me/password") and http_method == "PUT":
91
+ return self.change_user_password(event)
92
+ elif path.endswith("/users/{username}/groups") and http_method == "PUT":
93
+ return self.change_user_groups(event)
94
+ elif path.endswith("/sessions") and http_method == "POST":
95
+ return self.create_session(event)
96
+ elif path.endswith("/sessions/me") and http_method == "DELETE":
97
+ return self.delete_session(event)
98
+ except json.JSONDecodeError:
99
+ return bad_request("Request body must be JSON")
100
+ return {
101
+ "statusCode": 404,
102
+ "body": json.dumps({"message": f"No route for {http_method} {path}"}),
103
+ }
104
+
105
+ @staticmethod
106
+ def body(event) -> dict:
107
+ return json.loads(event.get("body") or "{}")
68
108
 
69
109
  def create_user(self, event):
70
- body = json.loads(event["body"])
110
+ body = self.body(event)
71
111
  username = body.get("username") or body.get("email")
72
112
  password = body.get("password")
113
+ if not username or not password:
114
+ return bad_request("username and password are required")
73
115
 
74
116
  try:
75
117
 
@@ -104,22 +146,12 @@ class AuthorizationServices:
104
146
  "body": json.dumps({"message": "Signup successful"}),
105
147
  }
106
148
  except ClientError as e:
107
- return {
108
- "statusCode": 400,
109
- "body": json.dumps({"message": e.response["Error"]["Message"]}),
110
- }
149
+ return error_response(e)
111
150
 
112
151
  def get_user(self, event):
113
- # Check if admin group is defined and user is an admin
114
- if self.user_admin_group:
115
- permissions = self.get_permissions_from_event(event)
116
- if self.user_admin_group not in permissions:
117
- return {
118
- "statusCode": 403,
119
- "body": json.dumps(
120
- {"message": "You are not authorized to delete users"}
121
- ),
122
- }
152
+ denied = self.require_admin(event)
153
+ if denied:
154
+ return denied
123
155
 
124
156
  username = unquote(event["pathParameters"]["username"])
125
157
  try:
@@ -129,22 +161,12 @@ class AuthorizationServices:
129
161
  "body": json.dumps({"user_info": user_info, "groups": sorted(groups)}),
130
162
  }
131
163
  except ClientError as e:
132
- return {
133
- "statusCode": 400,
134
- "body": json.dumps({"message": e.response["Error"]["Message"]}),
135
- }
164
+ return error_response(e)
136
165
 
137
166
  def delete_user(self, event):
138
- # Check if admin group is defined and user is an admin
139
- if self.user_admin_group:
140
- permissions = self.get_permissions_from_event(event)
141
- if self.user_admin_group not in permissions:
142
- return {
143
- "statusCode": 403,
144
- "body": json.dumps(
145
- {"message": "You are not authorized to delete users"}
146
- ),
147
- }
167
+ denied = self.require_admin(event)
168
+ if denied:
169
+ return denied
148
170
 
149
171
  username = event["pathParameters"]["username"]
150
172
  try:
@@ -168,13 +190,10 @@ class AuthorizationServices:
168
190
  }
169
191
  except ClientError as e:
170
192
  log.error(f"Error deleting user: {e.response}")
171
- return {
172
- "statusCode": 400,
173
- "body": json.dumps({"message": e.response["Error"]["Message"]}),
174
- }
193
+ return error_response(e)
175
194
 
176
195
  def change_user_password(self, event):
177
- body = json.loads(event["body"])
196
+ body = self.body(event)
178
197
  try:
179
198
  request_context = event.get("requestContext")
180
199
  username = request_context.get("authorizer", {}).get("username")
@@ -212,26 +231,15 @@ class AuthorizationServices:
212
231
  "body": json.dumps({"message": "Password changed successfully"}),
213
232
  }
214
233
  except ClientError as e:
215
- return {
216
- "statusCode": 400,
217
- "body": json.dumps({"message": e.response["Error"]["Message"]}),
218
- }
234
+ return error_response(e)
219
235
 
220
236
  def change_user_groups(self, event):
221
- # Check if admin group is defined and user is an admin
222
- if self.user_admin_group:
223
- permissions = self.get_permissions_from_event(event)
224
- log.info(f"permissions: {permissions}")
225
- if self.user_admin_group not in permissions:
226
- return {
227
- "statusCode": 403,
228
- "body": json.dumps(
229
- {"message": "You are not authorized to delete users"}
230
- ),
231
- }
237
+ denied = self.require_admin(event)
238
+ if denied:
239
+ return denied
232
240
 
233
241
  username = unquote(event["pathParameters"]["username"])
234
- body = json.loads(event["body"])
242
+ body = self.body(event)
235
243
  groups = body.get("groups", [])
236
244
 
237
245
  try:
@@ -259,49 +267,62 @@ class AuthorizationServices:
259
267
  "body": json.dumps({"message": "User groups updated successfully"}),
260
268
  }
261
269
  except ClientError as e:
262
- return {
263
- "statusCode": 400,
264
- "body": json.dumps({"message": e.response["Error"]["Message"]}),
265
- }
270
+ # AdminAddUserToGroup reports an unknown group as ResourceNotFound.
271
+ return error_response(e, {"ResourceNotFoundException": 400})
266
272
 
267
273
  def create_session(self, event):
268
- body = json.loads(event["body"])
274
+ """Start a session with a password, or renew one with a refresh token
275
+ (one resource, two grants, like an OAuth token endpoint)."""
276
+ body = self.body(event)
269
277
  username = body.get("username") or body.get("email")
270
- password = body.get("password")
271
- secret_hash = self.calculate_secret_hash(username)
278
+ if not username:
279
+ return bad_request("username is required")
280
+ if body.get("refresh_token"):
281
+ flow = "REFRESH_TOKEN_AUTH"
282
+ params = {"REFRESH_TOKEN": body["refresh_token"]}
283
+ elif body.get("password"):
284
+ flow = "USER_PASSWORD_AUTH"
285
+ params = {"USERNAME": username, "PASSWORD": body["password"]}
286
+ else:
287
+ return bad_request("password or refresh_token is required")
272
288
 
273
289
  try:
290
+ # A refresh's SECRET_HASH must use the user's Cognito username;
291
+ # in a pool that signs in by email that is the sub, not the email.
292
+ hash_name = (
293
+ cognito_client.admin_get_user(
294
+ UserPoolId=self.user_pool_id, Username=username
295
+ )["Username"]
296
+ if flow == "REFRESH_TOKEN_AUTH"
297
+ else username
298
+ )
299
+ params["SECRET_HASH"] = self.calculate_secret_hash(hash_name)
274
300
  response = cognito_client.initiate_auth(
275
- AuthFlow="USER_PASSWORD_AUTH",
276
- AuthParameters={
277
- "USERNAME": username,
278
- "PASSWORD": password,
279
- "SECRET_HASH": secret_hash,
280
- },
281
- ClientId=self.client_id,
301
+ AuthFlow=flow, AuthParameters=params, ClientId=self.client_id
282
302
  )
283
-
303
+ tokens = response["AuthenticationResult"]
284
304
  user_info, groups = self.fetch_user_info(username)
285
- return {
286
- "statusCode": 200,
287
- "body": json.dumps(
288
- {
289
- "user_info": user_info,
290
- "groups": groups,
291
- "id_token": response["AuthenticationResult"]["IdToken"],
292
- "access_token": response["AuthenticationResult"]["AccessToken"],
293
- "refresh_token": response["AuthenticationResult"][
294
- "RefreshToken"
295
- ],
296
- }
297
- ),
298
- }
299
305
  except ClientError as e:
300
- log.error(f"Error: {e.response}")
301
- return {
302
- "statusCode": 400,
303
- "body": json.dumps({"message": e.response["Error"]["Message"]}),
304
- }
306
+ log.error(f"{flow} failed: {e.response['Error']['Code']}")
307
+ # An unknown user is a failed login, not a 404 that tells a
308
+ # caller which usernames exist.
309
+ return error_response(e, {"UserNotFoundException": 401})
310
+
311
+ return {
312
+ "statusCode": 200,
313
+ "body": json.dumps(
314
+ {
315
+ "user_info": user_info,
316
+ "groups": groups,
317
+ "id_token": tokens["IdToken"],
318
+ "access_token": tokens["AccessToken"],
319
+ # A refresh returns no new refresh token; keep the old one.
320
+ "refresh_token": tokens.get(
321
+ "RefreshToken", body.get("refresh_token")
322
+ ),
323
+ }
324
+ ),
325
+ }
305
326
 
306
327
  def delete_session(self, event):
307
328
  try:
@@ -323,10 +344,7 @@ class AuthorizationServices:
323
344
  "body": json.dumps({"message": "Logout successful"}),
324
345
  }
325
346
  except ClientError as e:
326
- return {
327
- "statusCode": 400,
328
- "body": json.dumps({"message": e.response["Error"]["Message"]}),
329
- }
347
+ return error_response(e)
330
348
 
331
349
  def calculate_secret_hash(self, username):
332
350
  message = username + self.client_id
@@ -335,66 +353,6 @@ class AuthorizationServices:
335
353
  ).digest()
336
354
  return base64.b64encode(secret_hash).decode("utf-8")
337
355
 
338
- def refresh_session(self, event):
339
- body = json.loads(event["body"])
340
-
341
- refresh_token = body.get("refresh_token")
342
- if not refresh_token:
343
- return {
344
- "statusCode": 400,
345
- "body": json.dumps({"message": "Refresh token is required"}),
346
- }
347
-
348
- username = event["requestContext"]["authorizer"].get("username")
349
-
350
- try:
351
- # Use the refresh token to get new tokens
352
- secret_hash = self.calculate_secret_hash(
353
- username
354
- ) # Calculate the secret hash
355
- response = cognito_client.initiate_auth(
356
- AuthFlow="REFRESH_TOKEN_AUTH",
357
- AuthParameters={
358
- "REFRESH_TOKEN": refresh_token,
359
- "SECRET_HASH": secret_hash, # Include the secret hash
360
- },
361
- ClientId=self.client_id,
362
- )
363
-
364
- # Extract tokens from the response
365
- access_token = response["AuthenticationResult"]["AccessToken"]
366
- id_token = response["AuthenticationResult"]["IdToken"]
367
- new_refresh_token = response["AuthenticationResult"].get(
368
- "RefreshToken", refresh_token
369
- ) # Use the new refresh token if provided
370
-
371
- user_info, groups = self.fetch_user_info(username)
372
-
373
- return {
374
- "statusCode": 200,
375
- "body": json.dumps(
376
- {
377
- "access_token": access_token,
378
- "id_token": id_token,
379
- "refresh_token": new_refresh_token,
380
- "user_info": user_info,
381
- "groups": groups,
382
- }
383
- ),
384
- }
385
- except ClientError as e:
386
- log.error(f"ClientError occurred: {e.response}")
387
- return {
388
- "statusCode": 400,
389
- "body": json.dumps({"message": e.response["Error"]["Message"]}),
390
- }
391
- except Exception as e:
392
- log.error(f"Unexpected error occurred: {str(e)}")
393
- return {
394
- "statusCode": 500,
395
- "body": json.dumps({"message": "An unexpected error occurred"}),
396
- }
397
-
398
356
  def fetch_user_info(self, username):
399
357
  # Fetch user attributes
400
358
  user_details = cognito_client.admin_get_user(
@@ -412,6 +370,20 @@ class AuthorizationServices:
412
370
 
413
371
  return attributes, groups
414
372
 
373
+ def require_admin(self, event) -> Optional[dict]:
374
+ """403 response unless the caller is in the admin group. Fails closed:
375
+ with no USER_ADMIN_GROUP configured nobody gets admin actions, since
376
+ otherwise any signed-in user could delete users or grant themselves
377
+ any group."""
378
+ if self.user_admin_group and self.user_admin_group in (
379
+ self.get_permissions_from_event(event)
380
+ ):
381
+ return None
382
+ return {
383
+ "statusCode": 403,
384
+ "body": json.dumps({"message": "Admin permission required"}),
385
+ }
386
+
415
387
  def get_permissions_from_event(self, event):
416
388
  """
417
389
  Extracts permissions from a decoded JWT token.
@@ -422,7 +394,12 @@ class AuthorizationServices:
422
394
 
423
395
  def to_list(x):
424
396
  if isinstance(x, str):
425
- return re.split(r"[,\s]+", x.strip())
397
+ x = x.strip()
398
+ # Authorizer context values must be strings, so a token
399
+ # validator passes a list as JSON ('["admin"]').
400
+ if x.startswith("["):
401
+ return to_list(json.loads(x))
402
+ return re.split(r"[,\s]+", x)
426
403
  elif isinstance(x, list):
427
404
  return x
428
405
  else:
@@ -448,8 +425,10 @@ class AuthorizationServices:
448
425
  Authorization header is missing, so callers' `if not access_token`
449
426
  checks behave correctly.
450
427
  """
451
- headers = event.get("headers", {})
452
- authorization_header = headers.get("Authorization")
428
+ # Header names arrive in whatever case the client (or CloudFront,
429
+ # or HTTP/2's lower case) sent.
430
+ headers = {k.lower(): v for k, v in (event.get("headers") or {}).items()}
431
+ authorization_header = headers.get("authorization")
453
432
 
454
433
  if not authorization_header:
455
434
  log.error("Authorization header is missing")
@@ -13,35 +13,37 @@ MAIL_ORIGIN = os.environ["MAIL_ORIGIN"]
13
13
 
14
14
 
15
15
  def handler(event, context):
16
- log.info("Received event: %s", json.dumps(event))
17
- try:
18
- responses = []
19
- for record in event["Records"]:
20
- if "Sns" in record:
21
- sns_message = json.loads(record["Sns"]["Message"])
22
- elif "body" in record:
23
- sns_message = json.loads(record["body"])
24
- else:
25
- raise ValueError("Unsupported message format")
26
- template_name = sns_message["template_name"]
27
- context_data = sns_message["context"]
28
- recipients = sns_message["recipients"]
29
- subject = sns_message["subject"]
30
- cc = sns_message.get("cc", []) # Get CC list, default to an empty list
31
- bcc = sns_message.get("bcc", []) # Get BCC list, default to an empty list
16
+ # Errors must reach Lambda: a normal return tells SNS/SQS the message was
17
+ # delivered, so it is deleted instead of retried or sent to the DLQ.
18
+ failures = []
19
+ for record in event["Records"]:
20
+ try:
21
+ send_record(record)
22
+ except Exception:
23
+ if "messageId" not in record: # SNS or direct invoke: let it retry
24
+ raise
25
+ log.exception("Failed to send SQS message %s", record["messageId"])
26
+ failures.append({"itemIdentifier": record["messageId"]})
27
+ # Read by SQS event source mappings with ReportBatchItemFailures.
28
+ return {"batchItemFailures": failures}
32
29
 
33
- email_body = render_template(template_name, context_data)
34
- response = send_email(recipients, subject, email_body, cc, bcc)
35
- responses.append(response)
36
30
 
37
- return {
38
- "statusCode": 200,
39
- "body": json.dumps(
40
- {"message": "Emails sent successfully", "responses": responses}
41
- ),
42
- }
43
- except Exception as e:
44
- return {"statusCode": 500, "body": json.dumps({"error": str(e)})}
31
+ def send_record(record):
32
+ if "Sns" in record:
33
+ message = json.loads(record["Sns"]["Message"])
34
+ elif "body" in record:
35
+ message = json.loads(record["body"])
36
+ else:
37
+ raise ValueError("Unsupported message format")
38
+
39
+ email_body = render_template(message["template_name"], message["context"])
40
+ return send_email(
41
+ message["recipients"],
42
+ message["subject"],
43
+ email_body,
44
+ message.get("cc", []),
45
+ message.get("bcc", []),
46
+ )
45
47
 
46
48
 
47
49
  def render_template(template_name, context):
@@ -51,7 +51,7 @@ def request_mapping_enable(
51
51
  up from the caller's ambient environment/credentials.
52
52
  """
53
53
  events = boto3.client("events", region_name=region_name)
54
- events.put_events(
54
+ response = events.put_events(
55
55
  Entries=[
56
56
  {
57
57
  "EventBusName": event_bus_name,
@@ -61,3 +61,7 @@ def request_mapping_enable(
61
61
  }
62
62
  ]
63
63
  )
64
+ # put_events reports per-entry failures (e.g. throttling) in the response
65
+ # instead of raising; a lost request leaves the mapping disabled.
66
+ if response.get("FailedEntryCount"):
67
+ raise RuntimeError(f"EnableMapping event not accepted: {response['Entries']}")
File without changes
File without changes
File without changes