Spaces:
Running

fsanyoto commited on
Commit
5a9c174
·
verified ·
1 Parent(s): 44226ee

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "3c03ce294a",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "a03a8a2fa4",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 3c03ce294a
 
1
+ a03a8a2fa4
api/routes_auth.py CHANGED
@@ -314,8 +314,12 @@ def login(request: Request, response: Response, body: dict = Body(default=None))
314
  raise err(401, "mfa_required", "Enter the 6 digit code from your authenticator app.")
315
  # TOTP FIRST: redemption consumes a recovery code. Do not spend one when the app's
316
  # ordinary code already proves the factor, and never reset the guess budget on password.
317
- factor_valid = bool(remembered) or users.totp_valid(rec.get("mfa_secret"), code,
318
- username=user["username"])
 
 
 
 
319
  if not factor_valid:
320
  recovery_code_used = users.consume_recovery_code(user["username"], code)
321
  if not (factor_valid or recovery_code_used or remembered):
@@ -471,6 +475,16 @@ def _mfa_session_tenant(user, rec, throttle_key):
471
  return tenant
472
 
473
 
 
 
 
 
 
 
 
 
 
 
474
  def _mfa_set(user, secret, codes, *, require_unenrolled=False):
475
  """Translate a raced credential change into a retry, never a claimed successful setup."""
476
  try:
@@ -537,7 +551,7 @@ def mfa_enroll_confirm(request: Request, response: Response, body: dict = Body(d
537
  if users.mfa_enrolled(rec):
538
  raise err(409, "mfa_already_enrolled", _MFA_ALREADY_ENROLLED)
539
  secret = str(body.get("secret") or "").strip().upper()
540
- if not users.totp_valid(secret, str(body.get("code") or "")):
541
  _note_failure(throttle_key)
542
  try:
543
  audit.record("auth.mfa_failed", user["tenant"], user["username"], {"door": "enroll"})
@@ -637,7 +651,7 @@ def mfa_device_confirm(request: Request, response: Response, body: dict = Body(d
637
  if not users.mfa_enrolled(rec):
638
  raise err(409, "mfa_not_enrolled", "Sign in again to set up your authenticator app.")
639
  secret = str(body.get("secret") or "").strip().upper()
640
- if not users.totp_valid(secret, str(body.get("code") or "")):
641
  _note_failure(throttle_key)
642
  try:
643
  audit.record("auth.mfa_failed", user["tenant"], user["username"], {"door": "device"})
 
314
  raise err(401, "mfa_required", "Enter the 6 digit code from your authenticator app.")
315
  # TOTP FIRST: redemption consumes a recovery code. Do not spend one when the app's
316
  # ordinary code already proves the factor, and never reset the guess budget on password.
317
+ # consume=True spends the matched step: a used code, or an older one, is refused (RFC 6238).
318
+ try:
319
+ factor_valid = bool(remembered) or users.totp_valid(rec.get("mfa_secret"), code,
320
+ username=user["username"], consume=True)
321
+ except users.RegistryUnavailable as exc:
322
+ raise _auth_store_down("consume_totp_step", exc)
323
  if not factor_valid:
324
  recovery_code_used = users.consume_recovery_code(user["username"], code)
325
  if not (factor_valid or recovery_code_used or remembered):
 
475
  return tenant
476
 
477
 
478
+ def _spend_candidate_code(user, secret, code):
479
+ """Prove a candidate secret and spend its step, so the setup code cannot sign in again."""
480
+ if users.mfa_sealed(secret):
481
+ return False # a candidate is the plain base32 the phone scanned
482
+ try:
483
+ return users.totp_valid(secret, str(code or ""), username=user["username"], consume=True)
484
+ except users.RegistryUnavailable as exc:
485
+ raise _auth_store_down("consume_totp_step", exc)
486
+
487
+
488
  def _mfa_set(user, secret, codes, *, require_unenrolled=False):
489
  """Translate a raced credential change into a retry, never a claimed successful setup."""
490
  try:
 
551
  if users.mfa_enrolled(rec):
552
  raise err(409, "mfa_already_enrolled", _MFA_ALREADY_ENROLLED)
553
  secret = str(body.get("secret") or "").strip().upper()
554
+ if not _spend_candidate_code(user, secret, body.get("code")):
555
  _note_failure(throttle_key)
556
  try:
557
  audit.record("auth.mfa_failed", user["tenant"], user["username"], {"door": "enroll"})
 
651
  if not users.mfa_enrolled(rec):
652
  raise err(409, "mfa_not_enrolled", "Sign in again to set up your authenticator app.")
653
  secret = str(body.get("secret") or "").strip().upper()
654
+ if not _spend_candidate_code(user, secret, body.get("code")):
655
  _note_failure(throttle_key)
656
  try:
657
  audit.record("auth.mfa_failed", user["tenant"], user["username"], {"door": "device"})
api/routes_security.py CHANGED
@@ -342,6 +342,10 @@ def _authentication_control():
342
  ancestors.insert(0, ast.unparse(parent.test))
343
  node = parent
344
  covered = covered and ancestors == guards
 
 
 
 
345
  first = min((node.lineno for node in factors), default=0)
346
  covered = covered and not any(getattr(node, "lineno", 0) < first and (
347
  isinstance(node, ast.Return) or isinstance(node, ast.Call)
@@ -363,7 +367,7 @@ def _authentication_control():
363
  met = (policy == (12, 10, 1, 90) and covered and
364
  rules >= {"length", "uppercase", "lowercase", "digit", "symbol", "identifier"})
365
  return _answer("met" if met else "not_met", (
366
- "Runtime policy reads 12 characters, ten prior passwords and 1/90 day age limits; stored accounts require MFA enrollment and a factor or signed seven day browser proof, with a QA identity exception."
367
  if met else "The runtime password policy or inspected login factor block does not match the authentication baseline."))
368
 
369
 
 
342
  ancestors.insert(0, ast.unparse(parent.test))
343
  node = parent
344
  covered = covered and ancestors == guards
345
+ # RFC 6238 5.2: the login door must spend the step it accepts, so a used code is refused.
346
+ covered = covered and any(
347
+ kw.arg == "consume" and isinstance(kw.value, ast.Constant) and kw.value.value is True
348
+ for node in factors if ast.unparse(node.func) == "users.totp_valid" for kw in node.keywords)
349
  first = min((node.lineno for node in factors), default=0)
350
  covered = covered and not any(getattr(node, "lineno", 0) < first and (
351
  isinstance(node, ast.Return) or isinstance(node, ast.Call)
 
367
  met = (policy == (12, 10, 1, 90) and covered and
368
  rules >= {"length", "uppercase", "lowercase", "digit", "symbol", "identifier"})
369
  return _answer("met" if met else "not_met", (
370
+ "Runtime policy reads 12 characters, ten prior passwords and 1/90 day age limits; stored accounts require MFA enrollment and a single use factor or signed seven day browser proof, with a QA identity exception."
371
  if met else "The runtime password policy or inspected login factor block does not match the authentication baseline."))
372
 
373
 
platform/core/users.py CHANGED
@@ -263,6 +263,7 @@ MFA_PERIOD = 30
263
  MFA_DRIFT = 1 # accept the previous and next window: phones drift
264
  MFA_ISSUER = 'Loopable'
265
  RECOVERY_CODE_COUNT = 10
 
266
 
267
 
268
  def new_mfa_secret() -> str:
@@ -281,7 +282,11 @@ def totp_code(secret, at=None, offset=0) -> str:
281
  return str(number % (10 ** MFA_DIGITS)).zfill(MFA_DIGITS)
282
 
283
 
284
- def totp_valid(secret, code, at=None, *, username=None) -> bool:
 
 
 
 
285
  if mfa_sealed(secret):
286
  # A sealed secret opens only under its own username, which is the AAD.
287
  secret = open_mfa_secret(username, secret)
@@ -293,17 +298,55 @@ def totp_valid(secret, code, at=None, *, username=None) -> bool:
293
  try:
294
  # Capture the time once: crossing a step boundary mid-loop must not change the window.
295
  at = time.time() if at is None else at
296
- valid = False
297
  for offset in range(-MFA_DRIFT, MFA_DRIFT + 1):
 
298
  # There is no counter before the Unix epoch; this only matters for boundary tests.
299
- expected = (totp_code(secret, at=at, offset=offset)
300
- if int(at) // MFA_PERIOD + offset >= 0 else '')
301
  # Compare EVERY window, even after a match. Early return leaks which window matched.
302
- valid |= hmac.compare_digest(expected, code)
303
- return valid
304
  except (ValueError, TypeError, binascii.Error, struct.error, OverflowError):
305
  # A malformed stored/candidate secret is an invalid factor, never a login-path 500.
306
  return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307
 
308
 
309
  def otpauth_uri(secret, username, issuer=MFA_ISSUER) -> str:
 
263
  MFA_DRIFT = 1 # accept the previous and next window: phones drift
264
  MFA_ISSUER = 'Loopable'
265
  RECOVERY_CODE_COUNT = 10
266
+ MFA_LAST_STEP = 'mfa_last_step' # newest TOTP step this account spent at a sign-in door
267
 
268
 
269
  def new_mfa_secret() -> str:
 
282
  return str(number % (10 ** MFA_DIGITS)).zfill(MFA_DIGITS)
283
 
284
 
285
+ def totp_valid(secret, code, at=None, *, username=None, consume=False) -> bool:
286
+ """True when `code` matches a step in the drift window. `consume=True` also spends that step.
287
+
288
+ A spent step, or any older one, is refused for that account (RFC 6238 5.2).
289
+ """
290
  if mfa_sealed(secret):
291
  # A sealed secret opens only under its own username, which is the AAD.
292
  secret = open_mfa_secret(username, secret)
 
298
  try:
299
  # Capture the time once: crossing a step boundary mid-loop must not change the window.
300
  at = time.time() if at is None else at
301
+ matched = None
302
  for offset in range(-MFA_DRIFT, MFA_DRIFT + 1):
303
+ step = int(at) // MFA_PERIOD + offset
304
  # There is no counter before the Unix epoch; this only matters for boundary tests.
305
+ expected = totp_code(secret, at=at, offset=offset) if step >= 0 else ''
 
306
  # Compare EVERY window, even after a match. Early return leaks which window matched.
307
+ if hmac.compare_digest(expected, code):
308
+ matched = step
309
  except (ValueError, TypeError, binascii.Error, struct.error, OverflowError):
310
  # A malformed stored/candidate secret is an invalid factor, never a login-path 500.
311
  return False
312
+ if matched is None:
313
+ return False
314
+ return consume_totp_step(username, matched) if consume else True
315
+
316
+
317
+ def consume_totp_step(username, step) -> bool:
318
+ """Spend one verified TOTP step. False when this account already accepted it or a newer one.
319
+
320
+ Raises RegistryUnavailable when the account store cannot record the step: fail closed.
321
+ """
322
+ username = (username or '').strip().lower()
323
+ if not username or not isinstance(step, int) or step < 0:
324
+ return False
325
+ if freeze_notice.enabled():
326
+ # A freeze writes nothing, so only a step that is already recorded can be refused.
327
+ try:
328
+ rec = account_rows.get(username, st=store, fresh=True) or {}
329
+ except Exception as exc:
330
+ raise RegistryUnavailable('The account store is unavailable') from exc
331
+ last = rec.get(MFA_LAST_STEP)
332
+ return not (isinstance(last, int) and last >= step)
333
+ spent = [False]
334
+
335
+ def _set(reg):
336
+ spent[0] = False # report the final replay, not an earlier attempt
337
+ u = reg.get(username)
338
+ if isinstance(u, dict):
339
+ last = u.get(MFA_LAST_STEP)
340
+ if not (isinstance(last, int) and last >= step):
341
+ u[MFA_LAST_STEP] = step
342
+ spent[0] = True
343
+ # NO EPOCH BUMP: login owns the bump and the cookie it is about to mint.
344
+ return reg
345
+ try:
346
+ account_rows.update(username, _set, st=store)
347
+ except Exception as exc:
348
+ raise RegistryUnavailable('The account store is unavailable') from exc
349
+ return spent[0]
350
 
351
 
352
  def otpauth_uri(secret, username, issuer=MFA_ISSUER) -> str:
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- a6f25a81706b22189ac685acb89a7b2fb67cd089c3813325b1ddde7ee0834c32
 
1
+ d0bfdc507ff768fc6cc4e6e302e39ab32b905fbd7f380e7bb88fa3689e5f0c5c