velocity-python 0.13.2__py3-none-any.whl → 0.14.0__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.
velocity/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- __version__ = version = "0.13.2"
1
+ __version__ = version = "0.14.0"
2
2
 
3
3
  import importlib as _importlib
4
4
 
@@ -21,6 +21,11 @@ from velocity.cache import memo
21
21
  from velocity.db.core.lazy_engine import LazyEngine
22
22
  from velocity.db.core import tenant as _tenant_scope
23
23
  from velocity.db import exceptions as db_exceptions
24
+ from velocity.aws.identity import (
25
+ COGNITO_USER_POOL_ID_RE as _COGNITO_USER_POOL_ID_RE,
26
+ cognito_issuer_subject,
27
+ normalize_email,
28
+ )
24
29
  from velocity.aws.job_lifecycle import (
25
30
  CLAIM_COLUMN,
26
31
  CLAIM_ENDING_STATUSES,
@@ -66,7 +71,6 @@ logger = get_logger("velocity.aws.handlers.context")
66
71
 
67
72
  # Cognito User Pool id shape, e.g. "us-east-1_aBcD1234". Used to distinguish a
68
73
  # real user-pool identity from other Identity Pool providers (developer-auth).
69
- _COGNITO_USER_POOL_ID_RE = re.compile(r"^[\w-]+_[0-9a-zA-Z]+$")
70
74
 
71
75
 
72
76
  def _get_work_queue_name() -> str:
@@ -224,20 +228,10 @@ def _function_name(aws_context) -> str:
224
228
  return str(name or "local")
225
229
 
226
230
 
227
- def _cognito_issuer_subject(provider):
228
- """``(issuer, sub)`` from API Gateway's ``cognitoAuthenticationProvider``
229
- (``cognito-idp.<region>.amazonaws.com/<pool>,...:CognitoSignIn:<sub>``)
230
- when it is a User Pool identity, else None — the same parse and the
231
- same issuer as :meth:`Context.get_cognito_user`."""
232
- if not isinstance(provider, str) or "cognito-idp" not in provider:
233
- return None
234
- parts = provider.split(",")
235
- user_pool_segment = parts[0].strip()
236
- user_pool_id = user_pool_segment.split("/")[-1]
237
- user_sub = parts[-1].split(":")[-1].strip()
238
- if not user_sub or not _COGNITO_USER_POOL_ID_RE.match(user_pool_id):
239
- return None
240
- return f"https://{user_pool_segment}", user_sub
231
+ # The public parser is velocity.aws.identity.cognito_issuer_subject
232
+ # (re-exported above). The private name is kept through 0.14.x for callers
233
+ # that imported it; it goes in 0.15.0.
234
+ _cognito_issuer_subject = cognito_issuer_subject
241
235
 
242
236
 
243
237
  def _queue_retention_seconds() -> int:
@@ -976,12 +970,14 @@ class Context:
976
970
  session = {}
977
971
  masquerade = session.get("masquerade")
978
972
  if isinstance(masquerade, dict) and masquerade.get("effective_user"):
979
- return EMAIL_KEY_PREFIX + str(masquerade["effective_user"]).strip().lower()
973
+ # a grant's address the rule refuses is no namespace at all
974
+ effective = normalize_email(masquerade["effective_user"])
975
+ return EMAIL_KEY_PREFIX + effective if effective else None
980
976
  identity = request_context.get("identity") or {}
981
- pair = _cognito_issuer_subject(identity.get("cognitoAuthenticationProvider"))
977
+ pair = cognito_issuer_subject(identity.get("cognitoAuthenticationProvider"))
982
978
  if pair:
983
979
  return SUBJECT_KEY_PREFIX + "|".join(pair)
984
- email = str(session.get("email_address") or "").strip().lower()
980
+ email = normalize_email(session.get("email_address"))
985
981
  if email:
986
982
  return EMAIL_KEY_PREFIX + email
987
983
  return None
@@ -1332,35 +1328,22 @@ class Context:
1332
1328
  if not provider:
1333
1329
  raise AlertError("Cognito identity not found in requestContext") from None
1334
1330
 
1335
- parts = provider.split(",")
1336
-
1337
- try:
1338
- user_pool_segment = parts[0]
1339
- user_pool_id = user_pool_segment.split("/")[-1]
1340
- sign_in_segment = parts[-1]
1341
- user_sub = sign_in_segment.split(":")[-1]
1342
- except (IndexError, AttributeError):
1343
- raise AlertError(
1344
- "Unable to parse Cognito identity provider string"
1345
- ) from None
1346
-
1347
- if not user_pool_id or not user_sub:
1348
- raise AlertError("Incomplete Cognito identity provider data") from None
1349
-
1331
+ # the one parser (velocity.aws.identity.cognito_issuer_subject).
1350
1332
  # Federated identities that are not Cognito User Pool logins — e.g.
1351
1333
  # developer-authenticated Identity Pool identities used for admin
1352
1334
  # masquerade — carry a provider name (like "login.example.masquerade")
1353
- # that is not a user-pool id. Detect that and fail with a clear message
1354
- # rather than passing an invalid value to admin_get_user (which raises a
1355
- # cryptic "userPoolId failed to satisfy constraint" error).
1356
- if "cognito-idp" not in provider or not _COGNITO_USER_POOL_ID_RE.match(
1357
- user_pool_id
1358
- ):
1335
+ # that is not a user-pool id: refuse with a clear message rather than
1336
+ # pass an invalid value to admin_get_user (which raises a cryptic
1337
+ # "userPoolId failed to satisfy constraint" error).
1338
+ pair = cognito_issuer_subject(provider)
1339
+ if not pair:
1359
1340
  raise AlertError(
1360
1341
  "Request identity is not a Cognito User Pool user "
1361
- f"(authentication provider '{provider[:120]}'); "
1342
+ f"(authentication provider '{str(provider)[:120]}'); "
1362
1343
  "cannot resolve a Cognito user"
1363
1344
  ) from None
1345
+ issuer, user_sub = pair
1346
+ user_pool_id = issuer.rsplit("/", 1)[-1]
1364
1347
 
1365
1348
  # one Cognito round trip per user per UserCacheSeconds per container
1366
1349
  # (velocity.cache); a lookup that fails is never cached
@@ -1425,7 +1408,7 @@ class Context:
1425
1408
  "sub": attributes.get("sub", user_sub),
1426
1409
  # the token issuer for this pool: with "sub", the identity
1427
1410
  # the provider never reassigns (velocity.aws.identity)
1428
- "issuer": f"https://{user_pool_segment}",
1411
+ "issuer": issuer,
1429
1412
  }
1430
1413
 
1431
1414
  return user
@@ -1446,6 +1429,41 @@ class Context:
1446
1429
  except Exception:
1447
1430
  return None
1448
1431
 
1432
+ # resolved_cognito_user's per-request result (a resolved user only)
1433
+ _COGNITO_RESOLVE_MEMO = "_velocity_cognito_resolve_memo"
1434
+
1435
+ def resolved_cognito_user(self, mode: str = "required"):
1436
+ """The request's Cognito user, resolved once per request and memoised
1437
+ on this Context, so ``LambdaHandler.beforeAction`` and a layer that
1438
+ runs before it share one lookup and one set of claims.
1439
+
1440
+ * ``"required"``: the user, or raises (``AlertError`` when the
1441
+ identity is absent, is not a User Pool identity, or the lookup
1442
+ fails). A failure is never memoised: a later call looks again and
1443
+ raises again.
1444
+ * ``"optional"``: the user, or None on any of those.
1445
+ * ``"none"`` (or anything else): None, no lookup.
1446
+
1447
+ A provider that is not a User Pool identity
1448
+ (:func:`velocity.aws.identity.cognito_issuer_subject` is None) never
1449
+ reaches ``admin_get_user``. Pass ``handler.effective_auth_mode(context)``.
1450
+ """
1451
+ if mode not in ("required", "optional"):
1452
+ return None
1453
+ found = self.__dict__.get(self._COGNITO_RESOLVE_MEMO)
1454
+ if isinstance(found, dict):
1455
+ return found
1456
+ try:
1457
+ user = self.get_cognito_user(self.__aws_event)
1458
+ if not isinstance(user, dict):
1459
+ raise AlertError("Cognito user could not be resolved") from None
1460
+ except Exception:
1461
+ if mode == "required":
1462
+ raise
1463
+ return None
1464
+ self.__dict__[self._COGNITO_RESOLVE_MEMO] = user
1465
+ return user
1466
+
1449
1467
 
1450
1468
  _MAX_TRACKING_FIELDS = 30
1451
1469
  _MAX_TRACKING_PAYLOAD_BYTES = 4096
@@ -103,6 +103,76 @@ class LambdaHandler(BaseHandler):
103
103
  finally:
104
104
  _tenancy.end_pre_resolution(self)
105
105
 
106
+ _AUTH_MODES = ("required", "optional", "none")
107
+ # Context attribute holding this request's verified grant (or None):
108
+ # the grant's HMAC is verified once per request.
109
+ _MASQUERADE_GRANT_MEMO = "_velocity_masquerade_grant"
110
+
111
+ def _is_public_action(self, context) -> bool:
112
+ public_actions = getattr(self, "public_actions", None)
113
+ if not isinstance(public_actions, (list, tuple, set)):
114
+ return False
115
+ try:
116
+ current_action = context.action()
117
+ except Exception:
118
+ return False
119
+ return bool(current_action) and current_action in public_actions
120
+
121
+ def effective_auth_mode(self, context) -> str:
122
+ """``"required"``, ``"optional"`` or ``"none"``: the handler's
123
+ ``auth_mode``, or ``"none"`` for an action in ``public_actions``. A
124
+ value that is not one of the three (a typo, ``"None"``) is
125
+ ``"required"``: authentication fails closed."""
126
+ if self._is_public_action(context):
127
+ return "none"
128
+ mode = getattr(self, "auth_mode", "required") or "required"
129
+ return mode if mode in self._AUTH_MODES else "required"
130
+
131
+ def _verified_masquerade_grant(self, context):
132
+ """``context.get_masquerade_grant()``, verified once per request and
133
+ memoised on the Context."""
134
+ memo = getattr(context, "__dict__", None)
135
+ if isinstance(memo, dict) and self._MASQUERADE_GRANT_MEMO in memo:
136
+ return memo[self._MASQUERADE_GRANT_MEMO]
137
+ grant = context.get_masquerade_grant()
138
+ if isinstance(memo, dict):
139
+ memo[self._MASQUERADE_GRANT_MEMO] = grant
140
+ return grant
141
+
142
+ def applicable_masquerade_grant(self, context):
143
+ """The verified masquerade grant ``beforeAction`` WILL apply to this
144
+ request, or None. The one predicate: a layer that must skip its own
145
+ sign-in handling under masquerade asks this, never its own copy.
146
+
147
+ Applies only when the effective auth mode is not ``"none"``,
148
+ ``allow_masquerade`` is true, ``user_table`` is set, the grant
149
+ verifies (``Context.get_masquerade_grant``, once per request), its
150
+ ``pool`` is this handler's ``user_table``, and both its
151
+ ``real_user`` and ``effective_user`` pass
152
+ :func:`velocity.aws.identity.normalize_email`. A grant that fails
153
+ any of these is treated as absent (the request then needs its own
154
+ sign-in). The grant returned is a copy carrying the normalised
155
+ addresses, so every consumer (the session, the audit, the tenant
156
+ resolver, a layer) sees the same ones."""
157
+ if self.effective_auth_mode(context) == "none":
158
+ return None
159
+ if not getattr(self, "allow_masquerade", True):
160
+ return None
161
+ pool = getattr(self, "user_table", None)
162
+ if not pool:
163
+ return None
164
+ grant = self._verified_masquerade_grant(context)
165
+ if not isinstance(grant, dict) or grant.get("pool") != pool:
166
+ return None
167
+ from velocity.aws.identity import normalize_email
168
+
169
+ real_user = normalize_email(grant.get("real_user"))
170
+ effective_user = normalize_email(grant.get("effective_user"))
171
+ if not (real_user and effective_user):
172
+ logger.warning("Ignored masquerade grant: an address the rule refuses")
173
+ return None
174
+ return {**grant, "real_user": real_user, "effective_user": effective_user}
175
+
106
176
  def _before_action(self, tx, context):
107
177
  # Enhanced activity tracking is supplied by the WebHandler mixin; a bare
108
178
  # LambdaHandler (no WebHandler) simply skips it rather than crashing.
@@ -113,8 +183,10 @@ class LambdaHandler(BaseHandler):
113
183
 
114
184
  self.current_user = {}
115
185
 
116
- auth_mode = getattr(self, "auth_mode", "required") or "required"
186
+ auth_mode = self.effective_auth_mode(context)
117
187
  require_db_user = bool(getattr(self, "require_db_user", True))
188
+ if self._is_public_action(context):
189
+ require_db_user = False
118
190
 
119
191
  session = context.session() or {}
120
192
  # recorded below from server-side facts only; never one left over
@@ -122,73 +194,57 @@ class LambdaHandler(BaseHandler):
122
194
 
123
195
  session.pop(_identity.SESSION_MODE_KEY, None)
124
196
 
125
- public_actions = getattr(self, "public_actions", None)
126
- try:
127
- current_action = context.action()
128
- except Exception:
129
- current_action = None
130
-
131
- if (
132
- current_action
133
- and isinstance(public_actions, (list, tuple, set))
134
- and current_action in public_actions
135
- ):
136
- auth_mode = "none"
137
- require_db_user = False
138
-
139
197
  # Masquerade: a signed grant lets an authorized admin act as another
140
198
  # user. When a valid grant scoped to this app's user_table is present,
141
199
  # the request identity resolves to the target (effective_user) exactly
142
200
  # as if they had signed in, while the real admin is retained for audit.
143
- # The grant signature is verified in context.get_masquerade_grant().
144
- masquerade = None
145
- if (
146
- auth_mode != "none"
147
- and getattr(self, "allow_masquerade", True)
148
- and getattr(self, "user_table", None)
149
- ):
150
- grant = context.get_masquerade_grant()
151
- if grant and grant.get("pool") == self.user_table:
152
- self._refuse_disabled_real_user(tx, grant)
153
- masquerade = grant
154
- session["real_user"] = grant["real_user"]
155
- session["email_address"] = grant["effective_user"]
156
- session["masquerade"] = {
157
- "real_user": grant["real_user"],
158
- "effective_user": grant["effective_user"],
159
- "pool": grant["pool"],
160
- "jti": grant.get("jti"),
161
- "exp": grant.get("exp"),
162
- }
163
- logger.info(
164
- "Masquerade active: %s acting as %s on %s",
165
- grant["real_user"],
166
- grant["effective_user"],
167
- grant["pool"],
168
- )
169
- # Persist the audit the docstring promises: who acted as whom,
170
- # from where. Goes to the framework's one security audit sink
171
- # (sys_security_events, the Security Events page), on its own
172
- # transaction: this request's tx stays open. Fail-closed, as
173
- # authz.require is: no audit row, no masquerade.
174
- from velocity.aws.capabilities.security import record_event
175
-
176
- recorded = record_event(
177
- tx,
178
- "masquerade",
179
- f"{grant['real_user']} acting as {grant['effective_user']} "
180
- f"on {grant['pool']} (jti {grant.get('jti')})",
181
- aws_event=self.aws_event,
182
- context=context,
183
- user_email=grant["real_user"],
184
- # recorded before any request actor is set; the actor
185
- # format AuditTrailMixin uses under masquerade
186
- actor=f"{grant['effective_user']} as {grant['real_user']}",
201
+ # Whether a grant applies is decided once, by
202
+ # applicable_masquerade_grant (which a layer calls too).
203
+ masquerade = self.applicable_masquerade_grant(context)
204
+ if masquerade:
205
+ # addresses already normalised by applicable_masquerade_grant
206
+ grant = masquerade
207
+ real_user = grant["real_user"]
208
+ effective_user = grant["effective_user"]
209
+ self._refuse_disabled_real_user(tx, grant)
210
+ session["real_user"] = real_user
211
+ session["email_address"] = effective_user
212
+ session["masquerade"] = {
213
+ "real_user": real_user,
214
+ "effective_user": effective_user,
215
+ "pool": grant["pool"],
216
+ "jti": grant.get("jti"),
217
+ "exp": grant.get("exp"),
218
+ }
219
+ logger.info(
220
+ "Masquerade active: %s acting as %s on %s",
221
+ real_user,
222
+ effective_user,
223
+ grant["pool"],
224
+ )
225
+ # Persist the audit the docstring promises: who acted as whom,
226
+ # from where. Goes to the framework's one security audit sink
227
+ # (sys_security_events, the Security Events page), on its own
228
+ # transaction: this request's tx stays open. Fail-closed, as
229
+ # authz.require is: no audit row, no masquerade.
230
+ from velocity.aws.capabilities.security import record_event
231
+
232
+ recorded = record_event(
233
+ tx,
234
+ "masquerade",
235
+ f"{real_user} acting as {effective_user} "
236
+ f"on {grant['pool']} (jti {grant.get('jti')})",
237
+ aws_event=self.aws_event,
238
+ context=context,
239
+ user_email=real_user,
240
+ # recorded before any request actor is set; the actor
241
+ # format AuditTrailMixin uses under masquerade
242
+ actor=f"{effective_user} as {real_user}",
243
+ )
244
+ if not recorded:
245
+ raise AccessError(
246
+ "That masquerade could not be recorded, so it was refused."
187
247
  )
188
- if not recorded:
189
- raise AccessError(
190
- "That masquerade could not be recorded, so it was refused."
191
- )
192
248
 
193
249
  if masquerade or auth_mode == "none":
194
250
  # In masquerade mode the caller's own Cognito token is for a
@@ -196,20 +252,23 @@ class LambdaHandler(BaseHandler):
196
252
  # Cognito lookup; identity comes from the verified grant instead.
197
253
  self.cognito_user = None
198
254
  else:
255
+ # one lookup per request, shared with any layer that resolved it
256
+ # first (Context.resolved_cognito_user); "required" raises
199
257
  context.perf.start("get_cognito_user")
200
- if auth_mode == "optional":
201
- self.cognito_user = context.get_cognito_user_optional(self.aws_event)
202
- else:
203
- self.cognito_user = context.get_cognito_user(self.aws_event)
258
+ self.cognito_user = context.resolved_cognito_user(auth_mode)
204
259
  context.perf.log("get_cognito_user")
205
260
 
206
261
  logger.debug("DEBUG: !!! cognito_user %s", self.cognito_user)
207
262
  if isinstance(self.cognito_user, dict):
208
- try:
209
- email_address = self.cognito_user["attributes"]["email"]
263
+ attributes = self.cognito_user.get("attributes")
264
+ raw = attributes.get("email") if isinstance(attributes, dict) else None
265
+ # a refused address leaves the session without one, so
266
+ # require_db_user refuses the request by name below
267
+ email_address = _identity.normalize_email(raw)
268
+ if email_address:
210
269
  session["email_address"] = email_address
211
- except Exception:
212
- logger.warning("Unable to read email from Cognito user", exc_info=True)
270
+ else:
271
+ logger.warning("Cognito user has no usable email address")
213
272
 
214
273
  self._record_identity_mode(session, masquerade)
215
274
 
@@ -422,7 +481,9 @@ class LambdaHandler(BaseHandler):
422
481
 
423
482
  from velocity.aws.handlers.context import user_cache_seconds
424
483
 
425
- email = str(grant.get("real_user") or "").strip().lower()
484
+ from velocity.aws.identity import normalize_email
485
+
486
+ email = normalize_email(grant.get("real_user"))
426
487
 
427
488
  def load():
428
489
  row = tx.table(table).find({"email_address": email}) if email else None
@@ -448,10 +509,21 @@ class LambdaHandler(BaseHandler):
448
509
  from velocity.cache import memo
449
510
 
450
511
  from velocity.aws.handlers.context import user_cache_seconds
512
+ from velocity.aws.identity import find_case_variant, normalize_email
513
+
514
+ # the lookup value and the cache key are the normalised address; a
515
+ # refused one finds nobody and queries nothing
516
+ email_address = normalize_email(email_address)
517
+ if not email_address:
518
+ return None
451
519
 
452
520
  def load():
453
- row = tx.table(self.user_table).find({"email_address": email_address})
454
- return row.to_dict() if row else None
521
+ table = tx.table(self.user_table)
522
+ row = table.find({"email_address": email_address})
523
+ if row:
524
+ return row.to_dict()
525
+ # a row stored before the address rule (identity.find_case_variant)
526
+ return find_case_variant(table, email_address)
455
527
 
456
528
  # Grants kept as rows ride on this row (velocity.aws.permissions).
457
529
  # Keying the entry by the grants' change counter makes a change reach
@@ -85,13 +85,21 @@ def mint_grant(
85
85
  """Create a signed masquerade grant string.
86
86
 
87
87
  ``real_user``, ``effective_user`` and ``pool`` are required and must be
88
- non-empty. ``ttl_seconds`` bounds validity; ``jti`` defaults to a random id.
88
+ non-empty. Both addresses go through
89
+ :func:`velocity.aws.identity.normalize_email` and are signed in that form;
90
+ an address the rule refuses raises (``LambdaHandler`` would ignore such a
91
+ grant). ``ttl_seconds`` bounds validity; ``jti`` defaults to a random id.
89
92
  """
90
- real_user = (real_user or "").strip()
91
- effective_user = (effective_user or "").strip()
93
+ from velocity.aws.identity import normalize_email
94
+
95
+ real_user = normalize_email(real_user)
96
+ effective_user = normalize_email(effective_user)
92
97
  pool = (pool or "").strip()
93
98
  if not real_user or not effective_user or not pool:
94
- raise MasqueradeError("real_user, effective_user and pool are required")
99
+ raise MasqueradeError(
100
+ "real_user, effective_user (valid ASCII email addresses) and pool "
101
+ "are required"
102
+ )
95
103
  if ttl_seconds <= 0:
96
104
  raise MasqueradeError("ttl_seconds must be positive")
97
105
 
velocity/aws/identity.py CHANGED
@@ -33,6 +33,7 @@ grant's user, not a provider subject.
33
33
  from __future__ import annotations
34
34
 
35
35
  import logging
36
+ import re
36
37
 
37
38
  from velocity.aws import ssm_config
38
39
  from velocity.db.servers.tablehelper import escape_like
@@ -54,6 +55,56 @@ SUBJECT_COLUMN = "identity_subject"
54
55
  SCHEMA_COLUMNS = {ISSUER_COLUMN: "TEXT", SUBJECT_COLUMN: "TEXT"}
55
56
 
56
57
 
58
+ # ASCII blanks trimmed from an address's ends; nothing else is stripped.
59
+ _ASCII_BLANKS = " \t\r\n"
60
+
61
+
62
+ def normalize_email(value) -> str:
63
+ """THE address rule for every place velocity reads an email address (a
64
+ claim, a session, a user-table lookup or cache key, a masquerade grant,
65
+ a job key). Returns the address lower-cased, or ``""`` when refused (no
66
+ identity; callers refuse a blank by name).
67
+
68
+ * not a ``str`` (None, bytes, a number, a list) -> ``""``;
69
+ * the RAW value must be ASCII, tested before anything is stripped, so a
70
+ Unicode separator (U+3000, NBSP) is refused rather than trimmed away;
71
+ * only ASCII space, tab, CR and LF are trimmed from the ends;
72
+ * any character below 0x21 or DEL left inside -> ``""``;
73
+ * then ``lower()``. Lower-casing only after the ASCII test keeps a
74
+ non-ASCII letter (KELVIN SIGN -> ``k``) from folding onto an ASCII
75
+ address.
76
+ """
77
+ if not isinstance(value, str) or not value.isascii():
78
+ return ""
79
+ trimmed = value.strip(_ASCII_BLANKS)
80
+ if any(ord(c) < 0x21 or ord(c) == 0x7F for c in trimmed):
81
+ return ""
82
+ return trimmed.lower()
83
+
84
+
85
+ COGNITO_USER_POOL_ID_RE = re.compile(r"^[\w-]+_[0-9a-zA-Z]+$")
86
+
87
+
88
+ def cognito_issuer_subject(provider):
89
+ """``(issuer, sub)`` from API Gateway's ``cognitoAuthenticationProvider``
90
+ (``cognito-idp.<region>.amazonaws.com/<pool>,...:CognitoSignIn:<sub>``)
91
+ when it is a Cognito User Pool identity, else None (absent, not a str, a
92
+ developer-authenticated Identity Pool provider, a malformed pool id or
93
+ an empty sub). The one parser: ``Context.get_cognito_user`` resolves the
94
+ user from this pair, and the issuer is the token issuer for the pool.
95
+ Also importable as ``velocity.aws.handlers.context.cognito_issuer_subject``.
96
+ """
97
+ if not isinstance(provider, str) or "cognito-idp" not in provider:
98
+ return None
99
+ parts = provider.split(",")
100
+ user_pool_segment = parts[0].strip()
101
+ user_pool_id = user_pool_segment.split("/")[-1]
102
+ user_sub = parts[-1].split(":")[-1].strip()
103
+ if not user_sub or not COGNITO_USER_POOL_ID_RE.match(user_pool_id):
104
+ return None
105
+ return f"https://{user_pool_segment}", user_sub
106
+
107
+
57
108
  def mode_of(handler):
58
109
  """``IdentityMode`` config first, then the handler's ``identity_mode``,
59
110
  then ``"email"``. A value that is not a mode is ``"email"`` (logged):
@@ -74,16 +125,16 @@ def mode_of(handler):
74
125
 
75
126
  def claims_of(cognito_user):
76
127
  """``(issuer, subject, email, email_verified)`` from a resolved Cognito
77
- user (``Context.get_cognito_user``); ``None`` parts when absent."""
128
+ user (``Context.get_cognito_user``); ``None`` parts when absent. The
129
+ email is :func:`normalize_email`'s (None when it refuses the address)."""
78
130
  user = cognito_user if isinstance(cognito_user, dict) else {}
79
131
  attributes = user.get("attributes") or {}
80
- email = (attributes.get("email") or user.get("email") or "").strip() or None
81
- if email and email.isascii():
82
- # only an ASCII address is lower-cased: str.lower() folds some
83
- # non-ASCII letters onto ASCII ones (KELVIN SIGN -> "k"), which would
84
- # let one address pass for another; a non-ASCII one stays as given
85
- # and never binds (bind_by_verified_email)
86
- email = email.lower()
132
+ raw = attributes.get("email")
133
+ if raw is None:
134
+ raw = user.get("email")
135
+ # normalize_email: a refused address (non-ASCII, embedded control) is
136
+ # no email at all, so it never binds and never finds a row
137
+ email = normalize_email(raw) or None
87
138
  verified = str(attributes.get("email_verified", "")).strip().lower() == "true"
88
139
  return user.get("issuer") or None, user.get("sub") or None, email, verified
89
140
 
@@ -94,6 +145,44 @@ def _row(found):
94
145
  return found.to_dict() if hasattr(found, "to_dict") else dict(found)
95
146
 
96
147
 
148
+ # how many case-insensitive candidates find_case_variant reads: enough that
149
+ # rows the database merely folds (a non-ASCII look-alike) cannot crowd out
150
+ # the one row whose address really normalises to the caller's
151
+ CASE_VARIANT_SCAN = 10
152
+
153
+
154
+ def find_case_variant(table, email):
155
+ """The one row of ``table`` (a ``tx.table(...)``) whose stored
156
+ ``email_address`` normalises to ``email`` — a row saved before the
157
+ address rule, as ``Ava@Example.com`` — or None. For callers whose exact
158
+ lookup of the normalised address missed.
159
+
160
+ Matched case-insensitively (ILIKE on the escaped address, so LIKE
161
+ wildcards match only themselves), then kept only when
162
+ :func:`normalize_email` of the stored value equals ``email``: a
163
+ non-ASCII stored address the database folds onto it never matches and
164
+ never counts. Two rows that both normalise to it are ambiguous: None
165
+ (logged), as :func:`bind_by_verified_email` refuses to guess."""
166
+ email = normalize_email(email)
167
+ if not email:
168
+ return None
169
+ found = table.select(
170
+ where={"%%email_address": escape_like(email)}, qty=CASE_VARIANT_SCAN
171
+ )
172
+ rows = [
173
+ row
174
+ for row in (_row(f) for f in (found or ()))
175
+ if row and normalize_email(row.get("email_address")) == email
176
+ ]
177
+ if len(rows) > 1:
178
+ logger.warning(
179
+ "identity: more than one row's address normalises to the caller's; "
180
+ "not choosing one"
181
+ )
182
+ return None
183
+ return rows[0] if rows else None
184
+
185
+
97
186
  def find_bound(tx, user_table, issuer, subject):
98
187
  """The user row bound to ``issuer`` + ``subject``, or None."""
99
188
  if not (issuer and subject):
@@ -107,9 +196,10 @@ def bind_by_verified_email(tx, user_table, issuer, subject, email, verified):
107
196
  """Bind the unbound row with this verified email to ``issuer`` +
108
197
  ``subject`` and return it; None when there is nothing it may bind.
109
198
 
110
- The email must be plain ASCII and matches regardless of case (rows saved
111
- as ``Ava@Example.com`` bind like ``ava@example.com``), and only when
112
- exactly one row has it:
199
+ Both the caller's email and the matched row's stored address go through
200
+ :func:`normalize_email` (refused -> nothing binds), so they match
201
+ regardless of case (rows saved as ``Ava@Example.com`` bind like
202
+ ``ava@example.com``), and only when exactly one row has it:
113
203
  two rows sharing an address are ambiguous, and binding either would be a
114
204
  guess. Refuses (returns None, logs why) when the email is not verified,
115
205
  when no row or more than one row has it, or when that row is already
@@ -118,14 +208,12 @@ def bind_by_verified_email(tx, user_table, issuer, subject, email, verified):
118
208
  The binding write is guarded on the row still being unbound, so two
119
209
  first sign-ins racing for one row bind it once.
120
210
  """
211
+ email = normalize_email(email)
121
212
  if not (issuer and subject and email):
122
213
  return None
123
214
  if not verified:
124
215
  logger.warning("identity: not binding — email not verified")
125
216
  return None
126
- if not email.isascii():
127
- logger.warning("identity: not binding — email is not plain ASCII")
128
- return None
129
217
  table = tx.table(user_table)
130
218
  matches = [
131
219
  _row(found)
@@ -140,8 +228,7 @@ def bind_by_verified_email(tx, user_table, issuer, subject, email, verified):
140
228
  )
141
229
  return None
142
230
  row = matches[0]
143
- stored_email = str(row.get("email_address") or "").strip()
144
- if not stored_email.isascii() or stored_email.lower() != email:
231
+ if normalize_email(row.get("email_address")) != email:
145
232
  # the database folded a non-ASCII stored address onto this one
146
233
  logger.warning(
147
234
  "identity: %s row %s matched only by case folding; not binding",
@@ -193,9 +280,11 @@ def session_user(tx, user_table, session):
193
280
  (``require_db_user``) binds a first sign-in, so until one has, a
194
281
  handler without it gets None for that caller.
195
282
  * ``"email"`` / ``"masquerade"``: the one row with the session's
196
- ``email_address`` — a plain-ASCII address lower-cased, as user rows
197
- store it (a non-ASCII one as given: lower-casing could fold it onto
198
- another); None when more than one row has it — an ambiguous identity
283
+ ``email_address`` after :func:`normalize_email` (lower-cased, as user
284
+ rows store it), else the one row stored before the rule whose address
285
+ normalises to it (:func:`find_case_variant`, as
286
+ ``LambdaHandler._cached_user`` finds it); None when the rule refuses
287
+ the address, or when more than one row has it — an ambiguous identity
199
288
  is no identity.
200
289
  * no recorded mode (nobody signed in, or a session ``LambdaHandler`` did
201
290
  not build): None. Never a guess.
@@ -208,13 +297,15 @@ def session_user(tx, user_table, session):
208
297
  subject = str(session.get("sub") or "").strip()
209
298
  return find_bound(tx, user_table, issuer, subject)
210
299
  if mode in (IDENTITY_EMAIL, IDENTITY_MASQUERADE):
211
- email = str(session.get("email_address") or "").strip()
300
+ email = normalize_email(session.get("email_address"))
212
301
  if not email:
213
302
  return None
214
- if email.isascii():
215
- email = email.lower()
216
- found = list(
217
- tx.table(user_table).select(where={"email_address": email}, qty=2) or ()
218
- )
219
- return _row(found[0]) if len(found) == 1 else None
303
+ table = tx.table(user_table)
304
+ found = list(table.select(where={"email_address": email}, qty=2) or ())
305
+ if len(found) == 1:
306
+ return _row(found[0])
307
+ if found:
308
+ return None
309
+ # as LambdaHandler._cached_user: a row stored before the rule
310
+ return find_case_variant(table, email)
220
311
  return None
@@ -10,6 +10,7 @@ Gated like the rest of this directory (``VELOCITY_INTEGRATION=1`` and the
10
10
  ``DB*`` settings of a disposable PostgreSQL).
11
11
  """
12
12
 
13
+ from velocity.aws.handlers.exceptions import AlertError
13
14
  import secrets
14
15
  import types
15
16
 
@@ -796,6 +797,23 @@ def _web_handler():
796
797
  class Ctx(Context):
797
798
  user = None
798
799
 
800
+ def resolved_cognito_user(self, mode="required"):
801
+ # mirrors Context.resolved_cognito_user: only get_cognito_user is
802
+ # called; "required" raises when nothing resolves, "optional" is None
803
+ if mode not in ("required", "optional"):
804
+ return None
805
+ try:
806
+ user = self.get_cognito_user(None)
807
+ if not isinstance(user, dict):
808
+ raise AlertError("Cognito user could not be resolved")
809
+ except AssertionError:
810
+ raise # a fake that must not be asked stays loud
811
+ except Exception:
812
+ if mode == "required":
813
+ raise
814
+ return None
815
+ return user
816
+
799
817
  def get_cognito_user(self, aws_event):
800
818
  return type(self).user
801
819
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: velocity-python
3
- Version: 0.13.2
3
+ Version: 0.14.0
4
4
  Summary: A rapid application development library for interfacing with data storage
5
5
  Author-email: Velocity Team <info@codeclubs.org>
6
6
  License-Expression: MIT
@@ -1,4 +1,4 @@
1
- velocity/__init__.py,sha256=-p_wnPMwH7aEXhWHLXLK-bW2cEDvIg6FJEASvUKhYSs,363
1
+ velocity/__init__.py,sha256=ln6_95uhNgbgzmhzeTw6yRnqDq5ljs0mBhL5vXJsEFo,363
2
2
  velocity/cache.py,sha256=HacQGQXMcrEveDxs-AYVGceRsyi_ZHZ9dcW8YizoGEE,9659
3
3
  velocity/hooks.py,sha256=jY_qtAapNHvptmryFSD-Zc7RvLhV6e5nJEH3x2xTgCw,20575
4
4
  velocity/logging.py,sha256=MAsZap1cDSdOBNRc_9ezQxup5dHOS0ARxU9NI_-UK3E,4037
@@ -12,7 +12,7 @@ velocity/aws/email.py,sha256=CAvXTAUxJqMaT8ylpRwRcVEA4YLFMUuHCrwYLVE4G1E,6243
12
12
  velocity/aws/facets.py,sha256=vAXbp2PSjCTUzFpI84iUHvQoPXD1N-DJ6qIz9UhitFo,22574
13
13
  velocity/aws/failures.py,sha256=8mz2XD7eugPA4HJkMVcabOt-N-Wuf0Lgqi1N0Y8QmxY,33833
14
14
  velocity/aws/feature_flags.py,sha256=G2S1Ifjjex1QEmaAnAwRISyawxfGTdzaKUh3150M5aw,9604
15
- velocity/aws/identity.py,sha256=cUvwd9enEXxp665R1sApVAydU1x1JdZpv4iQFBpkx3Y,9409
15
+ velocity/aws/identity.py,sha256=0yOrk-ygxnYCNM3I7yHnsnWB2vEDO5SP-j4wL0H5jB0,13228
16
16
  velocity/aws/job_lifecycle.py,sha256=taxXEbq1WIg3Vbn9B8Ru0orgbk_J6KWBtAUTIptChWk,19567
17
17
  velocity/aws/job_results.py,sha256=FXQlMazFvkLFiT1BJlHiQj8RiQG5p3bf_X1Zek9StIg,22456
18
18
  velocity/aws/mirror.py,sha256=8Ik1_GVCcD7E2nCe1ci6sp56PEVBMYZF-alkMFlP4O4,8858
@@ -57,11 +57,11 @@ velocity/aws/deploy/reconcile.py,sha256=3xZXXiiVeCw4nUV8lKyk1XCgRbpNCLVYXIXbOLXe
57
57
  velocity/aws/deploy/targets.py,sha256=EgeD1f3adnUmefvvBKDVYak9SXLgxB8UeVi9vnvyP-s,7470
58
58
  velocity/aws/handlers/__init__.py,sha256=0yvVADxMHK8JOhgGRxMIz1XkNGlUk08AOmdR4qhNP2U,906
59
59
  velocity/aws/handlers/base_handler.py,sha256=9zXzZTpQQfRvBGx--Vbgk_dMZbbDHIoHu9BW2t6pTgc,23106
60
- velocity/aws/handlers/context.py,sha256=Ue0XieVy5wNMsgtYrypyPpM5LOueGJsIblb9LGbLrK8,62314
60
+ velocity/aws/handlers/context.py,sha256=5Wd24kYQnFJmcBA5ZI-9cUSvI7WbB04GMoA7XrWEIBs,63114
61
61
  velocity/aws/handlers/context_factory.py,sha256=8rhYKrylzwQxBFqBckmF7jgWGZhfomLOT_Yu404CtJQ,784
62
62
  velocity/aws/handlers/exceptions.py,sha256=PNh2y8kn8AIuD0-XNu6H6hSb-IcKtrAH0bmQMm8AkKQ,5350
63
- velocity/aws/handlers/lambda_handler.py,sha256=AN7S2wo8VD-x1_Jz7ouw5Re-GPRRPcTUZV8UpIQxLq0,28422
64
- velocity/aws/handlers/masquerade.py,sha256=ZMXGGB-w7pXRV8Fq0qBmJOL1Eq55hXP3Rq3dWjJk6Ck,5157
63
+ velocity/aws/handlers/lambda_handler.py,sha256=3N2k4-QHxDu7vHFO0znW0AuQyexUeiRCkSGIUQixuyk,32025
64
+ velocity/aws/handlers/masquerade.py,sha256=ZK0aKUTgD1fF0srDU9IWZ45TomTI-YOqi2z5GAbcOyE,5476
65
65
  velocity/aws/handlers/perf.py,sha256=zLAcr_IrvpnZS1zzzXi-YhopRgCv3OeetQgOx_S43Xw,1421
66
66
  velocity/aws/handlers/request_log.py,sha256=8dUO8wXVa5COKGlNfhfBhvRbkKKP4rR1BvojdG5BRmY,2951
67
67
  velocity/aws/handlers/response.py,sha256=Xi5mzBPiYC-VVS3qFyCgfuV3YyuGuhS1O54QGI7jGHs,17201
@@ -198,7 +198,7 @@ velocity/db/tests/postgres/test_sequence.py,sha256=5lYQasSkTmPvw3scLbkabr-4d2IKO
198
198
  velocity/db/tests/postgres/test_sql_comprehensive.py,sha256=ZuxKNDKmolysmOHU7l3s5p7AvcA450nxVCBK1zQBedY,19028
199
199
  velocity/db/tests/postgres/test_table.py,sha256=P2cOG7UffuZT82PO48HDzRpMN6gUTUJCs9jHfuy8llE,2328
200
200
  velocity/db/tests/postgres/test_table_comprehensive.py,sha256=sOHFshVM1ufK7QQKr-vi70RMzCOGk2BiJ5Iss6HGSQ4,24503
201
- velocity/db/tests/postgres/test_tenancy.py,sha256=pqCFtdLj0149JuY74cqJjy56wCsgOCHU6H2jp15rBcY,53872
201
+ velocity/db/tests/postgres/test_tenancy.py,sha256=ayY54pqNlxECQQ6LJtR1Nw559Yb4tNQAg4grn76U0lM,54666
202
202
  velocity/db/tests/postgres/test_transaction.py,sha256=0ktk1q0EY1FWSNYuXV_Ql3q_091o0Q0-_H1EMxB7jDc,2424
203
203
  velocity/db/tests/sql/__init__.py,sha256=evafiIjAB0jyhqZ8HfiPgRujXJkRpQ7a34Bjac4qyv8,12
204
204
  velocity/db/tests/sql/common.py,sha256=8EGdw9SRj-EywKnzUTVnoHw_C3GWwttFyecWOFxIv_I,5810
@@ -291,9 +291,9 @@ velocity/workflow/points.py,sha256=g_vQ3cdHdx_JloVCS5dVjo_jJoSolO92K5p3suDzxlE,1
291
291
  velocity/workflow/schema.py,sha256=1ZAkGZ_4YrTAfY6TIPCviWQJGLhhmAJmkxisfLyy2og,21597
292
292
  velocity/workflow/traveler.py,sha256=Ik1InoEo69sZB1wVV-UinVo4P0P5QlcV_hh858p3OWE,20562
293
293
  velocity/workflow/views.py,sha256=oTPjpuheND8y4VbcTY8c-4fMdSHKb0jgGzXMuT_G7_s,32175
294
- velocity_python-0.13.2.dist-info/licenses/LICENSE,sha256=aoN245GG8s9oRUU89KNiGTU4_4OtnNmVi4hQeChg6rM,1076
295
- velocity_python-0.13.2.dist-info/METADATA,sha256=M5jOfVPSKsv6zLd-ps8xPJkqBs2DoZnRJLNfhEG95CI,17709
296
- velocity_python-0.13.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
297
- velocity_python-0.13.2.dist-info/entry_points.txt,sha256=nXUKJHkOGQCSPoagdmMNd_qycrle1LVU-GhYknLGM1M,56
298
- velocity_python-0.13.2.dist-info/top_level.txt,sha256=JW2vJPmodgdgSz7H6yoZvnxF8S3fTMIv-YJWCT1sNW0,9
299
- velocity_python-0.13.2.dist-info/RECORD,,
294
+ velocity_python-0.14.0.dist-info/licenses/LICENSE,sha256=aoN245GG8s9oRUU89KNiGTU4_4OtnNmVi4hQeChg6rM,1076
295
+ velocity_python-0.14.0.dist-info/METADATA,sha256=9uy0kv8o9K8YayVM1Xbm1LJ4-PYDhnQ6Mj5nwJqVnsw,17709
296
+ velocity_python-0.14.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
297
+ velocity_python-0.14.0.dist-info/entry_points.txt,sha256=nXUKJHkOGQCSPoagdmMNd_qycrle1LVU-GhYknLGM1M,56
298
+ velocity_python-0.14.0.dist-info/top_level.txt,sha256=JW2vJPmodgdgSz7H6yoZvnxF8S3fTMIv-YJWCT1sNW0,9
299
+ velocity_python-0.14.0.dist-info/RECORD,,